Refreshing Screen Which Uses Json In Android
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 re
Solution 1:
Do this. create a class
publicclassData{
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 StringJSONObject jsonObjMain = newJSONObject(myjsonstring);
// Creating JSONArray from JSONObjectJSONArray jsonArray = jsonObjMain.getJSONArray("pgm");
// JSONArray has four JSONObjectfor (int i = 0; i < jsonArray.length(); i++) {
// Creating JSONObject from JSONArrayJSONObject jsonObj = jsonArray.getJSONObject(i);
// Getting data from individual JSONObjectData data = newData(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
customtestadapter=newcustomtest(MainActivity.this,R.layout.list_single,web);
ListViewlist= (ListView)findViewById(R.id.list);
list.setAdapter(adapter);
in your customtest
class , inside getview
when you will bind data, you will do
Datadt= web.get(position);
Stringname= dt.name;
Stringviewers= 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
publicclasscustomtestextendsArrayAdapter<Data>{
Context context;
int layoutResourceId;
ArrayList<Data> data = null;
publiccustomList(Context context, int layoutResourceId, ArrayList<Data> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
@Overridepublic View getView(int position, View convertView, ViewGroup parent) {
Viewrow= convertView;
CustomHolderholder=null;
if(row == null)
{
LayoutInflaterinflater= ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = newCustomHolder();
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();
}
Datadt= data.get(postition);
holder.txtName.setText(dt.name);
holder.txtViewers.setText(dt.viewers);
return row;
}
staticclassCustomHolder
{
TextView txtName;
TextView txtViewers;
}
}
//////////////////////////////////////////////////////////////////////////////////////////
new Thread(){
public void run()
{
While(true)
{
Thread.sleep(3000);
jsonParse(); //this is your method for parsing json
}
}
}.start();
Post a Comment for "Refreshing Screen Which Uses Json In Android"