I have created a list activty1 and an activity2. In the list activity the list is getting populated by the database, on list item selected activity2 is getting called. In activity2 i am updating the values in mysql database. when i am calling back to list activity1 another list item is getting added rather than the list item which was pressed getting updated. The values in database tables are updating fine. Please suggest.
Here is my list activity
#SuppressLint("UseValueOf")
public class DocPresc extends ListActivity {
//public static Context ctx;
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList = new ArrayList<HashMap<String,String>>();
String pid;
JSONArray products = null;
EditText ailm,date,comment;
Button delete;
ListAdapter adapter;
JSONParser jsonParser = new JSONParser();
// single product url
private static final String url_patient_presc = "http://192.168.44.208/get_prescription.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
// private static final String TAG_PATIENT_ID = "patient_id";
private static final String TAG_AIL = "ailment";
private static final String TAG_MED = "medicine_name";
private static final String TAG_D1 = "qty1";
private static final String TAG_D2 = "qty2";
private static final String TAG_D3 = "qty3";
private static final String TAG_DATE = "prescription_date";
private static final String TAG_COM = "comment";
private static final String TAG_DID = "dosage_id";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.docpresc);
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads().detectDiskWrites().detectNetwork() // StrictMode is most commonly used to catch accidental disk or network access on the application's main thread
.penaltyLog().build());
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
Intent i = getIntent();
Bundle extras = i.getExtras();
pid = extras.getString("TAG_PATIENT_ID");
System.out.println("Docpresc"+pid);
ailm = (EditText)findViewById(R.id.ailment1);
date = (EditText)findViewById(R.id.date1);
comment = (EditText)findViewById(R.id.comment1);
// if (savedInstanceState == null) {
new LoadPrescriptions().execute();
// }
}
class LoadPrescriptions extends AsyncTask<String, String, String> {
protected String doInBackground(String... args) {
// Building Parameters
runOnUiThread(new Runnable() {
public void run() {
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
params.add(new BasicNameValuePair("patient_id",pid));//search1.getText().toString()));
System.out.println("database"+pid);
JSONObject json = jParser.makeHttpRequest(url_patient_presc, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Patients: ", json.toString());
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
//-----------------------------------
/*JSONObject product = products.getJSONObject(0);
ailm = (EditText)findViewById(R.id.ailment1);
ailm.setText(product.getString(TAG_AIL));*/
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String medicine = c.getString(TAG_MED).toUpperCase();
String qty1 = c.getString(TAG_D1).toUpperCase();
String qty2 = c.getString(TAG_D2).toUpperCase();
String qty3 = c.getString(TAG_D3).toUpperCase();
String dsg_id = c.getString(TAG_DID).toUpperCase();
//String ail = c.getString(TAG_AIL).toUpperCase();
ailm.setText(c.getString(TAG_AIL));
date.setText(c.getString(TAG_DATE));
comment.setText(c.getString(TAG_COM));
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_MED, medicine);
map.put(TAG_D1,qty1);
map.put(TAG_D2,qty2);
map.put(TAG_D3,qty3);
map.put(TAG_DID,dsg_id);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
// pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
//ListAdapter
adapter = new SimpleAdapter(
DocPresc.this, productsList,
R.layout.list_item2, new String[] {
TAG_MED,TAG_D1,TAG_D2,TAG_D3,TAG_DID},
new int[] {R.id.med,R.id.d1,R.id.d2,R.id.d3,R.id.did });
// updating listview
//setListAdapter(adapter);
setListAdapter(adapter);
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.items, menu);
//menuSearch = menu.findItem(R.id.delete);
//menuSearch.setVisible(false);
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
// handle item selection
switch (item.getItemId()) {
case R.id.add:
Bundle bundle = new Bundle();
bundle.putString("TAG_PATIENT_ID",pid );
System.out.println("bundle"+pid);
Intent i = new Intent(DocPresc.this,AddPresc.class);
i.putExtras(bundle);
startActivityForResult(i,100);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void onListItemClick(ListView lv, View v, int position, long id) {
// TODO Auto-generated method stub
//onAttach(getActivity());
//lv.setAdapter(adapter);
String did1 = ((TextView) v.findViewById(R.id.did)).getText().toString();
String med1 = ((TextView) v.findViewById(R.id.med)).getText().toString();
String dg1 = ((TextView) v.findViewById(R.id.d1)).getText().toString();
String dg2 = ((TextView) v.findViewById(R.id.d2)).getText().toString();
String dg3 = ((TextView) v.findViewById(R.id.d3)).getText().toString();
// System.out.println("all patient"+id1);
Bundle bundle = new Bundle();
bundle.putString("TAG_DOSAGE_ID",did1 );
bundle.putString("TAG_DOSAGE_ID1",med1 );
bundle.putString("TAG_DOSAGE_ID2",dg1 );
bundle.putString("TAG_DOSAGE_ID3",dg2 );
bundle.putString("TAG_DOSAGE_ID4",dg3 );
// System.out.println("bundle"+id1);
Intent i = new Intent(DocPresc.this,EditPresc.class);
i.putExtras(bundle);
startActivityForResult(i,100);
//passData(date);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
/*Intent intent = getIntent();
finish();
startActivity(intent);*/
// ((SimpleAdapter)getListAdapter())
// ((SimpleAdapter) adapter).notifyDataSetChanged();
//getListView().setAdapter(null);
//getListView().refreshDrawableState();
new LoadPrescriptions().execute();
//adapter.notifyDataSetChanged()
}
}
}
Here is the activity getting called on list item pressed
public class EditPresc extends Activity implements View.OnClickListener{
//public static Context ctx;
EditText medicine;
EditText dosage1;
EditText dosage2;
EditText dosage3;
Button edit;
ImageButton up1 , up2,up3;
ImageButton down1,down2,down3;
String did,medi,q1,q2,q3;
int count = 1;
//JSONArray products = null;
//int pid = "100";
//private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// single product url
// private static final String url_getdosage = "http://192.168.44.208/get_dosage.php";
private static final String url_updatedosage = "http://192.168.44.208/update_dosage.php";
private static final String url_getmedname = "http://192.168.44.208/getmedname.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCT = "product";
// private static final String TAG_PATIENT_ID = "patient_id";
private static final String TAG_MED_ID ="medicine_id";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.editpresc);
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads().detectDiskWrites().detectNetwork() // StrictMode is most commonly used to catch accidental disk or network access on the application's main thread
.penaltyLog().build());
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
Intent i = getIntent();
Bundle extras = i.getExtras();
did = extras.getString("TAG_DOSAGE_ID");
medi = extras.getString("TAG_DOSAGE_ID1");
q1 = extras.getString("TAG_DOSAGE_ID2");
q2 = extras.getString("TAG_DOSAGE_ID3");
q3 = extras.getString("TAG_DOSAGE_ID4");
medicine = (EditText)findViewById(R.id.atxt1);
dosage1 = (EditText)findViewById(R.id.text1);
dosage2 = (EditText)findViewById(R.id.text2);
dosage3 = (EditText)findViewById(R.id.text3);
medicine.setText(medi);
dosage1.setText(q1);
dosage2.setText(q2);
dosage3.setText(q3);
System.out.println("Editpresc"+did);
//send = (Button)findViewById(R.id.b1);
up1=(ImageButton)findViewById(R.id.up1);
down1=(ImageButton)findViewById(R.id.down1);
dosage1=(EditText)findViewById(R.id.text1);
up2=(ImageButton)findViewById(R.id.up2);
down2=(ImageButton)findViewById(R.id.down2);
dosage2=(EditText)findViewById(R.id.text2);
up3=(ImageButton)findViewById(R.id.up3);
down3=(ImageButton)findViewById(R.id.down3);
dosage3=(EditText)findViewById(R.id.text3);
//dosage1.setText("1");
up1.setOnClickListener(this);
up2.setOnClickListener(this);
up3.setOnClickListener(this);
down1.setOnClickListener(this);
down2.setOnClickListener(this);
down3.setOnClickListener(this);
//ailment = (EditText)findViewById(R.id.atxt);
//comment = (EditText)findViewById(R.id.ctxt);
//presc=(EditText)findViewById(R.id.presc_id);
edit = (Button)findViewById(R.id.save);
// new GetDosage().execute();
edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new GetMedname().execute();
new EditDosageDetails().execute();
}
});
}
private class GetMedname extends AsyncTask<String, Void, String> {
// JSONObject product;
protected String doInBackground(String... args) {
runOnUiThread(new Runnable() {
public void run() {
// Check for success tag
int success;
try {
String med1 = medicine.getText().toString();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("medicine_name",med1));//search1.getText().toString()));
JSONObject json = jsonParser.makeHttpRequest(
url_getmedname, "GET", params);
// check your log for json response
Log.d("Single Product Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
JSONArray productObj = json
.getJSONArray(TAG_PRODUCT); // JSON Array
// get first product object from JSON Array
JSONObject product = productObj.getJSONObject(0);
if(product!= null){
// display product data in EditText
medicine.setText(product.getString(TAG_MED_ID));
}
}else{
// product with pid not found
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
//return product;
return null;
}
}
private class EditDosageDetails extends AsyncTask {
// JSONObject product;
protected String doInBackground(String... args) {
//JSONObject product = null;
//id.setText(100);
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
String med = medicine.getText().toString();
System.out.println("editdosage"+med);
String do1 = dosage1.getText().toString();
String do2 = dosage2.getText().toString();
String do3 = dosage3.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("medicine_id", med));
params.add(new BasicNameValuePair("dosage_id", did));
params.add(new BasicNameValuePair("qty1", do1));
params.add(new BasicNameValuePair("qty2", do2));
params.add(new BasicNameValuePair("qty3", do3));
JSONObject json = jsonParser.makeHttpRequest(url_updatedosage,
"POST", params);
// json success tag
// Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = getIntent();
setResult(100,i);
finish();
// super.onBackPressed();
// closing this screen
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
// }
}
});
//return product;
return null;
// });
// return product;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.items, menu);
//menuSearch = menu.findItem(R.id.delete);
//menuSearch.setVisible(false);
return super.onCreateOptionsMenu(menu);
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.up1:
int a=Integer.parseInt(dosage1.getText().toString());
int b = a+1;
dosage1.setText(new Integer(b).toString());
break;
case R.id.down1:
a=Integer.parseInt(dosage1.getText().toString());
b = a-1;
dosage1.setText(new Integer(b).toString());
break;
case R.id.up2:
a=Integer.parseInt(dosage2.getText().toString());
b = a+1;
dosage2.setText(new Integer(b).toString());
break;
case R.id.down2:
a=Integer.parseInt(dosage2.getText().toString());
b = a-1;
dosage2.setText(new Integer(b).toString());
case R.id.up3:
a=Integer.parseInt(dosage3.getText().toString());
b = a+1;
dosage3.setText(new Integer(b).toString());
break;
case R.id.down3:
a=Integer.parseInt(dosage3.getText().toString());
b = a-1;
dosage3.setText(new Integer(b).toString());
break;
//case R.id.save:
// System.out.println("save pressed");
}
}
}
1)make arraylist null
2)initialize arraylist
3)fill arraylist with your content
4)pass this arraylist to list
Related
I already try to display image in ListView, but I got an error at this line:
status.setImageResource(R.drawable.inprogress);
*setimageresource undefined for String.
I'm trying to display the image based on the status, if status equals to "Compalint in process" and then the in progress icon will display in the ListView.
This my full code:
public class SenaraiSemuaComplaint extends ListActivity {
String stud_staff_ID;
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> listcomplaint;
final Context context = this;
private static String url_listcomplaint = "...";
private static final String TAG_SUCCESS = "success";
private static final String TAG_REGISTER = "register";
private static final String TAG_PID = "pid";
private static final String TAG_DATE = "date";
private static final String TAG_STATUS = "status";
JSONArray register = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listallcomplaint_layout);
getActionBar().setHomeButtonEnabled(true);
String input = getIntent().getStringExtra("stud_staff_ID");
Toast.makeText(this, input, Toast.LENGTH_SHORT).show();
listcomplaint = new ArrayList<HashMap<String, String>>();
new LoadAllComplaint().execute();
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
String location = ((TextView) view.findViewById(R.id.location)).getText()
.toString();
String picture = ((TextView) view.findViewById(R.id.picture)).getText()
.toString();
String input = getIntent().getStringExtra("stud_staff_ID");
Intent in = new Intent(getApplicationContext(),
ViewPage.class);
in.putExtra("location", location);
in.putExtra("picture", picture);
in.putExtra("stud_staff_ID", input);
in.putExtra("pid", pid);
startActivityForResult(in, 100);
}
});
}
public boolean onOptionsItemSelected(MenuItem item){
if(android.R.id.home == item.getItemId()){
finish();
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 100) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
class LoadAllComplaint extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SenaraiSemuaComplaint.this);
pDialog.setMessage("Please wait, Loading Data...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
String input = getIntent().getStringExtra("stud_staff_ID");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("input", input));
JSONObject json = jParser.makeHttpRequest(url_listcomplaint, "GET", params);
Log.d("List Complaint: ", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
register = json.getJSONArray(TAG_REGISTER);
for (int i = 0; i < register.length(); i++) {
JSONObject c = register.getJSONObject(i);
// keep to variable
String pid = c.getString(TAG_PID);
String date = c.getString(TAG_DATE);
String status = c.getString(TAG_STATUS);
if (status.equals("Complaint in process."))
{
status.setImageResource(R.drawable.inprogress);
}
String location = c.getString("location");
String picture = c.getString("picture");
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_PID, pid);
map.put(TAG_DATE, date);
map.put(TAG_STATUS, status);
map.put("location", location);
map.put("picutre", picture);
listcomplaint.add(map);
}
} else {
runOnUiThread(new Runnable()
{
public void run(){
String msgs = "No complaint found, please create new complaint.";
Toast.makeText(getApplicationContext(), msgs, Toast.LENGTH_SHORT).show();
}
});
String i = getIntent().getStringExtra("stud_staff_ID");
Intent in12 = new Intent(getApplicationContext(),ComplaintBaru.class);
in12.putExtra("stud_staff_ID", i);
startActivity(in12);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
SenaraiSemuaComplaint.this, listcomplaint,
R.layout.list_pendaftaran, new String[] {TAG_PID,
TAG_DATE, TAG_STATUS, "location", "picture" },
new int[] {R.id.pid, R.id.inputDate, R.id.inputStatus, R.id.location, R.id.picture});
setListAdapter(adapter);
}
});
}
}
}
I suggest judging by what you want to achieve that handle this in your Adapter for the ListView which would be the adapter you supply to the ListActivity.
In the getView() of your adapter check the value of your TextView and then replace it with a ProgressBar either dynamically or by toggling its visibility by letting it reside in the layout for your rows.
it's require to take ImageView than set to Image
Imageview img=(ImageView)findViewById(R.id.yourimageID).setImageResource(R.drawable.inprogress);
I work in Android App ListView working under a layer fragment by fragment, but I can not make it work. I got an error that says:
setListAdapter method (ListAdapter) is undefined for new Runnable () {}
I do not know what I need to change to get this working.
public class FragmentA extends Fragment {
private String url = "http://192.168.2.150/54_tower/Json_Tower.php";
private static final String J_NAME = "t_name";
private static final String J_NUM = "t_num";
private static final String J_FLOOR = "t_floor";
private static final String J_CLASS = "t_room_class";
private static final String J_TEACHER = "t_room_teacher";
private static final String J_TOILET = "t_toilet";
private static final String J_MAP = "t_map";
private static final String D_NAME = "NAME";
private static final String D_NUM = "NUM";
private static final String D_FLOOR = "FLOOR";
private static final String D_CLASS = "CLASS";
private static final String D_TEACHER = "TEACHER";
private static final String D_TOILET = "TOILET";
private static final String D_MAP = "MAP";
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
Activity act;
ListView ListView1;
JSONArray products = null;
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> MyArrList;
public static FragmentA newInstance(int page, String title) {
FragmentA fragmentFirst = new FragmentA();
Bundle args = new Bundle();
args.putInt("someInt", page);
args.putString("someTitle", title);
fragmentFirst.setArguments(args);
return fragmentFirst;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.main_tower, container, false);
// Permission StrictMode
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
MyArrList = new ArrayList<HashMap<String, String>>();
new LoadAllData().execute();
final ListView lisView1 = (ListView) rootView
.findViewById(R.id.listView1);
lisView1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i = new Intent(getActivity(), Map.class);
startActivity(i);
}
});
return rootView;
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
// Intent intent = act.getIntent();
// act.finish();
// startActivity(intent);
}
}
class LoadAllData extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url, "GET", params);
Log.d("All JSon: ", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
products = json.getJSONArray(TAG_PRODUCTS);
HashMap<String, String> map = new HashMap<String, String>();
// Log.d("TAG JSON",""+data.toString());
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// adding each child node to HashMap key => value
map = new HashMap<String, String>();
map.put(D_NAME, c.getString(J_NAME));
map.put(D_NUM, c.getString(J_NUM));
map.put(D_FLOOR, c.getString(J_FLOOR));
map.put(D_CLASS, c.getString(J_CLASS));
map.put(D_TEACHER, c.getString(J_TEACHER));
map.put(D_TOILET, c.getString(J_TOILET));
map.put(D_MAP, c.getString(J_MAP));
MyArrList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
// Intent i = new Intent(getApplicationContext(),
// NewProductActivity.class);
// Closing all previous activities
// i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
final ArrayList<HashMap<String, String>> MyArrList = new ArrayList<HashMap<String, String>>();
final ListView myList = (ListView) getView().findViewById(
R.id.listView1);
act.runOnUiThread(new Runnable() {
public void run() {
ListAdapter sAdap = new SimpleAdapter(getActivity(),
MyArrList, R.layout.tower_column, new String[] {
D_NAME, D_NUM, D_FLOOR, D_CLASS, D_TEACHER,
D_TOILET, D_MAP }, new int[] { R.id.Name,
R.id.Num, R.id.Floor, R.id.Room_Class,
R.id.Room_Teacher, R.id.Toilet });
myList.setAdapter(sAdap);
}
});
}
}
}
Here is the LogCat: Image LogCat
You do not need to post to the UI thread onPostExecute since you started the task on the UI thread. Remove the runOnUIThread and it should work.
Instead of runOnUIThread just create a Handler and post this runnable to that handler.
Also create the listview as a field of this class and get reference of it in onCreateView or onActivityCreated. I think its causing nullPointerException. The important thing is that you should make Listview as field of the fragment class instead of having it inside local scope of methods.
So i have this problem passing data through 2 activities in my android project, i dont know what am i doing wrong ill try to explain my problem in the simple way possible. i have 2 activities and i want to pass 2 diferent values to a diferent activity. i made this
1 activity:
public class Linhas_pesagem extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
ListAdapter adapter;
String id2;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://10.0.2.2/webprojecto4/ler_linha_doc.php";
// url to get all products list
private static String url_delete_products = "http://10.0.2.2/webprojecto4/eliminar_linha.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "lin_doc";
private static final String TAG_ID = "id";
private static final String TAG_ESTAB = "estab";
private static final String TAG_DATA = "dt";
private static final String TAG_HORA = "hr";
private static final String TAG_QTD = "quantidade";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_lin_products);
Intent i = getIntent();
// getting product id (pid) from intent
id2 = i.getStringExtra(TAG_ID);
// Create button
Button btnCreateProduct = (Button) findViewById(R.id.button1);
// button click event
btnCreateProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
Intent in = new Intent(getApplicationContext(),
Newlin_ProductActivity.class);
in.putExtra(TAG_ID, id2);
startActivity(in);
}
});
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
registerForContextMenu(lv);
// on seleting single product
// launching Edit Product Screen
// on seleting single product
// launching Edit Product Screen
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Linhas_pesagem.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", id2));
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "POST", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String id_estab = c.getString(TAG_ESTAB);
String dt = c.getString(TAG_DATA);
String hr = c.getString(TAG_HORA);
String quantidade = c.getString(TAG_QTD);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_ESTAB, id_estab);
map.put(TAG_DATA, dt);
map.put(TAG_HORA, hr);
map.put(TAG_QTD, quantidade);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
Newlin_ProductActivity.class);
// Closing all previous activities
i.putExtra(TAG_ID, id2);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
adapter = new SimpleAdapter(
Linhas_pesagem.this, productsList,
R.layout.list_lin_items, new String[] { TAG_ID,
TAG_ESTAB, TAG_DATA, TAG_HORA, TAG_QTD},
new int[] { R.id.id, R.id.id_estab, R.id.dt, R.id.hr, R.id.quantidade});
// updating listview
setListAdapter(adapter);
EditText inputSearch = (EditText)findViewById(R.id.editText1);
/**
* Enabling Search Filter
* */
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
((SimpleAdapter) Linhas_pesagem.this.adapter).getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
});
}
}
/*****************************************************************
* Background Async Task to Delete Product
* */
class DeleteProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Linhas_pesagem.this);
pDialog.setMessage("Deleting Product...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Deleting product
* */
protected String doInBackground(String... args) {
String id = args[0];
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", id));
// getting product details by making HTTP request
JSONObject json = jParser.makeHttpRequest(
url_delete_products, "POST", params);
// check your log for json response
Log.d("Delete Product", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// product successfully deleted
// notify previous activity by sending code 100
Intent i = getIntent();
// send result code 100 to notify about product deletion
setResult(100, i);
finish();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo){
getMenuInflater().inflate(R.menu.context, menu);
}
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
switch(item.getItemId()) {
case R.id.item1:
HashMap <String, String> product2 = productsList.get(info.position);
String id9 = product2.get("id");
String id3 = product2.get(TAG_DATA);
String id4 = product2.get(TAG_ESTAB);
String id5 = product2.get(TAG_HORA);
String id6 = product2.get(TAG_QTD);
Intent in = new Intent(this,
Edit_linha_prod.class);
in.putExtra("id", id9);
in.putExtra(TAG_DATA, id3);
in.putExtra(TAG_HORA, id5);
in.putExtra(TAG_ESTAB, id4);
in.putExtra(TAG_QTD, id6);
in.putExtra("TAG_ID", id2);
Toast.makeText(getApplicationContext(), id9,
Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), id2,
Toast.LENGTH_LONG).show();
startActivity(in);
// sending pid to next activity
return true;
case R.id.item2:
HashMap <String, String> product = productsList.get(info.position);
String id = product.get(TAG_ID);
// Starting new intent
new DeleteProduct().execute(id);
Intent in3 = new Intent(getApplicationContext(),
Linhas_pesagem.class);
in3.putExtra(TAG_ID, id2);
Toast.makeText(getApplicationContext(), id2,
Toast.LENGTH_LONG).show();
startActivity(in3);
return true;
default:
return super.onContextItemSelected(item);
}
}
}
2 activity:
public class Edit_linha_prod extends Activity {
EditText inputdtestab;
EditText inputdata;
EditText inputhora;
EditText quantidade;
Button btnSave;
String id9;
String id3;
String id4;
String id5;
String id6;
String id2;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// url to update product
private static final String url_update_product = "http://10.0.2.2/webprojecto4/actualizar_linha.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCT = "lin_doc";
private static final String TAG_ID = "id";
private static final String TAG_ESTAB = "estab";
private static final String TAG_DATA = "dt";
private static final String TAG_HORA = "hr";
private static final String TAG_QTD = "quantidade";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_linha);
// save button
btnSave = (Button) findViewById(R.id.button1);
// getting product details from intent
Intent i = getIntent();
// getting product id (pid) from intent
id9 = i.getStringExtra("id");
id3 = i.getStringExtra(TAG_DATA);
id4 = i.getStringExtra(TAG_ESTAB);
id5 = i.getStringExtra(TAG_HORA);
id6 = i.getStringExtra(TAG_QTD);
id2= i.getStringExtra(TAG_ID);
Toast.makeText(getApplicationContext(), id9,
Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), id2,
Toast.LENGTH_LONG).show();
inputdata = (EditText) findViewById(R.id.editdata);
inputdtestab = (EditText) findViewById(R.id.editestab);
inputhora = (EditText) findViewById(R.id.edithora);
quantidade = (EditText) findViewById(R.id.editquantidade);
// display product data in EditText
inputdata.setText(id3);
inputdtestab.setText(id4);
inputhora.setText(id5);
quantidade.setText(id6);
// Getting complete product details in background thread
// save button click event
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// starting background task to update product
new SaveProductDetails().execute();
}
});
}
/**
* Background Async Task to Save product Details
* */
class SaveProductDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Edit_linha_prod.this);
pDialog.setMessage("Saving product ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Saving product
* */
protected String doInBackground(String... args) {
// getting updated data from EditTexts
String data = inputdata.getText().toString();
String estab = inputdtestab.getText().toString();
String hora = inputhora.getText().toString();
String quantidades = quantidade.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", id9));
params.add(new BasicNameValuePair("id_produto", "00000"));
params.add(new BasicNameValuePair("id_tipo_produto", "00"));
params.add(new BasicNameValuePair("id_estab", estab));
params.add(new BasicNameValuePair("quantidade", quantidades));//ir buscar criar
params.add(new BasicNameValuePair("dt", data));
params.add(new BasicNameValuePair("hr", hora));
// sending modified data through http request
// Notice that update product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_update_product,
"POST", params);
// check json success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully updated
Intent i = getIntent();
Intent i2 = new Intent(getApplicationContext(), Linhas_pesagem.class);
i2.putExtra("TAG_ID", id2);
startActivity(i2);
// send result code 100 to notify about product update
setResult(100, i);
finish();
} else {
// failed to update product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product uupdated
pDialog.dismiss();
}
}
}
So in my 1 activity i pass in the context menu item 1 the values that i want the id9 and id2, ive made a toast to see what values they are passing, and they pass the way i want 637 and 8
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
switch(item.getItemId()) {
case R.id.item1:
HashMap <String, String> product2 = productsList.get(info.position);
String id9 = product2.get("id");
String id3 = product2.get(TAG_DATA);
String id4 = product2.get(TAG_ESTAB);
String id5 = product2.get(TAG_HORA);
String id6 = product2.get(TAG_QTD);
Intent in = new Intent(this,
Edit_linha_prod.class);
in.putExtra("id", id9);
in.putExtra(TAG_DATA, id3);
in.putExtra(TAG_HORA, id5);
in.putExtra(TAG_ESTAB, id4);
in.putExtra(TAG_QTD, id6);
in.putExtra("TAG_ID", id2);
Toast.makeText(getApplicationContext(), id9,
Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), id2,
Toast.LENGTH_LONG).show();
startActivity(in);
// sending pid to next activity
return true;
on my 2 activity i get the values of this 2 variables but they are the same 637 and 637 instead of 637 and 8
Intent i = getIntent();
// getting product id (pid) from intent
id9 = i.getStringExtra("id");
id3 = i.getStringExtra(TAG_DATA);
id4 = i.getStringExtra(TAG_ESTAB);
id5 = i.getStringExtra(TAG_HORA);
id6 = i.getStringExtra(TAG_QTD);
id2= i.getStringExtra(TAG_ID);
Toast.makeText(getApplicationContext(), id9,
Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), id2,
Toast.LENGTH_LONG).show();
because you are using the same key for both id9 and id2, which is "id" (notice that the constant TAG_ID has the value of "id" as well), so simply make sure that all of the keys you are using are different.
so your activity 1 should be something like this, (notice that i removed the quotes around the constant TAG_ID)
in.putExtra("id9", id9);
in.putExtra(TAG_DATA, id3);
in.putExtra(TAG_HORA, id5);
in.putExtra(TAG_ESTAB, id4);
in.putExtra(TAG_QTD, id6);
in.putExtra(TAG_ID, id2);
and activity 2 :
id9 = i.getStringExtra("id9");
id3 = i.getStringExtra(TAG_DATA);
id4 = i.getStringExtra(TAG_ESTAB);
id5 = i.getStringExtra(TAG_HORA);
id6 = i.getStringExtra(TAG_QTD);
id2= i.getStringExtra(TAG_ID);
in.putExtra("id", id9);
in.putExtra(TAG_DATA, id3);
in.putExtra(TAG_HORA, id5);
in.putExtra(TAG_ESTAB, id4);
in.putExtra(TAG_QTD, id6);
in.putExtra("TAG_ID", id2);
It looks like you've stored "TAG_ID" as the key here instead of the variable TAG_ID
I have a API which responds in JSON. When I clicked a button I am comfortably parse the JSON and implement it in the listview. The problem is When I go back to the previous activity and clicked the button once again I am getting the values repeat. i.e. previous values also, even I had called finish(); in on pause state of the listview activity. Following is my code.
Invoice Class
public class Invoice extends Activity{
public static ArrayList<HashMap<String, String>> ModuleName = new ArrayList<HashMap<String, String>>();
boolean tree = true;
ArrayList<String> KEY = new ArrayList<String>();
ListView mListView;
ProgressBar mProgress;
JSONObject json;
JSONArray Module_list = null;
Invoice_adapter adapter;
public static String KEY_SUCCESS = "success";
public static String KEY_ERROR = "error";
public static String KEY_ERROR_MSG = "error_msg";
public static String KEY_MODULELIST_MODULEHEADER = "moduleHeader";
public static String KEY_MODULELIST_MODULELIST = "moduleList";
public static String KEY_MODULELIST_DATAFOUND = "datafound";
public static String KEY_INVOICE_INVOICENO = "";
public static String KEY_INVOICE_SUBJECT = "";
public static String KEY_INVOICE_SALESORDER = "";
public static String KEY_INVOICE_STATUS = "";
public static String KEY_INVOICE_TOTAL = "";
public static String KEY_INVOICE_ASSIGNEDTO = "";
public static String KEY_INVOICE_RECORDID = "";
public static String KEY_INVOICE_ACTION = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_module_data);
mListView = (ListView) findViewById(R.id.module_list);
mProgress = (ProgressBar) findViewById(R.id.progressBar1);
try {
json = new ParseDATA().execute().get();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ExecutionException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
String data_found = json.getString(KEY_MODULELIST_DATAFOUND);
if (data_found.equals("Data Found!")){
JSONArray array = json.getJSONArray(KEY_MODULELIST_MODULELIST);
int count1 = array.length();
String Count1 = Integer.toString(count1);
Log.d("Count_array", Count1);
JSONObject keyarray = array.getJSONObject(0);
#SuppressWarnings("rawtypes")
Iterator temp = keyarray.keys();
while (temp.hasNext()) {
String curentkey = (String) temp.next();
KEY.add(curentkey);
}
Collections.sort(KEY, String.CASE_INSENSITIVE_ORDER);
KEY_INVOICE_ACTION = KEY.get(0);
KEY_INVOICE_ASSIGNEDTO = KEY.get(1);
KEY_INVOICE_INVOICENO = KEY.get(2);
KEY_INVOICE_RECORDID = KEY.get(3);
KEY_INVOICE_SALESORDER = KEY.get(4);
KEY_INVOICE_STATUS = KEY.get(5);
KEY_INVOICE_SUBJECT = KEY.get(6);
KEY_INVOICE_TOTAL = KEY.get(7);
Log.d("Parsing Json class", " ---- KEYS---- " + KEY);
Module_list = json.getJSONArray(KEY_MODULELIST_MODULELIST);
int count = Module_list.length();
String Count = Integer.toString(count);
Log.d("Count_Module_LIST", Count);
// looping through All Contacts
for(int i = 0; i < Module_list.length(); i++){
JSONObject c = Module_list.getJSONObject(i);
// Storing each json item in variable
String mAction = c.getString(KEY_INVOICE_ACTION);
String mAssignedTo = c.getString(KEY_INVOICE_ASSIGNEDTO);
String mInvoice = c.getString(KEY_INVOICE_INVOICENO);
String mRecordid = c.getString(KEY_INVOICE_RECORDID);
String mSalesorder = c.getString(KEY_INVOICE_SALESORDER);
String mStatus = c.getString(KEY_INVOICE_STATUS);
String mSubject = c.getString(KEY_INVOICE_SUBJECT);
String mTotal = c.getString(KEY_INVOICE_TOTAL);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_INVOICE_ACTION, mAction);
map.put(KEY_INVOICE_ASSIGNEDTO, mAssignedTo);
map.put(KEY_INVOICE_INVOICENO, mInvoice);
map.put(KEY_INVOICE_RECORDID, mRecordid);
map.put(KEY_INVOICE_SALESORDER, mSalesorder);
map.put(KEY_INVOICE_STATUS, mStatus);
map.put(KEY_INVOICE_SUBJECT, mSubject);
map.put(KEY_INVOICE_TOTAL, mTotal);
// adding HashList to ArrayList
ModuleName.add(map);
}
}else
{
Toast.makeText(getApplicationContext(), "No Data", Toast.LENGTH_LONG).show();
return;
}
}
mProgress.setVisibility(View.INVISIBLE);
adapter = new Invoice_adapter(Invoice.this, ModuleName);
mListView.setAdapter(adapter);
mListView.setVisibility(View.VISIBLE);
//mListView.invalidateViews();
}
else
{
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_ERROR, "Error");
ModuleName.add(map);
//JSONObject json_user = json.getJSONObject("user");
//error_message = json_user.getString(KEY_ERROR_MSG);
}
}catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Something went wrong.Please try again.!!", Toast.LENGTH_LONG).show();
}
}
class ParseDATA extends AsyncTask<Void, String,JSONObject >
{
ProgressDialog dialog = new ProgressDialog(Invoice.this);
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setTitle("Loading");
dialog.setIndeterminate(true);
dialog.setMessage("Please wait");
dialog.setCancelable(false);
dialog.show();
}
#Override
protected JSONObject doInBackground(
Void... params) {
// TODO Auto-generated method stub
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.getModuleList("1", "20", "Invoice");
return json;
}
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
dialog.dismiss();
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
Toast.makeText(getApplicationContext(), "PAUSE STATE", Toast.LENGTH_LONG).show();
finish();
}}
Adapter class
public class Invoice_adapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public Invoice_adapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return data.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.activity_module_data_detail, null);
TextView title = (TextView)vi.findViewById(R.id.textView1); // category title name
//ImageView moduleImage = (ImageView) vi.findViewById(R.id.recipe_image);
HashMap<String, String> song = new HashMap<String, String>();
song = data.get(position);
Log.i("list", ""+data.get(position));
//Log.i("list", data);
String ff = song.get(Invoice.KEY_INVOICE_SUBJECT);
title.setText(ff);
//moduleImage.setImageResource(mModuleImages[position]);
return vi;
}}
Please Help.. !! I dnt know what Is I am doing wrong.
Thanks in advance.
The problem is with the "static" key word for the ArrayList
public static ArrayList<HashMap<String, String>> ModuleName = new ArrayList<HashMap<String, String>>();
static variables are initialized only when the class is loaded, that means the value will be persisted till the end of the application process.
Either remove static keyword for array list or clear the array list before you load new data.
ModuleName.clear();
When I am clicking on my list items only the 1st item's id is going to the next activity. As I am getting patient name and id in this list fragment and passing the patient id to another activity, only the 1st list item's id is passing through even if I tap on another item... Hope you got my point...
Here is my ListFragment,
public class AllPatient extends ListFragment {
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList = new ArrayList<HashMap<String,String>>();
// url to get all products list
private static String url_all_patients = "http://192.168.44.208/get_all_patients.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PATIENT_ID = "patient_id";
private static final String TAG_PATIENT_NAME = "patient_name";
JSONArray products = null;
Context ctx;
String pid;
EditText inputSearch = null;
ListAdapter adapter;
ListView lv;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.patient_list, container, false);
//ListView lv;
lv = (ListView)view.findViewById(android.R.id.list);
//ListView v = getListView();
new LoadAllPatients().execute();
return view;
}
#Override
public void onListItemClick(ListView lv, View v, int position, long id) {
// TODO Auto-generated method stub
onAttach(getActivity());
//lv.setAdapter(adapter);
String id1 = ((TextView) getView().findViewById(R.id.pid)).getText().toString();
System.out.println("all patient"+id1);
Bundle bundle = new Bundle();
bundle.putString("TAG_PATIENT_ID",id1 );
System.out.println("bundle"+id1);
Intent i = new Intent(getActivity(),DocPresc.class);
i.putExtras(bundle);
startActivity(i);
//passData(date);
Toast.makeText(
getActivity(),
getListView().getItemAtPosition(position).toString(),
Toast.LENGTH_LONG).show();
}
class LoadAllPatients extends AsyncTask<String, String, String> {
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_patients, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Patients: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PATIENT_ID).toUpperCase();
String name = c.getString(TAG_PATIENT_NAME).toUpperCase();
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PATIENT_ID, id);
map.put(TAG_PATIENT_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
}
} 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
getActivity().runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
getActivity(), productsList,
R.layout.list_item1, new String[] { TAG_PATIENT_ID,
TAG_PATIENT_NAME},
new int[] { R.id.pid, R.id.name });
// updating listview
//setListAdapter(adapter);
setListAdapter(adapter);
}
});
}
}
}
Try this.
Change this line:
String id1 = ((TextView) getView().findViewById(R.id.pid)).getText().toString();
to
String id1 = ((TextView) v.findViewById(R.id.pid)).getText().toString();