启动活动在doInBackground方法 [英] Start activity in doInBackground method

查看:100
本文介绍了启动活动在doInBackground方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在从互联网上低于codeI下载JSON,并希望在列表中显示。 如果列表为空,去到另一个活动,但其他活动无法启动。 没有错误,但无从下手的活动。 感谢您的帮助

 包ir.mohammadi.android.nightly;

进口的java.util.ArrayList;
进口的java.util.HashMap;

进口org.json.JSONArray;
进口org.json.JSONException;
进口org.json.JSONObject;

进口android.app.ListActivity;
进口android.app.ProgressDialog;
进口android.content.Intent;
进口android.os.AsyncTask;
进口android.os.Bundle;
进口android.util.Log;
进口android.widget.ListAdapter;
进口android.widget.ListView;
进口android.widget.SimpleAdapter;
进口android.widget.Toast;

公共类AllNotes扩展ListActivity {

    ProgressDialog pDialog;

    ArrayList的< HashMap的<字符串,字符串>> noteList;

    JSONArray注意到= NULL;

    私有静态字符串KEY_SUCCESS =成功;
    私有静态字符串KEY_ERROR_MSG =ERROR_MESSAGE;
    私有静态字符串KEY_NOTE_ID =note_id;
    私有静态字符串KEY_NOTE_SUBJECT =note_subject;
    私有静态字符串KEY_NOTE_DATE =note_date;

    私有静态字符串EXECUTE_RESULT = NULL;

    @覆盖
    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.note_list);

        noteList =新的ArrayList< HashMap的<字符串,字符串>>();
        新LoadAllNotes()执行();
        ListView的LV = getListView();
    }

    公共类LoadAllNotes扩展的AsyncTask<字符串,字符串,字符串> {
        @覆盖
        在preExecute保护无效(){
            super.on preExecute();
            pDialog =新ProgressDialog(AllNotes.this);
            pDialog.setMessage(لطفاصبرکنید......);
            pDialog.setIndeterminate(假);
            pDialog.setCancelable(真正的);
            pDialog.show();
        }

        保护字符串doInBackground(字符串参数... args){

            UserFunctions userFunctions =新UserFunctions();

            的JSONObject JSON = userFunctions.getAllNotes(1);

            Log.i(AllNotes>> JSON>>中,jSon.toString());
            尝试 {
                字符串的成功= jSon.getString(KEY_SUCCESS);
                如果(成功==1){
                    注释= jSon.getJSONArray(票据);

                    的for(int i = 0; I< notes.length();我++){
                        JSONObject的C = notes.getJSONObject(我);

                        字符串ID = c.getString(KEY_NOTE_ID);
                        字符串主题= c.getString(KEY_NOTE_SUBJECT);
                        字符串日期= c.getString(KEY_NOTE_DATE);

                        HashMap的<字符串,字符串>图=新的HashMap<字符串,字符串>();
                        map.put(KEY_NOTE_ID,ID);
                        map.put(KEY_NOTE_SUBJECT,学科);
                        map.put(KEY_NOTE_DATE,日期);

                        noteList.add(图)
                    }

                } 其他 {

                    完();
                    Toast.makeText(getApplicationContext(),
                            jSon.getString(KEY_ERROR_MSG),Toast.LENGTH_SHORT).show();

                    Log.i(AllNotes>&GT否夜间>>中,...);

                    意图I =新的意图(getApplicationContext(),login.class);
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(ⅰ);
                }
            }赶上(JSONException E){
                e.printStackTrace();
            }

            返回null;
        }

        保护无效onPostExecute(字符串file_url){
            pDialog.dismiss();

            runOnUiThread(新的Runnable(){

                公共无效的run(){
                    ListAdapter适配器=新SimpleAdapter(AllNotes.this,
                            noteList,R.layout.list_item,新的String [] {
                                    KEY_NOTE_ID,KEY_NOTE_SUBJECT,
                                    KEY_NOTE_DATE},新的INT [] {
                                    R.id.list_lbl_id,R.id.list_lbl_subject,
                                    R.id.list_lbl_date});
                    setListAdapter(适配器);
                }
            });
        }
    }
}
 

logcat的JSON:

  11-08 22:17:44.467:I / getAllNotes PARAMS净&GT获得前;>(599):[标签= getNotesList,USER_ID = 1]
11-08 22:17:47.647:I /输入流>>(599):org.apache.http.conn.EofSensorInputStream@44ededd8
11-08 22:17:47.767的:I / JSON字符串助洗剂>>(599):一个{错误:1,ERROR_MESSAGE:\ u0634 \ u0645 \ u0627 \ u0647 ​​\ u0646 \ u0648 \ u0632 \ u0634 \ u0628 \ u0627 \ u0646 \ u0647 ​​\ u0627 \ u06cc \ u0646 \ u0646 \ u0648 \ u0634 \ u062a \ u0647 ​​\ u0627 \ u06cc \ u062f。}
11-08 22:17:47.797:净&GT后得到的I / getAllNotes PARAMS;>(599):{错误:1,ERROR_MESSAGE:不要有任何笔记}
11-08 22:17:47.797:I / AllNotes>> JSON>>(599):{错误:1,ERROR_MESSAGE:不要有任何笔记}
 

解决方案

你的问题的最可能的原因是该行:

 字符串成功= jSon.getString(KEY_SUCCESS);
 

您没有发布,但我敢打赌,有低于上年线JSONException堆栈跟踪。 的getString()如果没有找到钥匙,并在您退出JSON数据,没有成功键会抛出异常。这种异常是造成所有code你写不被调用后,其实在所有的,这就是为什么你看到什么情况发生。

一对夫妇的其他注意事项:

  1. 成功==1不是正确的方式做字符串相等。该 == 运营商检查对象平等(同一个对象),如果你要检查,如果两个字符串是相同的,我们 success.equals(1 )代替。
  2. onPostExecute <$ C C $>()总是要求你在主线程。你不必叫 runOnUiThread()从方法......这是多余的。
  3. 这在技术上是好的开始从后台线程就像你做了一个活动,但你不能表现出吐司这种方式。当您解决您的例外, Toast.makeText()行最终会失败,因为你不能从一个线程比主线程其他显示吐司。

在一般情况下,这是最好做的所有UI操作的主线程,并作为一个点的设计,你应该将任何code表示操纵或改变屏幕进入 onPostExecute(),以便它可以被称为在正确的时间。那它是什么在那里。

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. thanks for your help

package ir.mohammadi.android.nightly;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class AllNotes extends ListActivity {

    ProgressDialog pDialog;

    ArrayList<HashMap<String, String>> noteList;

    JSONArray notes = null;

    private static String KEY_SUCCESS = "success";
    private static String KEY_ERROR_MSG = "error_message";
    private static String KEY_NOTE_ID = "note_id";
    private static String KEY_NOTE_SUBJECT = "note_subject";
    private static String KEY_NOTE_DATE = "note_date";

    private static String EXECUTE_RESULT = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.note_list);

        noteList = new ArrayList<HashMap<String, String>>();
        new LoadAllNotes().execute();
        ListView lv = getListView();
    }

    public class LoadAllNotes extends AsyncTask<String, String, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(AllNotes.this);
            pDialog.setMessage("لطفا صبر کنید...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        protected String doInBackground(String... args) {

            UserFunctions userFunctions = new UserFunctions();

            JSONObject jSon = userFunctions.getAllNotes("1");

            Log.i("AllNotes >> jSon >>", jSon.toString());
            try {
                String success = jSon.getString(KEY_SUCCESS);
                if (success == "1") {
                    notes = jSon.getJSONArray("notes");

                    for (int i = 0; i < notes.length(); i++) {
                        JSONObject c = notes.getJSONObject(i);

                        String id = c.getString(KEY_NOTE_ID);
                        String subject = c.getString(KEY_NOTE_SUBJECT);
                        String date = c.getString(KEY_NOTE_DATE);

                        HashMap<String, String> map = new HashMap<String, String>();
                        map.put(KEY_NOTE_ID, id);
                        map.put(KEY_NOTE_SUBJECT, subject);
                        map.put(KEY_NOTE_DATE, date);

                        noteList.add(map);
                    }

                } else {

                    finish();
                    Toast.makeText(getApplicationContext(),
                            jSon.getString(KEY_ERROR_MSG), Toast.LENGTH_SHORT).show();

                    Log.i("AllNotes >> No nightly >>", "...");

                    Intent i = new Intent(getApplicationContext(), login.class);
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(i);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        protected void onPostExecute(String file_url) {
            pDialog.dismiss();

            runOnUiThread(new Runnable() {

                public void run() {
                    ListAdapter adapter = new SimpleAdapter(AllNotes.this,
                            noteList, R.layout.list_item, new String[] {
                                    KEY_NOTE_ID, KEY_NOTE_SUBJECT,
                                    KEY_NOTE_DATE }, new int[] {
                                    R.id.list_lbl_id, R.id.list_lbl_subject,
                                    R.id.list_lbl_date });
                    setListAdapter(adapter);
                }
            });
        }
    }
}

Logcat json :

11-08 22:17:44.467: I/getAllNotes params before getting from net >>(599): [tag=getNotesList, user_id=1]
11-08 22:17:47.647: I/Input stream >>(599): org.apache.http.conn.EofSensorInputStream@44ededd8
11-08 22:17:47.767: I/JSON string builder >>(599): a{"error":"1","error_message":"\u0634\u0645\u0627 \u0647\u0646\u0648\u0632 \u0634\u0628\u0627\u0646\u0647 \u0627\u06cc \u0646\u0646\u0648\u0634\u062a\u0647 \u0627\u06cc\u062f."}
11-08 22:17:47.797: I/getAllNotes params after getting from net >>(599): {"error":"1","error_message":"dont have any note"}
11-08 22:17:47.797: I/AllNotes >> jSon >>(599): {"error":"1","error_message":"dont have any note"}

解决方案

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.

这篇关于启动活动在doInBackground方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆