I am a complete noob with HashMaps and have spent the better part of a week trying to find what I need.
I am successfully parsing a JSON response from an HTTP request. What I'm having trouble with is saving each data variable/value from each JSON row into a HashMap and then retrieving those data values later.
In my for loop where I'm parsing the JSON response, I need to make sure I'm using the correct syntax for the put command.
More importantly, in getBottles() I need to know how to set o1.setname_abbr to the first record in the HashMap for name. I will eventually need to turn that into a for loop and assign all of the names from the JSON response and then get them all back from the HashMap in getBottles().
Many thanks for any assistance!
Here is my code...
public class Bottles extends ListActivity {
private int category_id;
private int subcategory_id;
String subcategory_idString = "false";
String postQuery;
private int bottleID;
String name_abbr;
String name_abbrArray[];
String bottlePicture;
private ProgressDialog m_ProgressDialog = null;
private ArrayList<Bottles> m_bottles = null;
private BottleAdapter m_adapter;
private Runnable viewBottles;
ArrayList<HashMap<String, String>> bottleNameArray = new ArrayList<HashMap<String, String>>();
HashMap<String, String> bottleNamesMap = new HashMap<String, String>();
String name[];
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.bottleslist);
String result = "";
Bundle extras = getIntent().getExtras();
if(extras != null){
category_id = getIntent().getExtras().getInt("id");
subcategory_id = getIntent().getExtras().getInt("subid");
if(subcategory_id==0){
subcategory_idString = "";
}
}
InputStream is = null;
//http post
try{
if(subcategory_idString==""){
postQuery = "my api call goes here";
}
if(subcategory_idString=="false"){
postQuery = "different api call goes here";
}
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(postQuery);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
try {
JSONObject row = new JSONObject(result);
JSONArray array = row.getJSONArray("response name");
for (int i = 0; i < array.length(); i++) {
row = array.getJSONObject(i);
bottleID = row.getInt("id");
name_abbr = row.getString("name_abbr");
bottleNamesMap = new HashMap<String, String>();
bottleNamesMap.put("name", name_abbr);
bottlePicture = row.getString("bottlePicture");
}
}catch(Exception e){
Log.e("log_tag", "Error parsing JSON "+e.toString());
}
m_bottles = new ArrayList<Bottles>();
this.m_adapter = new BottleAdapter(this, R.layout.bottlelistimagelayout, m_bottles);
setListAdapter(this.m_adapter);
viewBottles = new Runnable(){
public void run() {
getBottles();
}
};
Thread thread = new Thread(null, viewBottles, "MagentoBackground");
thread.start();
m_ProgressDialog = ProgressDialog.show(Bottles.this,
"Please wait...", "Retrieving data ...", true);
}
public class Bottle{
public String name_abbrArray;
//public String lastName;
//public int age;
}
private void getBottles(){
try{
//will put this into a for loop after I figure out how to reference the HashMap values
m_bottles = new ArrayList<Bottles>();
Bottles o1 = new Bottles();
o1.setname_abbr("I want to get the HashMap value of the first name here");
o1.setbottlePicture("Pending");
Bottles o2 = new Bottles();
o2.setname_abbr("I want to get the HashMap value of the second name here");
o2.setbottlePicture("Completed");
m_bottles.add(o1);
m_bottles.add(o2);
Thread.sleep(2000);
Log.i("ARRAY", ""+ m_bottles.size());
} catch (Exception e) {
Log.e("BACKGROUND_PROC", e.getMessage());
}
runOnUiThread(returnRes);
}
private Runnable returnRes = new Runnable() {
public void run() {
if(m_bottles != null && m_bottles.size() > 0){
m_adapter.notifyDataSetChanged();
for(int i=0;i<m_bottles.size();i++)
m_adapter.add(m_bottles.get(i));
}
m_ProgressDialog.dismiss();
m_adapter.notifyDataSetChanged();
}
};
private class BottleAdapter extends ArrayAdapter<Bottles> {
private ArrayList<Bottles> items;
public BottleAdapter(Context context, int textViewResourceId, ArrayList<Bottles> items) {
super(context, textViewResourceId, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.bottlelistimagelayout, null);
}
Bottles o = items.get(position);
if (o != null) {
TextView tt = (TextView) v.findViewById(R.id.toptext);
TextView bt = (TextView) v.findViewById(R.id.bottomtext);
if (tt != null) {
tt.setText("Name: "+o.getname_abbr()); }
if(bt != null){
bt.setText("Picture: "+ o.getbottlePicture());
}
}
return v;
}
}
}
I think I don't fully understand your question, but if you add every bottle hashmap to an arraylist (by the way I see you have an ArrayList<Bottle> what should be its purpose, look empty to me).
You can, then, loop your arraylist containing your hashmaps: arrayListOfBottles.get(position)
Related
"http://soccer.sportsopendata.net/v1/leagues/premier-league/seasons/16-17/standings" - Link Which Iam Trying to parse
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button GetServerData = (Button) findViewById(R.id.GetServerData);
GetServerData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// WebServer Request URL
String serverURL = "http://soccer.sportsopendata.net/v1/leagues/premier-league/seasons/16-17/standings";
// Use AsyncTask execute Method To Prevent ANR Problem
new LongOperation().execute(serverURL);
}
});
}
private class LongOperation extends AsyncTask<String, Void, Void> {
private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
String data = "";
TextView uiUpdate = (TextView) findViewById(R.id.textView2);
TextView jsonParsed = (TextView) findViewById(R.id.textView3);
int sizeData = 0;
EditText serverText = (EditText) findViewById(R.id.textView);
protected void onPreExecute() {
// NOTE: You can call UI Element here.
//Start Progress Dialog (Message)
Dialog.setMessage("Please wait..");
Dialog.show();
try {
// Set Request parameter
data += "&" + URLEncoder.encode("data", "UTF-8") + "=" + serverText.getText();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected Void doInBackground(String... urls) {
/************ Make Post Call To Web Server ***********/
BufferedReader reader = null;
// Send data
try {
// Defined URL where to send data
URL url = new URL(urls[0]);
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
// Append server response in string
sb.append(line + "");
}
// Append Server Response To Content String
Content = sb.toString();
} catch (Exception e) {
Error = e.getMessage();
} finally {
try {
reader.close();
} catch (Exception ex) {
}
}
return null;
}
protected void onPostExecute(Void unused) {
// NOTE: You can call UI Element here.
// Close progress dialog
Dialog.dismiss();
if (Error != null) {
uiUpdate.setText("Output : " + Error);
}else
{
//Show Response Json Onscreen(Activity)
uiUpdate.setText( Content );
/****************** Start Parse Response JSON Data *************/
String OutputData = "";
try {
JSONObject jsono = new JSONObject(Content);
JSONObject mainObject = jsono.getJSONObject("data");
JSONArray jsonArray = mainObject.getJSONArray("standing");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
// get details2 JSONObject
String position = object.optString("position").toString();
String team = object.optString("team").toString();
OutputData += "Position: " + position + " "
+ "Team Name : " + team + " ";
}
/****************** End Parse Response JSON Data *************/
//Show Parsed Output on screen (activity)
jsonParsed.setText( OutputData );
}catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}
**I am Creating a premier league application which shows all the datas needed for a premier league fan. As Iam new to this I am getting confused over json parsing and getting data from apis. So Can anyone Explain to me how to change my code or Some links which would help me correct it.
Above given is my java code of Main Activity.**
Thank You Everyone for Helping out. But I found my answer from the search over the internet. Here I used VOLLEY to call the link.
JSON PARSER CLASS
public class ParseJSON {
public static String[] position1;
public static String[] team;
public static String[] points;
public static final String JSON_ARRAY = "data";
public static final String CHILD_ARRAY = "standings";
public static final String KEY_ID = "position";
public static final String KEY_NAME = "team";
private JSONObject users = null;
private JSONArray user2=null;
private JSONObject user3=null;
private String json;
public ParseJSON(String json){
this.json = json;
}
protected void parseJSON() {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(json);
users = jsonObject.getJSONObject(JSON_ARRAY);
try {
user2=users.getJSONArray(CHILD_ARRAY);
position1 = new String[user2.length()];
team = new String[user2.length()];
points=new String[user2.length()];
for (int i = 0; i < user2.length(); i++) {
JSONObject jo = user2.getJSONObject(i);
try {
user3=jo.getJSONObject("overall");
points[i] = user3.getString("points");
System.out.println("Message me: "+points[i]);
}catch (Exception e)
{
e.printStackTrace();
}
position1[i] = jo.getString(KEY_ID);
team[i] = jo.getString(KEY_NAME);
System.out.println("Message me: "+position1[i]);
System.out.println("Message me: "+team[i]);
}
}catch (Exception e)
{
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Main Activity Class
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public static final String JSON_URL="http://soccer.sportsopendata.net/v1/leagues/premier-league/seasons/16-17/standings";
private Button buttonGet;
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonGet = (Button) findViewById(R.id.buttonGet);
buttonGet.setOnClickListener(this);
listView = (ListView) findViewById(R.id.listView);
}
#Override
public void onClick(View v) {
sendRequest();
}
private void sendRequest() {
final StringRequest stringRequest = new StringRequest(JSON_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String json){
ParseJSON pj = new ParseJSON(json);
pj.parseJSON();
CustomList cl = new CustomList(this, ParseJSON.position1,ParseJSON.team,ParseJSON.points);
listView.setAdapter(cl);
}
}
Custom Class for adding datas to list view
public class CustomList extends ArrayAdapter<String> {
private String[] position1;
private String[] team;
private String[] points;
private Activity context;
public CustomList(Activity context, String[] position1, String[] team, String[] points) {
super(context, R.layout.list_view_layout, position1);
this.context = context;
this.position1 = position1;
this.team = team;
this.points = points;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.list_view_layout, null, true);
TextView pos1 = (TextView) listViewItem.findViewById(R.id.position1);
TextView teamname = (TextView) listViewItem.findViewById(R.id.teamname);
TextView points1 = (TextView) listViewItem.findViewById(R.id.points);
pos1.setText("Position: "+position1[position]);
teamname.setText("Team: "+team[position]);
points1.setText("Points: "+points[position]);
return listViewItem;
}
}
Step 1 : Use Retroft + RxJava for Asynchronous API calls
Step 2 : Use Gson to Serialize and Deserialize.
Step 3 : Use json to POJO to have a Model Class
Simplify the code.
i am getting JSON data from http://abinet.org/?json=1 and displaying the titles in a ListView. the code is working fine but the problem is, it is skipping few titles in my ListView and one title is being repeated.
You can see the json data from url given above by copy paste it in JSON editor online http://www.jsoneditoronline.org/
i want titles in the "posts" array to be displayed in ListView, however it is being displayed like this:
if you see the JSON data from the link above, its missing like 3 titles (they should come between the first and second title) and 5th title is being repeated. Dont know why this is happening. What minor adjustments i need to do? Please help me.
this is my code :
public class MainActivity extends Activity {
// URL to get contacts JSON
private static String url = "http://abinet.org/?json=1";
// JSON Node names
private static final String TAG_POSTS = "posts";
static final String TAG_TITLE = "title";
private ProgressDialog pDialog;
JSONArray contacts = null;
TextView img_url;
ArrayList<HashMap<String, Object>> contactList;
ListView lv;
LazyAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.newslist);
contactList = new ArrayList<HashMap<String, Object>>();
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
protected Void doInBackground(Void... arg0) {
// Making a request to url and getting response
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject jsonObj = jParser.getJSONFromUrl(url);
// if (jsonStr != null) {
try {
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_POSTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
// JSONObject c = contacts.getJSONObject(i);
JSONObject posts = contacts.getJSONObject(i);
String title = posts.getString(TAG_TITLE).replace("’", "'");
JSONArray attachment = posts.getJSONArray("attachments");
for (int j = 0; j< attachment.length(); j++){
JSONObject obj = attachment.getJSONObject(j);
JSONObject image = obj.getJSONObject("images");
JSONObject image_small = image.getJSONObject("thumbnail");
String imgurl = image_small.getString("url");
HashMap<String, Object> contact = new HashMap<String, Object>();
contact.put("image_url", imgurl);
contact.put(TAG_TITLE, title);
contactList.add(contact);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
adapter=new LazyAdapter(MainActivity.this, contactList);
lv.setAdapter(adapter);
}
}
}
this is my JsonParser class (although its not required):
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
and this is adapter class:
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, Object>> data;
private static LayoutInflater inflater=null;
public LazyAdapter(Activity a,ArrayList<HashMap<String, Object>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.third_row, null);
TextView title = (TextView)vi.findViewById(R.id.headline3); // title
SmartImageView iv = (SmartImageView) vi.findViewById(R.id.imageicon);
HashMap<String, Object> song = new HashMap<String, Object>();
song = data.get(position);
// Setting all values in listview
title.setText((CharSequence) song.get(MainActivity.TAG_TITLE));
iv.setImageUrl((String) song.get("image_url"));
thumb_image);
return vi;
}
}
Please help me. I am stuck at this for more than a week now. I think there is just something to be changed in my MainActivity class.
Some of the 10 (well today there are 10 ) 'titles' have no 'attachments'. Some have one and some have two. There are only 5 titles wich have one or two images. You only create a new
HashMap<String, Object> contact
if there are attachments. (The attachment are the images). You should create the 'contact' before you enter the attachments loop. Further you only need one image for each title. You can set the image null if there are no attachments. In getView if the image is null you set some image from your drawable res.
I'm practising with some tutorials I found on the web, I am communicating with a database for a listing, the unfold in a listview listview adapter as show you various names, I would like to add a search dialog, something like this Example Image but no where in the deploy, I have tried in various ways.
this is part of the code example:
LIST ACTIVITY:
public class List extends Activity {
private ProgressDialog pDialog;
public int i = 0;
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> DaftarRS = new ArrayList<HashMap<String, String>>();
private static String url_daftar_rs = "my_url";
public static final String TAG_SUCCESS = "success";
public static final String TAG_DAFTAR_RS = "daftar_rs";
public static final String TAG_ID_RS = "id_rs";
public static final String TAG_NAMA_RS = "nama_rs";
public static final String TAG_LINK_IMAGE_RS = "link_image_rs";
public static final String TAG_ALAMA_RS = "alamat_rs";
public static final String TAG_TELEPONS_RS = "telepon_rs";
JSONArray daftar_rs = null;
ListView list;
ListAdapter adapter;
private ListadoActivity activity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
DaftarRS = new ArrayList<HashMap<String, String>>();
new Activity().execute();
activity = this;
list = (ListView) findViewById(R.id.list);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String id_rs = ((TextView) view
.findViewById(R.id.id_rs)).getText().toString();
Intent in = new Intent(getApplicationContext(),
DetallesActivity.class);
in.putExtra(TAG_ID_RS, id_rs);
startActivityForResult(in, 100);
}
});
}
public void SetListViewAdapter(ArrayList<HashMap<String, String>> daftar) {
adapter = new ListAdapter(activity, daftar);
list.setAdapter(adapter);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 100) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
class Activity extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(List.this);
pDialog.setMessage("wait..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
Conexion();
if (i == 0) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url_daftar_rs, "GET",
params);
Log.d("All Products: ", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
daftar_rs = json.getJSONArray(TAG_DAFTAR_RS);
for (int i = 0; i < daftar_rs.length(); i++) {
JSONObject c = daftar_rs.getJSONObject(i);
String id_rs = c.getString(TAG_ID_RS);
String nama_rs = c.getString(TAG_NAMA_RS);
String link_image_rs = c
.getString(TAG_LINK_IMAGE_RS);
String alamat_rs = c.getString(TAG_ALAMAT_RS);
String telepon_rs = c.getString(TAG_TELEPON_RS);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ID_RS, id_rs);
map.put(TAG_NAMA_RS, nama_rs);
map.put(TAG_LINK_IMAGE_RS, link_image_rs);
map.put(TAG_ALAMAT_RS, alamat_rs);
map.put(TAG_TELEPON_RS, telepon_rs);
DaftarRS.add(map);
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
else{ finish();
}
return null;
}
JSON PARSER:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if (method == "POST") {
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} else if (method == "GET") {
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
LISTADAPTER:
public class ListAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;
public ListAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data = d;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.item_list_rs, null);
TextView id_rs = (TextView) vi.findViewById(R.id.id_rs);
TextView nama_rs = (TextView) vi.findViewById(R.id.nama_rs);
TextView link_image_rs = (TextView) vi.findViewById(R.id.link_image_rs);
TextView alamat_rs = (TextView) vi.findViewById(R.id.alamat_rs);
TextView telepon_rs = (TextView) vi.findViewById(R.id.telepon_rs);
ImageView thumb_image = (ImageView) vi.findViewById(R.id.image_rs);
HashMap<String, String> daftar_rs = new HashMap<String, String>();
daftar_rs = data.get(position);
id_rs.setText(daftar_rs.get(ListadoActivity.TAG_ID_RS));
nama_rs.setText(daftar_rs.get(ListadoActivity.TAG_NAMA_RS));
link_image_rs.setText(daftar_rs.get(ListadoActivity.TAG_LINK_IMAGE_RS));
alamat_rs.setText(daftar_rs.get(ListadoActivity.TAG_ALAMAT_RS));
telepon_rs.setText(daftar_rs.get(ListadoActivity.TAG_TELEPON_RS));
imageLoader.DisplayImage(daftar_rs.get(ListadoActivity.TAG_LINK_IMAGE_RS),
thumb_image);
return vi;
}
}
Why don't you add an EditText to the layout xml and pass the text as an argument after the List<NameValuePair> params = new ArrayList<NameValuePair>();
Something like:
params.add(new BasicNameValuePair(TAG_NAME, name));
public ArrayList<String> getData()
{
ArrayList<String> listItems = new ArrayList<String>();
String result = "";
InputStream isr=null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/get_data.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
isr = entity.getContent();
}
catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
//resultView.setText("Couldnt connect to database");
}
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(isr,"iso- 8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
result=sb.toString();
}
catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try {
String s = "";
JSONArray jArray = new JSONArray(result);
for(int i=0; i<jArray.length();i++)
{
JSONObject json=jArray.getJSONObject(i);
listItems.add(json.getString("name"));
listItems.add(json.getString("ph.no"));
listItems.add(json.getString("id"));
// adding HashList to ArrayList
}
// resultView.setText(s);
} catch (Exception e)
{
// TODO: handle exception
Log.e("log_tag", "Error Parsing Data "+e.toString());
}
return listItems;
// selecting single ListView item
}
I am developing an android application called phone book. I am extracting details of person
from sever as json object. Displaying details on android
I am able to display contact details of a particular person in different rows. How to display details of a single person on same row.
You can Customizing Android ListView Items with Custom ArrayAdapter.
You can do this way,
/* In main activity */
ListView myListView = (ListView)findViewById(R.id.myListView);
final ArrayList<Phonebook> todoItems = new ArrayList<Phonebook>();
final YourAdapter x= new YourAdapter(this,R.layout.your_listviewlayout,todoItems);
myListView.setAdapter(x);
Phonebook phnbk= new Phonebook();
// enter code for set values to Phonebook class variables
/* Inserting the values to array */
todoItems.add(phnbk);
/* Customized array adaptor class */
private class YourAdapter extends ArrayAdapter<Phonebook>
{
private ArrayList<Phonebook> items;
public YourAdapter (Context context, int textViewResourceId, ArrayList<Phonebook> items)
{
super(context, textViewResourceId, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View v = convertView;
if (v == null)
{
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.your_listviewlayout, null);
}
Phonebook o = items.get(position);
if (o != null)
{
//insert values to each text view in your list view layout
tv1.setText(o.name);
tv2.setText(o.phnnum);
tv3.setText(o.email);
}
return v;
}
}
/* Phonebook class */
public class Phonebook{
public String name;
public String phnnum;
public String email;
public Phonebook(){
super();
}
public Phonebook(String name, String phnnum, String email) {
super();
this.name = name;
this.phnnum = phnnum;
this.email = email;
}
}
I have read plenty of examples ,but if I wish to maintain my scroll position after a ListView is updated from JSON ,then can I do that without using an AsyncTask instance ???
the code for my list is
String wrd;
//ArrayList<HashMap<String,String>> mylist;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent i2=getIntent();
wrd=i2.getStringExtra("entrd");
Log.v("keyis",wrd);
final Handler handler = new Handler();
Runnable runable = new Runnable() {
#Override
public void run() {
//call the function
LoadData();
//also call the same runnable
handler.postDelayed(this, 40000);
}
};
handler.postDelayed(runable, 10);
}public void LoadData(){
JSONObject j2=JSONfunctions.getJSONfromURL("/webservice_search.php?keyword="+wrd+"&format=json");
ArrayList<HashMap<String,String>> mylist = new ArrayList<HashMap<String,String>>();
try{JSONArray jray=j2.getJSONArray("listings");
for(int i=0;i<jray.length();i++){
Log.v("state","json data being read");
JSONObject j3= jray.getJSONObject(i);
String first=j3.getString("listing");
Log.v("sublist", first);
JSONObject j4=j3.getJSONObject("listing");
String sec=j4.getString("links");
int maxLength = (sec.length() < 30)?sec.length():27;
sec.substring(0, maxLength);
String cutsec=sec.substring(0,maxLength);
Log.v("links are",cutsec);
String img=j4.getString("image_name");
Log.v("image name is ",img);
//Uri dimg=Uri.parse("http://zeesms.info/android_app_images/Koala.jpg");
HashMap<String,String> map=new HashMap<String,String>();
map.put("Id",String.valueOf(i));
map.put(Li_nk,cutsec);
map.put(Image_name,j4.getString("image_name"));
map.put(KEY_THUMB_URL,"http://zeesms.info/android_app_images/"+img);
mylist.add(map);
}
}
catch(JSONException e){
Log.e("loG_tag","Error parsing"+e.toString());
}
LazyAdapter adapter = new LazyAdapter(this,mylist);
adapter.notifyDataSetChanged();
ListView list=(ListView)findViewById(R.id.lv1);
list.setEmptyView(findViewById(R.id.empty));
list.setAdapter(adapter);
list.setItemsCanFocus(false);
and my adapter is
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.custom_row_view1, null);
TextView title = (TextView)vi.findViewById(R.id.linkname); // merchnts name
TextView artist = (TextView)vi.findViewById(R.id.imagename); // address
//TextView duration = (TextView)vi.findViewById(R.id); // distance
ImageView thumb_image=(ImageView)vi.findViewById(R.id.mClogo); // logo
HashMap<String, String> jsn = new HashMap<String, String>();
jsn = data.get(position);
// Setting all values in listview
title.setText(jsn.get(Second.Li_nk));
artist.setText(jsn.get(Second.Image_name));
//duration.setText(song.get(CustomizedListView.KEY_DURATION));
imageLoader.DisplayImage(jsn.get(Second.KEY_THUMB_URL), thumb_image);
return vi;
}
and finally the class being used for json parsing is
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url){
InputStream is = null;
String result = "";
JSONObject jArray = null;
String str1="http://zeesms.info"+url;
// ArrayList<NameValuePair> namevaluepairs = new ArrayList<NameValuePair>();
Log.v("url result",url);
//namevaluepairs.add(new BasicNameValuePair("location",str1));
//http post
try{
HttpClient httpclient= new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(str1));
HttpResponse response = httpclient.execute(request);
is = response.getEntity().getContent();
if(is==null){
Log.v("url result","is null");
}
else
{
Log.v("url result","is not null");
}
/* BufferedReader buf = new BufferedReader(new InputStreamReader(is,"UTF-8"));
StringBuilder sb = new StringBuilder();
String s;
while(true )
{
s = buf.readLine();
if(s==null || s.length()==0)
break;
sb.append(s);
}
buf.close();
is.close();
sb.toString(); */
// httppost.setEntity(new UrlEncodedFormEntity(namevaluepairs));
//HttpResponse response=httpclient.execute(httppost);
//HttpEntity entity=response.getEntity();
//is=entity.getContent();
/*
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
*/
}catch(Exception e){
Log.v("log_tag", "Error in http connection "+e.toString());
AlertDialog.Builder alert=new AlertDialog.Builder(null);
alert.setMessage("Invalid Keyword").setPositiveButton("Ok", new OnClickListener(){
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
}
});
}
//convert response to string
try{
Log.v("url result","getting result starts");
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
Log.v("url result","getting result");
while ((line = reader.readLine()) != null) {
Log.v("url result","getting result");
sb.append(line + "\n");
}
is.close();
result=sb.toString();
Log.v("url result",result);
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
try{
jArray = new JSONObject(result);
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return jArray;
}
}
along with this if the data is updated from the webpage, what would be the simplest way to show the updated item on top ??
It is easier to maintain scroll position by calling notifydatasetchanged() only. The problem there is that you are creating a new adapter every time the data gets updated... you should do something like this:
if(listView.getAdapter()==null)
listView.setAdapter(myAdapter);
else{
myAdapter.updateData(myNewData); //update adapter's data
myAdapter.notifyDataSetChanged(); //notifies any View reflecting data to refresh
}
This way, your listview will mantain the scrolling position.
In case you want to scroll to a new position, use:
list.smoothScrollToPosition(int position);
In case for some reason you don't want to call notifyDataSetChanged(), the you can maintain the position by using setSelectionFromTop()
Before updating the adaptor:
lastViewedPosition = listView.getFirstVisiblePosition();
//get offset of first visible view
View v = listView.getChildAt(0);
topOffset = (v == null) ? 0 : v.getTop();
After updating the adaptor:
listView.setSelectionFromTop(lastViewedPosition, topOffset);
list.smoothScrollToPosition(int position); //my favorite :)
It may also help you to scroll nice'n'smooth to a particular item
listview.setSelection( i );
this will help you to set particular row at top
For overall picture:
In your API response callback, call this function(example) below:
MyAdapter mAdapter;
ArrayList<Users> mUsers;
private void updateListView(ArrayList<Users> users) {
mUsers.addAll(users);
if(mAdapter == null) {
mAdapter = new MyAdapter(getContext(), mUsers);
mListView.setAdapter(mAdapter);
}
mAdapter.notifyDataSetChanged(); // Add this one
}
If you're using an ArrayAdapter (or a subclass of it), the problem may be caused by that the adapter updates the list when you clean it before adding the new items:
adapter.clear();
adapter.addAll(...);
You can fix it by wrapping the code that modifies the adapter like this:
adapter.setNotifyOnChange(false); // Disable calling notifyDatasetChanged() on modification
adapter.clear();
adapter.addAll(...); // Notify the adapter about that data has changed. Note: it will re-enable notifyOnChange
adapter.notifyDataSetChanged();