Start activity in doInBackground method

前端 未结 2 1124
忘掉有多难
忘掉有多难 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.

提交回复
热议问题