I'm trying put the all alert box in my code.. but still can't run... when the editText in empty or null. It will show a dialog box which is needed to be filled by user. I've already tried all the steps and all dialog alert box. But it still functional. but in my case... this is more than 3 edittext involve. Just need an opinion where should I put the code for error empty edittext and need user fill it before they push the button.
JSONParser jsonParser = new JSONParser();
EditText inputName;
EditText inputPrice;
EditText inputDesc;
// url to create new product
private static String url_create_product = "http://192.168.0.102/android_connect/create_product.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
//private static final CharSequence TITLE_DIALOG = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_product);
// Edit Text
inputName = (EditText) findViewById(R.id.inputName);
inputPrice = (EditText) findViewById(R.id.inputPrice);
inputDesc = (EditText) findViewById(R.id.inputDesc);
// Create button
Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct);
// button click event
btnCreateProduct.setOnClickListener(new View.OnClickListener() {
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();
ProgressDialog pDialog = new ProgressDialog(NewProductActivity.this);
pDialog.setMessage("Creating Product..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
List<EditText> editTextList = new ArrayList<EditText>();
//editTextList.add(myEditText);
String name = inputName.getText().toString();
String price = inputPrice.getText().toString();
String description = inputDesc.getText().toString();
for(EditText inputName : editTextList)
{
if (name == null || inputName.getText().toString().length() == 0)
{
Context context = getApplicationContext();
CharSequence error = "Please enter a track name" + name;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, error, duration);
toast.show();
}
else {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("price", price));
params.add(new BasicNameValuePair("description", description));
// 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
Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
startActivity(i);
// 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) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
I actually would do this quite a bit differently... The error checking code should be a part of the Dialog onClick button. Check to see if all of the values are entered, and if they are not, put an indicator that the user needs to fill in that box, all while not finishing the dialog. Here's an example of this from one of my programs, in this case, getting a name to add to a high scores routine.
EditText input;
input=new EditText(this.getApplicationContext());
final int index=i;
new AlertDialog.Builder(this)
.setTitle("Update Status")
.setMessage(R.string.getName)
.setView(input)
.setPositiveButton(sayings_array[rnum], new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Editable value = input.getText();
String name=value.toString();
if (name!=null)
{
addToHighScore(name,level,score,index);
dialog.dismiss();
}
}
}).show();
Check Edittext for null before starting AsyncTask execution. just first check EditText for empty on button click first then start CreateNewProduct AsyncTask . change your code as:
// button click event
btnCreateProduct.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String name = inputName.getText().toString();
String price = inputPrice.getText().toString();
String description = inputDesc.getText().toString();
if (name != null || inputName.getText().toString().length() != 0)
{
if (price != null || price.getText().toString().length() != 0)
{
if (description != null || description.getText().toString().length() != 0)
{
// creating new product in background thread
new CreateNewProduct().execute();
}
else{
//show alert here
}
}else{
//show alert here
}
}else{
//show alert here
}
}
});
Related
There is a listview showing all products. It is supposed that a new activity page which allows me to edit product(either save or delete)will be shown after I click the item on the listview. However, when I click the item, the app stopped with error message: Unfortunately, XXX(my app name) has stopped. Could anyone help ? Thank you !
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.128.0.101/android_connect/get_product_details.php";
// url to update product
private static final String url_update_product = "http://192.128.0.101/android_connect/update_product.php";
// url to delete product
private static final String url_delete_product = "http://192.128.0.101/android_connect/delete_product.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
new SaveProductDetails().execute();
}
});
// Delete button click event
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// deleting product in background thread
new DeleteProduct().execute();
}
});
}
/**
* 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();
}
}
/**
* 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(EditProductActivity.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 name = txtName.getText().toString();
String price = txtPrice.getText().toString();
String description = txtDesc.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_PID, pid));
params.add(new BasicNameValuePair(TAG_NAME, name));
params.add(new BasicNameValuePair(TAG_PRICE, price));
params.add(new BasicNameValuePair(TAG_DESCRIPTION, description));
// 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();
// 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();
}
}
/*****************************************************************
* 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(EditProductActivity.this);
pDialog.setMessage("Deleting Product...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Deleting product
* */
protected String doInBackground(String... args) {
// 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
JSONObject json = jsonParser.makeHttpRequest(
url_delete_product, "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();
}
}
}
You are using UI widgets from AsyncTask background thread:
protected String doInBackground(String... args) {
// getting updated data from EditTexts
String name = txtName.getText().toString();
String price = txtPrice.getText().toString();
String description = txtDesc.getText().toString();
this throws exception. Move this code to onPreExecute (which is called on UI thread) and store in class variables, then use in doInBackground.
If you are using Eclipse, try to enable LogCat, it is in menu:
Window->Show view>Other>LogCat
Surround the code of action of listView with this try-catch, and modify any exception handlig code, to catch any throwable and logging it like this:
try {
// Your code
} catch (Throwable t)
{
Log.e("error","error",t);
}
see the logcat output, should help.
I've got a simple class. It loads data from my localhost and populates in a listview with android:id/list.
I've set a onclick listener to call my delete async task when I click an item.
My profileList.remove(position), works I can't seem to get the notifyDataSetChanged(); method to work and don't know where to place it?
Lastly, Im not sure but I don't think my class is referencing the position of the item I want to delete and matching it with my database? I keep getting "success=0 no profile" found in my LOG.
Any Ideas? I just want my count/listview to be refreshed and my item deleted.
Class:
public class ViewAllLocations extends ListActivity {
String id;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
ArrayList<HashMap<String, String>> profileList;
SimpleAdapter adapter;
// url to get all products list
private static String url_all_profile = "http://MYIP:8888/android_connect/get_all_location.php";
// url to delete product
private static final String url_delete_profile = "http://MYIP:8888/android_connect/delete_location.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_LOCATION = "Location";
private static final String TAG_ID = "id";
private static final String TAG_LATITUDE = "latitude";
private static final String TAG_LONGITUDE = "longitude";
// products JSONArray
JSONArray userprofile = null;
TextView locationCount;
int count = 0;
Button deleteLocation;
ListView lo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_all_locations);
// Hashmap for ListView
profileList = new ArrayList<HashMap<String, String>>();
deleteLocation = (Button) findViewById(R.id.deleteLocation);
locationCount = (TextView) findViewById(R.id.locationCount);
lo = (ListView) findViewById(android.R.id.list);
//setup adapter first //now no items, after getting items (LoadAllLocations) will update it
adapter = new SimpleAdapter(
ViewAllLocations.this, profileList,
R.layout.locationitem, new String[]{TAG_ID,
TAG_LATITUDE, TAG_LONGITUDE},
new int[]{R.id.id, R.id.latitude, R.id.longitude});
// updating listview
setListAdapter(adapter);
// Loading products in Background Thread
new LoadAllLocation().execute();
deleteLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
// getting product details from intent
Intent i = getIntent();
// getting product id (pid) from intent
id = i.getStringExtra(TAG_ID);
// Get listview
ListView lo = getListView();
lo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
new DeleteLocation(position).execute();
Map<String, String> item = profileList.get(position);
String selectedItemId = item.get(TAG_ID);
new DeleteLocation(position).execute(selectedItemId);
}
});
}
/**
* **************************************************************
* Background Async Task to Delete Product
*/
class DeleteLocation extends AsyncTask<String, String, Integer> {
int deleteItemPosition;
public DeleteLocation(int position) {
// TODO Auto-generated constructor stub
this.deleteItemPosition = position;
}
/**
* Before starting background thread Show Progress Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ViewAllLocations.this);
pDialog.setMessage("Deleting Location...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Deleting product
*/
protected Integer doInBackground(String... args) {
String selectedId = args[0];
// Check for success tag
int success = 0; //0=failed 1=success
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", selectedId));
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
url_delete_profile, "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);
//you cant update UI on worker thread, it must be done on UI thread
// Toast.makeText(getApplicationContext(), "Location Deleted",
// Toast.LENGTH_SHORT).show();
//finish();
// }
} catch (JSONException e) {
e.printStackTrace();
}
return success;
}
/**
* After completing background task Dismiss the progress dialog
* *
*/
protected void onPostExecute(Integer result) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (result == 1) {
//success
//delete from list and update listview
profileList.remove(deleteItemPosition);
adapter.notifyDataSetChanged();
} else {
//failed
}
}
}
/**
* Background Async Task to Load all product by making HTTP Request
*/
class LoadAllLocation extends AsyncTask<String, String, Integer> {
int success;
/**
* Before starting background thread Show Progress Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ViewAllLocations.this);
pDialog.setMessage("Loading Locations. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
*/
protected Integer doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jsonParser.makeHttpRequest(url_all_profile, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Profiles: ", json.toString());
try {
// Checking for SUCCESS TAG
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
userprofile = json.getJSONArray(TAG_LOCATION);
// looping through All Products
for (int i = 0; i < userprofile.length(); i++) {
JSONObject c = userprofile.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String latitude = c.getString(TAG_LATITUDE);
String longitude = c.getString(TAG_LONGITUDE);
// 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_LATITUDE, latitude);
map.put(TAG_LONGITUDE, longitude);
// adding HashList to ArrayList
profileList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
//Intent i = new Intent(getApplicationContext(),
// UserLocation.class);
// Closing all previous activities
// i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return success;
}
/**
* After completing background task Dismiss the progress dialog
* *
*/
protected void onPostExecute(Integer result) {
// dismiss the dialog after getting all products
pDialog.dismiss();
locationCount.setText("" + profileList.size());
if (result == 1) {
//success
//update adapter items
adapter.notifyDataSetChanged();
} else {
//failed
//launch activity here
}
}
}
PHP:
<?php
/*
* Following code will delete a profile from table
* A product is identified by profile id (id)
*/
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['id'])) {
$id = $_POST['id'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql update row with matched pid
$result = mysql_query("DELETE FROM Location WHERE id = $id");
// check if row deleted or not
if (mysql_affected_rows() > 0) {
// successfully updated
$response["success"] = 1;
$response["message"] = "Profile successfully deleted";
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No Profile found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
I am trying to display information depending on the item pressed in a ListView. When click the item in List view,it will display the subject information.
But i faced a problem that is when click the item in List view,it cannot display the subject information based on the item that i clicked and display error in logcat.
Logcat Json response show that success get the subject information Single Product Details but still failed display subject information.Thanks
05-14 17:54:36.671: D/All Products:(1227): {"success":1,"products":[{"session":"2-2014\/2015","subject_code":"BITS 3323 Local Area Network","section":"1\/1","class_ID":"1"},{"session":"2-2014\/2015","subject_code":"BITS 3323 Local Area Network","section":"1\/2","class_ID":"2"},{"session":"2-2014\/2015","subject_code":"BITS 3323","section":"1\/2","class_ID":"8"},{"session":"2-2014\/2015","subject_code":"BITS2323 Wide Area Network","section":"1\/1","class_ID":"9"}]}
05-14 17:54:37.731: E/JSON Parser(1227): Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
05-14 17:54:37.731: D/Single Product Details(1227): {"success":1,"products":[{"session":"2-2014\/2015","subject_code":"BITS 3323 Local Area Network","section":"1\/1","class_ID":"1"},{"session":"2-2014\/2015","subject_code":"BITS 3323 Local Area Network","section":"1\/2","class_ID":"2"},{"session":"2-2014\/2015","subject_code":"BITS 3323","section":"1\/2","class_ID":"8"},{"session":"2-2014\/2015","subject_code":"BITS2323 Wide Area Network","section":"1\/1","class_ID":"9"}]}
05-14 17:54:37.731: D/JSON Parser(1227): {"success":1,"products":[{"session":"2-2014\/2015","subject_code":"BITS 3323 Local Area Network","section":"1\/1","class_ID":"1"},{"session":"2-2014\/2015","subject_code":"BITS 3323 Local Area Network","section":"1\/2","class_ID":"2"},{"session":"2-2014\/2015","subject_code":"BITS 3323","section":"1\/2","class_ID":"8"},{"session":"2-2014\/2015","subject_code":"BITS2323 Wide Area Network","section":"1\/1","class_ID":"9"}]}
05-14 17:54:37.731: W/System.err(1227): org.json.JSONException: No value for product
I trying use some suggestion such as change echo->print in php, using require_once 'DB_Connect.php that provided in previous post to solve Error parsing data org.json.JSONExceptio but still does not work
Listview java to passes EditProductActivity2
public class AllAttendanceActivity 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.14/android/get_class.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "class_ID";
private static final String TAG_NAME = "subject_code";
private static final String TAG_SECTION = "section";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_attendance);
// 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 class_ID = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
EditProductActivity2.class);
// sending pid to next activity
in.putExtra(TAG_PID, class_ID);
// 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(AllAttendanceActivity.this);
pDialog.setMessage("Loading Subject.. 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 class_ID = c.getString(TAG_PID);
String subject_code = c.getString(TAG_NAME);
String section = c.getString(TAG_SECTION);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID,class_ID);
map.put(TAG_NAME, subject_code);
map.put(TAG_SECTION, section);
// 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(
AllAttendanceActivity.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME,TAG_SECTION},
new int[] { R.id.pid, R.id.name,R.id.section});
// updating listview
setListAdapter(adapter);
}
});
}
}
}
public class EditProductActivity2
public class EditProductActivity2 extends Activity {
EditText txtName;
EditText txtPrice;
EditText txtDesc;
EditText txtCreatedAt;
Button btnSave;
Button btnDelete;
String class_ID;
String subject_code;
String session;
String section;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// single product url
private static final String url_class_detials = "http://192.168.1.14/android/get_class_details.php";
// url to update product
private static final String url_update_product = "http://10.0.2.2/android_connect/update_product.php";
// url to delete product
private static final String url_delete_product = "http://10.0.2.2/android_connect/delete_product.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCT = "product";
private static final String TAG_PID = "class_ID";
private static final String TAG_NAME = "subject_code";
private static final String TAG_PRICE = "session";
private static final String TAG_DESCRIPTION = "section";
#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
class_ID = 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
new SaveProductDetails().execute();
}
});
// Delete button click event
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// deleting product in background thread
new DeleteProduct().execute();
}
});
}
/**
* 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(EditProductActivity2.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", class_ID));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_class_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
Log.d("JSON Parser",json.toString() );
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();
}
}
/**
* 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(EditProductActivity2.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
subject_code = txtName.getText().toString();
session = txtPrice.getText().toString();
section = txtDesc.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_PID, class_ID));
params.add(new BasicNameValuePair(TAG_NAME, subject_code ));
params.add(new BasicNameValuePair(TAG_PRICE, session ));
params.add(new BasicNameValuePair(TAG_DESCRIPTION, section ));
// 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();
// 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();
}
}
/*****************************************************************
* 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(EditProductActivity2.this);
pDialog.setMessage("Deleting Product...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Deleting product
* */
protected String doInBackground(String... args) {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("pid", class_ID));
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
url_delete_product, "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();
}
}
}
PHP CODE
$response = array();
require_once __DIR__ . '/db_connect.php';
//require_once 'db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// check for post data
if (isset($_GET["pid"])) {
$pid = $_GET['pid'];
// get a product from products table
$result = mysql_query("SELECT *FROM class WHERE class_ID=$pid ");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$product = array();
$product["class_ID"] = $row["class_ID"];
$product["subject_code"] = $row["subject_code"];
$product["session"] = $row["session"];
$product["section"] = $row["section"];
// success
$response["success"] = 1;
// user node
$response["product"] = array();
array_push($response["product"], $product);
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 9 years ago.
Hi I've the RegisterActivity.java like this:
public class RegisterActivity extends Activity{
private static final String TAG = "PostFetcher";
private static String URL = "http://api.example.com/";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
final EditText inputFname = (EditText) findViewById(R.id.registerFname);
final EditText inputLname = (EditText) findViewById(R.id.registerLname);
final EditText inputEmail = (EditText) findViewById(R.id.registerEmail);
Button btnRegister = (Button) findViewById(R.id.btnRegister);
Button btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLogin);
final TextView loginErrorMsg = (TextView) findViewById(R.id.register_error);
// Register Button Click event
btnRegister.setOnClickListener(new View.OnClickListener() {
Login login2;
RadioGroup radioSexGroup = (RadioGroup) findViewById(R.id.sex);
public void onClick(View view) {
String fname = inputFname.getText().toString();
String lname = inputLname.getText().toString();
String email = inputEmail.getText().toString();
// get selected radio button from radioGroup
int selectedId = radioSexGroup.getCheckedRadioButtonId();
RadioButton radioSexButton = (RadioButton) findViewById(selectedId);
String gender = radioSexButton.getText().toString();
//System.out.println(fname);
//Toast.makeText(RegisterActivity.this, radioSexButton.getText(), Toast.LENGTH_SHORT).show();
String registerURL = URL +"&user_email="+ email /**+"&first_name="+ fname +"&last_name="+ lname*/ +"&gender="+ gender;
System.out.println(registerURL);
if( email.length() == 0) {
loginErrorMsg.setText(R.string.empty);
//Toast.makeText(view.getContext(), R.string.empty, Toast.LENGTH_SHORT).show();
return;
}else{
try {
//Create an HTTP client
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(registerURL);
//Perform the request and check the status code
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
try {
//Read the server response and attempt to parse it as JSON
Reader reader = new InputStreamReader(content);
Gson gson = new Gson();
this.login2 = gson.fromJson(reader, Login.class);
//System.out.println(this.login2);
//handlePostsList(posts);
} catch (Exception ex) {
Log.e(TAG, "Failed to parse JSON due to: " + ex);
failedLoading();
}
} else {
Log.e(TAG, "Server responded with status code: " + statusLine.getStatusCode());
failedLoading();
}
} catch(Exception ex) {
Log.e(TAG, "Failed to send HTTP POST request due to: " + ex);
failedLoading();
}
//To set register message
if(login2.getResult().equals("OK")){
loginErrorMsg.setText(login2.getMessage().toString());
}else if(login2.getResult().equals("KO")){
loginErrorMsg.setText(login2.getMessage().toString());
}
}
}
});
// Link to Login
btnLinkToLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),LoginActivity.class);
startActivity(i);
finish();
}
});
}
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.male:
if (checked)
// Pirates are the best
break;
case R.id.female:
if (checked)
// Ninjas rule
break;
}
}
private void failedLoading() {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(RegisterActivity.this, "Failed to Register. look at LogCat.", Toast.LENGTH_SHORT).show();
}
});
}
}
But I'm getting error as follows: Failed to send HTTP POST request due to: android.os.NetworkOnMainThreadException
Android developers forum suggest me to implement it using AsyncTask to solve this problem. But I don't know how to change this. Can someone help me to solve this issue? I spent several hours, but couldn't find any solution.
You want to put all of your network/parsing code in doInBackground() of your AsyncTask. Make the AsyncTask an inner class of your Activity. After getting your result you will want to return this to onPostExecute() to do any UI stuff such as updating Views.
By making the AsyncTask an inner class you will have access to member variables of the Activity and its functions.
This answer will give you a good starting point for creating your AsyncTask and calling it.
Read through the AsyncTask Docs to understand the rules it requires
Check out those links and give it a try. Then post a question with a more specific problem when you run into trouble (be sure to include relevant code and logcat errors if you get stuck).
The simplest approach to get you started is to create an anonymous inner class and execute it in your onCreate:
// if email length != 0
new AsyncTask<Void, Void, Void> {
protected void doInBackground() {
//Create an HTTP client
//Update login2
}
}.execute();
There are, however, a lot of subtle nuances and I highly recommend reading all of these 2 pages: http://developer.android.com/reference/android/os/AsyncTask.html and http://developer.android.com/guide/components/processes-and-threads.html
I honestly think you would figure it out with some effort, but here you go:
public class RegisterActivity extends Activity{
private static final String TAG = "PostFetcher";
private static String URL = "http://api.example.com/";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
final EditText inputFname = (EditText) findViewById(R.id.registerFname);
final EditText inputLname = (EditText) findViewById(R.id.registerLname);
final EditText inputEmail = (EditText) findViewById(R.id.registerEmail);
Button btnRegister = (Button) findViewById(R.id.btnRegister);
Button btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLogin);
final TextView loginErrorMsg = (TextView) findViewById(R.id.register_error);
// Register Button Click event
btnRegister.setOnClickListener(new View.OnClickListener() {
Login login2;
RadioGroup radioSexGroup = (RadioGroup) findViewById(R.id.sex);
public void onClick(View view) {
String fname = inputFname.getText().toString();
String lname = inputLname.getText().toString();
String email = inputEmail.getText().toString();
// get selected radio button from radioGroup
int selectedId = radioSexGroup.getCheckedRadioButtonId();
RadioButton radioSexButton = (RadioButton) findViewById(selectedId);
String gender = radioSexButton.getText().toString();
//System.out.println(fname);
//Toast.makeText(RegisterActivity.this, radioSexButton.getText(), Toast.LENGTH_SHORT).show();
String registerURL = URL +"&user_email="+ email /**+"&first_name="+ fname +"&last_name="+ lname*/ +"&gender="+ gender;
System.out.println(registerURL);
if( email.length() == 0) {
loginErrorMsg.setText(R.string.empty);
//Toast.makeText(view.getContext(), R.string.empty, Toast.LENGTH_SHORT).show();
return;
}else{
new LoginTask.execute();
}
}
});
// Link to Login
btnLinkToLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),LoginActivity.class);
startActivity(i);
finish();
}
});
}
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.male:
if (checked)
// Pirates are the best
break;
case R.id.female:
if (checked)
// Ninjas rule
break;
}
}
private void failedLoading() {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(RegisterActivity.this, "Failed to Register. look at LogCat.", Toast.LENGTH_SHORT).show();
}
});
private class LoginTask extends
AsyncTask<Void, Void, Void> {
ProgressDialog progressDialog;
// Before running code in separate thread
#Override
protected void onPreExecute() {
// Create a new progress dialog.
progressDialog = new ProgressDialog(context);
// Set the progress dialog to display a horizontal bar .
// progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
// Set the dialog title to 'Loading...'.
// progressDialog.setTitle("Loading...");
// Set the dialog message to 'Loading application View, please
// wait...'.
progressDialog.setMessage("Loading...");
// This dialog can't be canceled by pressing the back key.
progressDialog.setCancelable(false);
// This dialog isn't indeterminate.
progressDialog.setIndeterminate(true);
// The maximum number of progress items is 100.
// progressDialog.setMax(100);
// Set the current progress to zero.
// progressDialog.setProgress(0);
// Display the progress dialog.
progressDialog.show();
}
// The code to be executed in a background thread.
#Override
protected VoiddoInBackground(Void... arg) {
try {
//Create an HTTP client
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(registerURL);
//Perform the request and check the status code
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
try {
//Read the server response and attempt to parse it as JSON
Reader reader = new InputStreamReader(content);
Gson gson = new Gson();
this.login2 = gson.fromJson(reader, Login.class);
//System.out.println(this.login2);
//handlePostsList(posts);
} catch (Exception ex) {
Log.e(TAG, "Failed to parse JSON due to: " + ex);
failedLoading();
}
} else {
Log.e(TAG, "Server responded with status code: " + statusLine.getStatusCode());
failedLoading();
}
} catch(Exception ex) {
Log.e(TAG, "Failed to send HTTP POST request due to: " + ex);
failedLoading();
}
}
// after executing the code in the thread
#Override
protected void onPostExecute() {
// close the progress dialog
progressDialog.dismiss();
//To set register message
if(login2.getResult().equals("OK")){
loginErrorMsg.setText(login2.getMessage().toString());
}else if(login2.getResult().equals("KO")){
loginErrorMsg.setText(login2.getMessage().toString());
}
}
}
}
I'm working on an application that stores user inputs into the database table via PHP API but i get an error message from the PHP code to the LogCat. Any advice would be greatly appreciated.
D/Create Response(284): {"message":"Required field(s) is missing","success":0}
PHP API
<?php
// array for JSON response
$response = array();
// check for the fields
if (isset($_POST['title']) && isset($_POST['request_date']) && isset($_POST['reqEndDate']) && isset($_POST['reason']) && isset($_POST['requestor']) && isset($_POST['status']) && isset($_POST['submitDate']) && isset($_POST['explanation']) && isset($_POST['hours']) && isset($_POST['id'])) {
$title = $_POST["request_title"];
$date = $_POST["request_date"];
$eDate = $_POST["reqEndDate"];
$reason = $_POST["reason"];
$requestor = $_POST["requestor"];
$status = $_POST["status"];
$dateSubmitted = $_POST["submitDate"];
$explanation = $_POST["explanation"];
$numhours = $_POST["hours"];
$id = $_POST['id'];
// mysql inserting a new row
$result = mysql_query("INSERT INTO requests(request_title, request_date, reqEndDate, reason, requestor, status, submitDate, explanation, hours, empid)
VALUES('$title', '$date', '$eDate', '$reason', '$requestor', '$status', '$dateSubmitted', '$explanation', '$numhours', '$id')");
?>
JAVA CLASS
// url to the PHP API to create new request
private static String url_create_request = "http://mywebsite.com/create_request.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_request);
// Edit Text
inputTitle = (EditText) findViewById(R.id.inputTitle);
inputSdate = (EditText) findViewById(R.id.inputSdate);
inputEdate = (EditText) findViewById(R.id.inputEdate);
inputHours = (EditText) findViewById(R.id.inputHours);
inputReason = (EditText) findViewById(R.id.inputReason);
inputExp = (EditText) findViewById(R.id.inputExp);
// Create button
Button btnCreateRequest = (Button) findViewById(R.id.btnCreateRequest);
// button click event
btnCreateRequest.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// creating new product in background thread
new CreateNewRequest().execute();
}
});
}
class CreateNewRequest extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewRequestActivity.this);
pDialog.setMessage("Creating Request..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating Request Required Fields
* */
protected String doInBackground(String... args) {
String title = inputTitle.getText().toString();
String date = inputSdate.getText().toString();
String eDate = inputEdate.getText().toString();
String hours = inputHours.getText().toString();
String reason = inputReason.getText().toString();
String explanation = inputExp.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("request_title", title));
params.add(new BasicNameValuePair("request_date", date));
params.add(new BasicNameValuePair("reqEndDate", eDate));
params.add(new BasicNameValuePair("hours", hours));
params.add(new BasicNameValuePair("reason", reason));
params.add(new BasicNameValuePair("explanation", explanation));
// getting JSON Object
// Note that create request url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_request,
"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 request
Intent i = new Intent(getApplicationContext(), AllRequestsActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create request
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
Just counting your DB columns: there appears to be 12 of them. You're only inserting into 11, and after process of elimination, it looks like you're leaving out "active," which, unless it has a default value or can be null, would throw a "Required field(s) is missing" error that you're getting when trying to insert into the DB.