I am working on a project where data from a mysql database is loaded from my server and displayed in the form of a ListView. However, I am experiencing some hurdles in achieving this where the application ends up force closing whenever I open the ContentActivity. From my logcat, I get two sets of errors:
First I get errors on lines 196 (class LoadAllContent extends AsyncTask<String, String, String> {) and line 221 (Log.d("All Posts: ", json.toString());). The complete error for this segment is:
10-13 13:42:58.978 20090-20315/? W/System.err? at com.app.appname.ContentActivity$LoadAllContent.doInBackground(ContentActivity.java:221)
10-13 13:42:58.978 20090-20315/? W/System.err? at com.app.appname.ContentActivity$LoadAllContent.doInBackground(ContentActivity.java:196)
10-13 13:42:58.980 20090-20315/? E/AndroidRuntime? FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
at java.util.concurrent.FutureTask.run(FutureTask.java:239)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:838)
Caused by: java.lang.NullPointerException
at com.app.appname.ContentActivity$LoadAllContent.doInBackground(ContentActivity.java:221)
at com.app.appname.ContentActivity$LoadAllContent.doInBackground(ContentActivity.java:196)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:838)
10-13 13:42:59.007 553-3073/? W/ActivityManager? Force finishing activity com.app.appname/.ContentActivity
The Second set of errors are at lines 85 (new LoadAllContent().execute();) and line 208 (pDialog.show();)
10-13 13:42:59.856 20090-20090/? E/WindowManager? Activity com.app.appname.ContentActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41ec1f80 V.E..... R......D 0,0-480,96} that was originally added here
android.view.WindowLeaked: Activity com.app.appname.ContentActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41ec1f80 V.E..... R......D 0,0-480,96} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:424)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:218)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:281)
at com.app.appname.ContentActivity$LoadAllContent.onPreExecute(ContentActivity.java:208)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at com.app.appname.ContentActivity.onCreate(ContentActivity.java:85)
at android.app.Activity.performCreate(Activity.java:5122)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1150)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2315)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2403)
at android.app.ActivityThread.access$600(ActivityThread.java:165)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1373)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5370)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
What I am not sure of is whether these two errors are related. My ContentActivity.java and index.php files are as below.
ContentActivity.java
public class ContentActivity extends ListActivity implements ISideNavigationCallback {
Utils util;
final Context context = this;
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> contentList;
// url to get all content
private static String getContent = "http://192.168.43.87/app/index.php?act=getContent";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_POSTS = "posts";
private static final String TAG_PID = "id";
private static final String TAG_TITLE = "title";
// products JSONArray
JSONArray posts = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_content);
util = new Utils(this);
TextView appTit = (TextView) findViewById(R.id.appTitle);
String pageTitle = "MySql Database Content";
appTit.setText((CharSequence)pageTitle);
// Hashmap for ListView
contentList = new ArrayList<HashMap<String, String>>();
new LoadAllContent().execute();
// Get listview
ListView lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String postId = ((TextView) view.findViewById(R.id.postId)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), ContentViewActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, postId);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
/**
* Background Async Task to Load all content by making HTTP Request
* */
class LoadAllContent extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ContentActivity.this);
pDialog.setMessage("Loading blog. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All content from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(getContent, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Posts: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
posts = json.getJSONArray(TAG_POSTS);
// looping through All Products
for (int i = 0; i < posts.length(); i++) {
JSONObject c = posts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String title = c.getString(TAG_TITLE);
// 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_TITLE, title);
// adding HashList to ArrayList
contentList.add(map);
}
} else {
// no content found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NoPostActivity.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(
ContentActivity.this, contentList,
R.layout.list_item, new String[] { TAG_PID,
TAG_TITLE},
new int[] { R.id.postId, R.id.title });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
index.php
<?php
$action = $_GET['act'];
if ($action == 'getallposts') {
$posts = get_posts('numberposts=10&order=DESC&orderby=post_desc_gmt');
$numPosts = count($posts);
if ($numPosts > 0) {
$response["posts"] = array();
foreach ($posts as $postr) : setup_postdata( $post );
// temp user array
$post = array();
$post['id'] = $postr->ID;
$post["title"] = $postr->post_title;
$post["desc"] = substr($postr->post_content,0,50).'...';
$post['comments'] = $postr->comment_count;
$post["created"] = $postr->post_date_gmt;
array_push($response["posts"], $post);
endforeach;
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
echo json_encode($response);
}
}
?>
I would really appreciate any pointers to sort out this issue as all the research I have done has not borne any fruit.
Just few comments:
Move Log.d("All Posts: ", json.toString()); to the try .. catch
block and catch for NullPointerException too.
You dont need to use runOnUiThread on the postExecute as
postExecute always runs on the UI thread ( main thread)
Dont start activity from doInBackground ( It might be
possible but dont do it); do this from postExecute rather, like this:
if(success != 1){
Intent i = new
Intent(getApplicationContext(),NoPostActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
Related
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;
}
Hi I was viewing the details then when i hit the bottom right back button, to go back to the listview, I have the error "android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views."
but I don't know how to solve this:
public class Record extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
//testing on Emulator:
private static final String READ_SPECIFIC_RECORD_URL = "http://192.168.1.178:8888/searchdb/record.php";
//JSON IDS:
private static final String TAG_TITLE = "title";
private static final String TAG_POSTS = "posts";
private static final String TAG_ADDRESS = "address";
private static final String TAG_OPHOURS = "ophours";
private static final String TAG_CONTACT = "contact";
private static final String TAG_CONTACT2 = "contact2";
private static final String TAG_CAT = "cat";
private static final String TAG_BRAND = "brand";
private static final String TAG_COMPANY = "company";
private static final String TAG_RATINGS = "avgrating";
//An array of all of our comments
private JSONArray mComments = null;
//manages all of our comments in a list.
private ArrayList<HashMap<String, String>> mCommentList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//note that use read_comments.xml instead of our single_post.xml
setContentView(R.layout.details);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
//loading the comments via AsyncTask
new LoadRecordDetails().execute();
}
/**
* Retrieves json data of comments
*/
/**
* Retrieves recent post data from the server.
*/
public void updateJSONdata() {
// Instantiate the arraylist to contain all the JSON data.
// we are going to use a bunch of key-value pairs, referring
// to the json element name, and the content, for example,
// message it the tag, and "I'm awesome" as the content..
Bundle b = getIntent().getExtras();
String id = b.getString("key");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", id));
Log.d("request!", "starting");
//Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(
READ_SPECIFIC_RECORD_URL, "POST", params);
// full json response
Log.d("Search attempt", json.toString());
mCommentList = new ArrayList<HashMap<String, String>>();
//when parsing JSON stuff, we should probably
//try to catch any exceptions:
try {
mComments = json.getJSONArray(TAG_POSTS);
// looping through all posts according to the json object returned
for (int i = 0; i < mComments.length(); i++) {
JSONObject c = mComments.getJSONObject(i);
//gets the content of each tag
String title = c.getString(TAG_TITLE);
String address = c.getString(TAG_ADDRESS);
String ophours = c.getString(TAG_OPHOURS);
String contact = c.getString(TAG_CONTACT);
String contact2 = c.getString(TAG_CONTACT2);
String cat = c.getString(TAG_CAT);
String brand = c.getString(TAG_BRAND);
String company = c.getString(TAG_COMPANY);
String avgrating = c.getString(TAG_RATINGS);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, title);
map.put(TAG_ADDRESS, address);
map.put(TAG_OPHOURS, ophours);
map.put(TAG_CONTACT, contact);
map.put(TAG_CONTACT2, contact2);
map.put(TAG_CAT, cat);
map.put(TAG_BRAND, brand);
map.put(TAG_COMPANY, company);
map.put(TAG_RATINGS, avgrating);
// adding HashList to ArrayList
mCommentList.add(map);
//annndddd, our JSON data is up to date same with our array list
}
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* Inserts the parsed data into our listview
*/
private void updateList() {
// For a ListActivity we need to set the List Adapter, and in order to do
//that, we need to create a ListAdapter. This SimpleAdapter,
//will utilize our updated Hashmapped ArrayList,
//use our single_post xml template for each item in our list,
//and place the appropriate info from the list to the
//correct GUI id. Order is important here.
ListAdapter adapter = new SimpleAdapter(this, mCommentList,
R.layout.single_record, new String[] { TAG_TITLE, TAG_ADDRESS,
TAG_OPHOURS, TAG_CONTACT, TAG_CONTACT2, TAG_CAT, TAG_BRAND, TAG_COMPANY, TAG_RATINGS },
new int[] { R.id.outletname, R.id.outletaddress, R.id.outletophours, R.id.outletcontact,
R.id.outletcontact2, R.id.outletcat, R.id.outletbrand, R.id.outletcompany, R.id.ratings});
((SimpleAdapter) adapter).setViewBinder(new MyBinder());
setListAdapter(adapter);
//Showing empty view when ListView is empty
ListView listView = (ListView) findViewById(android.R.id.list);
listView.setEmptyView(findViewById(android.R.id.empty));
}
//ratingsbar
class MyBinder implements SimpleAdapter.ViewBinder {
public boolean setViewValue(View view, Object data, String textRepresentation) {
if(view.getId() == R.id.ratings){
String stringval = (String) data;
float ratingValue = Float.parseFloat(stringval);
RatingBar ratingBar = (RatingBar) view;
ratingBar.setRating(ratingValue);
return true;
}
return false;
}
}
//call
public class LoadRecordDetails extends AsyncTask<Void, Boolean, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Record.this);
pDialog.setMessage("Loading details...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Boolean doInBackground(Void... arg0) {
updateJSONdata();
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
pDialog.dismiss();
updateList();
}
}
}
From logcat:
02-24 23:38:26.033 5653-5789/com.example.searchtest W/dalvikvm﹕ threadid=19: thread exiting with uncaught exception (group=0x4172ac08)
02-24 23:38:26.038 5653-5789/com.example.searchtest E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #4
Process: com.example.searchtest, PID: 5653
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:7069)
at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:1108)
at android.view.ViewGroup.invalidateChild(ViewGroup.java:4542)
at android.view.View.invalidate(View.java:11795)
at android.view.View.invalidate(View.java:11736)
at android.widget.ImageView.invalidateDrawable(ImageView.java:211)
at android.graphics.drawable.Drawable.invalidateSelf(Drawable.java:393)
at android.graphics.drawable.Drawable.setVisible(Drawable.java:624)
at android.widget.ImageView.onDetachedFromWindow(ImageView.java:1265)
at android.view.View.dispatchDetachedFromWindow(View.java:13543)
at android.view.ViewGroup.dispatchDetachedFromWindow(ViewGroup.java:2800)
at android.view.ViewGroup.dispatchDetachedFromWindow(ViewGroup.java:2800)
at android.view.ViewGroup.dispatchDetachedFromWindow(ViewGroup.java:2800)
at android.view.ViewGroup.removeAllViewsInLayout(ViewGroup.java:4249)
at android.widget.AbsListView.resetList(AbsListView.java:2388)
at android.widget.ListView.resetList(ListView.java:527)
at android.widget.ListView.setAdapter(ListView.java:468)
at android.app.ListActivity.setListAdapter(ListActivity.java:265)
at com.example.searchtest.Results.updateList(Results.java:90)
at com.example.searchtest.Results.access$100(Results.java:23)
at com.example.searchtest.Results$LoadResults.doInBackground(Results.java:154)
at com.example.searchtest.Results$LoadResults.doInBackground(Results.java:138)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Thanks!! :D
Log file tells this :
android.view.ViewRootImpl$CalledFromWrongThreadException:
Only the original thread that created a view hierarchy can touch its views.
This exeption means that you are trying to thouch view that's not in this thread.
Here is an explanation:
There is the thread call UI and in your code there is an another one called AsyncTask
and in this line : updateList(); you are calling the method that trying to thouch the view that is in UI thread,like this :
ListView listView = (ListView) findViewById(android.R.id.list);
So, for solving this issue just remove this line and put it in onCreate, so your code should look like this :
public class Record extends ListActivity {
.
.
.
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//note that use read_comments.xml instead of our single_post.xml
setContentView(R.layout.details);
listView = (ListView) findViewById(android.R.id.list);
}
}
I have made an android application where there are a login form, an update details form, etc.
Whenever I enter a wrong detail, the app stops working and a force close dialog box appears.
This is my code:
Login.java
public class AllProductsActivity extends ListActivity
{
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
private static String url_all_products = "http://192.168.1.4/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);
}
});
}
}
}
UpdateDetails.java
public class UpdateDetails extends Activity
{
EditText inputName;
EditText inputAddress;
EditText inputPassword;
EditText confirmPassword;
EditText inputEmailId, inputMobileno;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// JSON Node names
private static final String resp = "success";
//private static final String Flag = "flag";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.updatedetails);
// Edit Text
inputName = (EditText) findViewById(R.id.editName);
inputAddress = (EditText) findViewById(R.id.editAddress);
inputPassword = (EditText) findViewById(R.id.editPassword);
confirmPassword=(EditText) findViewById(R.id.editConfirmPassword);
inputEmailId=(EditText) findViewById(R.id.editText2_emailid);
inputMobileno=(EditText) findViewById(R.id.editText1_mobile);
// Create button
Button update_details = (Button) findViewById(R.id.buttonUpdate);
// button click event
update_details.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (inputPassword == confirmPassword){
// updating user in background thread
new UpdateUserDetails().execute();
}
else {
//Some Sort Of Alert Box
Toast.makeText(getApplicationContext(), "Please Enter Valid Details", Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* Background Async Task to Create new product
* */
class UpdateUserDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(UpdateDetails.this);
pDialog.setMessage("Updating User Details.. Please wait");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* Updating User
* */
protected String doInBackground(String... args) {
String name = inputName.getText().toString();
String address = inputAddress.getText().toString();
String password = inputPassword.getText().toString();
String mobileno = inputMobileno.getText().toString();
String emailid = inputEmailId.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("address", address));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("mobile_no", mobileno));
params.add(new BasicNameValuePair("email_id",emailid));
final String url_user = "http://"+ Login.serve +"/catxam/android_update.php";
// getting JSON Object
JSONObject json = jsonParser.makeHttpRequest(url_user,"POST", params);
// check log cat from response
Log.d("Update Response", json.toString());
// check for success tag
try {
int success = json.getInt(resp);
if (success == 1) {
// successfully update user
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
Toast.makeText(getApplicationContext(), "Unsuccessful Updation", 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();
}
}
}
Can anyone help me in identifying my mistake and help me in rectifying mistakes in my project.
I appreciate your help. Thanks in advance
Here is the logCat window!
02-13 19:32:10.096: E/AndroidRuntime(7328): FATAL EXCEPTION: AsyncTask #2
02-13 19:32:10.096: E/AndroidRuntime(7328): java.lang.RuntimeException: An error occured while executing doInBackground()
02-13 19:32:10.096: E/AndroidRuntime(7328): at android.os.AsyncTask$3.done(AsyncTask.java:299)
02-13 19:32:10.096: E/AndroidRuntime(7328): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
02-13 19:32:10.096: E/AndroidRuntime(7328): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
02-13 19:32:10.096: E/AndroidRuntime(7328): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
02-13 19:32:10.096: E/AndroidRuntime(7328): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
02-13 19:32:10.096: E/AndroidRuntime(7328): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
02-13 19:32:10.096: E/AndroidRuntime(7328): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
02-13 19:32:10.096: E/AndroidRuntime(7328): at java.lang.Thread.run(Thread.java:838)
02-13 19:32:10.096: E/AndroidRuntime(7328): Caused by: java.lang.NullPointerException
02-13 19:32:10.096: E/AndroidRuntime(7328): at
com.example.catxam.Login$CreateNewUser.doInBackground(Login.java:146)
02-13 19:32:10.096: E/AndroidRuntime(7328): at com.example.catxam.Login$CreateNewUser.doInBackground(Login.java:1)
02-13 19:32:10.096: E/AndroidRuntime(7328): at android.os.AsyncTask$2.call(AsyncTask.java:287)
02-13 19:32:10.096: E/AndroidRuntime(7328): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
02-13 19:32:10.096: E/AndroidRuntime(7328): ... 4 more
Sorry not able to post images :(
Excecute this in postExecute. To display or pass to another activity, Use in postExecute.
Only main operation to be performed in doInBackground.
try {
int success = json.getInt(resp);
if (success == 1) {
// successfully update user
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
Toast.makeText(getApplicationContext(), "Unsuccessful Updation", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
As in other answers, your error (althought without logcat....) is that you call:
Toast.makeText(getApplicationContext(), "Unsuccessful Updation", Toast.LENGTH_SHORT).show();
in doInBackground, UI operations are permitted only on UI thread. On the other hand you dont need:
runOnUiThread(new Runnable() {
in onPostExecute because it is already executed on UI thread, so you should use onPostExecute for your toast message.
You cannot make a call to Toast.makeText from the doInBackground method, as it needs to be done on the UI thread.
Do this at the end of doInBackground :
// check for success tag
try {
int success = json.getInt(resp);
String success = success == 1 ? "success" : null;
return success;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
and this in onPostExecute :
protected void onPostExecute(String result) {
if (result!= null) {
// successfully update user
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
Toast.makeText(getApplicationContext(), "Unsuccessful Updation", Toast.LENGTH_SHORT).show();
}
pDialog.dismiss();
}
Additionally, you should not do this in LoadAllProducts:
// updating UI from Background Thread
runOnUiThread(new Runnable()
onPostExecute is designed for you to update the UI at the end of your background task, so you don't need to create an additional Thread to execute that code.
after the crashing problem been solved now the application is not executing the update or deleting
when i update it crashes immediately but when i delete it shows me the toast and nothing happens then
this is the class
public class EditCard extends Activity {
EditText txtName;
EditText txtPosition;
EditText txtCollege;
EditText txtPhone;
Button btnSave;
Button btnDelete;
String cid;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// single product url
private static final String url_card_details = "http://XXX";
// url to update product
private static final String url_update_card = "http://XXX";
// url to delete product
private static final String url_delete_card = "http://XXX";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_CARDS = "cards";
private static final String TAG_CID = "cid";
private static final String TAG_CNAME = "name";
private static final String TAG_POSITION = "position";
private static final String TAG_COLLEGE = "college";
private static final String TAG_PHONE = "phone";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_card);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
// save button
btnSave = (Button) findViewById(R.id.SaveCard);
btnDelete = (Button) findViewById(R.id.DeleteCard);
// getting product details from intent
Intent i = getIntent();
// getting product id (pid) from intent
cid = i.getStringExtra(TAG_CID);
// Getting complete product details in background thread
new GetCardDetails().execute();
// save button click event
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// starting background task to update product
new SaveCardDetails().execute();
}
});
// Delete button click event
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// deleting product in background thread
new DeleteCard().execute();
}
});
}
/**
* Background Async Task to Get complete product details
* */
class GetCardDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EditCard.this);
pDialog.setMessage("Loading card 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("cid", cid));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_card_details, "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 cardObj = json
.getJSONArray(TAG_CARDS); // JSON Array
// get first product object from JSON Array
JSONObject card = cardObj.getJSONObject(0);
// product with this pid found
// Edit Text
txtName = (EditText) findViewById(R.id.editCard1);
txtPosition = (EditText) findViewById(R.id.editCard2);
txtCollege= (EditText) findViewById(R.id.editCard3);
txtPhone= (EditText) findViewById(R.id.editCard4);
// display product data in EditText
txtName.setText(card.getString(TAG_CNAME));
txtPosition.setText(card.getString(TAG_POSITION));
txtCollege.setText(card.getString(TAG_COLLEGE));
txtPhone.setText(card.getString(TAG_PHONE));
}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 SaveCardDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EditCard.this);
pDialog.setMessage("Saving Card ...");
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 position = txtPosition.getText().toString();
String college = txtCollege.getText().toString();
String phone = txtPhone.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("position", position));
params.add(new BasicNameValuePair("college", college));
params.add(new BasicNameValuePair("phone", phone));
// sending modified data through http request
// Notice that update product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_update_card,
"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
Toast.makeText(getApplicationContext(), "The Student Card Updated sucessfully", Toast.LENGTH_LONG).show();
pDialog.dismiss();
}
}
/*****************************************************************
* Background Async Task to Delete Product
* */
class DeleteCard extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EditCard.this);
pDialog.setMessage("Deleting Card...");
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("cid", cid));
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
url_delete_card, "POST", params);
// check your log for json response
Log.d("Delete Card", 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
Toast.makeText(getApplicationContext(), "The Student Card deleted sucessfully", Toast.LENGTH_LONG).show();
pDialog.dismiss();
}
}
}
and this is the LogCat when i update
07-18 01:15:53.053: W/dalvikvm(8740): threadid=11: thread exiting with uncaught exception (group=0x40a71930)
07-18 01:15:53.383: E/AndroidRuntime(8740): FATAL EXCEPTION: AsyncTask #1
07-18 01:15:53.383: E/AndroidRuntime(8740): java.lang.RuntimeException: An error occured while executing doInBackground()
07-18 01:15:53.383: E/AndroidRuntime(8740): at android.os.AsyncTask$3.done(AsyncTask.java:299)
07-18 01:15:53.383: E/AndroidRuntime(8740): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
07-18 01:15:53.383: E/AndroidRuntime(8740): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
07-18 01:15:53.383: E/AndroidRuntime(8740): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
07-18 01:15:53.383: E/AndroidRuntime(8740): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
07-18 01:15:53.383: E/AndroidRuntime(8740): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
07-18 01:15:53.383: E/AndroidRuntime(8740): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
07-18 01:15:53.383: E/AndroidRuntime(8740): at java.lang.Thread.run(Thread.java:856)
07-18 01:15:53.383: E/AndroidRuntime(8740): Caused by: java.lang.NullPointerException
07-18 01:15:53.383: E/AndroidRuntime(8740): at com.example.ahliaevents.EditCard$SaveCardDetails.doInBackground(EditCard.java:210)
07-18 01:15:53.383: E/AndroidRuntime(8740): at com.example.ahliaevents.EditCard$SaveCardDetails.doInBackground(EditCard.java:1)
07-18 01:15:53.383: E/AndroidRuntime(8740): at android.os.AsyncTask$2.call(AsyncTask.java:287)
07-18 01:15:53.383: E/AndroidRuntime(8740): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
07-18 01:15:53.383: E/AndroidRuntime(8740): ... 4 more
and this is the LogCat when i delete
07-18 01:18:01.584: E/JSON Parser(8850): Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
For your delete crash, you're not getting JSON back from the server, you're probably getting an error page. The parser is expecting to see JSON and it sees what appears to be the beginning of an XML/XHTML document.
For your other crash, just look at your source at line 210. You're getting a NullPointerException, which means that you expect something to be an object, but it's a null reference.
Most alarming is your use of runOnUiThread() within a doInBackground() the whole point of doInBackground is to avoid the UI Thread.
I am stuck on this stack trace, I don't know what is reason behind it .
06-27 17:05:14.841: W/SingleClientConnManager(1519): Invalid use of SingleClientConnManager: connection still allocated.
06-27 17:05:14.841: W/SingleClientConnManager(1519): Make sure to release the connection before allocating another one.
06-27 17:05:15.031: E/log_tag(1519): Error in http connection java.net.SocketException: Socket closed
06-27 17:05:15.077: E/log_tag(1519): Error converting result java.lang.NullPointerException
06-27 17:05:15.181: E/log_tag(1519): Error parsing data org.json.JSONException: End of input at character 0 of
06-27 17:05:15.531: W/dalvikvm(1519): threadid=10: thread exiting with uncaught exception (group=0x40014760)
06-27 17:05:15.821: E/AndroidRuntime(1519): FATAL EXCEPTION: AsyncTask #2
06-27 17:05:15.821: E/AndroidRuntime(1519): java.lang.RuntimeException: An error occured while executing doInBackground()
06-27 17:05:15.821: E/AndroidRuntime(1519): at android.os.AsyncTask$3.done(AsyncTask.java:266)
06-27 17:05:15.821: E/AndroidRuntime(1519): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
06-27 17:05:15.821: E/AndroidRuntime(1519): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
06-27 17:05:15.821: E/AndroidRuntime(1519): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
06-27 17:05:15.821: E/AndroidRuntime(1519): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
06-27 17:05:15.821: E/AndroidRuntime(1519): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1081)
06-27 17:05:15.821: E/AndroidRuntime(1519): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:574)
06-27 17:05:15.821: E/AndroidRuntime(1519): at java.lang.Thread.run(Thread.java:1020)
06-27 17:05:15.821: E/AndroidRuntime(1519): Caused by: java.lang.NullPointerException
06-27 17:05:15.821: E/AndroidRuntime(1519): at com.si.gtc.Feeds$DownloadJSON.doInBackground(Feeds.java:87)
06-27 17:05:15.821: E/AndroidRuntime(1519): at com.si.gtc.Feeds$DownloadJSON.doInBackground(Feeds.java:1)
06-27 17:05:15.821: E/AndroidRuntime(1519): at android.os.AsyncTask$2.call(AsyncTask.java:252)
06-27 17:05:15.821: E/AndroidRuntime(1519): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
06-27 17:05:15.821: E/AndroidRuntime(1519): ... 4 more
There are two json responses work at the same time in different activities. If I run single Response above Null pointer error does not affect on my output.
First activity contain tabhost (Tab) . First tab(default tab) has another async task.
This is my first activity wich contain Json call and Tab host.
public class Login_Header extends TabActivity
{
Button Find;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
//To show Custom Title as image
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
//getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
setContentView(R.layout.login_header_bar);
super.onCreate(savedInstanceState);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title_about_tab);
// Font size has been changed through Styles.xml for tab
TabHost tabHost = getTabHost();
Intent feeds = new Intent(this,Feeds.class);
tabHost.addTab(tabHost.newTabSpec("Tab1")
.setIndicator("Feeds")
.setContent(feeds));
Intent challenges = new Intent(this,Challenges.class);
tabHost.addTab(tabHost.newTabSpec("Tab2")
.setIndicator("Challenges")
.setContent(challenges));
Intent friends = new Intent(this,Friends.class);
tabHost.addTab(tabHost.newTabSpec("Tab3")
.setIndicator("Friends")
.setContent(friends));
Intent group = new Intent(this,Groups.class);
tabHost.addTab(tabHost.newTabSpec("Tab4")
.setIndicator("Groups")
.setContent(group));
Intent details = new Intent(this,Details.class);
tabHost.addTab(tabHost.newTabSpec("Tab5")
.setIndicator("Details")
.setContent(details));
tabHost.setCurrentTab(0);
Find.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
Intent find = new Intent(Login_Header.this,Find.class);
startActivity(find);
}
});
//To call async task
callNotificationCount();
}
private void callNotificationCount()
{
new NotificationCount_Async().execute("");
}
private class NotificationCount_Async extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... params)
{
try
{
URL url=new URL(getString(R.string.WebServiceURL)+"/notifications/notificationcount");
HttpPost httppost = new HttpPost(url.toString());
HttpResponse responsePOST = LoginPage.httpClient.execute(httppost);
HttpEntity resEntity = responsePOST.getEntity();
InputStream instream = resEntity.getContent();
String result = convertStreamToString(instream);
Log.i("User Feed",result);
return result;
}
catch(Exception ex)
{
Log.e("error", "error", ex);
return null;
}
}
#Override
protected void onPostExecute(String result)
{
try {
JSONObject json = new JSONObject(result);
//Below code is for user count
JSONObject userNotificationjson = json.getJSONObject("user_notification");
if(json.has("user_notification"))
{
String userCount = userNotificationjson.getString("count");
int Count = Integer.parseInt(userCount);
if(Count > 0)
{
LinearLayout llUserCount = (LinearLayout)findViewById(R.id.llUserCount);
TextView userCountTextView =(TextView)findViewById(R.id.txtUserCount);
llUserCount.setVisibility(View.VISIBLE);
userCountTextView.setText(userCount);
}
}
}
private String convertStreamToString(InputStream is)
{
//code
}
Now this is my second activity , Default Tab activity which again have json request.
public class Feeds extends Activity
{
SessionManager session;
String custom_phpsess_id,logged_in_id_User,returnString;
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String FIRST_NAME = "firstname";
static String LAST_NAME = "lastname";
static String ACTION = "action";
// static String ACTIVITY_NAME = "activity_name";
static String IMAGE_URL = "image";
static String USER_ID = "user_id";
static String ACTIVITY_NAME = "activityname";
String strUrl = =new URL(getString(R.string.WebServiceURL)+"/users/userfeeds";
ListView mListView;
String id_User;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Get the view from feeds.xml
setContentView(R.layout.feeds);
session = new SessionManager(getApplicationContext());
//To get values from session
HashMap<String, String> User = session.getUserDetails();
logged_in_id_User = User.get(SessionManager.KEY_ID);
custom_phpsess_id = User.get(SessionManager.KEY_USE);
// Creating a new non-ui thread task to download json data
// Execute DownloadJSON AsyncTask
Log.i("On Create", "Main On Create");
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute()
{
Log.i("On DownloadJSON", "onPreExecute");
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(Feeds.this);
// Set progressdialog title
mProgressDialog.setTitle("");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params)
{
Log.i("On doInBackground", "doInBackground");
// Create the array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrive JSON Objects from the given website URL in JSONfunctions.class
jsonobject = JSONfunctions
.getJSONfromURL(strUrl);
Log.i("On doInBackground-jsonObject", jsonobject.toString());
try
{
// Locate the array name
jsonarray = jsonobject.getJSONArray("userdata");
Log.i("On doInBackground-jsonarray", jsonarray.toString());
for (int i = 0; i < jsonarray.length(); i++)
{
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
if(jsonobject.getString("actions").equals("Completed"))
{
map.put("firstname", jsonobject.getString("first_name"));
map.put("lastname", jsonobject.getString("last_name"));
map.put("action", jsonobject.getString("actions"));
map.put("image", jsonobject.getString("file_name"));
map.put("user_id", jsonobject.getString("id_user"));
map.put("activityname", jsonobject.getString("activity_name"));
Log.i("On doInBackground-Map", map.toString());
// Set the JSON Objects into the array
arraylist.add(map);
}
}
}
catch (JSONException e)
{
Log.i("On doInBackground-JSONException", e.toString());
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args)
{
Log.i("On onPostExecute", "ON post exe");
// Locate the listview in listview_main.xml
listview = (ListView)findViewById(R.id.listview);
Log.i("On onPostExecute-onPostExecute-arraylist", arraylist.toString());
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(Feeds.this, arraylist);
Log.i("On onPostExecute-onPostExecute-Adapter", adapter.toString());
// Binds the Adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
and null pointer line is ..
Line no. 97 is = Log.i("On doInBackground-jsonObject", jsonobject.toString());