Acess listview data from context menu - android

I have created a list view with the following data: id name date and i created a context menu my problem is to retreive the name from the item selected in the context menu option. How can i do this:
#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:
return true;
case R.id.item2:
return true;
default:
return super.onContextItemSelected(item);
}
}
}
my code:
public class AllProductsActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// 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/index_pesagem.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "cab_doc";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "descricao";
private static final String TAG_DATA = "dt_ini_camp";
private static final String TAG_DATA2 = "dt_fim_camp";
private static final String TAG_QTD = "qtd";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_products);
// 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
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String id2 = ((TextView) view.findViewById(R.id.id)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
Linhas_pesagem.class);
// sending pid to next activity
in.putExtra(TAG_ID, id2);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// 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(AllProductsActivity.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
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", 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_ID);
String name = c.getString(TAG_NAME);
String data = c.getString(TAG_DATA);
String data2 = c.getString(TAG_DATA2);
String qtd = 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_NAME, name);
map.put(TAG_DATA, data);
map.put(TAG_DATA2, data2);
map.put(TAG_QTD, qtd);
// adding HashList to ArrayList
productsList.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;
}
/**
* 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
* */
ListAdapter adapter = new SimpleAdapter(
AllProductsActivity.this, productsList,
R.layout.list_item, new String[] { TAG_ID,
TAG_NAME, TAG_DATA, TAG_DATA2, TAG_QTD},
new int[] { R.id.id, R.id.descricao, R.id.data, R.id.data2, R.id.qtd});
// updating listview
setListAdapter(adapter);
}
});
}
}
#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:
return true;
case R.id.item2:
return true;
default:
return super.onContextItemSelected(item);
}
}
}

The info.position is the index in the collection of the element that was pressed to invoke the context menu. So YourObject temp = yourCollection.get(info.position); will give you the whole object.
EDIT:
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
HashMap <String, String> product = productsList.get(info.position);
String name = product.get(TAG_NAME);
//name contians the name of the product, similarly you can get the others
}

Related

passing data between 2 activities android

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

Getting JSON VALUE in mySQL using android

I have a problem getting a json value in PHP(mySQL). How can i get the value of totaly in the php page. I just want the value of totaly. Please help me. I am newbie in android programming.
This is my php page.
{"sales":[{"pid":"1","name":"book of eden","number_to_sale":"2","price":"2.00","total":"4.00","created_at":"2014-02-02 11:31:53"},{"pid":"2","name":"shirt","number_to_sale":"2","price":"500.00","total":"1000.00","created_at":"2014-02-03 14:23:49"},{"pid":"3","name":"mars","number_to_sale":"2","price":"2.00","total":"4.00","created_at":"2014-02-03 21:07:48"},{"pid":"4","name":"shirt","number_to_sale":"1","price":"500.00","total":"500.00","created_at":"2014-02-07 12:05:18"},{"pid":"5","name":"item2","number_to_sale":"4","price":"400.00","total":"1600.00","created_at":"2014-02-12 13:57:49"},{"pid":"6","name":"shirt","number_to_sale":"2","price":"500.00","total":"1000.00","created_at":"2014-02-12 15:42:04"}],"success":1}
[{"totaly":"4108.00"}]
and this is my activity in android
package com.sales;
public class AllSalesActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
AdminJSONParser jParser = new AdminJSONParser();
ArrayList<HashMap<String, String>> salesList;
// url to get all products list
private static String url_all_products = "http://10.0.2.2/android_supplyinfo/sales/get_all_sales.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_SALES = "sales";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_DATE= "created_at";
private static final String TAG_TOTAL_ALL= "totaly";
// products JSONArray
JSONArray sales = null;
JSONArray wtf = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sales_all);
// Hashmap for ListView
salesList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
EditSalesActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
Button btnBacktoMain = (Button)findViewById(R.id.btnBackMain);
btnBacktoMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(), DashboardActivity.class);
startActivity(i);
}
});
}
// 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(AllSalesActivity.this);
pDialog.setMessage("Loading sales. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
sales = json.getJSONArray(TAG_SALES);
// looping through All Products
for (int i = 0; i < sales.length(); i++) {
JSONObject c = sales.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
String date = c.getString(TAG_DATE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
map.put(TAG_DATE, date);
// adding HashList to ArrayList
salesList.add(map);
}
JSONArray wtf = new JSONArray("");
for (int i = 0; i < wtf.length(); i++) {
JSONObject total = wtf.getJSONObject(i);
TextView txtTotal = (TextView) findViewById(R.id.total_all);
txtTotal.setText(total.getString(TAG_TOTAL_ALL));
}
} else {
// no products found
// Launch Add New product Activity
//Intent i = new Intent(getApplicationContext(),
// AddSalesActivity.class);
// Closing all previous activities
//i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AllSalesActivity.this, salesList,
R.layout.sales_list_item, new String[] { TAG_PID,TAG_NAME,TAG_DATE},new int[] { R.id.pid, R.id.name, R.id.date });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
I am not an expert on JSON-objects, but it seems to me that the php page is not returning the "totaly" part inside your JSON-object. If it instead returned it like this:
{"sales":[{"pid":"1","name":"book of eden","number_to_sale":"2","price":"2.00","total":"4.00","created_at":"2014-02-02 11:31:53"},{"pid":"2","name":"shirt","number_to_sale":"2","price":"500.00","total":"1000.00","created_at":"2014-02-03 14:23:49"},{"pid":"3","name":"mars","number_to_sale":"2","price":"2.00","total":"4.00","created_at":"2014-02-03 21:07:48"},{"pid":"4","name":"shirt","number_to_sale":"1","price":"500.00","total":"500.00","created_at":"2014-02-07 12:05:18"},{"pid":"5","name":"item2","number_to_sale":"4","price":"400.00","total":"1600.00","created_at":"2014-02-12 13:57:49"},{"pid":"6","name":"shirt","number_to_sale":"2","price":"500.00","total":"1000.00","created_at":"2014-02-12 15:42:04"}],"success":1, "totaly":"4108.00"}
Then you could get the "totaly" part like your "success":
int success = json.getInt(TAG_SUCCESS);
String totaly = json.getString(TAG_TOTAL_ALL);

Error parsing data org.json.JSONException: End of input at character 0 of

Error converting result:
java.lang.NullPointerExceptionError parsing data org.json.JSONException: End of input at character 0 of
FATAL EXCEPTION: AsyncTask #1
My code is:
Please help me how to solve this error?
public class AllProductsActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// 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://localhost/android_connect/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_products);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
EditProductActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// 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(AllProductsActivity.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
List<NameValuePair> params = new ArrayList<NameValuePair>();
// JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
try {
if (json.getString(TAG_SUCCESS) != null)
{
if(json != null && !json.isNull(TAG_SUCCESS))
{
// Check your log cat for JSON reponse
Log.d("All Products: ", 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_PID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.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();
}
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
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
* */
ListAdapter adapter = new SimpleAdapter(
AllProductsActivity.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME},
new int[] { R.id.pid, R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}

Fragment list data not passing correctly to activity

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();

Delete refresh listview in Android

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

Categories

Resources