How to make android Listview update every 10 sec? - android

i have a list view data come from server and show on the list view . i want listview refresh every 10 sec how can i do this here is my code of list view .
protected void showList() {
try {
JSONObject jsonObj = new JSONObject(myJSON);
peoples = jsonObj.getJSONArray(TAG_RESULTS);
for (int i = 0; i < peoples.length(); i++) {
JSONObject c = peoples.getJSONObject(i);
String data = c.getString(TAG_DATA);
final String dataaaa = rcdata.getText().toString().trim();
HashMap<String, String> user_data = new HashMap<String, String>();
user_data.put(TAG_DATA, data);
personList.add(user_data);
}
ListAdapter adapter = new SimpleAdapter(
DataSendActivity.this, personList, R.layout.layout_chat,
new String[]{TAG_DATA},
new int[]{R.id.data}
);
list.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}

How repeat a piece of code in a fixed interval, in this case update listview
//instance variable for adapter
ListAdapter adapter;
//instance variable for timer
Timer timer;
//create the listview, adapter and set the adapter
public void showList(){
//method code;
adapter=//call adapter constructor
listView.setSetAdapter(adapter);
//create a handler to update the adapter
final Hanlder handler=new Handler(){
//run your listview update command here. Possibly;
adapter.notifyDataSetChanged();
//or else create a new adapter
adapter=new ListAdapter(//parameters);
listView.setAdapter(adapter);
}
//create timer and the scheduled task
//this will run in every 10 seconds. Make sure to stop it when you dont
//want it any more
timer=new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
handler.obtainMessage().sendToTarget();
}
}, 0, 10000);
}
//if you want to stop the timer on onDestroy()
#Override
public void onDestroy(){
super.onDestroy();
if(timer!=null){
timer.cancel();
}
}
The code is as an example only.

Related

How to refresh listview AsyncTask

I have a json file and I want to check this json every minute because my json changes every minute.
I can parse json from an url in this way;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
runOnUiThread(new Runnable() {
#Override
public void run() {
new ReadJSON().execute("http://www.url.com/json1.json");
}
});
}
class ReadJSON2 extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
return readURL(params[0]);
}
#Override
protected void onPostExecute(String content) {
try {
JSONObject jsonObject = new JSONObject(content);
JSONArray jsonArray = jsonObject.getJSONArray("level");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
JSONArray server = c.getJSONArray("server");
for(int j=0; j<server.length(); j++){
JSONObject serverObject = server.getJSONObject(j);
String name = serverObject.getString("name");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
How can I check this json every minute?
I did everything, but I didn't it.
Thank you for your help.
Use listview.invalidateViews(); or adapter.notifyDataSetchanged(); method in onPostExecute method after parsing your json.
This method works if some of the contents have been changes/added/removed in the list that is attached to the adapter.
So whenever you parse your data . make sure the object of adapter and the List/JsonArray remain same. Means dont initialize it every time on web service result. Just use it like this -> list.add(some data); and jsonArray.put(some data);
Let me know if i misunderstood.
We can use TimerTask to solve this problem:
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
//use a handler to run a toast that shows the current timestamp
handler.post(new Runnable() {
public void run() {
new ReadJSON().execute("http://www.url.com/json1.json");
}
});
}
};
public void startTimer() {
//set a new Timer
timer = new Timer();
//initialize the TimerTask's job
initializeTimerTask();
//schedule the timer, after the first 0ms the TimerTask will run every 1m
timer.schedule(timerTask, 0, 60 * 1000); //
}
An on ur postExe, after parse JSON, u should check Adapter here, if it's was empty for first time, you set adapter by this json, and if it's already has data, please call adapter.notifyDataSetChanged()

i want to fetch items at particular interval of time in android

public class AllProductsActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://www.rush.com/android_connect/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_products);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
EditProductActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllProductsActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AllProductsActivity.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME},
new int[] { R.id.pid, R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
This is my code to view all product and it gives complete output . But each and every time i have to refresh manually to show new items...
Now i want to do auto refresh at every 10 seconds for retrieve all the product list....
so how can i do that?
You can user TimerTask. see TimerTask
see example
if(timer != null){
timer.cancel();
}
//re-schedule timer here
//otherwise, IllegalStateException of
//"TimerTask is scheduled already"
//will be thrown
timer = new Timer();
myTimerTask = new MyTimerTask();
if(optSingleShot.isChecked()){
//singleshot delay 1000 ms
timer.schedule(myTimerTask, 1000);
}else{
//delay 1000ms, repeat in 5000ms
timer.schedule(myTimerTask, 1000, 5000);
}
Timer Class
class MyTimerTask extends TimerTask {
#Override
public void run() {
new LoadAllProducts().execute();
}
}
}
example refer this
// Loading products in Background Thread
new LoadAllProducts().execute();
use below one instead of abve one
new LoadAllProducts().execute(); //first time load
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
setListAdapter(null);
new LoadAllProducts().execute();
}
}, 10000);//you specify the particular time
You can try what given below -
Timer t;
t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
private Context context;
#Override
public void run() {
// do your task that you want to refresh at reguler interval
}
},
//Set how long before to start calling the TimerTask (in milliseconds)
startdelay,
//Set the amount of time between each execution (in milliseconds)
timeinterval
);

Clear Android ListView

I have a ListView. I want to dynamically change the contents of the listview.I used "adapter.notifyDataSetChanged();" to change the contents. I have also tried setting the adapter of the listview to null but still I get the same results. It is refreshing but not clearing the listview, instead it is appending it with the previous results. What i want is the previous contents should be deleted and the new results should be displayed.
I am not able to understand where is my mistake and what i am missing.
I would be Thankful if someone could please help me out with this.
Below is the code that generates the listview
public void ListDrawer() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("myRegisteredList");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String registered_name = jsonChildNode.optString("seminar");
String org = jsonChildNode.optString("organizer");
String sem_id = jsonChildNode.optString("id");
String r_sem = jsonChildNode.optString("seminar_id");
registeredlist = new HashMap<String, String>();
registeredlist.put("registeredList", registered_name);
registeredlist.put("seminar_id", r_sem);
registeredlist.put("sem_id", sem_id);
registeredlist.put("organizer", org);
registeredList.add(registeredlist);
}
} catch (JSONException e) {
//Toast.makeText(this, e.getMessage().toString() + " 1", Toast.LENGTH_LONG).show();
Toast.makeText(ViewReservedSeminarList.this, "Sorry...You don't have any reserved seminar/s.", Toast.LENGTH_LONG).show();
}
try{
simpleAdapter = new SimpleAdapter(this, registeredList,
android.R.layout.simple_list_item_2,
new String[] { "registeredList" ,"organizer", "seminar_id" }, new int[] { android.R.id.text1 , android.R.id.text2 , android.R.id.title });
listView.setAdapter(simpleAdapter);
listView.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> a, View v, int i, long l) {
// TODO Auto-generated method stub
#SuppressWarnings("unchecked")
HashMap<String, String> selected_row = (HashMap<String, String>) simpleAdapter.getItem(i);
s_id = selected_row.get("seminar_id");
Intent intent = new Intent(ViewReservedSeminarList.this, ReservedSeminar.class);
startActivity(intent);
//Toast.makeText(ViewReservedSeminarList.this, "Selected Item : "+s_id, Toast.LENGTH_LONG).show();
}
});
}catch(Exception e){
//Toast.makeText(this, e.getMessage().toString() + " 2", Toast.LENGTH_LONG).show();
Toast.makeText(ViewReservedSeminarList.this, "There is no data being fetched", Toast.LENGTH_LONG).show();
}
}
Below is the snippet I placed on the onCreate method to refresh the listview every 10 seconds. I am calling the ListDrawer method under the accessWebService method.
final Handler handler = new Handler();
handler.postDelayed( new Runnable(){
#Override
public void run(){
accessWebService();
handler.postDelayed(this, 10 * 1000);
Log.i("TAG", "notify");
}
}, 10 * 1000
);
Try this please:
Clear the arraylist/HashMap
Add new items
adapter.notifyDataSetChanged();
set adapter.
If you use an ArrayAdapter instead of a SimpleAdapter you can call
ArrayAdapter.clear();
ArrayAdapter.notifyDataSetChanged();
To remove all the elements from the adapter.
Try This
final Handler handler = new Handler();
handler.postDelayed( new Runnable(){
#Override
public void run(){
//this line i have added in your code
registeredList.clear();
accessWebService();
handler.postDelayed(this, 10 * 1000);
Log.i("TAG", "notify");
}
}, 10 * 1000
);
remove adapter.notifyDataSetChanged(); hope it works

Clear ListView Items and Refresh it in Android

I use internet service to fill a list view. I want to refresh the list view items when user press the refresh button. how can i do this?
In AsyncTask and postExecute i fill the list view:
protected void onPostExecute(String file_url) {
pDialog.dismiss();
try {
if (jSon.has(KEY_SUCCESS)) {
String success = jSon.getString(KEY_SUCCESS);
if (success.equals("1")) {
notes = jSon.getJSONObject("notes");
for (int i = 0; i < notes.length(); i++) {
JSONObject c = notes.getJSONObject(Integer
.toString(i));
Log.i("JSONObject c >>", c.toString());
String id = c.getString(KEY_NOTE_ID);
String subject = c.getString(KEY_NOTE_SUBJECT);
String date = c.getString(KEY_NOTE_DATE);
HashMap<String, String> map = new HashMap<String, String>();
map.put(KEY_NOTE_ID, id);
map.put(KEY_NOTE_SUBJECT, subject);
map.put(KEY_NOTE_DATE, date);
noteList.add(map);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(AllNotes.this,
noteList, R.layout.list_item, new String[] {
KEY_NOTE_ID, KEY_NOTE_SUBJECT,
KEY_NOTE_DATE }, new int[] {
R.id.list_lbl_id, R.id.list_lbl_subject,
R.id.list_lbl_date });
setListAdapter(adapter);
}
});
}
The most basic approach is to empty noteList and run your AsyncTask again.
Inside onPreExecute() (or the first line of doInBackground()) call either:
noteList = new ArrayList<Map<String, String>>(); // or noteList.clear();
Call your AsyncTask's execute() method again.
Also I don't believe you need to use runOnUiThread() in onPostExecute() because it already has access to the main thread.

thread exiting error in android

Please help with this error .... In the following code the get info function works correctly but it gives an error saying the thread caught an exception at exiting.... I am trying to use a tab host and the first tab page is the following... In this i show a progress dialog until i get my data and then show it in a list view
public class History extends Activity implements OnItemClickListener
{
/** Called when the activity is first created. */
ListView list;
//LIST OF ARRAY STRINGS WHICH WILL SERVE AS LIST ITEMS
ArrayList<String> listItems;
//DEFINING STRING ADAPTER WHICH WILL HANDLE DATA OF LISTVIEW
ArrayAdapter<String> adapter;
private String resDriver,resPassenger,ID;
private ProgressDialog dialog;
ArrayList<HashMap<String, Object>> listInfo = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> item;
JSONObject jDriver;
//JSONObject jPassenger;
// Make strings for logging
private final String TAG = this.getClass().getSimpleName();
private final String RESTORE = ", can restore state";
private final String state = "Home Screen taking care of all the tabs";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent loginIntent = getIntent();
ID = loginIntent.getStringExtra("ID");
listItems = new ArrayList<String>();
Log.i(TAG, "Started view active rides");
setContentView(R.layout.searchresults);
list = (ListView)findViewById(R.id.ListView01);
list.setOnItemClickListener(this);
adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,listItems);
list.setAdapter(adapter);
getInfo();
}
The function getInfo is used to start a thread which shows a dialog box and starts a http request to get some data ...
public void getInfo(){
GetInfoThread checkUpdate = new GetInfoThread();
checkUpdate.start();
dialog = ProgressDialog.show(History.this, "Retrieving Info","Please Wait ...", true);
}
private class GetInfoThread extends Thread
{
public void run() {
jDriver = new JSONObject();
try {
jDriver.put("ID", ID);
jDriver.put("task", "GET DATES");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
listItems = new ArrayList<String>();
Log.i(TAG,"Sending data for the driver rides");
resDriver = HTTPPoster.sendJson(jDriver,"http://dsadsada"); // Any Server URL
JSONObject driver;
try {
driver = new JSONObject(resDriver);
Log.i(TAG,"Recieved Driver details");
listItems.add(array[0]);
handler.sendEmptyMessage(0);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
listItems.add("No driver rides created");
handler.sendEmptyMessage(0);
}
}
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
dialog.dismiss();
Log.i(TAG,"hello 123");
adapter.notifyDataSetChanged();
}
};
}
I am not sure exactly what is causing your error but I suspect it has to do with UI changes not running on the actual UI thread. In Android there is a class called AsyncTask that will do the threading for you and handle the passing of data between the background thread an the UI thread. I would suggest rewriting your code to utilize the AsyncTask class.

Categories

Resources