Start activity in doInBackground method

前端 未结 2 1123
忘掉有多难
忘掉有多难 2021-01-25 23:47

In below code i download json from internet and want to show in list. if list is empty go to another activity but other activity not start. no error but no start activity. thank

相关标签:
2条回答
  • 2021-01-26 00:08

    The most likely cause of your problem is this line:

    String success = jSon.getString(KEY_SUCCESS);
    

    You didn't post it, but I'll bet there is a JSONException stack trace below that last line. getString() will throw an exception if the key is not found, and in the JSON data you logged out, there is no "success" key. That exception is causing all the code you wrote after the fact to not get called at all, which is why you see nothing happening.

    A couple other things to note:

    1. success == "1" is not the proper way to do String equality. The == operator checks object equality (same object), if you want to check if two Strings are the same, us success.equals("1") instead.
    2. onPostExecute() is always called on the main thread for you. You do not have to call runOnUiThread() from the method...it is redundant.
    3. It is technically okay to start an Activity from a background thread like you have done, but you cannot show a Toast this way. When you fix your exception, the Toast.makeText() line will end up failing because you cannot show a Toast from a thread other than the main thread.

    In general, it's best to do all UI operations on the main thread and as a point of design you should move any code that manipulates or changes the screen into onPostExecute() so it can be called at the right time. That's what it is there for.

    0 讨论(0)
  • 2021-01-26 00:22

    This gets tricky. Some things to watch out for:

     Intent i = new Intent(getApplicationContext(), login.class);
    

    Make sure that the login class's type is in the manifest. Usually you reference the class by the class's name, not the instantiated variable. Honestly, it shouldn't make a difference but it's worth trying.

    Sometimes you get weird side-effects using different contexts. I think startActivity is one that's pretty sensitive to this. You can try AllNotes.this to get the running activity's context. There's a slim chance that this needs to be run on the UI thread, so you can try runOnUiThread() if that doesn't work.

    0 讨论(0)
提交回复
热议问题