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.
Related
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
this is a pice of my code and i use async task to search from database and fill the listview using simple adapter.
protected String doInBackground(String... arg0)
{
Cursor TROWS;
ArrayList<HashMap<String, String>> LstViw_VItem=new ArrayList<HashMap<String,String>>();
HashMap<String, String>VMap;
try
{
DBH.openDataBase();
SQLiteDatabase SQLITE=SQLiteDatabase.openDatabase(myPath, null, Context.MODE_PRIVATE);
if (TxtVerminSearch.getText().length()==0)
{
TROWS=SQLITE.rawQuery("select id,vermin_name from pistachio_vermins", null);
}
else
{
TROWS=SQLITE.rawQuery("select id,vermin_name from pistachio_vermins where vermin_name like '%"+TxtVerminSearch.getText()+"%'", null);
}
if (TROWS.moveToFirst())
{
do
{
String VID =TROWS.getString(0);
String VName =TROWS.getString(1);
VMap=new HashMap<String, String>();
VMap.put("VerminID", VID);
VMap.put("VerminName", VName);
LstViw_VItem.add(VMap);
}
while (TROWS.moveToNext());
SimpleAdapter SA=new SimpleAdapter(getApplicationContext(), LstViw_VItem, R.layout.xvermin_items, new String[]{"VerminID","VerminName"}, new int[]{R.id.mainmenu_items__lbl_vermin_id,R.id.mainmenu_items__lbl_vermins});
LstViwVerminItems.setAdapter(SA);
LstViwVerminItems.setEnabled(true);
}
else
{
VMap=new HashMap<String, String>();
VMap.put("VerminID", "-1");
VMap.put("VerminName", "nothing found");
VMap.put("ImgViw",String.valueOf(R.drawable.warning_48));
LstViw_VItem.add(VMap);
SimpleAdapter SA=new SimpleAdapter(getApplicationContext(), LstViw_VItem, R.layout.xvermin_items, new String[]{"VerminID","VerminName","ImgViw"}, new int[]{R.id.mainmenu_items__lbl_vermin_id,R.id.mainmenu_items__lbl_vermins,R.id.mainmenu_items__ImgViw});
LstViwVerminItems.setAdapter(SA);
LstViwVerminItems.setEnabled(false);
}
}
catch (Exception e)
{
final String errString;
errString=e.getMessage();
Log.d("ERR: ", errString);
runOnUiThread(new Runnable()
{
public void run()
{
Toast.makeText(JAct_Vermins.this, errString, Toast.LENGTH_LONG).show();
}
});
}
return null;
}
every thing work fine but when result of search is empty i give an error like this:
Only the original thread that created a view hierarchy can touch its views.
and the problem happen on the this line
VMap.put("ImgViw",String.valueOf(R.drawable.warning_48));
befor of this, i use runOnUiThread function to access ui. but i can not do it right now because i can not declare VMap as final
try to declare HashMap<String, String> VMap; outside doInBackgound() and use runOnUiThread(). If it still doesn't work, try to create a Handler and pass your hashmap key-val as Message.
Note: Declare your VMap variable outside doInBackground()
example:
HashMap<String, String> VMap;
#Override
protected String doInBackground(String... params) {
Cursor TROWS;
ArrayList<HashMap<String, String>> LstViw_VItem = new ArrayList<HashMap<String, String>>();
try {
DBH.openDataBase();
SQLiteDatabase SQLITE = SQLiteDatabase.openDatabase(myPath, null,
Context.MODE_PRIVATE);
if (TxtVerminSearch.getText().length() == 0) {
TROWS = SQLITE.rawQuery("select id,vermin_name from pistachio_vermins", null);
} else {
TROWS = SQLITE.rawQuery(
"select id,vermin_name from pistachio_vermins where vermin_name like '%"
+ TxtVerminSearch.getText() + "%'", null);
}
if (TROWS.moveToFirst()) {
do {
String VID = TROWS.getString(0);
String VName = TROWS.getString(1);
VMap = new HashMap<String, String>();
VMap.put("VerminID", VID);
VMap.put("VerminName", VName);
LstViw_VItem.add(VMap);
} while (TROWS.moveToNext());
SimpleAdapter SA = new SimpleAdapter(getApplicationContext(), LstViw_VItem,
R.layout.xvermin_items, new String[] { "VerminID", "VerminName" },
new int[] { R.id.mainmenu_items__lbl_vermin_id,
R.id.mainmenu_items__lbl_vermins });
LstViwVerminItems.setAdapter(SA);
LstViwVerminItems.setEnabled(true);
} else {
VMap = new HashMap<String, String>();
VMap.put("VerminID", "-1");
VMap.put("VerminName", "nothing found");
mHandler.sendEmptyMessage(0);
LstViw_VItem.add(VMap);
SimpleAdapter SA = new SimpleAdapter(getApplicationContext(), LstViw_VItem,
R.layout.xvermin_items, new String[] { "VerminID", "VerminName",
"ImgViw" }, new int[] { R.id.mainmenu_items__lbl_vermin_id,
R.id.mainmenu_items__lbl_vermins, R.id.mainmenu_items__ImgViw });
LstViwVerminItems.setAdapter(SA);
LstViwVerminItems.setEnabled(false);
}
} catch (Exception e) {
final String errString;
errString = e.getMessage();
Log.d("ERR: ", errString);
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(JAct_Vermins.this, errString, Toast.LENGTH_LONG).show();
}
});
}
return null;
}
private Handler mHandler = new Handler(){
#Override
public void handleMessage(Message msg) {
VMap.put("ImgViw", String.valueOf(R.drawable.warning_48));
super.handleMessage(msg);
}
};
Hope it helps!
You should use the method onPostExecute to show the result at your UI. Learn more about AsyncTask. You shouldn't handle with UI at the doInBackground method.
You are trying to update listview from background which is wrong.
For updating ui android provide post execute method , you should write code for updating listview in postexecute method. For your reference you can see this link http://www.compiletimeerror.com/2013/01/why-and-how-to-use-asynctask.html
function doInBackgound() - cannot call function from ui tread
use runOnUiThread() or onPostExecute()
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
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();
}
});
I know there are many questions asking about returning to the last position scrolled when the list has been refreshed. However I don't know why in my case (Adapter) the given answers don't work.
I have an adapter where at a given time it refreshes with new info and loads it in the adapter. What I want is that when it refreshes not come again to the top of the adapter and save the previous state.
Here is the code I use.
OnCreate
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_candidatos);
if (Titulacion.IsReachable1(getApplicationContext())){
new CargarCandidatos().execute();
timer();
}else{
Toast.makeText(getApplicationContext(), R.string.errorserver, Toast.LENGTH_LONG).show();
}
setListAdapter(adapter);
candidatosList = new ArrayList<HashMap<String, String>>();
The asynctask is divided in 2 parts. The retrieval of information and adapting the data into the adapter.
Here is the code of adapting it:
protected void onPostExecute(String file_url) {
runOnUiThread(new Runnable() {
public void run() {
adapter = new SimpleAdapter(
Monitorizacion.this, candidatosList,
R.layout.list_item, new String[] { TAG_ID,TAG_NSERIE,TAG_TABLET,
TAG_DNI, TAG_NOMBRE, TAG_TEST, TAG_PREGUNTA, TAG_BATERIA,TAG_CORRECTAS, TAG_ERRORES},
new int[] { R.id.autoid,R.id.id,R.id.tablet, R.id.dni, R.id.nombre, R.id.test, R.id.pregunta, R.id.bateria, R.id.correctas, R.id.fallos});
adapter.notifyDataSetChanged();
setListAdapter(adapter);
}
});
}
But how should I save the state of the adapter and then start showing the items considering the previous state.
Thank you
Edit: I have tried the answer approbed here Maintain/Save/Restore scroll position when returning to a ListView, but I cannot make it work.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_candidatos);
if (Titulacion.IsReachable1(getApplicationContext())){
new CargarCandidatos().execute();
timer();
}else{
Toast.makeText(getApplicationContext(), R.string.errorserver, Toast.LENGTH_LONG).show();
}
setListAdapter(adapter);
candidatosList = new ArrayList<HashMap<String, String>>();
lv = (ListView)findViewById(android.R.id.list);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String idd = ((TextView) view.findViewById(R.id.dni)).getText()
.toString();
Intent in = new Intent(getApplicationContext(),
MonitDetail.class);
in.putExtra("idd", idd);
startActivityForResult(in, 100);
}
});
}
//
//
public void timer(){
new CountDownTimer(tiempo, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
index = lv.getFirstVisiblePosition();
v = lv.getChildAt(0);
top = (v == null) ? 0 : v.getTop();
if (Titulacion.IsReachable1(getApplicationContext())){
new CargarCandidatos().execute();
timer();
}else{
Toast.makeText(getApplicationContext(), R.string.errorserver, Toast.LENGTH_LONG).show();
}
}
}.start();}
class CargarCandidatos extends AsyncTask<String, Void, String> {
protected String doInBackground(String... args) {
try {
monitorizar();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();}
return null;
}
protected void onPostExecute(String file_url) {
runOnUiThread(new Runnable() {
public void run() {
adapter = new SimpleAdapter(
Monitorizacion.this, candidatosList,
R.layout.list_item, new String[] { TAG_ID,TAG_NSERIE,TAG_TABLET,
TAG_DNI, TAG_NOMBRE, TAG_TEST, TAG_PREGUNTA, TAG_BATERIA,TAG_CORRECTAS, TAG_ERRORES},
new int[] { R.id.autoid,R.id.id,R.id.tablet, R.id.dni, R.id.nombre, R.id.test, R.id.pregunta, R.id.bateria, R.id.correctas, R.id.fallos});
lv.setSelectionFromTop(index, top);
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
}
});
}
}
public void monitorizar() throws Exception{
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("fecha",Titulacion.fecha()));
JSONObject json = jParser.makeHttpRequest(url_candidatos, "GET", params);
ArrayList<HashMap<String, String>> temp;
temp = new ArrayList<HashMap<String, String>>();
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
candidatos = json.getJSONArray(TAG_CANDIDATOS);
for (int i = 0; i < candidatos.length(); i++) {
JSONObject c = candidatos.getJSONObject(i);
String id = c.getString(TAG_ID);
String nserie = c.getString(TAG_NSERIE);
String tablet = c.getString(TAG_TABLET);
String dni = c.getString(TAG_DNI);
String nombre = c.getString(TAG_NOMBRE);
String test = c.getString(TAG_TEST);
String pregunta = c.getString(TAG_PREGUNTA);
String bateria = c.getString(TAG_BATERIA);
String correctas = c.getString(TAG_CORRECTAS);
String errores = c.getString(TAG_ERRORES);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ID, id);
map.put(TAG_NSERIE, nserie);
map.put(TAG_TABLET, tablet);
map.put(TAG_DNI, dni);
map.put(TAG_NOMBRE, nombre);
map.put(TAG_TEST, test);
map.put(TAG_PREGUNTA, pregunta);
map.put(TAG_BATERIA, bateria);
map.put(TAG_CORRECTAS, correctas);
map.put(TAG_ERRORES, errores);
temp.add(map);
candidatosList = temp;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
You can use like this
getListView().setSelection(position);
method of your ListView.
where you can get 'position' from the length of list you are passing to the adapter.
Declare you listview Globally and then you can keep the last position before New-Data-call. After then you can call listview for a position selection.