Hi Now I'm retrieving data to spinner dynamically, but now it displaying some id's but those Id details are stored in other table, I want display those details in the spinner instead of id. And if I select particular product in spinner according that product details should display in list.
I'm using Retrofit method for retrieving data from server
package cfirst.live.com.activity;
public class Pos_outlet extends AppCompatActivity implements RestCallback,View.OnClickListener{
Spinner spinner;
ArrayList<String> products;
String numberAsString, product_name;
int i;
private int cartProductNumber = 0;
String[] items;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pos_outlet);
sharedPreference = new MySharedPreference(Pos_outlet.this);
GsonBuilder builder = new GsonBuilder();
gson = builder.create();
initViews();
}
private void initViews() {
row1 =(TableRow)findViewById(R.id.row1);
spinner=(Spinner)findViewById(R.id.spinner);
POSStoreID = (TextView) findViewById(R.id.POSStoreID);
POSLocationID = (TextView) findViewById(R.id.POSLocationID);
Intent intent = getIntent();
id = intent.getStringExtra("id");
index_id= intent.getStringExtra("index_id");
callStoreDetaislsAPI();
callSmbProductsAPI();
getProductAPI();
}
// **Using this api I'm setting id'd to spinner**
private void getProductAPI() {
HashMap<String, String> map = new HashMap<String, String>();
map.put("store", index_id);
Toast.makeText(getApplicationContext(),index_id, Toast.LENGTH_LONG).show();
RestService.getInstance(Pos_outlet.this).getproductlist(map, new MyCallback<List<PosmultistoresModel>>(Pos_outlet.this,
Pos_outlet.this, true, "Finding products....", GlobalVariables.SERVICE_MODE.GET_PRODUCTS));
}
// **this API have product Id's Details**
private void callSmbProductsAPI() {
HashMap<String, String> map = new HashMap<String, String>();
map.put("index_id", product);
//Toast.makeText(getApplicationContext(),added_by, Toast.LENGTH_LONG).show();
RestService.getInstance(Pos_outlet.this).getSmbProduct(map, new MyCallback<List<PosSmbProductModel>>(Pos_outlet.this,
Pos_outlet.this, true, "Fetching details....", GlobalVariables.SERVICE_MODE.SMB_PRODUCT));
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.AddtoBasket:
callPosProductsAPI();
callSmbProductsAPI();
break;
}
}
#Override
public void onFailure(Call call, Throwable t, GlobalVariables.SERVICE_MODE mode) {
//Toast.makeText(getApplication(),"failure",Toast.LENGTH_LONG).show();
}
#Override
public void onSuccess(Response response, GlobalVariables.SERVICE_MODE mode) {
switch (mode) {
//** I'm setting data to spinner **
case GET_PRODUCTS:
try {
List<PosmultistoresModel> businessgroups = (List<PosmultistoresModel>) response.body();
product_name = businessgroups.get(0).getProduct();
List<PosmultistoresModel> list=null;
for(i=0;i<businessgroups.size();i++)
{
list=businessgroups;
}
items = new String[list.size()];
for(int i=0; i<businessgroups.size(); i++){
//Storing names to string array
items[i] = list.get(i).getProduct();
}
ArrayAdapter<String> adapter1;
adapter1 = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, items);
//setting adapter to spinner
spinner.setAdapter(adapter1);
} catch (Exception e) {
e.printStackTrace();
}
break;**
// ** Product id details (title, image, etc) Api
case SMB_PRODUCT:
try {
ArrayList<PosSmbProductModel> products = (ArrayList<PosSmbProductModel>) response.body();
//Product_id = products.get(0).getProduct();
// for (int i = 0; i < products(); i++) {
Title = products.get(0).getTitle();
productname1.setText(Title);
imageid12 = products.get(0).getMain_image();
Picasso.with(this).load("https://www.consumer1st.in/pre_production/uploads/" + imageid12).into(imageid1);
}
// }
catch(Exception e)
{
e.printStackTrace();
}
break;
}
}
}
I am assuming that your product_name = businessgroups.get(0).getProduct(); is getting a pruduct.
First of all please remove this part
product_name = businessgroups.get(0).getProduct();
List<PosmultistoresModel> list=null;
for(i=0;i<businessgroups.size();i++)
{
list=businessgroups;
}
items = new String[list.size()];
for(int i=0; i<businessgroups.size(); i++){
//Storing names to string array
items[i] = list.get(i).getProduct();
}
then can you try
ArrayList<String> productList = new ArrayList<>();
for (int i = 0; i < businessgroups.size(); i++) {
productList.add(businessgroups.get(i).getProduct());
}
And finally
adapter1 = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, productList);
Related
im trying to get data from a server inform of JSON and im storing the data to my offline database ( in this case : Realm ), whenever i try to retrieve the data, nothing is displayed in the listview.
public class MainActivity extends AppCompatActivity {
public static ListView myList;
public static ListAdapter myAdapter;
public static Realm realm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Realm.init(this);
realm = Realm.getDefaultInstance();
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
RealmResults<Recipe> dRecipies = realm.where(Recipe.class).findAll();
if(dRecipies!= null)dRecipies.deleteAllFromRealm();
}
});
DownloadTask newTask = new DownloadTask();
newTask.execute("hi");
setContentView(R.layout.activity_main);
myList = (ListView) findViewById(R.id.Recipe_list);
// getData();
setDisplay();
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String p = String.valueOf(position);
Intent in = new Intent(MainActivity.this, SecondScreenDetails.class);
in.putExtra("Position", p);
startActivity(in);
}
});
}
public void setDisplay(){
ArrayList<Recipe> finalRecipies = new ArrayList<>();
RealmResults<Recipe> rrRecipies = realm.where(Recipe.class).findAll();
for(Recipe r: rrRecipies){
finalRecipies.add(r);
Toast.makeText(this, r.getName(), Toast.LENGTH_SHORT).show();
}
myAdapter = new ListViewAdapter(this, finalRecipies);
myList.setAdapter(myAdapter);
}
#Override
protected void onDestroy() {
realm.close();
super.onDestroy();
}
}
im doing this because, if i dont, the data keeps getting repeatedly stored, resulting in repetition.
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
RealmResults<Recipe> dRecipies = realm.where(Recipe.class).findAll();
if(dRecipies!= null)dRecipies.deleteAllFromRealm();
}
});
when i tried without actually deleting the data, then the Toast in the
setDisplay() method is working and the data is being shown.(Toasts are repeated as i open the app second time, it gets twice... etc)
When i insert this, even the toasts dont show up.
My download activity
public class DownloadTask extends AsyncTask<String,Void,String> {
private RealmList<Recipe> realmRecipe = new RealmList<>();
String result;
#Override
protected String doInBackground(String... params) {
result = "";
Realm realm = null;
realm = Realm.getDefaultInstance();
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url("https://d17h27t6h515a5.cloudfront.net/topher/2017/May/59121517_baking/baking.json").build();
try {
result = client.newCall(request).execute().body().string();
Log.i("RESULT", result);
JSONArray rootArray = new JSONArray(result);
for (int i = 0; i < rootArray.length(); i++) {
JSONObject tempObject = rootArray.getJSONObject(i);
JSONArray jIngredients = tempObject.getJSONArray("ingredients");
JSONArray jSteps = tempObject.getJSONArray("steps");
// Get the ingredients
List<Ingredients> ingredients = new ArrayList<>();
for (int j = 0; j < jIngredients.length(); j++) {
JSONObject tempIngredient = jIngredients.getJSONObject(j);
Ingredients nIngredient = realm.createObject(Ingredients.class);
nIngredient.setIngredient(tempIngredient.getString("ingredient"));
nIngredient.setMeasure(tempIngredient.getString("measure"));
nIngredient.setQuantity(tempIngredient.getString("quantity"));
// Ingredients newIngredient = new Ingredients(tempIngredient.getString("quantity"),
// tempIngredient.getString("measure"),
// tempIngredient.getString("ingredient"));
// ingredients.add(newIngredient);
ingredients.add(nIngredient);
}
// Get the steps
List<Steps> steps = new ArrayList<>();
for (int j = 0; j < jSteps.length(); j++) {
JSONObject tempStep = jSteps.getJSONObject(j);
Steps nStep = realm.createObject(Steps.class);
nStep.setDescription(tempStep.getString("description"));
nStep.setId(tempStep.getString("id"));
nStep.setShortDescription(tempStep.getString("shortDescription"));
nStep.setVideoURL(tempStep.getString("videoURL"));
steps.add(nStep);
// Steps newStep = new Steps(tempStep.getString("id"), tempStep.getString("shortDescription"),
// tempStep.getString("description"), tempStep.getString("videoURL"));
// steps.add(newStep);
}
// Create the recipe
Recipe nRecipe = realm.createObject(Recipe.class);
nRecipe.setId(tempObject.getString("id"));
nRecipe.setName(tempObject.getString("name"));
nRecipe.setServings(tempObject.getString("servings"));
nRecipe.setIngredients(ingredients);
nRecipe.setSteps(steps);
realmRecipe.add(nRecipe);
// Recipe newRecipe = new Recipe(tempObject.getString("id"), tempObject.getString("name"), tempObject.getString("servings"), ingredients, steps);
// MainActivity.mRecipies.add(newRecipe);
}
}catch (Exception e){
Log.i("Error Message", e.getMessage());
}
}
});
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
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");
There are two spinners in my application.when i select a value from one spinner, according to the selection, values will be loaded to second spinner. The problem is when i select the second spinner, the application unfortunately stops. Thanks in advance.
public class CreateAppointment extends AppCompatActivity {
String[] lect_name = new String[100];
String[] spinner_subjects_load;
Spinner spSubject,spLecturer;
String chosedSubject;
String chosedLectName;
String chosedDateString;
RequestQueue requestQueue;
String url = "http://quick-appointment.b2creations.net/getLecturerNames.php";
CustomRequest customRequest;
String dayOfWeekString;
Calendar currentDate,chosedDate;
User user;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_appointment);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent intent = getIntent();
user = (User) intent.getExtras().getSerializable("user");
currentDate = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.format(currentDate.getTime()); //get current date
spinner_subjects_load = new String[]{"SPDC", "HCI", "MAD", "SEIII", "SEP", "DAA", "ITP"};
spSubject = (Spinner) findViewById(R.id.spSubject);
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, spinner_subjects_load);
spSubject.setAdapter(adapter1);
requestQueue = Volley.newRequestQueue(this);
spSubject.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
chosedSubject = spSubject.getSelectedItem().toString();
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("subj_name", chosedSubject);
customRequest = new CustomRequest(Request.Method.POST, url, hashMap, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
int count = 0;
try {
JSONArray jsonArray = response.getJSONArray("Lecturers");
while (count < jsonArray.length()) {
JSONObject jo = jsonArray.getJSONObject(count);
lect_name[count] = jo.getString("name");
count++;
}
spLecturer = (Spinner) findViewById(R.id.spLecturer);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(CreateAppointment.this, android.R.layout.simple_spinner_item, lect_name);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spLecturer.setAdapter(adapter2);
chosedLectName = spLecturer.getSelectedItem().toString();
Toast.makeText(CreateAppointment.this, chosedLectName, Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(customRequest);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
Looks like you initialize the second spinner spLecturer, and then immediately after you make a call to spLecturer.getSelectedItem().toString(), which I believe will return null at this point.
Perhaps you intended to add an OnItemSelectedListener to it first?
I have been having a problem lately, I have successfully created a listview in the FillList method that displays the items that i need. That is all well. The problem is how do I convert it to a multi-select checkbox like style so that when I select an item it will just be stored in an array for later use. Any insight is helpful.
Here is my PathfinderUpdate.java:
public class PathfinderUpdate extends Fragment {
ConnectionClass connectionClass;
EditText edtproname, edtprodesc;
Button btnadd,btnupdate,btndelete,btnrefresh;
ProgressBar pbbar;
ListView lstpro;
String pathid;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.update_pathfinder, container, false);
connectionClass = new ConnectionClass();
btnupdate = (Button) rootView.findViewById(R.id.btnupdate);
lstpro = (ListView) rootView.findViewById(R.id.lstproducts);
btnrefresh = (Button) rootView.findViewById(R.id.btnrefresh);
pathid = "";
FillList fillList = new FillList();
fillList.execute("");
btnrefresh.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
FillList Fill = new FillList();
Fill.execute("");
}
});
return rootView;
}
#Override
public void onResume(){
super.onResume();
FillList Fill = new FillList();
Fill.execute("");
}
public class FillList extends AsyncTask<String, String, String> {
String z = "";
List<Map<String, String>> prolist = new ArrayList<Map<String, String>>();
#Override
protected void onPreExecute() {
//old pbbar
}
#Override
protected void onPostExecute(String r) {
String[] from = { "pathfinder_id", "pathfinder_name"};
int[] views = { R.id.lblproid, R.id.lblproname };
final SimpleAdapter ADA = new SimpleAdapter(getActivity(),
prolist, R.layout.lsttemplate, from,views);
lstpro.setAdapter(ADA);
lstpro.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
#SuppressWarnings("unchecked")
HashMap<String, Object> obj = (HashMap<String, Object>) ADA
.getItem(arg2);
pathid = (String) obj.get("pathfinder_id");
String idea_name = (String) obj.get("pathfinder_name");
String benefit_eqv = (String) obj.get("pathfinder_eqv");
String quickwin = (String) obj.get("pathfinder_quick");
String observe = (String) obj.get("pathfinder_obs");
String ideaId = (String) obj.get("pathfinder_idea_id");
String BenefitId = (String) obj.get("pathfinder_benefit");
String closure = (String) obj.get("pathfinder_closure");
Integer ideaIdMain = Integer.parseInt(ideaId);
Integer benefitIdMain = Integer.parseInt(BenefitId);
Integer pathfinderId = Integer.parseInt(pathid);
Double benefiteqv = Double.parseDouble(benefit_eqv);
Bundle bundle = new Bundle();
bundle.putString("id2", pathid);
bundle.putString("name", idea_name);
bundle.putDouble("eqv", benefiteqv);
bundle.putString("quick", quickwin);
bundle.putString("observation", observe);
bundle.putInt("idea_id", ideaIdMain);
bundle.putInt("benefit_id", benefitIdMain);
bundle.putString("closure", closure);
bundle.putInt("id", pathfinderId);
Intent updateMain = new Intent(getActivity(), PathfinderUpdateMain.class);
updateMain.putExtras(bundle);
startActivity(updateMain);
// qty.setText(qtys);
}
});
}
#Override
protected String doInBackground(String... params) {
try {
Connection con = connectionClass.CONN();
if (con == null) {
z = "Error in connection with SQL server";
} else {
String query = "select * from pathfinder ORDER BY pathfinder_id ASC";
PreparedStatement ps = con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
ArrayList<String> data1 = new ArrayList<String>();
while (rs.next()) {
Map<String, String> datanum = new HashMap<String, String>();
datanum.put("pathfinder_id", rs.getString("pathfinder_id"));
datanum.put("pathfinder_name", rs.getString("pathfinder_name"));
datanum.put("pathfinder_status", rs.getString("pathfinder_status"));
datanum.put("pathfinder_eqv", rs.getString("pathfinder_potential_eqv"));
datanum.put("pathfinder_obs", rs.getString("pathfinder_observation"));
datanum.put("pathfinder_quick", rs.getString("pathfinder_quickwin"));
datanum.put("pathfinder_idea_id", rs.getString("idea_id"));
datanum.put("pathfinder_benefit", rs.getString("benefit_id"));
datanum.put("pathfinder_closure", rs.getString("pathfinder_target_closure"));
prolist.add(datanum);
}
z = "Success";
}
} catch (Exception ex) {
z = "Error retrieving data from table";
Log.e("MYAPP", "exception", ex);
}
return z;
}
}
}
Check this out i believe its much more close to the new design guidelines!!!
You can create your own adapter and customise list item.
here is a tutorial about list view.
for your questions. chapter 15 might be what you have been looking for.
http://www.vogella.com/tutorials/AndroidListView/article.html#listview_selection
hope this help !!!
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.