Showing a dialog while requesting GPS location in FragmentActivity using a AsyncTask - java

I'm having a lot of trouble with showing a dialog while getting a GPS fix :(
Code: http://pastie.org/private/5a1yclz1qt7wywafpmdckw
MyLocation code from here: https://stackoverflow.com/a/3145655/3210508
locationResult = new MyLocation.LocationResult() {
#Override
public void gotLocation(Location location)
{
lat = location.getLatitude();
lon = location.getLongitude();
acc = location.getAccuracy();
Log.i("TRIREC", "Got location: " + lat + ", " + lon + ", " + acc);
}
};
myLocation = new MyLocation();
myLocation.getLocation(Home.this, locationResult);
Error when calling above code outside of runonuithread
20136-20364/nl.deadpixel.trianglerecycling E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: nl.deadpixel.trianglerecycling, PID: 20136
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: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:200)
at android.os.Handler.<init>(Handler.java:114)
at android.location.LocationManager$ListenerTransport$1.<init>(LocationManager.java:221)
at android.location.LocationManager$ListenerTransport.<init>(LocationManager.java:221)
at android.location.LocationManager.wrapListener(LocationManager.java:844)
at android.location.LocationManager.requestLocationUpdates(LocationManager.java:857)
at android.location.LocationManager.requestLocationUpdates(LocationManager.java:454)
at nl.deadpixel.trianglerecycling.MyLocation.getLocation(MyLocation.java:38)
at nl.deadpixel.trianglerecycling.Home$getLocationTask.doInBackground(Home.java:288)
at nl.deadpixel.trianglerecycling.Home$getLocationTask.doInBackground(Home.java:254)
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)

Related

whenever i try to enter my settings logcat show me this error and i don't know what is wrong

I'm trying to list all installed applications on my setting Listview but whenever I try to enter to it it freezes and closed iI don't know why, it seems everything is fine.
I even tried some ready answers but logcat keeps showing me this error.
2019-02-01 23:27:17.563 7458-7479/com.example.sony.econet1 E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.example.sony.econet1, PID: 7458
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:318)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
at com.example.sony.econet1.My_Settings$LoaddAppsInfoTask.doInBackground(My_Settings.java:79)
at com.example.sony.econet1.My_Settings$LoaddAppsInfoTask.doInBackground(My_Settings.java:65)
at android.os.AsyncTask$2.call(AsyncTask.java:304)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
this is my AsyncTask
class LoaddAppsInfoTask extends AsyncTask <Integer, Integer,List<AppInfo>>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
//loaded();
//loadappsinfo
}
#Override
protected List<AppInfo> doInBackground(Integer... params) {
List<AppInfo> apps=new ArrayList<>();
PackageManager packageManager =getPackageManager();
List<ApplicationInfo> infos = packageManager.getInstalledApplications(params[0]);
for (ApplicationInfo info:infos)
{
if (mIncludeSystemApps && (info.flags & ApplicationInfo.FLAG_SYSTEM) == 1)
{
continue;
}
AppInfo app = new AppInfo();
app.info = info;
app.label = (String)info.loadLabel(packageManager);
apps.add(app);
}
return null;
}
#Override
protected void onPostExecute(List<AppInfo> appInfos) {
super.onPostExecute(appInfos);
listView.setAdapter(new Appadapter(My_Settings.this,appInfos));
Snackbar.make(listView,appInfos.size() + "Applications loaded", Snackbar.LENGTH_LONG).show();
}

Android IAP getPurchases NullPointerException

I have implemented the In-App Billing feature in my app, it works on most of the devices but some of them reported a null pointer exception. Here are the stacktrace:
Fatal Exception: java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:304)
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:818)
Caused by java.lang.NullPointerException: Attempt to invoke virtual method 'long java.lang.Long.longValue()' on a null object reference
at android.os.Parcel.readException(Parcel.java:1552)
at android.os.Parcel.readException(Parcel.java:1499)
at com.android.vending.billing.IInAppBillingService$Stub$Proxy.getPurchases(IInAppBillingService.java:349)
at com.vectorspace.roadcon.MyApplication$1$1.doInBackground(MyApplication.java:84)
at com.vectorspace.roadcon.MyApplication$1$1.doInBackground(MyApplication.java:78)
at android.os.AsyncTask$2.call(AsyncTask.java:292)
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:818)
And I am running the above code inside an Asynctask in OnServiceConnected:
#Override
public void onServiceConnected(ComponentName name,
IBinder service) {
mService = IInAppBillingService.Stub.asInterface(service);
AsyncTask<Object, Void, Bundle> getPurchasedItemTask = new AsyncTask<Object, Void, Bundle>() {
#Override
protected Bundle doInBackground(Object... objects) {
try {
Bundle ownedItems = mService.getPurchases(3, getPackageName(), "inapp", null);
return ownedItems;
} catch (RemoteException e) {
e.printStackTrace();
}
return null;
}
I have no idea what's wrong, please help.

Get List<string> from db class and store in other class

I am creating a selection of questions in my db class (SQLDatabaseHelper.java) and have a method which creates a ListArray for use in other classes:
public List<List<String>> getAllAnswersByQuestion2() {
List<String> array1 = new ArrayList<String>();
List<String> array2 = new ArrayList<String>();
//Clear arrays just in case they still existed and had values
array1.clear();
array2.clear();
SQLiteDatabase db = this.getReadableDatabase();
//Get 5 random values from the questions table
String selectQuery = "SELECT DISTINCT questionDescr, answerSetId FROM " + TABLE_QUESTION + " ORDER BY RANDOM() LIMIT 5";
Cursor c = db.rawQuery(selectQuery, null);
try {
//Ignore any null values in the table, go the first value
if (c!= null && c.moveToFirst())
{
do {
//Create two strings - one for all question descriptions and one for answersetIDs
String questdescr = c.getString(c.getColumnIndex(QDESCR));
String answerSetIds = c.getString(c.getColumnIndex(ASID));
//Put these strings into two separate arrays
array1.add(questdescr);
array2.add(answerSetIds);
//And when all values have been put into arrays......
} while (c.moveToNext());
}
//Create another array to bundle up the two arrays already created
List< List<String> > listArray = new ArrayList< List<String> >();
//Clear this array just in case of residual values
listArray.clear();
listArray.add(array1);
listArray.add(array2);
//Return this array to be picked up in the 'showRandomNextQuestion' method
return listArray;
} finally {
//Close cursor and database to prevent memory leaks
c.close();
db.close();
}
}
I have a separate class (QuizQuestionBank.java) which tries to take the returned ListArray and splits it into two separate List for further use:
import java.util.List;
import android.app.Application;
public class QuizQuestionBank extends Application {
Object db;
#SuppressWarnings("unused")
private List<String> questionStrings;
public List<String> getQuestionStrings() {
SQLDatabaseHelper db = new SQLDatabaseHelper(QuizQuestionBank.this);
//get the data from the database
List<List<String>> listList = db.getAllAnswersByQuestion2();
//Get the question/text/answer Strings
List<String> questionStrings = listList.get(0); //question Strings
return questionStrings;
}
public List<String> setQuestionStrings(List<String> questionStrings) {
return this.questionStrings = questionStrings;
}
}
And finally I have a MainActivity that tries to get the List from my QuizQuestionBank class, and use that to get a value within to then output into a textview:
private class showNextRandomQuestion1 extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
QuizQuestionBank qb = new QuizQuestionBank();
//question Strings
List<String> questionStrings = qb.getQuestionStrings();
//Generate random index
Random r = new Random();
int rand = Math.abs((r.nextInt() % questionStrings.size()));
String questionString = questionStrings.get(rand);
//remove and square brackets from array of strings
String regex = "\\[|\\]";
aQuestionString = questionString.replaceAll(regex, "");
return aQuestionString;
}
#Override
protected void onPostExecute(String result) {
//take returned question from above and display it
questionView.setText(aQuestionString);
}
}
however, I am currently getting the following errors when my 'showNextRandomQuestion1()' method is called:
08-31 19:24:55.637: I/Choreographer(20638): Skipped 63 frames! The application may be doing too much work on its main thread.
08-31 19:24:55.887: I/ActivityManager(20638): Timeline: Activity_idle id: android.os.BinderProxy#41ec2f08 time:939408562
08-31 19:25:01.887: W/dalvikvm(20638): threadid=13: thread exiting with uncaught exception (group=0x41a71d88)
08-31 19:25:02.037: E/AndroidRuntime(20638): FATAL EXCEPTION: AsyncTask #2
08-31 19:25:02.037: E/AndroidRuntime(20638): Process: com.example.quizapp, PID: 20638
08-31 19:25:02.037: E/AndroidRuntime(20638): java.lang.RuntimeException: An error occured while executing doInBackground()
08-31 19:25:02.037: E/AndroidRuntime(20638): at android.os.AsyncTask$3.done(AsyncTask.java:300)
08-31 19:25:02.037: E/AndroidRuntime(20638): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
08-31 19:25:02.037: E/AndroidRuntime(20638): at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
08-31 19:25:02.037: E/AndroidRuntime(20638): at java.util.concurrent.FutureTask.run(FutureTask.java:242)
08-31 19:25:02.037: E/AndroidRuntime(20638): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
08-31 19:25:02.037: E/AndroidRuntime(20638): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
08-31 19:25:02.037: E/AndroidRuntime(20638): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
08-31 19:25:02.037: E/AndroidRuntime(20638): at java.lang.Thread.run(Thread.java:841)
08-31 19:25:02.037: E/AndroidRuntime(20638): Caused by: java.lang.NullPointerException
08-31 19:25:02.037: E/AndroidRuntime(20638): at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:263)
08-31 19:25:02.037: E/AndroidRuntime(20638): at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:224)
08-31 19:25:02.037: E/AndroidRuntime(20638): at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:188)
08-31 19:25:02.037: E/AndroidRuntime(20638): at com.example.quizapp.SQLDatabaseHelper.getAllAnswersByQuestion2(SQLDatabaseHelper.java:445)
08-31 19:25:02.037: E/AndroidRuntime(20638): at com.example.quizapp.QuizQuestionBank.getQuestionStrings(QuizQuestionBank.java:20)
08-31 19:25:02.037: E/AndroidRuntime(20638): at com.example.quizapp.MainActivity$showNextRandomQuestion1.doInBackground(MainActivity.java:371)
08-31 19:25:02.037: E/AndroidRuntime(20638): at com.example.quizapp.MainActivity$showNextRandomQuestion1.doInBackground(MainActivity.java:1)
08-31 19:25:02.037: E/AndroidRuntime(20638): at android.os.AsyncTask$2.call(AsyncTask.java:288)
08-31 19:25:02.037: E/AndroidRuntime(20638): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
08-31 19:25:02.037: E/AndroidRuntime(20638): ... 4 more
08-31 19:25:02.227: W/dalvikvm(20638): threadid=14: thread exiting with uncaught exception (group=0x41a71d88)
08-31 19:25:02.227: I/Process(20638): Sending signal. PID: 20638 SIG: 9
It seems it is having initial trouble when my QuizQuestionBank class is trying to retrieve the listarray from the db helper class. Anyone see what I need to do to get around this? Many thanks
Try this in your onPostExecute:
Change this
questionView.setText(aQuestionString);
to
questionView.setText(result);

java.lang.NullPointerException occuring, developing android, how do I fix that? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
java.lang.NullPointerException occuring
Log-cat says Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference
Here's my code:
I'm trying to get jSon data from a server(MySql) database, then displaying it in a list.
public class AllProducts extends ListActivity {
private ProgressDialog pDialog;
JSONParser jParser=new JSONParser();
ArrayList<HashMap<String,String>> productsList;
private static String url_all_products = "http://server:host.../view.php";
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";
JSONArray products=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_products);
productsList=new ArrayList<HashMap<String, String>>();
new LoadAllProducts().execute();
Exception at new LoadAllProducts().execute();
ListView lv = getListView();
}
class LoadAllProducts extends AsyncTask<String,String,String>
Java.lang.NullPointerException Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference
occuring at class LoadAllProducts extends AsyncTask<String,String,String>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog= new ProgressDialog(AllProducts.this);
pDialog.setMessage("Loading Products....Wait..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
Exception at pDialog.show();
}
#Override
protected String doInBackground(String... params) {
ContentValues param=new ContentValues();
JSONObject json= jParser.makeHttpRequest(url_all_products,"GET",param);
Log.d("All Products: ", json.toString());
java.lang.NullPointerException occuring at Log.d("All Products: ", json.toString());
try{
int success=json.getInt(TAG_SUCCESS);
if(success==1)
{
products = json.getJSONArray(TAG_PRODUCTS);
for(int j=0; j<products.length() ; j++ )
{
JSONObject c = products.getJSONObject(j);
String id=c.getString(TAG_PID);
String name=c.getString(TAG_NAME);
HashMap<String,String> map=new HashMap<String,String>();
map.put(TAG_PID,id);
map.put(TAG_NAME,name);
productsList.add(map);
}
}
else {
Intent i=new Intent(getApplicationContext(),NewProduct.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
}catch(JSONException e)
{
e.printStackTrace();
}
return null;
}
}
}
I have a button in my UI to get data from server and show it in a list, as i tap the button, pDialog shows and then the app goes "not responding" and these exceptions occur
Here is the LogCat
09-03 16:10:40.500 27696-31923/com.example.vashisht.myapplication W/System.err﹕ at libcore.io.IoBridge.connectErrno(IoBridge.java:137)
09-03 16:10:40.500 27696-31923/com.example.vashisht.myapplication W/System.err﹕ at libcore.io.IoBridge.connect(IoBridge.java:122)
09-03 16:10:40.500 27696-31923/com.example.vashisht.myapplication W/System.err﹕ ... 19 more
09-03 16:10:40.500 27696-31923/com.example.vashisht.myapplication E/Buffer Error﹕ Error converting result java.lang.NullPointerException: lock == null
09-03 16:10:40.500 27696-31923/com.example.vashisht.myapplication E/JSON Parser﹕ Error parsing data org.json.JSONException: End of input at character 0 of
09-03 16:10:40.510 27696-31923/com.example.vashisht.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.example.vashisht.myapplication, PID: 27696
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:818)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference
at com.example.vashisht.myapplication.AllProducts$LoadAllProducts.doInBackground(AllProducts.java:76)
at com.example.vashisht.myapplication.AllProducts$LoadAllProducts.doInBackground(AllProducts.java:57)
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:818)
09-03 16:10:40.980 27696-27696/com.example.vashisht.myapplication E/WindowManager﹕ android.view.WindowLeaked: Activity com.example.vashisht.myapplication.AllProducts has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{10a4b377 V.E..... R......D 0,0-1026,348} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:382)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:261)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:298)
at com.example.vashisht.myapplication.AllProducts$LoadAllProducts.onPreExecute(AllProducts.java:67)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at com.example.vashisht.myapplication.AllProducts.onCreate(AllProducts.java:50)
at android.app.Activity.performCreate(Activity.java:5958)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1129)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2364)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2474)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1359)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5696)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1029)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:824)
09-03 16:10:44.250 27696-31923/com.example.vashisht.myapplication D/Process﹕ killProcess, pid=27696
09-03 16:10:44.260 27696-31923/com.example.vashisht.myapplication D/Process﹕ com.android.internal.os.RuntimeInit$UncaughtHandler.uncaughtException:138 java.lang.ThreadGroup.uncaughtException:693 java.lang.ThreadGroup.uncaughtException:690
this means that the JSONObject json == null. You can check this in code before calling methods on the JSONObject. I guess you dont actually get data when you call the httprequest.

Android populate listview from arraylist Error

I am trying to populate a listview in my android App (android studio) from a list to which I dynamically added Strings.
First, the list is declared as an attribute of the activity:
private List<String> your_array_list = new ArrayList<String>();
Then, I have the class where the method populatelist() is called. There are other methods called in it, but they all work fine, populatelist() is the only method that gives me an error:
private class SendMessage extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
parse(message);
populatelist();
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
And this is the method itself:
public void populatelist() {
// String[] myitems = {"World Weather Online","Open Weather Map","Weather"};
Log.d("Matcher", "Populate! Test 1");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.items,R.id.textting,your_array_list);
Log.d("Matcher", "Populate! Test 2");
ListView list;
Log.d("Matcher", "Populate! Test 3");
list = (ListView) findViewById(R.id.services);
Log.d("Matcher", "Populate! Test 4");
list.setAdapter(adapter);
Log.d("Matcher", "Populate! Test 5");
}
All the logs print except the last one "Test 5". When I run my app, I get the following error:
07-19 21:13:32.399 1575-1591/com.example.othmane.servicefinder E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #2
Process: com.example.othmane.servicefinder, PID: 1575
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:818)
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:6247)
at android.view.ViewRootImpl.focusableViewAvailable(ViewRootImpl.java:2855)
at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:679)
at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:679)
at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:679)
at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:679)
at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:679)
at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:679)
at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:679)
at android.view.View.setFlags(View.java:9603)
at android.view.View.setFocusableInTouchMode(View.java:6741)
at android.widget.AdapterView.checkFocus(AdapterView.java:722)
at android.widget.ListView.setAdapter(ListView.java:488)
at com.example.othmane.servicefinder.MainActivity.populatelist(MainActivity.java:277)
at com.example.othmane.servicefinder.MainActivity$SendMessage.doInBackground(MainActivity.java:100)
at com.example.othmane.servicefinder.MainActivity$SendMessage.doInBackground(MainActivity.java:67)
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:818)
Does anyone see any mistake of how I try to populate the list ? I followed a tutorial to do it, but I don't know why it does not work.
Read the logcat and you will see the answer:
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. at
The error is caused by you are trying to populate view in the background thread. In order to perform work in the main thread, you need to call onPostExecute method.
Here is the example from one of my app:
public class FetchArtistData extends AsyncTask<String,Void, List<Artist>> {
private static final String TAG="FetchArtistData";
#Override
protected List<Artist> doInBackground(String... params) {
SpotifyApi api=new SpotifyApi();
SpotifyService spotify=api.getService();
ArtistsPager results=spotify.searchArtists(params[0]);
List<Artist> list=results.artists.items;
Log.d(TAG, list.toString());
return list;
}
#Override
protected void onPostExecute(List<Artist> artists) {
mArtistList=(ArrayList<Artist>)artists;
Log.d(TAG,Integer.toString(mArtistList.size()));
updateAdapter(mArtistList);
}
}
Noticed that I update the view in onPostExecute.

Categories

Resources