How to clear data in ListView? AsyncTask - android

I have the following AsyncTask in a Fragment and would like to clear the listview and repopulate it when a button is clicked. Here is what I have tried:
The button click:
btnRefresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
lv.setAdapter(null);
new LoadAllProducts().execute();
}
});
And here is my AsyncTask:
class LoadAllProducts extends AsyncTask<String, String, String> {
//ListView lv = (ListView) rootView.findViewById(R.id.list);
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
lv.setAdapter(null);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading your trips. 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_trips, "GET", params);
// Check your log cat for JSON response
Log.d("All Trips: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
trips = json.getJSONArray(TAG_TRIPS);
// looping through All Products
for (int i = 0; i < trips.length(); i++) {
JSONObject c = trips.getJSONObject(i);
// Storing each json item in variable
String tripid = c.getString(TAG_TRIPID);
String tripname = c.getString(TAG_TRIPNAME);
String userId = c.getString("uid");
// creating new HashMap
DatabaseHandler_Helpers db = new DatabaseHandler_Helpers(getActivity());
HashMap<String, String> map = new HashMap<String, String>();
if (userId.equals(db.getUserDetails().get("uid"))) {
// adding each child node to HashMap key => value
map.put(TAG_TRIPID, tripid);
map.put(TAG_TRIPNAME, tripname);
// adding HashList to ArrayList
tripList.add(map);
} //else {
//map.put(TAG_TRIPID, "");
//map.put(TAG_TRIPNAME, "You have no tracked trips.");
//tripList.add(map);
//}
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getActivity(),
NewTrip_Activity.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
((Activity) getActivity()).runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
getActivity(), tripList,
R.layout.list_item, new String[] { TAG_TRIPID,
TAG_TRIPNAME, "TEST"},
new int[] { R.id.pid, R.id.name, R.id.mileage });
// updating listview
((ListView) lv.findViewById(R.id.list)).setAdapter(adapter);
}
});
}
}
Problem is that clicking the button clears the listview but then adds twice the items back. So what was already in the listview plus the same items again. If you click the button again, it adds the items a third time!
I know I must be missing something but all I find online is using a ArrayAdapter rather than ListAdapter. Thanks for any help solving this!

You need to Clear the tripList.clear() your tripList(arraylist) before add the map to them tripList.add(map) otherwise it will add to the existing old value

Make adapter global
ListAdapter adapter ;
And change onClick to this
public void onClick(View view) {
new LoadAllProducts().execute();
adapter.notifyDataSetChanged();
}
Also you need to check tripList that its not appending the list before adding items make it clear.

do adpater.clear();
and tripList.clear();

After your AsyncTask is executed you can clear your arraylist
tripList.clear();
adapter.notifyDataSetChanged();
or you can set adapter null also
lv.setAdapter(null);
adapter.notifyDataSetChanged();

You have to declare adapter globally and used its instance to clear data and then fill it again

You have to referesh the Listview after setting null in adapter
btnRefresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
lv.setAdapter(null);
adapter.notifyDataSetChanged();
new LoadAllProducts().execute();
}
});

Related

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
);

keep a ProgessDialog until the callback is executed

im using the azure mobile service. I have some users in the db i want to authenticate, and in order to do that, I execute a query to get a User after you enter a username and a password and press OK. When OK is pressed, if all it's well an intent should be started. How can I display a ProgressDialog until the callback method of the executed query is completed?
EDIT: the problem is that i have a button(logIn button) and when you click it, it will build a query and execute it in an async task, hence my problem. If i just add a progress dialog the call flow will move on since from the onClickListener point of view, the action has finished.
Just show() it before you call the query and dismiss() it in the callback method.
As your using the AsyncTask to query the data , use the onPreExecute and onPostExecute methods to show/dismiss the ProgressDialog.
Create a class which extends the AsyncTask , like this . In the onPreExecute show the ProgressDialog and when your done with fetching the data in doInBackground , in onPostExecute dismiss the dialog
public class QueryTask extends AsyncTask<Void,Void,Object> {
private ProgressDialog progressDialog = null;
private final Context mContext;
public QueryTask(Context context) {
mContext = context;
}
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(mContext);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// do your stuff to query the data
return null;
}
#Override
protected void onPostExecute(Object result) {
progressDialog.dismiss();
// do your other stuff with the queried result
}
#Override
protected void onCancelled(Object result) {
progressDialog.dismiss();
}
}
Finally, when button onClick execute the task
new QueryTask(YourActivity.this).execute();
This example code was used by me to load all the events from an SQL database. Until the app gets the data from the server, a progress dialog is displayed to the user.
class LoadAllEvents extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Just a moment...");
pDialog.setIndeterminate(true);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_events,
"GET", params);
try {
// Checking for SUCCESS TAG
int success = json.getInt(CONNECTION_STATUS);
if (success == 1) {
// products found
// Getting Array of Products
Events = json.getJSONArray(TABLE_EVENT);
// looping through All Contacts
for (int i = 0; i < Events.length(); i++) {
JSONObject evt = Events.getJSONObject(i);
// Storing each json item in variable
id = evt.getString(pid);
group = evt.getString(COL_GROUP);
name = evt.getString(COL_NAME);
desc = evt.getString(COL_DESC);
date = evt.getString(COL_DATE);
time = evt.getString(COL_TIME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(pid, id);
map.put(COL_GROUP, group);
map.put(COL_NAME, name);
map.put(COL_DESC, desc);
map.put(COL_DATE, date);
map.put(COL_TIME, time);
// adding HashList to ArrayList
eventsList.add(map);
}
} else {
// Options are not available or server is down.
// Dismiss the loading dialog and display an alert
// onPostExecute
pDialog.dismiss();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
getActivity().runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(getActivity(),
eventsList, R.layout.list_item, new String[] {
pid, COL_GROUP, COL_NAME, COL_DATE, COL_TIME },
new int[] { R.id.pid, R.id.group, R.id.name, R.id.header,
R.id.title2 });
setListAdapter(adapter);
}
});
}
hope this helps.

Recreate same Listview on item click

I have a Listview and is working well. I'm getting JSON data from remote server and using SimpleAdapter. Basically I get song list from the server. But now, I want to let user select category first. After selecting any category I want to change the URL depending on the selected category, and then populate the listview again. Like, I'm calling getlist.php to get categories. Now if user selects a category named POP, want to call getlist.php?cat=pop to get all pop songs and re-populate the listview where user will see a list of pop songs.
private static String url_json = "http://10.0.2.2/aaa/getlist.php"; //this gives only the categories
private static String url_json = "http://10.0.2.2/aaa/getlist.php?cat=pop"; //this gives all songs those are under category pop
I don't think code is necessary here, if you still need please tell me, I'll update with code given.
Till now I used the following code in onItemClick but not working:
categorySelected = true;
url_json += "?c=Bangla";
new LoadAllProducts().execute();
lv.invalidateViews(); //final ListView lv = getListView();
So, let me summerise the full thing. On category item click, I want to change the URL I'm getting data from, and refresh the Listview with new data. Thanks in advance.
Code: Please have a look at my code and suggest any change.
public class AllRBT extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
//private static String url_all_products = "http://aloashbei.com.bd/vasonapps/getList.php";
private static String url_all_products = "http://10.0.2.2/aaa/getlist.php";
private static Boolean categorySelected = false;
private static String confTitle = "Confirmation needed !";
private static String confBody = "We want to send message from next time you select any ring back tone. This may cost 15 taka by your network operator.";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "rbts";
private static final String TAG_PID = "code";
private static final String TAG_NAME = "name";
private static final String TAG_ARTIST = "artist";
private String mobileNumber = "";
// products JSONArray
JSONArray products = null;
private EditText inputSearch;
SimpleAdapter adapter;
//ListAdapter adapter;
///////////////////////////////////////////////////////////////////////////////////////////////////
private void getMobileNumber(){
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle(confTitle);
alert.setMessage(confBody);//Are you sure want to buy this ring back tones?
// Set an EditText view to get user input
//final EditText input = new EditText(this);
//alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//String m = input.getText().toString();
// Do something with value!
mobileNumber = "017";
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
mobileNumber = "";
}
});
alert.show();
}
public String[] generateMessage(String number, int code){
String opCode = number.substring(0, 3);
String messageBody = "", destination = "";
String[] returnValue;
if(opCode.equals("015")){
messageBody = "TT "+code;
destination = "5000";
}else if(opCode.equals("017")){
messageBody = "WT "+code;
destination = "4000";
}else if(opCode.equals("019")){
messageBody = ""+code;
destination = "2222";
}else if(opCode.equals("016")){
messageBody = "CT "+code;
destination = "3123";
}else if(opCode.equals("018")){
messageBody = "GET "+code;
destination = "8466";
}else if(opCode.equals("011")){
messageBody = "Get"+code;
destination = "9999";
}else{
messageBody = "Invalid number";
}
return new String[] {messageBody, destination};
}
private void sendMessage(String dest, String body, String popupText){
if(popupText != "")
Toast.makeText(getApplicationContext(), popupText, Toast.LENGTH_LONG).show();
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(dest, null, body, null, null);
}
///////////////////////////////////////////////////////////////////////////////////////////////////
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_rbt);
//setContentView(R.layout.activity_all_rbt);
//filterText = (EditText) findViewById(R.id.search_box);
//filterText.addTextChangedListener(filterTextWatcher);
//setListAdapter(new ArrayAdapter<String>(this,
//android.R.layout.list_content,
//getStringArrayList());
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
//filter listView
inputSearch = (EditText) findViewById(R.id.inputSearch);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3){
// When user changed the Text
AllRBT.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
#Override
public void afterTextChanged(Editable arg0) {
}
});
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
final 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){
//lv.invalidateViews();
//if(false){
categorySelected = true;
url_all_products += "?c=Bangla";
new LoadAllProducts().execute();
lv.invalidateViews();
//}
//Context context = getApplicationContext();
String[] values;
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText().toString();
if(mobileNumber == ""){
getMobileNumber();
return;
}
values = generateMessage(mobileNumber, Integer.parseInt(pid));
String popup = "Sending message '"+values[0]+"' to "+values[1];
sendMessage(values[1], values[0], popup);
//Toast toast = Toast.makeText(context, msg, Toast.LENGTH_SHORT);
//toast.show();
}
});
}
// 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(AllRBT.this);
pDialog.setMessage("Loading ring back tones. 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
//Toast toast = Toast.makeText(getApplicationContext(), "text", Toast.LENGTH_LONG);
//toast.show();
JSONParser jParser = new JSONParser();
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 = 1;//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);
String artist = c.getString(TAG_ARTIST);
// 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);
map.put(TAG_ARTIST, artist);
// 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
* */
AllRBT.this.adapter = new SimpleAdapter(
AllRBT.this, productsList,
R.layout.list_item, new String[] { TAG_PID, TAG_NAME, TAG_ARTIST}, new int[] { R.id.pid, R.id.name, R.id.artist });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
Judging from the (very minimal) few lines of code you've provided you are loading stuff into your List that is backing your ListView from an AsyncTask (LoadAllProducts?). If that is the case, be sure to update your ListView's data in the onPostExecute() method you should override, and call something like notifyDataSetChanged() when you finished updating.
For more info on how to use AsyncTasks, check the great number of answers on this topic on SO. For instance, I put an answer with some info on AsyncTasks here: progress dialog is not displaying in async task when asynctask is called from separate class
Update after code was added:
OK, I never used a ListActivity before, but after reading some documentation I think the problem is that calling setListAdapter() a second time will not refresh the ListView (as was mentioned here). Instead of creating a new SimpleAdapter every time I think you should update your productList (clear it, add to it, whatever you want) and then call AllRBT.this.adapter.notifyDataSetChanged(). This should trigger the ListView to re-fetch the data from your adapter, which by now contains your new data.
Also some other remarks that will make your code cleaner:
you need not call runOnUiThread() from onPostExecute(), since onPostExecute() is guaranteed to run on the main thread already (as per AsyncTask contract).
I think you don't need to add an OnItemClickListener by yourself. It seems that a ListActivity already does that for you and you can instead simply override its onListItemClick() method.

java.lang.NullPointerException AllSuggestionsActivity.onTextChanged (AllSuggestionsActivity.this.adapter.getFilter().filter(cs);)

I am getting an error (java.lang.NullPointerException) when I execute the code for the ListView with EditText for filtering at the line
AllSuggestionsActivity.this.adapter.getFilter().filter(cs);
kindly help.
public class AllSuggestionsActivity extends ListActivity {
EditText inputSearch;
ListView lstList;
// Progress Dialog
private ProgressDialog pDialog;
ArrayAdapter<String> adapter = null;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> suggestionsList;
// url to get all suggestions list
private static String url_all_suggestions = "http://10.0.2.2/JKUAT-M-SUGGESTION-BOX/get_all_suggestions.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_SUGGESTIONS = "suggestions";
private static final String TAG_SID = "sid";
private static final String TAG_SUBJECT = "subject";
// suggestions JSONArray
JSONArray suggestions = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_suggestions);
inputSearch = (EditText) findViewById(R.id.inputSearch);
lstList = (ListView) findViewById(android.R.id.list);
// Hashmap for ListView
suggestionsList = new ArrayList<HashMap<String, String>>();
// Loading suggestions in Background Thread
new LoadAllSuggestions().execute();
// Get listview
ListView lv = getListView();
/**
* Enabling Search Filter
* */
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
AllSuggestionsActivity.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
// on seleting single suggestion
// launching Edit Suggestion Screen
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String sid = ((TextView) view.findViewById(R.id.sid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
EditSuggestionActivity.class);
// sending sid to next activity
in.putExtra(TAG_SID, sid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Suggestion 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 suggestion
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all suggestion by making HTTP Request
* */
class LoadAllSuggestions extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllSuggestionsActivity.this);
pDialog.setMessage("Loading all suggestions. Please wait.......");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All suggestions from url
* */
#Override
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_suggestions,
"GET", params);
// Check your log cat for JSON reponse
Log.d("All Suggestions: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// suggestions found
// Getting Array of Suggestions
suggestions = json.getJSONArray(TAG_SUGGESTIONS);
// looping through All Suggestions
for (int i = 0; i < suggestions.length(); i++) {
JSONObject c = suggestions.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_SID);
String subject = c.getString(TAG_SUBJECT);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_SID, id);
map.put(TAG_SUBJECT, subject);
// adding HashList to ArrayList
suggestionsList.add(map);
}
} else {
// no suggestions found
Intent i = new Intent(getApplicationContext(),
MainScreenActivity.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
* **/
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all suggestions
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
#Override
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AllSuggestionsActivity.this, suggestionsList,
R.layout.list_item, new String[] { TAG_SID,
TAG_SUBJECT }, new int[] { R.id.sid,
R.id.subject });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
xml code for the listview:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<EditText
android:id="#+id/inputSearch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:ems="10"
android:maxLines="1"
android:hint="Search" >
<requestFocus />
</EditText>-->
<!-- Main ListView
Always give id value as list(#android:id/list)
-->
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
enter code here
</ScrollView>
You've initialized your adapter to null & never re-initialized it with real values. So when the line executes AllSuggestionsActivity.this.adapter.getFilter().filter(cs) the part in bold is where the NullPointerException is being thrown.
ArrayAdapter<String> adapter = null;
Also, it looks like your adapter depends on some JSON data, if thats the case & your trying to have filter options for that data, you could set the text watcher for your edit text in onPostExecute() after your adapter has the data ready.
Finally, you should get rid of runOnUiThread in your onPostExecute(). The onPostExecute() runs on the main UI thread by default so there is no need for runOnUiThread to be there.
Kindly find solution to the error:
public class AllSuggestionsActivity extends ListActivity {
SimpleAdapter adapter;
EditText inputSearch;
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> suggestionsList;
// url to get all suggestions list
private static String url_all_suggestions = "http://10.0.2.2/JKUAT-M-SUGGESTION-BOX/get_all_suggestions.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_SUGGESTIONS = "suggestions";
private static final String TAG_SID = "sid";
private static final String TAG_SUBJECT = "subject";
// suggestions JSONArray
JSONArray suggestions = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_suggestions);
// Hashmap for ListView
suggestionsList = new ArrayList<HashMap<String, String>>();
// Loading suggestions in Background Thread
new LoadAllSuggestions().execute();
// Get listview
ListView lv = getListView();
// on seleting single suggestion
// launching Edit Suggestion Screen
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String sid = ((TextView) view.findViewById(R.id.sid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
EditSuggestionActivity.class);
// sending sid to next activity
in.putExtra(TAG_SID, sid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Suggestion 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 suggestion
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all suggestion by making HTTP Request
* */
class LoadAllSuggestions extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllSuggestionsActivity.this);
pDialog.setMessage("Loading all suggestions. Please wait.......");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All suggestions from url
* */
#Override
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_suggestions,
"GET", params);
// Check your log cat for JSON reponse
Log.d("All Suggestions: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// suggestions found
// Getting Array of Suggestions
suggestions = json.getJSONArray(TAG_SUGGESTIONS);
// looping through All Suggestions
for (int i = 0; i < suggestions.length(); i++) {
JSONObject c = suggestions.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_SID);
String subject = c.getString(TAG_SUBJECT);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_SID, id);
map.put(TAG_SUBJECT, subject);
// adding HashList to ArrayList
suggestionsList.add(map);
}
} else {
// no suggestions found
Intent i = new Intent(getApplicationContext(),
MainScreenActivity.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
* **/
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all suggestions
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
#Override
public void run() {
/**
* Updating parsed JSON data into ListView
* */
adapter = new SimpleAdapter(
AllSuggestionsActivity.this, suggestionsList,
R.layout.list_item, new String[] { TAG_SID,
TAG_SUBJECT }, new int[] { R.id.sid,
R.id.subject });
// updating listview
setListAdapter(adapter);
/**
* Enabling Search Filter
* */
inputSearch = (EditText) findViewById(R.id.inputSearch);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
AllSuggestionsActivity.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
});
}
}
}
xml file remains intact

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.

Categories

Resources