Java.lang.NullPointerException in doInBackground put HashMap in ArrayList - android

I have developed app which connects to server and receive JSON response .Till this it works fine.But then it puts in Hashmap and HashMap in ArrayList to display data.It gives error on while putting Hashmap in ArrayList.My LogCat is
06-03 16:23:10.540: E/AndroidRuntime(15457): FATAL EXCEPTION: AsyncTask #1
06-03 16:23:10.540: E/AndroidRuntime(15457): java.lang.RuntimeException: An error occured while executing doInBackground()
06-03 16:23:10.540: E/AndroidRuntime(15457): at android.os.AsyncTask$3.done(AsyncTask.java:278)
06-03 16:23:10.540: E/AndroidRuntime(15457): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
06-03 16:23:10.540: E/AndroidRuntime(15457): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
06-03 16:23:10.540: E/AndroidRuntime(15457): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
06-03 16:23:10.540: E/AndroidRuntime(15457): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
06-03 16:23:10.540: E/AndroidRuntime(15457): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
06-03 16:23:10.540: E/AndroidRuntime(15457): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
06-03 16:23:10.540: E/AndroidRuntime(15457): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
06-03 16:23:10.540: E/AndroidRuntime(15457): at java.lang.Thread.run(Thread.java:856)
06-03 16:23:10.540: E/AndroidRuntime(15457): Caused by: java.lang.NullPointerException
06-03 16:23:10.540: E/AndroidRuntime(15457): at com.example.project.MainActivity$LoadAllProducts.doInBackground(MainActivity.java:498)
06-03 16:23:10.540: E/AndroidRuntime(15457): at com.example.project.MainActivity$LoadAllProducts.doInBackground(MainActivity.java:1)
06-03 16:23:10.540: E/AndroidRuntime(15457): at android.os.AsyncTask$2.call(AsyncTask.java:264)
06-03 16:23:10.540: E/AndroidRuntime(15457): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
06-03 16:23:10.540: E/AndroidRuntime(15457): ... 5 more
and my class is
public class asasa extends Activity {
//ListView listView;
Intent intent;
public int currentimageindex=0;
private ProgressDialog pDialog;
Timer timer;
TimerTask task;
ImageView slidingimage;
ProgressDialog progressDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
static final String URL = "http://172.20.55.175/android_connect/get_all_products.php";
private static final String TAG_SUCCESS = "success";
private TextView mStatusView;
private EditText searchEditText;
private static final String TAG_PRODUCTS = "products";
private static final String TAG_NAME = "name";
private static final String TAG_Description = "description";
private static final String TAG_URL = "url";
private static final String TAG_Price = "price";
ListView list;
LazyAdapter adapter;
// flag for Internet connection status
Boolean isInternetPresent = false;
// products JSONArray
JSONArray products = null;
// Connection detector class
ConnectionDetector cd;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cd = new ConnectionDetector(getApplicationContext());
// get Internet status
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
LoadAllProducts il = new LoadAllProducts();
il.execute(URL);
}
else
{
// Internet connection is not present
// Ask user to connect to Internet
Toast.makeText(asasa.this, "No Internet Connection You don't have internet connection.", Toast.LENGTH_LONG).show();
}
}
public void longToast(CharSequence message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private LayoutInflater inflater=null;
public ImageLoader imageLoader;
public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.list_row, null);
TextView title = (TextView)vi.findViewById(R.id.title); // title
TextView artist = (TextView)vi.findViewById(R.id.artist); // artist name
TextView duration = (TextView)vi.findViewById(R.id.duration); // duration
ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // thumb image
HashMap<String, String> song = new HashMap<String, String>();
song = data.get(position);
// Setting all values in listview
title.setText(song.get(asasa.TAG_NAME));
artist.setText(song.get(asasa.TAG_Description));
duration.setText(song.get(asasa.TAG_Price));
imageLoader.DisplayImage(song.get(asasa.TAG_URL), thumb_image);
return vi;
}
}
class LoadAllProducts extends AsyncTask<String, String, String> {
// creating new HashMap
ArrayList<HashMap<String, String>> productsList;
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(asasa.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>();
HashMap<String, String> map = new HashMap<String, String>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(URL, "GET", params);
// Check your log cat for JSON reponse
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()-1; i++) {
JSONObject c = products.getJSONObject(i);
String name = c.getString(TAG_NAME);
String description = c.getString(TAG_Description);
String URl = c.getString(TAG_URL);
String price = c.getString(TAG_Price);
// adding each child node to HashMap key => value
map.put(TAG_NAME, name);
map.put(TAG_Description, description);
map.put(TAG_URL, URl);
map.put(TAG_Price, price);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
}
} 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
list=(ListView)findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
adapter=new LazyAdapter(asasa.this, productsList);
list.setAdapter(adapter);
}
}
public void onPause()
{
super.onPause();
if (progressDialog.isShowing()) {
progressDialog.dismiss();
// progressDialog.setCancelable(true);
}
}
}
line 498 is
productsList.add(map);
in protected String doInBackground(String... args)
i cant figure out error...why it is occuring.it is succesfully return json response but can put in hashmap

You haven't initialized your
ArrayList<HashMap<String, String>> productsList;
Initialize it before using.
ArrayList<HashMap<String, String>> productsList = new ArrayList<HashMap<String, String>>();

ArrayList<HashMap<String, String>> productsList;
This only declares productsList. You never intialized it, so it's null by defaut. You should initialize it:
ArrayList<HashMap<String, String>> productsList = new ArrayList<HashMap<String, String>>();
Also usually I recommend using interface in the declaration, so you can later switch interface implementation if needed without much headache. Also specifying minimum visiblity possible is a good OOP practice as it enforces encapsulation.
private List<Map<String, String>> productsList = new ArrayList<HashMap<String, String>>();

Related

Android onPreExecute(), progressDialog and json.toString() error

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

go back error: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views

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

uunable to pass current activity from asynctask

I am trying to pass current activity object to custom listview adapter but am getting nullpointer exception as it is being passed from async class. Here's my code:
public class MainActivity extends Activity {
ListView list;
LazyAdapter adapter;
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://api.androidhive.info/contacts/";
// JSON Node names
static final String Events_date = "ev_date";
static final String TAG_CONTACTS = "contacts";
static final String TAG_ID = "id";
static final String TAG_NAME = "name";
static final String TAG_EMAIL = "email";
static final String TAG_ADDRESS = "address";
static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<HashMap<String, String>>();
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone node is JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_EMAIL, email);
contact.put(TAG_PHONE_MOBILE, mobile);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
list=(ListView)findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
adapter=new LazyAdapter(this, contactList);
list.setAdapter(adapter);
}
}
}
and here is adapterclass main code snippets
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
// public ImageLoader imageLoader;
public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// imageLoader=new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.list_row, null);
TextView title = (TextView)vi.findViewById(R.id.title); // title
TextView artist = (TextView)vi.findViewById(R.id.artist); // artist name
TextView duration = (TextView)vi.findViewById(R.id.duration); // duration
HashMap<String, String> song = new HashMap<String, String>();
song = data.get(position);
// Setting all values in listview
title.setText(song.get(CustomizedListView.KEY_TITLE));
artist.setText(song.get(CustomizedListView.KEY_ARTIST));
duration.setText(song.get(CustomizedListView.KEY_DURATION));
// imageLoader.DisplayImage(song.get(CustomizedListView.KEY_THUMB_URL), thumb_image);
return vi;
}
}
I understand that I am supposed to pass instance of MainActivity. So,can any one tell me how to do it, as if I am calling a function from postexecute then also getting nullpointer as data is not being inserted in hashmap.Kindly help!!!
Log cat:
01-25 23:08:29.779: D/Response:(607): "name": "Clint Eastwood",
01-25 23:08:29.779: D/Response:(607): "address": "xx-xx-xxxx,x - street, x - coun
01-25 23:08:30.029: D/AndroidRuntime(607): Shutting down VM
01-25 23:08:30.029: W/dalvikvm(607): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
01-25 23:08:30.052: E/AndroidRuntime(607): FATAL EXCEPTION: main
01-25 23:08:30.052: E/AndroidRuntime(607): at info.androidhive.jsonparsing.MainActivity$GetContacts.onPostExecute(MainActivity.java:155)
01-25 23:08:30.052: E/AndroidRuntime(607): at info.androidhive.jsonparsing.MainActivity$GetContacts.onPostExecute(MainActivity.java:1)
Use MainActivity.this to refer to the parent class this in a nested class such as your async task.
However, this requires that you keep your asynctask nested class non-static which isn't a good idea. Non-static nested class hold references to their parent (activity in this case) and since activity and asynctask lifecycles are different, the asynctask can hold onto the wrong activity for too long.
use adapter=new LazyAdapter(MainActivity.this, contactList);
only this will pass the asynctask class context.
You could create a new constructor for the AsyncTask accepting an Activity as input parameter
public GetContacts(Activity mActivity){
this.mActivity = mActivity;}
In the doInBackground method you could then use mActivity but be aware that until you have a reference to the Activity, this one cannot die.
When creating the AsyncTask from the MainActivity, you could just pass this as input parameter and it should work.

error in running two async task

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

Orientation change makes App crash (if done while loading SherlockFragment)

I have two tabs hosted in my Main Activity (I use ActionBarSherlock).
My fragments load and parse a distant xml to populate the listview.
If I change the device orientation when fragment is fully loaded, it loads again without problem with the new orientation.
But if I change it while the fragment is loading, the app force closes at the completion of loading.
Am I doing something wrong?
public class PartOne extends SherlockListFragment{
// All static variables
static final String URL = "http://Y.xml";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_TITLE = "title";
static final String KEY_CAT = "category";
static final String KEY_DESC = "description";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new BackgroundAsyncTask().execute();
}
public class BackgroundAsyncTask extends AsyncTask<String, String, ArrayList<HashMap<String, String>>> {
#Override
protected void onPreExecute() {
}
#Override
protected ArrayList<HashMap<String, String>> doInBackground(String... paths) {
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
if (xml != null) {
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
if(i%2 != 1) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// data to string (to modify them)
String titre = parser.getValue(e, KEY_TITLE);
String categorie = parser.getValue(e, KEY_CAT);
String description = parser.getValue(e, KEY_DESC);
// adding each child node to HashMap key => value
map.put(KEY_TITLE, titre);
map.put(KEY_CAT, categorie);
map.put(KEY_DESC, description);
// adding HashList to ArrayList
menuItems.add(map);
}
}
}
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.title)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.categ)).getText().toString();
String description = ((TextView) view.findViewById(R.id.desciption)).getText().toString();
// Starting new intent
Intent in = new Intent(view.getContext(), SingleMenuItemActivity.class);
in.putExtra(KEY_TITLE, name);
in.putExtra(KEY_CAT, cost);
in.putExtra(KEY_DESC, description);
startActivity(in);
}
});
return menuItems;
}
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
ListAdapter adapter = new SimpleAdapter(getActivity(),
result, R.layout.list_item,
new String[] {KEY_TITLE, KEY_DESC, KEY_CAT},
new int[] {R.id.title, R.id.desciption, R.id.categ});
setListAdapter(adapter);
}
}
Log :
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:278)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.IllegalStateException: Content view not yet created
at android.support.v4.app.ListFragment.ensureList(ListFragment.java:328)
at android.support.v4.app.ListFragment.getListView(ListFragment.java:222)
Handle your task in onConfigurationChanged (Configuration newConfig) mothod,
something like this
Thread th=null;
public void onCreate(bundle savedInstanceState)
{
//Initialize layout
if(th==null) //This is to check whether task is running
{
//Assign your task
th=new Thread();
th.start();
}
}
//handle the same here
public void onConfigurationChanged (Configuration newConfig)
{
//Do the layout changes
if(th==null)//This is to check whether task is running
{
//Assign your task
th=new Thread();
th.start();
}
}

Categories

Resources