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;
}
}
Related
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 have a module in my application which uses json.
The json gets updated always.
Here i want to refresh the screen as new data arrives.
Is there any method for this ?
I want to refresh the screen as new data arrives or once in every 5 seconds or something(a fixed amount of time).How to do this ?
I simply used a local json file to test this.
I just need the code for refreshing.
This is my code for json parsing :
public class MainActivity extends Activity
{
String myjsonstring;
ArrayList<Data> web = new ArrayList<Data>();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
JsonParser();
// Try to parse JSON
try {
JSONObject jsonObjMain = new JSONObject(myjsonstring);
JSONArray jsonArray = jsonObjMain.getJSONArray("pgm");
for (int i = 0; i < jsonArray.length(); i++) {
// Creating JSONObject from JSONArray
JSONObject jsonObj = jsonArray.getJSONObject(i);
// Getting data from individual JSONObject
Data data = new Data(jsonObj.getString("name") , jsonObj.getString("viewers"));
web.add(data);
}
final customtest1 adapter = new customtest1(MainActivity.this,R.layout.list_single,web);
ListView list = (ListView)findViewById(R.id.list);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "Test.........", Toast.LENGTH_SHORT).show();
adapter.notifyDataSetChanged();
}
});
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void JsonParser()
{
// Reading text file from assets folder
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(getAssets().open(
"main.json")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close(); // stop reading
} catch (IOException e) {
e.printStackTrace();
}
}
myjsonstring = sb.toString();
}
}
Do this.
create a class
public class Data
{
String name ="";
String viewers ="";
public Data(String n,String v)
{
name = n;
viewers=v;
}
}
then in MainActivity create only single arraylist with type Data
ArrayList<Data> web = new ArrayList<Data>();
and then parse your json like
// Creating JSONObject from String
JSONObject jsonObjMain = new JSONObject(myjsonstring);
// Creating JSONArray from JSONObject
JSONArray jsonArray = jsonObjMain.getJSONArray("pgm");
// JSONArray has four JSONObject
for (int i = 0; i < jsonArray.length(); i++) {
// Creating JSONObject from JSONArray
JSONObject jsonObj = jsonArray.getJSONObject(i);
// Getting data from individual JSONObject
Data data = new Data(jsonObj.getString("name") , jsonObj.getString("viewers"));
web.add(data);
now instead of passing two array list to your custom adapter , pass only single arraylist i.e web
customtest adapter = new customtest(MainActivity.this,R.layout.list_single,web);
ListView list = (ListView)findViewById(R.id.list);
list.setAdapter(adapter);
in your customtest class , inside getview when you will bind data, you will do
Data dt = web.get(position);
String name = dt.name;
String viewers = dt.viewers;
and then do what you were doing before.
and after all this, now ehnever you want to update your list simply call
adapter.notifyDataSetChanged();
your customtest class now will be like
public class customtest extends ArrayAdapter<Data>{
Context context;
int layoutResourceId;
ArrayList<Data> data = null;
public customList(Context context, int layoutResourceId, ArrayList<Data> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
CustomHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new CustomHolder();
holder.txtName = (TextView)row.findViewById(R.id.txtName); //this is id of textview where you want to set name
holder.txtViewers = (TextView)row.findViewById(R.id.txtViewers); //this is id of textview where you want to set viewers
row.setTag(holder);
}
else
{
holder = (CustomHolder)row.getTag();
}
Data dt = data.get(postition);
holder.txtName.setText(dt.name);
holder.txtViewers.setText(dt.viewers);
return row;
}
static class CustomHolder
{
TextView txtName;
TextView txtViewers;
}
}
//////////////////////////////////////////////////////////////////////////////////////////
new Thread(){
public void run()
{
While(true)
{
Thread.sleep(3000);
jsonParse(); //this is your method for parsing json
}
}
}.start();
I am trying to parse the data into the list View in android
JSON:: http://54.218.73.244:7000/
It has a JSON output :: [{"restaurantID":1,"restaurantNAME":"CopperChimney"},{"restaurantID":2,"restaurantNAME":"Aroy"},{"restaurantID":3,"restaurantNAME":"MarkBoulevard"}]
I am trying to display the CopperChimney, Aroy, MarkBoulevard in a
list view
I figured some small parts but can someone help me fill
AndroidJSONParsingActivity.java part of the code which invoolves putting data in a collection and displaying it
Any ideas ?
JSONParser
public class JSONParser {
static InputStream is = null;
static JSONArray jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONArray 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 JSONArray(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Item.java
public class Item{
private String Name;
public Item(String name){
this.Name = name;
}
public String getName(){
return Name;
}
}
ListAdapter.java
public class ListAdapter extends ArrayAdapter<Item> {
private List<Item> items;
public ListAdapter(Context context, int resource, List<Item> items) {
super(context, resource, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
TextView tt = null;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.itemlistrow, null);
tt = (TextView) v.findViewById(R.id.RestaurantNameID);
}
Item p = items.get(position);
if (p != null) {
if (tt != null) {
tt.setText(""+p.getName());
}
}
return v;
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ListView
android:id="#+id/listViewID"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center">
</ListView>
</LinearLayout>
itemlistrow.xml
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content" android:orientation="vertical"
android:layout_width="fill_parent">
<TableRow android:layout_width="fill_parent"
android:id="#+id/TableRow01"
android:layout_height="wrap_content">
<TextView
android:id="#+id/RestaurantNameID"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="name" android:textStyle="bold"
android:gravity="left"
android:layout_weight="1"
android:typeface="monospace"
android:height="40sp"/>
</TableRow>
</TableLayout>
AndroidJSONParsingActivity.java
public class AndroidJSONParsingActivity extends Activity {
private static String url = "http://54.218.73.244:7000/";
//
//
//
//
/------ CODE -Trying to ADD ------ /
//
//
}
CODE I TRIED FOR AndroidJSONParsingActivity.java
public class AndroidJSONParsingActivity extends Activity {
// url to make request
private static String url = "http://54.218.73.244:7000/";
List<Item> yourData = new ArrayList<Item>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url);
try {
for (int i = 0; i < json.length(); i++) {
JSONObject c = json.getJSONObject(i);
// Storing each json item in variable
String NAME=c.getString("restaurantNAME");
yourData.add(new Item(NAME));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ListView yourListView = (ListView) findViewById(R.id.listViewID);
ListAdapter customAdapter = new ListAdapter(this, R.layout.itemlistrow, yourData);
yourListView.setAdapter(customAdapter);
yourListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
if(position == 0)
{
//code specific to first list item
Intent myIntent = new Intent(AndroidJSONParsingActivity.this,Employee1.class);
startActivity(myIntent);
}else if(position == 1)
{
Intent myIntent = new Intent(AndroidJSONParsingActivity.this,Employee2.class);
startActivity(myIntent);
}
}
});
}
}
public class AndroidJSONParsingActivity extends ListActivity {
ArrayList <Item> list = new ArraList <Item>();
#Override
public void onStart() {
super.onStart();
new GetHttpData().execute();
}
private class GetHttpData extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
private static String url = "http://54.218.73.244:7000/";
JSONArray jArray = getJSONFromUrl(url);
int len = jArray.length();
for(int i = 0; i < len; i++) {
JSONObject restaurant = jArray.getJSONObject(i);
list.add(new Item(restaurant.getString("restaurantNAME"));
}
return null;
}
#Override
protected void onPostExecute(Void result) {
setListAdapter(new ListAdapter(AndroidJSONParsingActivity.this, android.R.layout.simple_list_item_1, list));
}
}
}
This is just one way to parse it, you should also do all HttpRequests and JSON parsing in a separate thread, see http://developer.android.com/reference/android/os/AsyncTask.html
Edited:
You can also check this Example
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();
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)