Android: can't get doInBackground result in OnPostExecute method in an Asynctask - android

I have a problem with an Asynctask, I can't get the return values of the doInBackground method in the OnPostExecute, can you help me?
I setted the return value of the Asynctask as an Integer, and the value that I'm returning is an int, so why does the app stop on the return of the doInBackground?
If you can explain to me how the Asynctask works I will really appreciate it.
Thank you very much!!
public class LoginActivity extends Activity
{
ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
Button btnLogin;
Button btnLinkToRegister;
EditText inputEmail;
EditText inputPassword;
TextView loginErrorMsg;
JSONArray user = null;
ArrayList<HashMap<String, String>> userList;
private static String loginURL = "htttp://example.com/query.php";
private static String KEY_SUCCESS = "success";
private static String KEY_EMAIL = "email";
private static String KEY_PASSWORD = "password";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
userList = new ArrayList<HashMap<String, String>>();
inputEmail = (EditText) findViewById(R.id.loginEmail);
inputPassword = (EditText) findViewById(R.id.loginPassword);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
btnLogin.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
new CheckUser().execute();
}
});
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class CheckUser extends AsyncTask<String, String, Integer>
{
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setMessage("Verifica dati inseriti...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected Integer doInBackground(String... args)
{
int valoreOnPostExecute = 0;
String emailInserted = inputEmail.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", emailInserted));
// getting JSON string from URL
JSONObject json = null;
json = jParser.getJSONFromUrl(loginURL, params);
// Check your log cat for JSON response
Log.d("All Users: ", json.toString());
try
{
// Checking for SUCCESS TAG
int success = json.getInt(KEY_SUCCESS);
if (success == 1)
{
// users found
// Getting Array of users
user = json.getJSONArray("utenti");
// looping through All users
for (int i = 0; i < user.length(); i++)
{
JSONObject c = user.getJSONObject(i);
// Storing each json item in variable
String email = c.getString(KEY_EMAIL);
String password = c.getString(KEY_PASSWORD);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_EMAIL, email);
map.put(KEY_PASSWORD, password);
// adding HashList to ArrayList
userList.add(map);
}
// Intent intent = new Intent(LoginActivity.this,GenereMusicale.class);
// startActivity(intent);
valoreOnPostExecute = success;
}
// else
// {
// Log.d("success != 1", json.toString());
// //Toast.makeText(LoginActivity.this, "Username/password non corretti", Toast.LENGTH_SHORT).show();
// }
}
catch (JSONException e)
{
e.printStackTrace();
Log.d("User ARRAY", "user array: "+user);
}
return valoreOnPostExecute;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(int valoreOnPostExecute)
{
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
if(valoreOnPostExecute == 1)
{
Intent intent = new Intent(LoginActivity.this,GenereMusicale.class);
startActivity(intent);
}
else
{
new AlertDialog.Builder(LoginActivity.this)
.setTitle("Fine del Round!")
//.setMessage("Terminare round?")
//.setNegativeButton(android.R.string.no, null)
.setPositiveButton(android.R.string.ok, new OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
finish();
}
}).create().show();
}
}
}
}

Your return type from doInBackground() and receiving type in onPostExecute() does not match
try like this
class CheckUser extends AsyncTask<String, String, Integer>
protected Integer doInBackground(String... args)
protected void onPostExecute(Integer valoreOnPostExecute)

Related

Error in viewing all info from MYSQL database in android

In AllProductActivity.java where data is view in list form. On onItemClick depending on pid data move to next EditProductActivity.
Following code is working fine in eclipse but while working in Android Studio activity unfortunately stopped. why I just don't get it if anyone know it.
Logcat for error
Please help me.
AllProductActivity.java
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://192.168.1.2/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>();
// 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_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();
}
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);
}
});
}
}
}
EditProductActivity.java
public class EditProductActivity extends Activity {
EditText txtName;
EditText txtPrice;
EditText txtDesc;
EditText txtCreatedAt;
Button btnSave;
Button btnDelete;
String pid;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// single product url
private static final String url_product_detials = "http://192.168.1.2/android_connect/get_product_details.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCT = "product";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_PRICE = "price";
private static final String TAG_DESCRIPTION = "description";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_product);
// save button
btnSave = (Button) findViewById(R.id.btnSave);
btnDelete = (Button) findViewById(R.id.btnDelete);
// getting product details from intent
Intent i = getIntent();
// getting product id (pid) from intent
pid = i.getStringExtra(TAG_PID);
// Getting complete product details in background thread
new GetProductDetails().execute();
// save button click event
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// starting background task to update product
}
});
// Delete button click event
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// deleting product in background thread
}
});
}
/**
* Background Async Task to Get complete product details
*/
class GetProductDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EditProductActivity.this);
pDialog.setMessage("Loading product details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting product details in background thread
*/
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("pid", pid));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_product_detials, "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);
// product with this pid found
// Edit Text
txtName = (EditText) findViewById(R.id.inputName);
txtPrice = (EditText) findViewById(R.id.inputPrice);
txtDesc = (EditText) findViewById(R.id.inputDesc);
// display product data in EditText
txtName.setText(product.getString(TAG_NAME));
txtPrice.setText(product.getString(TAG_PRICE));
txtDesc.setText(product.getString(TAG_DESCRIPTION));
} else {
// product with pid not found
}
} 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 got all details
pDialog.dismiss();
}
}
}
Logcat error:-
Process: info.androidhive.androidphpconnection, PID: 10068
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)
at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:110)
at libcore.io.IoBridge.connectErrno(IoBridge.java:137)
at libcore.io.IoBridge.connect(IoBridge.java:122)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:452)
at java.net.Socket.connect(Socket.java:884)
at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:124)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:149)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:169)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:124)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:366)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:560)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:492)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:470)
at info.androidhive.androidphpconnection.JSONParser.makeHttpRequest(JSONParser.java:62)
at info.androidhive.androidphpconnection.EditProductActivity$GetProductDetails$1.run(EditProductActivity.java:131)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Reason : Calling networking stuff on UI thread. This line
JSONObject json = jsonParser.makeHttpRequest(
url_product_detials, "GET", params);
1.runOnUiThread runs on UI thread and where you never ever make HTTP/networking stuff.
2.
doInBackGround runs on worker thread where you can make http/networking stuff.
3. No need to call runOnUiThread inside onPreExecute and onPostExecute because these method run on UI thread only.
you code changes go like this.
protected String doInBackground(String... args) {
// Check for success tag
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("pid", pid));
final JSONObject json = jsonParser.makeHttpRequest(
url_product_detials, "GET", params);
final int success = json.getInt(TAG_SUCCESS);
//below code runs on UI thread.
runOnUiThread(new Runnable() {
public void run() {
if (success == 1) {
// successfully received product details
try {
JSONArray productObj = json.getJSONArray(TAG_PRODUCT); // JSON Array
// get first product object from JSON Array
JSONObject product = productObj.getJSONObject(0);
// product with this pid found
// Edit Text
txtName = (EditText) findViewById(R.id.inputName);
txtPrice = (EditText) findViewById(R.id.inputPrice);
txtDesc = (EditText) findViewById(R.id.inputDesc);
// display product data in EditText
txtName.setText(product.getString(TAG_NAME));
txtPrice.setText(product.getString(TAG_PRICE));
txtDesc.setText(product.getString(TAG_DESCRIPTION));
} catch (JSONException e) {
}
} else {
// product with pid not found
}
}
});
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}

How to pass value from text view to variable for other activities in Android?

I am having a problem assigning a Text-view result [from database] to a new variable.
Text-view retrieve data from database no issue.
Now issue is i need to link the value "4" in the Text-view to a new variable. Then use button function for my next activity.
public class MainActivity extends Activity {
TextView name1;
TextView rating1;
TextView sourse1;
Button Btngetdata;
int ratingvalue;
// URL to get contacts JSON
private static String url = "http://lawrencetucksoon.netau.net/json_get_data.php";
// JSON Node names
private static final String TAG_APPINFO = "appinfo";
private static final String TAG_NAME = "name";
//private static final String TAG_UPDATE_PATCH = "update patch";
//private static final String TAG_PUBLISH_YEAR = "publish year";
private static final String TAG_RATING = "rating";
private static final String TAG_SOURSE = "sourse";
JSONArray app = null;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name1 = (TextView) findViewById(R.id.name);
rating1 = (TextView) findViewById(R.id.rating);
sourse1 = (TextView) findViewById(R.id.sourse);
Btngetdata=(Button)findViewById(R.id.btn1);
Btngetdata = (Button)findViewById(R.id.btn1);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
System.out.println(ratingvalue);
}
});
}
public void selectapp (View view)
{
boolean checked = ((RadioButton) view).isChecked();
switch (view.getId())
{
case R.id.radio_365:
if (checked)
{
new JSONParse().execute();
if((Integer.parseInt(rating1.getText().toString()) ) <=3)
{
ratingvalue =0;
}
else
{
ratingvalue = 1;
}
}
break;
case R.id.radio_candy: //if (R.id.rating > 3){
// ratingvalue = 0;
if (checked)
{
new JSONParse1().execute();
}
// else
// {
// ratingvalue = 1;
// }
// }
break;
case R.id.radio_FB:
if (checked)
{
new JSONParse().execute();
}
break;
case R.id.radio_summoner:
if (checked)
{
new JSONParse1().execute();
}
break;
}
}
/**
* Async task class to get json by making HTTP call
*/
private class JSONParse extends AsyncTask<Void, Void, JSONObject> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
name1 = (TextView) findViewById(R.id.name);
rating1 = (TextView) findViewById(R.id.rating);
sourse1 = (TextView) findViewById(R.id.sourse);
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(Void... args) {
// Creating service handler class instance
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
//super.onPostExecute(result);
// Dismiss the progress dialog
// if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
try {
// Getting JSON Array
app = json.getJSONArray(TAG_APPINFO);
JSONObject c = app.getJSONObject(0);
// Storing JSON item in a Variable
String name = c.getString(TAG_NAME);
String rating = c.getString(TAG_RATING);
String sourse = c.getString(TAG_SOURSE);
//Set JSON Data in TextView
name1.setText(name);
rating1.setText(rating);
sourse1.setText(sourse);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private class JSONParse1 extends AsyncTask<Void, Void, JSONObject> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
name1 = (TextView) findViewById(R.id.name);
rating1 = (TextView) findViewById(R.id.rating);
sourse1 = (TextView) findViewById(R.id.sourse);
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(Void... args) {
// Creating service handler class instance
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
//super.onPostExecute(result);
// Dismiss the progress dialog
// if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
try {
// Getting JSON Array
app = json.getJSONArray(TAG_APPINFO);
JSONObject c = app.getJSONObject(1);
// Storing JSON item in a Variable
String name = c.getString(TAG_NAME);
String rating = c.getString(TAG_RATING);
String sourse = c.getString(TAG_SOURSE);
//Set JSON Data in TextView
name1.setText(name);
rating1.setText(rating);
sourse1.setText(sourse);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
In first activity you need to pass argument to intent
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("param", myTextView.getText().toString());
startActivity(intent);
Then in second activity's onCreate
Intent intent = getIntent()
String value = intent.getStringExtra("param", null);
You can do this in many ways. The first one is to declare a static variable and make it public. Then u can access the variable from other activity. For example if you have the TextView on activity A and want to access the value from activity B. In you can declare the variable as
public static String someVariable;
then set the value for the variable whereever you want. After that when activity B is launched access the variable where required. Eg.
...
String variable=A.someVariable;
...
although this method is simple it is not considered to be a good option. The good option is to send the value in intents. For the intents see here

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

FATAL EXCEPTION : AsyncTask#5

They have mentionned that the ERROR was occured while excecuting doInBackground()
public class NewClientActivity extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText name;
EditText login;
EditText password;
EditText rePassword;
EditText email;
EditText adresse;
EditText tel;
// url to create new product
private static String url_add_client = "http://192.168.1.3/android_connect/add_client.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity1);
// Edit Text
name = (EditText) findViewById(R.id.textViewNom);
login = (EditText) findViewById(R.id.textViewLogin);
password = (EditText) findViewById(R.id.textViewPassword);
rePassword = (EditText) findViewById(R.id.textViewPassword1);
email = (EditText) findViewById(R.id.textViewEmail);
adresse = (EditText) findViewById(R.id.textViewAdresse);
tel = (EditText) findViewById(R.id.textViewTel);
// Create button
Button btnAddClient = (Button) findViewById(R.id.connect);
// button click event
btnAddClient.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
new CreateNewProduct().execute();
}
});
}
/**
* Background Async Task to Create new product
* */
class CreateNewProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewClientActivity.this);
pDialog.setMessage("Adding Customer to DataBase..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
String Name = name.getText().toString();
String Login = login.getText().toString();
String Password = password.getText().toString();
// String RePassword = rePassword.getText().toString();
String Email = email.getText().toString();
String Adresse = adresse.getText().toString();
String Tel = tel.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Name", Name));
params.add(new BasicNameValuePair("Login", Login));
params.add(new BasicNameValuePair("Password", Password));
params.add(new BasicNameValuePair("Email", Email));
params.add(new BasicNameValuePair("Adresse", Adresse));
params.add(new BasicNameValuePair("Tel", Tel));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_add_client,
"POST", params);
// check log cat fro response
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 = new Intent(getApplicationContext(), AllProductsActivity.class);
// startActivity(i);
// closing this screen
// finish();
} else {
Toast.makeText(getApplicationContext(), "L'inscription n'a pas été éfectuée correctement", Toast.LENGTH_SHORT).show(); }
} 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 done
pDialog.dismiss();
}
}
}
Please if you can check it out and tell me where the ERROR is ??
thank you in advance !!
just override into your AsyncTask the method onProgressUpdate
class CreateNewProduct extends AsyncTask<String, String, String> {
...
...
#Override
protected void onProgressUpdate(String... values) {
Toast.makeText(getApplicationContext(), values[0], Toast.LENGTH_SHORT).show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
...
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
// Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
// startActivity(i);
// closing this screen
// finish();
} else {
publishProgress("L'inscription n'a pas été éfectuée correctement");
}
} catch (JSONException e) {
e.printStackTrace();
}
...
}
}
I believe the error is because you are trying to update the UI in the doInBackground method of the AsyncTask.
Toast.makeText(getApplicationContext(), "L'inscription n'a pas été éfectuée correctement", Toast.LENGTH_SHORT).show();
Move the above code to postExecute.
Also the following code in doInBackground wouldn't possibly cause an error to occur
String Name = name.getText().toString();
String Login = login.getText().toString();
String Password = password.getText().toString();
String Email = email.getText().toString();
String Adresse = adresse.getText().toString();
String Tel = tel.getText().toString();
Forget ASyncTask,
Android Annotations is the better solution!
Look this:
https://github.com/excilys/androidannotations/wiki
Toast.makeText(getApplicationContext(), "L'inscription n'a pas été éfectuée correctement", Toast.LENGTH_SHORT).show();
You are trying to update ui from the background thread ie displaying toast.
Display toast in onPostExecute() or use runonuithread
runOnUiThread(new Runnable() //run on ui thread
{
public void run()
{
Toast.makeText(NewClientActivity.this,"mymessage", 1000).show();
}
});
Use a activity context in place of getApplicationContext()
When to call activity context OR application context?
For more information check the link below .
http://developer.android.com/reference/android/os/AsyncTask.html

check text boxes if written android

i want your help in something
i am looking to put a code that can check if the text boxes are empty or not
if the text boxes are empty i want to show a text messg saying that informations are incomplete and if not we continue our processus
the problem that i am not knowing where should i write the if condition to check if the text boxes are empty or not
please check my code :
public class register extends Activity {
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputName;
EditText inputUser;
EditText inputPass;
EditText inputAge;
EditText inputBloodType;
// url to create new product
private static String url_create_product = "http://10.0.2.2/blood_needed/create_product.php" ;
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
inputName = (EditText) findViewById(R.id.editText1);
inputUser = (EditText) findViewById(R.id.editText5);
inputPass = (EditText) findViewById(R.id.editText3);
inputAge = (EditText) findViewById(R.id.editText2);
inputBloodType = (EditText) findViewById(R.id.editText4);
// Create button
Button btnRegister = (Button) findViewById(R.id.Button01);
// button click event
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
new CreateNewProduct().execute();
}
});}
class CreateNewProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(register.this);
pDialog.setMessage("Regestering..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
String name = inputName.getText().toString();
String user = inputUser.getText().toString();
String pass = inputPass.getText().toString();
String age = inputAge.getText().toString();
String bloodtype = inputBloodType.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("username", user));
params.add(new BasicNameValuePair("password", pass));
params.add(new BasicNameValuePair("age", age));
params.add(new BasicNameValuePair("bloodtype", bloodtype));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
Toast.makeText(getBaseContext(), "Succes!", Toast.LENGTH_SHORT).show();
// dismiss the dialog once done
pDialog.dismiss();
}}
Put it in onClick()
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
String name = inputName.getText().toString();
String user = inputUser.getText().toString();
String pass = inputPass.getText().toString();
String age = inputAge.getText().toString();
String bloodtype = inputBloodType.getText().toString();
if(user.equals("") || pass.equals("") || age.equals("") || bloodtype.equals("") || name.equals("")){
// add message here
}else{
new CreateNewProduct().execute();
}
}
});}

Categories

Resources