This is my JSON:
{
"NEWS": [
{
"ID": 1,
"Title": "A",
"News": "A"
},
{
"ID": 2,
"Title": "B",
"News": "B"
}
]
}
I am parsing this JSON in a listview and just showing the Title. Now, If I click on listview item, say, I clicked "A", I want to populate Title and News in other activity. How can i constraint them?
ArrayList<HashMap<String, String>> newList ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
newList = new ArrayList<>();
String items = String.valueOf(newList);
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray NEWS= jsonObj.getJSONArray("NEWS");
for (int i = 0; i < NEWS.length(); i++) {
JSONObject c = icerik.getJSONObject(i);
String ID= c.getString("ID");
String Title= c.getString("Title");
String News= c.getString("News");
HashMap<String, String> newss= new HashMap<>();
newss.put("ID", ID);
newss.put("Title", Title);
newss.put("News", News);
newList.add(newss);
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
final ListAdapter adapter = new SimpleAdapter(
news.this, newList,
R.layout.new_list, new String[]{"Title"},
new int[]{
R.id.Ttile});
lv.setAdapter(adapter);
lv.setClickable(true);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position >= 0)
{
//Intent myIntent = new Intent(view.getContext(), MYSECONDACTIVTY.class);
//startActivityForResult(myIntent, 0);
}
I found it, and tried but it doesn't work. I just want to show item details on other activity when I click on list item.
insert your data to Bundle, Bundle to Intent
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent myIntent = new Intent(view.getContext(), MYSECONDACTIVTY.class);
Bundle myBundle = new Bundle();
myBundle.putString("title", newList.get(postiyion).get("Title");
myBundle.putString("id", newList.get(postiyion).get("ID");
myBundle.putString("news", newList.get(postiyion).get("News");
myIntent.putExtras(mByundle);
startActivityForResult(myIntent, 0);
}
recover these values in MYSECONDACTIVTY e.g. inside onCreate or wherever you need them
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
String title = getIntent().getExtras().getString("Title");
String id = getIntent().getExtras().getString("ID");
String news = getIntent().getExtras().getString("News")
}
this must work! also check this SO question for more details about Bundle and passing to another Activity
Related
This question already has answers here:
Passing JSONObject into another activity
(7 answers)
Closed 6 years ago.
public class MainActivity extends **strong text**
AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ListView lv;
ArrayList<HashMap<String, String>> companyList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
companyList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list_row_xml);
new GetCompany().execute();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Intent i = new Intent(MainActivity.this, SingleView.class);
i.putExtra("venue", venue);
startActivity(i);
}
});
}
private class GetCompany extends AsyncTask<Void, Void, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(MainActivity.this,"Json Data is downloading",Toast.LENGTH_LONG).show();
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected JSONObject doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "http://10.0.2.2:6060/api/v1/company/getInfo?limit=10&page=1";
JSONArray company = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + company);
if (company != null) {
try {
// JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
//JSONArray company = new JSONArray(jsonStr);
// System.out.println("Reached");
// looping through All Contacts
for (int i = 0; i < company.length(); i++) {
//System.out.println("Reached1");
JSONObject c = company.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("companyName");
// Walking Details in Json object
JSONObject walkingDetails=c.getJSONObject("walkingdetails");
String date = walkingDetails.getString("walkingdate");
String venue = walkingDetails.getString("venu");
// tmp hash map for single contact
HashMap<String, String> companyy = new HashMap<>();
// adding each child node to HashMap key => value
companyy.put("id",id);
companyy.put("date", date);
companyy.put("companyname", name);
companyy.put("venue", venue);
// adding contact to contact list
companyList.add(companyy);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Json parsing error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Couldn't get json from server. Check LogCat for possible errors!", Toast.LENGTH_LONG).show();
}
});
}
return null;
}
/* #Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, companyList,
R.layout.list_row, new String[]{"date","companyname","venue"}, new int[]{ R.id.date, R.id.companyname, venue});
lv.setAdapter(adapter);*/
}
}
second acivity:
public class SingleView extends AppCompatActivity {
EditText txtVenue;
// String[] Venue;
int position;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_view);
Intent i = getIntent();
position = i.getExtras().getInt("positi`enter code here`on");
txtVenue = (EditText) findViewById(R.id.Venue);
}
}
You can not pass directly JSONObject to another activity. But you can convert json to string and pass it. Then in SecondActivity you can convert it to json again.
Start SecondActivity codes in FirstActivity:
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("data", json.toString());
startActivity(intent);
Then get this data from SecondActivity:
String data = getIntent().getStringExtra("data");
try {
JSONObject json = new JSONObject(data);
} catch (JSONException e) {
e.printStackTrace();
}
Good luck.
You can achieve by creating your own class by extending the JSONObject and implementing Serializable interface. So that you can pass through the intent.
You have 2 options:
1. Convert json to string and pass as string.
2. Make model class for json , make it parcelable. Pass this object to next activity.
HashMaps do not preserve ordering.
Better use a model class, it would also be easy to retrieve data.
public class CompanyData {
public String id;
public String date;
public String name;
public String venue;
}
then change arraylist,
ArrayList<CompanyData> companyList;
then store values,
CompanyData companyy = new CompanyData();
companyy.id = id;
companyy.date = date;
companyy.name = name;
companyy.venue = venue;
companyList.add(companyy);
then implement onitemclicklistener,
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
CompanyData data = companyList.get(position);
Intent i = new Intent(MainActivity.this, SingleView.class);
i.putExtra("venue", data.venue);
startActivity(i);
}
});
***To get position simply send position value inside onItemClickListener
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
CompanyData data = companyList.get(position);
Intent i = new Intent(MainActivity.this, SingleView.class);
i.putExtra("position", position);
startActivity(i);
}
});
You can also send all data of a specific position by
CompanyData data = companyList.get(position);
i.putExtra("data", data); //this will pass all data of clicked row
Ive been searching for the right answer but nothing can solve my problems. I have a list view which is populated by my database from webserver. So basically what need is to get the data from the listview that is checked by user and pass the data to another activity. Sorry for my bad english hope you guys can help me.
Error ive received
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
at java.util.ArrayList.get(ArrayList.java:304)
at firin.myuploads.Attendance$1.onClick(Attendance.java:74)
Attendance.java
public class Attendance extends AppCompatActivity {
//For Checkbox
ArrayList<String> selectedItems=new ArrayList<>();
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
private CheckBox cb;
private Button bGet;
//private id[] id;
private static String url = "www.myphpurl.com";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_attendance);
contactList = new ArrayList<>();
bGet = (Button) findViewById(R.id.button7);
lv = (ListView) findViewById(R.id.list);
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
new GetContacts().execute();
bGet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// String selected =((TextView)view.findViewById(R.id.mobile)).getText().toString();
CheckBox cb = (CheckBox) findViewById(R.id.cb);
cb.setChecked(true);
int len = lv.getCount();
SparseBooleanArray checked = lv.getCheckedItemPositions();
for (int i = 0; i < len; i++)
if (checked.get(i)) {
String item = selectedItems.get(i);
Toast.makeText(getApplicationContext(), item, Toast.LENGTH_LONG).show();
/*some code to save data in MainActivity*/
Intent in = new Intent(Attendance.this, SendMail.class);
in.putExtra("ListValue", item);
startActivity(in);}
}
});
}
This is the code where i populate my data to the listview
public class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray result = jsonObj.getJSONArray("result");
// looping through All Contacts
for (int i = 0; i < result.length(); i++) {
JSONObject c = result.getJSONObject(i);
String id = c.getString("userID");
String studentName = c.getString("studentName");
String parentName = c.getString("parentName");
String parentEmail = c.getString("parentEmail");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("UID", id);
contact.put("sName", studentName);
contact.put("pName", parentName);
contact.put("pEmail", parentEmail);
// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(Attendance.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
public void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
Attendance.this, contactList,
R.layout.list_item, new String[]{"sName", "pName",
"pEmail"}, new int[]{R.id.name,
R.id.email, R.id.mobile});
lv.setAdapter(adapter);
}
}
Is this how i set my setOnClick?
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String selected =((TextView)findViewById(R.id.mobile)).getText().toString();
CheckBox cb = (CheckBox) findViewById(R.id.cb);
cb.setChecked(true);
}});
Hope you guys can help me. thanks in advance
First you need to get how many item is selected in the listview, then after store in another array and pass that array to another activity.
Set you listview selection mode as Multi Choice.
listview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
Set Listener on listview as below
ArrayList<String> selectedItem = new ArrayList();
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
view.setSelected(true);
adapter.getView(position, view, parent).setBackgroundColor(getResources().getColor(R.color.btn_login));
adapter.notifyDataSetChanged();
Log.i(TAG, "Selected Item is " + stateList.get(position));
selectedItem.add(yourArray.get(position))
}
});
you can invok your intent and pass selectedItem to that intent like this
Intent intent = new Intent(activity, YourActivity.class);
intent.putStringArrayListExtra("selected_list", selectedItem);
startActivity(intent);
and In your receiving intent you need to do:
ArrayList<String> selectedItem;
Intent i = getIntent();
selectedItem = i.getStringArrayListExtra("selected_list");
I have a ListView that is updated from a ASyncTask, The adapter updates the list properly, however my setOnItemClickListener always has the same data in the intent.
This is the code for the loop that populates the ListView
if (JsonStr != null) {
//Get list of courses
JSONObject json = new JSONObject(JsonStr);
JSONObject Username = json.getJSONObject(InputUsername);
JSONObject Courses = Username.getJSONObject("Courses");
JSONObject CoursesItems = Courses.getJSONObject("items");
//Iterate around all courses
Iterator<String> i = CoursesItems.keys();
while (i.hasNext()) {
final String key = i.next();
JSONObject Course = (JSONObject) CoursesItems.get(key);
//Create a course entry
Map<String, String> ListEntry = new HashMap<>(2);
ListEntry.put("code", key);
if (Course.has("m_name")) {
String CourseName = (String) Course.get("m_name");
ListEntry.put("title", CourseName);
}
if (Course.has("original_source")) {
String Source = (String) Course.get("original_source");
ListEntry.put("source", Source);
}
JSONObject Units = null;
if (Course.has("Units")) {
Units = Course.getJSONObject("Units");
ListEntry.put("Units", Units.toString());
}
ListEntries.add(ListEntry);
final JSONObject finalUnits = Units;
runOnUiThread(new Runnable() {
public void run() {
SimpleAdapter adapter = new SimpleAdapter(
getApplicationContext(), //Activity
ListEntries, //List of pairs
R.layout.mymodules__list_item, //Target Parent Layout
new String[]{"title", "code", "source"}, //Key for pairs
new int[]{R.id.list_item_alert_textview,
R.id.list_item_date_textview,
R.id.list_item_source_textview}); //target items
ListView lv = (ListView) findViewById(R.id.listview);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getApplicationContext(), CourseActivity.class);
intent.putExtra("Data", finalUnits.toString());
startActivity(intent);
}
});
}
});
}
}
'finalUnits' is final value .
move listener and data(List Units) to inside adapter.
and set listener in bindview method.
{
Intent i = new Intent(context,CourseActivity.class);
i.putExtra("Data",list.get(position).toString());
startActivity(i);
}
just replace by this code onitemclick
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?>parent, View view, int position, long id) {
String value = (new ArrayList<String>(ListEntry.values())).get(position);
Intent intent = new Intent(getApplicationContext(), CourseActivity.class);
intent.putExtra("Data", value);
startActivity(intent);
}
});
Sorry for my bad English.I am new android.
I have some problem for JSON in Android that
(1.)I've been to obtain information from the Internet (JSON). How can I mark all station on googlemap on particular page?
(2.1) I've been to obtain information from the Internet(JSON) and show those information in the listView. This listView is composed by two TextView(txtV1, txtV2). How can I Use the keyword_search to filter the ListView by the editText?
(2.2) If I click the option, the relevant information will be transmitted to the next page and display. Now, I can only bunndle the String data. How can I bundle the (lat,lng) and mark on google map?
This is json :
{
"retCode": "1",
"retVal": [
{
"iid": "339",
"sno": "0001",
"mday": "20140711003603",
"lat": "25.0408578889",
"lng": "121.567904444"
},
{
"iid": "340",
"sno": "0002",
"mday": "20140711003508",
"lat": "25.041",
"lng": "121.556945"
}
]
}
This is problem(2.1) code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.station);
oslist = new ArrayList<HashMap<String, String>>();
new JSONParse().execute();
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
sna = (TextView) findViewById(R.id.sna);
ar = (TextView) findViewById(R.id.ar);
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
youbike = json.getJSONArray(TAG_retVal);
for (int i = 0; i < youbike.length(); i++) {
JSONObject c = youbike.getJSONObject(i);
// Storing JSON item in a Variable
final String iid = c.getString(TAG_iid);
final String sno = c.getString(TAG_sno);
final String mday = c.getString(TAG_mday);
final String lat = c.getString(TAG_lat);
final String lng = c.getString(TAG_lng);
// Adding value HashMap key => value
final HashMap<String, String> map = new HashMap<String, String>();
map.clear();
map.put(TAG_iid, iid);
map.put(TAG_sno, sno);
map.put(TAG_mday, mday);
map.put(TAG_lat, lat);
map.put(TAG_lng, lng);
oslist.add(map);
list = (ListView) findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(station.this,
oslist, R.layout.station_list, new String[] {
TAG_iid, TAG_sno }, new int[] { R.id.sno,
R.id.iid });
list.setAdapter(adapter);
// bundle to next page
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
Intent intent = new Intent();
intent.setClass(station.this, station_1.class);
Bundle b = new Bundle();
b.putString("TAG_iid",
oslist.get(+position).get("iid"));
b.putString("TAG_sno",
oslist.get(+position).get("sno"));
b.putString("TAG_mday",
oslist.get(+position).get("mday"));
b.putString("TAG_lat",
oslist.get(+position).get("lat"));
b.putString("TAG_lng",
oslist.get(+position).get("lng"));
intent.putExtras(b);
startActivity(intent);
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
To filter your results, take a look at SimpleAdapter#getFilter(). Example:
private void filterResults(CharSequence filterText){
Filter filter = mSimpleAdapter.getFilter();
filter.filter(filterText);
}
...
mSearchBox.addTextChangeListener(new TextWatcher(){
...
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
filterResults(s);
}
});
To pass lat/long trough Bundle, either parse them when taking from JSON by calling JSONObject#getLong or parse them in other Activity with Long#parseLong
It seems that you are trying to parse the data from Taipei city's Youbike service on the Android platform. I wrote such piece of code already, and it's open source (License AGPL).
You might want to take a look at my source code and find out how to do:
https://github.com/le-moulin-studio/bike-friend/blob/master/android/src/main/java/com/lemoulinstudio/bikefriend/ubike/YouBikeStationProvider.java
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.