Android: not able to add listview items dynamically through volley - android

Hi I'm working on CardSwipe functionality like tinder. (For understanding see the attached image)
For this i followed this code, when using static data like bellow, I'm successfully adding items in ListView
private void loadCards2(){
itemsaArrayList = new ArrayList<>();
for(int i = 0; i < 10; i++){
CardSwipeItems items = new CardSwipeItems();
items.setCardImageUrl("http://i.ytimg.com/vi/PnxsTxV8y3g/maxresdefault.jpg");
items.setCardDescription("But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness.");
itemsaArrayList.add(items);
}
flingContainer = (SwipeFlingAdapterView) findViewById(R.id.frame);
myAppAdapter = new CardSwipeAdapter(itemsaArrayList, CardSwipeActivity.this);
flingContainer.setAdapter(myAppAdapter);
initControlls();
}
But when I'm trying to add the items dynamically by using volley means, items are not adding in the ListView. (For this volley
please see the loadCards() method in the CardSwipeActivity)
I tried lot of approaches to load the items in the list view dynamically. For ex: I used Thread (For code see this) and i also used Handler (For code see this) but I'm not able to add the items in ListView dynamically
If any one know the solution for this means please tell me. Thank you.......
Edit
*My method*
private void loadCards(){
String Url = "myApi";
Log.e("Url", Url);
final ProgressDialog dialog = ProgressDialog.show(CardSwipeActivity.this, null, null);
ProgressBar spinner = new android.widget.ProgressBar(CardSwipeActivity.this, null,android.R.attr.progressBarStyle);
spinner.getIndeterminateDrawable().setColorFilter(Color.parseColor("#009689"), android.graphics.PorterDuff.Mode.SRC_IN);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.setContentView(spinner);
dialog.setCancelable(false);
dialog.show();
StringRequest request = new StringRequest(Request.Method.GET, Url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
dialog.dismiss();
if(response != null && !response.startsWith("<HTML>")){
Log.e("OnResponse", response);
try {
JSONArray jsonArray = new JSONArray(response);
if(jsonArray.length() > 0){
itemsaArrayList = new ArrayList<>();
for(int i = 0; i< jsonArray.length(); i++){
JSONObject singleObj = jsonArray.getJSONObject(i);
String imgId = singleObj.getString("avatar_file_id");
String name = singleObj.getString("name");
CardSwipeItems items = new CardSwipeItems();
Log.e("imgId", imgId);
Log.e("name", name);
items.setCardImageUrl(imgId);
items.setCardDescription(name);
itemsaArrayList.add(items);
}
flingContainer = (SwipeFlingAdapterView) findViewById(R.id.frame);
myAppAdapter = new CardSwipeAdapter(itemsaArrayList, CardSwipeActivity.this);
flingContainer.setAdapter(myAppAdapter);
initControlls();
}
} catch (JSONException e) {
e.printStackTrace();
}
}else{
Log.e("Internet", "Internet");
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
if(error != null){
Log.e("error", error.toString());
}else{
}
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("token","b32daf7b50c7f21dba80dd0651174e3839c22f56");
params.put("user_id","386");
Log.e("Headers", "**********Headers*************");
Log.e("token","b32daf7b50c7f21dba80dd0651174e3839c22f56");
Log.e("user_id","386");
return params;
}
};
RequestQueue queue = Volley.newRequestQueue(CardSwipeActivity.this);
queue.add(request);
queue.getCache().remove(Url);
}

You can add items dynamically to the adapter by addding items to the list you passed originally to adapter like this:
itemsaArrayList.add(items);
than you need to notify the adapter like this from your UI thread:
runOnUiThread(new Runnable() {
public void run() {
adapter.notifyDataSetChanged();
}
});
And to call it on the UI-Thread, use have to use runOnUiThread() of Activity. Then only, notifyDataSetChanged() will work.
Also have a look at this post

If you are getting response from server then try to move below line from onResponse method to onCreate method.
flingContainer = (SwipeFlingAdapterView) findViewById(R.id.frame);
Hope this will work

Related

Volley json parsing displays nothing in ListView

I would like to display movie titles from themoviedb.org. But the applications is not displaying anything in the ListView. Here is my code:
try{
JsonObjectRequest request = new JSonObjectRequest(Request.Method.Get,url,null,new Response.Listener<JSONObject>(){
#Override
public void onResponse(JSONObject response){
try{
JSONArray titlesArray =response.getJSONArray("results");
for(int i=0;i<titlesArray.length();i++){`
JSONObject inner = titlesArray.getJSONObject(i);
String id=inner.getString("id");
String title =inner.getString("title");
String c= id+title;
arrayListMovies=new ArrayListMovies<>();
arrayListMovies.add(c);
}
RequestQueue requestQueue=Volley.newRequestQueue(this);
requestQueue.add(request);
And I am setting the arrayadapter to movieList ListView outside of the Volley function
moviesList = findViewById(R.id.listViewForMovies);
ArrayAdapter<String> adapter =new ArrayAdapter<String>(getApplicationContext(),android.R.layout.android_simple_list_item1,arrayListMovies);
moviesList.setAdapter(adapter);
Thanks.
I would not recommend make REST API calls the way you are doing, this is prone to errors, I recommend you to check about retrofit:
https://square.github.io/retrofit/
You have various problems with your code:
You are creating the adapter and assigning data before the call to the API completes.
You are creating the string list on every iteration of your titlesArray
You are not notifying the adapter that the list have changed.
Dont use a try block inside your response, because if there is errors with your code, it will be useful that the app crashes in order to get notified about this errors.
public class Test extends AppCompatActivity {
private ArrayAdapter<String> myAdapter;
private ArrayList<String> arrayListMovies = new ArrayList<>();
#Override
public void onCreate(#Nullable Bundle savedInstanceState, #Nullable PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
this.myAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.android_simple_list_item1, arrayListMovies);
this.makeRequest();
}
public void makeRequest() {
try {
JsonObjectRequest request = new JSonObjectRequest(Request.Method.Get, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONArray titlesArray = response.getJSONArray("results");
arrayListMovies = new ArrayList<>();
for (int i = 0; i < titlesArray.length(); i++) {
JSONObject inner = titlesArray.getJSONObject(i);
String id = inner.getString("id");
String title = inner.getString("title");
String c = id + title;
arrayListMovies.add(c);
}
myAdapter.notifyDataSetChanged();
RequestQueue requestQueue = Volley.newRequestQueue(this);
}
}
}
}
}
Note some things: I have moved the adapter and arrayListMovies declarations to the top of the class.
I initialize the adapter before making the api call.
In the response of the network call I create the arrayListMovies ONCE.
At the end i call myAdapter.notifyDataSetChanged(); to refresh the adapter data.

AnyChart AreaChart gets doubled everytime I switch the tabs

I have implemented AnyChart in my app and I am using it on 3 different tabs, according to month, week and year. The problem it's that when the fragments are Created, I send a query to the server to return some values, to populate the chart. I have followed the steps according to the github of AnyChart to implement it and it works, but when I switch between the tabs, the charts gets doubled or even tripled. I have implemented the same code for AsyncTask and AnyChart in all of the tabs, according to the number of days. I use the following code for the charts:
private void CreareGraficDinamicInterventie() {
APIlib.getInstance().setActiveAnyChartView(anyChartView);
Cartesian areaChart = AnyChart.area();
areaChart.animation(true);
Crosshair crosshair = areaChart.crosshair();
crosshair.enabled(true);
// TODO yStroke xStroke in crosshair
crosshair.yStroke((Stroke) null, null, null, (String) null, (String) null)
.xStroke("#fff", 1d, null, (String) null, (String) null)
.zIndex(39d);
crosshair.yLabel(0).enabled(false);
areaChart.yScale().stackMode(ScaleStackMode.VALUE);
List<DataEntry> seriesData = new ArrayList<>();
for (int j=data_grafic.size()-1 ; j>0 ; j-- ) {
seriesData.add(new CustomDataEntry(String.valueOf(data_grafic.get(j)), Double.valueOf(timpi_interventie.get(j))));
}
ChartCredits credits = areaChart.credits();
credits.enabled(false);
Set set = Set.instantiate();
set.data(seriesData);
Mapping series1Data = set.mapAs("{ x: 'x' }");
Area series1 = areaChart.area(series1Data);
series1.name("Timp de interventie ");
series1.stroke("3 #fff");
series1.hovered().stroke("3 #fff");
series1.hovered().markers().enabled(true);
series1.hovered().markers()
.type(MarkerType.CIRCLE)
.size(4d)
.stroke("1.5 #fff");
series1.markers().zIndex(100d);
areaChart.legend().enabled(true);
areaChart.legend().fontSize(13d);
areaChart.legend().padding(0d, 0d, 20d, 0d);
areaChart.xAxis(0).title(false);
areaChart.yAxis(0).title("Timp de interventie (h)");
areaChart.interactivity().hoverMode(HoverMode.BY_X);
areaChart.tooltip()
.valuePostfix("h")
.displayMode(TooltipDisplayMode.UNION);
anyChartView.setChart(areaChart);
}
The CreareGrafiDinamicInterventie() gets called after the onPostExecute in the AsyncTask querying the server. I have tried to use anyChartView.clear(); but the chart dissapears, it does not show anything.
This is the AsyncTask called in OnCreateView:
private void GasesteDetaliiSaptamana(){
class GasesteDetaliiSaptamana extends AsyncTask<Void, Void, String> {
User user = SharedPrefManager.getInstance(getContext()).getUser();
final String id_user = String.valueOf(user.getId());
#Override
protected String doInBackground(Void... voids) {
//creating request handler object
RequestHandler requestHandler = new RequestHandler();
//creating request parameters
HashMap<String, String> params = new HashMap<>();
params.put("interval_zile", "6");
//returing the response
return requestHandler.sendPostRequest(URLs.URL_STATISTICIGRAFICE, params);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//displaying the progress bar while user registers on the server
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
timpi_interventie.clear();
timpi_rezolvare.clear();
data_grafic.clear();
//hiding the progressbar after completion
try {
//converting response to json object
JSONObject obj = new JSONObject(s);
//if no error in response
if (!obj.getBoolean("error")) {
timp_raportare_rezolvare= obj.getString("timp_raportare_rezolvare");
timp_catalogare_rezolvare= obj.getString("timp_catalogare_rezolvare");
timp_raportare_catalogare= obj.getString("timp_raportare_catalogare");
numar_total_alerte_catalogate = obj.getString("numar_total_alerte_catalogate");
numar_alerte_remediate = obj.getString("numar_alerte_remediate");
numar_total_alerte = obj.getString("numar_total_alerte");
timp_mediu_interventie = obj.getString("timp_mediu_interventie");
timp_mediu_rezolvare = obj.getString("timp_mediu_rezolvare");
JSONArray rap_cat = obj.getJSONArray("vector_rap_cat");
for (int i = 0; i < rap_cat.length(); i++) {
JSONObject Rap_cat = rap_cat.getJSONObject(i);
timpi_interventie.add(Rap_cat.getString("rap_cat"));
}
JSONArray rap_rez = obj.getJSONArray("vector_rap_rez");
for (int i = 0; i < rap_rez.length(); i++) {
JSONObject Rap_rez = rap_rez.getJSONObject(i);
timpi_rezolvare.add(Rap_rez.getString("rap_rez"));
}
JSONArray data_alerte = obj.getJSONArray("data_alerte");
for (int i = 0; i < data_alerte.length(); i++) {
JSONObject Data = data_alerte.getJSONObject(i);
data_grafic.add(Data.getString("data"));
}
}
} catch (JSONException ex) {
ex.printStackTrace();
}
CreareGraficDinamicInterventie();
}
}
GasesteDetaliiSaptamana ru =new GasesteDetaliiSaptamana();
ru.execute();
}
I have figured out a way, and I will write it down, maybe in the future it will help others too. I have added in the .xml a linear layout, to where I want my chart to be:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="200dp"
android:id="#+id/linear_chart"
android:orientation="horizontal">
</LinearLayout>
And, programically, I've created the chart, and added the view to this layout, removing all the views in the beginning.
private void CreareGraficDinamicInterventie() {
linear_chart.removeAllViews();
AnyChartView anyChartView = new AnyChartView(getContext());
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
params.setMargins(10,10,10,10);
params.weight=1;
anyChartView.setLayoutParams(params);
Cartesian areaChart = AnyChart.area();
....
anyChartView.setChart(areaChart);
linear_chart.addView(anyChartView);
}
Combine those with declaring the LinearLayout in onCreate and it should work, deleting the last chart and adding the new one.

Arraylist that sometimes contain data, and sometimes not

A newbie for here.
I'm working in an app with Android and a strange thing happens to me with a While loop. I make a series of requests to the database with volley library and it returns the data well. No problem.
The problem, i think, is in the last function DameColorPlato(), because sometimes the code accesses the while loop and it passes through it well, but sometimes it does not, and it returns the default value of the CC variable (#000000) and it does not show me well the colors of the text.
This is my code (In summary):
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
Bundle datos = getIntent().getExtras();
id_usuario = datos.getString("id_usuario");
idCentro = datos.getString("id_centro");
fecha_actual = datos.getString("fechaActual");
fecha_actual_SQL = datos.getString("fechaActualSQL");
plato1 = (TextView)findViewById(R.id.textView4);
plato2 = (TextView)findViewById(R.id.textView3);
ObtPlatos_volley(idCentro, fecha_actual_SQL);
ObtColores_volley();
public void ObtPlatos_volley(final String id_centro, final String fecha_actual_SQL){
String url = "http://neton.es/WS_neton/menu_dia.php?id_centro="+id_centro+"&fecha_actual_SQL="+fecha_actual_SQL;
StringRequest eventfulRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
for (int i=0; i<jsonArray.length(); i++) {
platouno = jsonArray.getJSONObject(i).getString("plato1");
platodos = jsonArray.getJSONObject(i).getString("plato2");
platounoColor = jsonArray.getJSONObject(i).getInt("tipo1");
platodosColor = jsonArray.getJSONObject(i).getInt("tipo2");
}
plato1.setText(platouno);
String co1 = DameColorPlato(CodTipoPlato, ColorLetra, platounoColor);
plato1.setTextColor(Color.parseColor(co1));
plato2.setText(platodos);
String co2 = DameColorPlato(CodTipoPlato, ColorLetra, platodosColor);
plato2.setTextColor(Color.parseColor(co2));
} catch (Exception e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error: ", error.toString());
}
});
VolleySingleton.getInstance(this)
.addToRequestQueue(eventfulRequest);
}
public void ObtColores_volley(){
String url = "http://neton.es/WS_neton/color_platos.php";
StringRequest eventfulRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
int cod_color_letra;
String color_letra;
JSONArray jsonArray = new JSONArray(response);
for (int i=0; i<jsonArray.length(); i++){
cod_color_letra = jsonArray.getJSONObject(i).getInt("cod_tipoplato");
color_letra = jsonArray.getJSONObject(i).getString("color");
CodTipoPlato.add(cod_color_letra);
ColorLetra.add(color_letra);
}
} catch (Exception e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error: ", error.toString());
}
});
VolleySingleton.getInstance(this)
.addToRequestQueue(eventfulRequest);
}
public String DameColorPlato(ArrayList<Integer> CodColorL, ArrayList<String> ColorL, int tipoplato){
String CC="#000000";
int i=0;
boolean encontrado=false;
while (i < CodColorL.size() && !encontrado) {
if (tipoplato == CodColorL.get(i)) {
CC = ColorL.get(i);
encontrado = true;
}else {
i++;
}
}
return CC;
}
}
With a Toast I have found that ArrayList CodColorL and ArrayList ColorL variables sometimes come with values, and sometimes they come empty. But i cannot found the error.
Thanks in advance!
(sorry for my bad English)
As I explained out in the comments, for anyone else looking at this question, the reason why OP was seeing the issue of unreliable data is because they are making two Volley requests and expecting one to finish before implicitly.
By default, Volley requests are run in a queue but are Asynchronous which means that the requests won't necessarily finish in the order that they were started in the queue. Since OP's one request is dependent on the data from the other the correct way to do this is by synchronously running the requests. This can be done in a few ways such as using a callback from the first request or through starting the second request in the onResponse block of the first one.
One more way to achieve the same is to create your own architecture of running requests where you have a way to run all the requests on a single thread but that is over optimizing for this particular case.

Is there any way to load 5 - 10 items in recyclerview at a time instead of 50k?

I have to show a list of airports of the world, and user has to choose one of them. So I have made a recyclerview:
RecyclerView recyclerView = (RecyclerView)rootView.findViewById(R.id.recyclerview);
SearchView searchView = (SearchView)rootView.findViewById(R.id.searchview);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
final AirportAdapter adapter = new AirportAdapter(airports,getActivity());
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
where airports is the List<Airport>. The problem is that it loads 20 seconds for time to charge the complete list in recyclerview and when I try to search any item it is so slow. So I want to load 20 airports for time and then, load the others when the users scroll the recyclerview. Is there a way to do it? I also want to do it because the search with the searchview it's also a bit slow, and I want to make it fast. I thought that notifyDataSetChanged() preload it but it not works...
EDIT: this is how to retrieve my list from Realm:
final RealmResults<AirportR> airps = realm.where(AirportR.class).findAll();
airports = realm.copyFromRealm(airps, 0);
Thank you for answers...
You can use pagination in recycle view for resolve your issue.
Please refer below links.
how to implement pagination in RecyclerView on scroll
https://medium.com/#etiennelawlor/pagination-with-recyclerview-1cb7e66a502b#.gxn5ft3n1
You can use pagination concept.
Pagination:It is a process of dividing a document into multiple pages.
I used pagination as below:
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
LinearLayoutManager linearLayoutManager= (LinearLayoutManager) recyclerView.getLayoutManager();
/*countToShowLoadButton here is total number of items available to
*user after no. of page requests. So when total visible item would
*reach to the end (i.e. countToShowLoadButton-3) then a "load more"
*button would appear and it will call a new request loadMoreData
*/
if(linearLayoutManager.findLastVisibleItemPosition() > countToShowLoadButton-3 && currentPageNumber < totalPageNumber){
loadMoreButton.setVisibility(View.VISIBLE);
loadMoreButton.setEnabled(true);
}
super.onScrolled(recyclerView, dx, dy);
}
});
loadMoreData:
public void loadMoreData(View view){
getAllData(currentPageNumber+1);
}
getAllData:
public void getAllData(int pageNo){
progressBar.setVisibility(View.VISIBLE);
final String key = sharedPreferences.getString("Auth_key",null);
String pageNumber = String.valueOf(pageNo);
checkInternet = new InternetConnectivityChecker(getApplicationContext());
if(checkInternet.isOnline()) {
StringRequest stringRequest = new StringRequest(Request.Method.GET,
URL_string.api_url +"?"+pageNumber,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("Result", "Success \n" + response);
try {
JSONObject responseJSON = new JSONObject(response);
JSONArray dataPart = responseJSON.getJSONArray("data");
JSONObject metaPart = responseJSON.getJSONObject("meta").getJSONObject("pagination");
//Here it updates all the variable so that when user clicks on "load more"
// button again then it loads the data from new page
currentPageNumber = metaPart.getInt("current_page");
totalPageNumber = metaPart.getInt("total_pages");
totalNumberOfData = metaPart.getInt("total");
perPageItems = metaPart.getInt("per_page");
dataAtShownPage = metaPart.getInt("count");
countToShowLoadButton = perPageItems * currentPageNumber;
//Here it adds new data to the shown page of the app
prepareValueWithServerData(dataPart,dataAtShownPage);
} catch (Exception e) {
Toast.makeText(getApplicationContext(),noNetConnMessage,Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),noNetConnMessage,Toast.LENGTH_LONG).show();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> header = new HashMap<>();
header.put("Authorization", "Bearer " + key);
return header;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
stringRequest.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(stringRequest);
if(stringRequest.getTimeoutMs() > DefaultRetryPolicy.DEFAULT_TIMEOUT_MS*2){
requestQueue.stop();
Toast.makeText(getApplicationContext(),noNetConnMessage,Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.INVISIBLE);
}
} else {
Toast.makeText(getApplicationContext(),"Please Check Internet Connection",Toast.LENGTH_LONG).show();
}
}
PrepareValueWithServerData:
public void prepareValueWithServerData(JSONArray data, int count){
progressBar.setVisibility(View.INVISIBLE);
for(int i=0; i<count; i++){
try {
JSONObject singleItem = data.getJSONObject(i);
item_details a = new item_details(details_1,details_2,..);
list.add(a);
//notifying adapter that data has been changed in the list
adapter.notifyDataSetChanged();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Note: Server would have to return data according to pages counts i.e. pagination concept will be used in server-side programming so that it doesn't return 50K data at once, else it should return just 10-20 or so data according to the requested page. It would make your app work faster.

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