【问题标题】:Start activity in doInBackground method在 doInBackground 方法中启动活动
【发布时间】:2012-11-09 03:16:09
【问题描述】:

在下面的代码中,我从 Internet 下载 json 并希望显示在列表中。 如果列表为空,则转到另一个活动,但其他活动未开始。 没有错误,但没有开始活动。 感谢您的帮助

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"}

【问题讨论】:

    标签: android android-asynctask


    【解决方案1】:

    您的问题最可能的原因是这一行:

    String success = jSon.getString(KEY_SUCCESS);
    

    您没有发布它,但我敢打赌最后一行下方有一个 JSONException 堆栈跟踪。 getString() 如果没有找到密钥,会抛出异常,并且在您注销的 JSON 数据中,没有“成功”密钥。该异常导致您在事后编写的所有代码根本没有被调用,这就是您看不到任何事情发生的原因。

    还有几点需要注意:

    1. success == "1" 不是进行字符串相等的正确方法。 == 操作符检查对象是否相等(同一个对象),如果你想检查两个字符串是否相同,我们 success.equals("1") 代替。
    2. onPostExecute() 总是在主线程上为您调用。您不必从方法中调用runOnUiThread()...这是多余的。
    3. 从技术上讲,像您所做的那样从后台线程启动 Activity 是可以的,但您不能以这种方式显示 Toast。当您修复异常时,Toast.makeText() 行最终会失败,因为您无法从主线程以外的线程显示 Toast。

    一般来说,最好在主线程上执行所有 UI 操作,并且作为设计点,您应该将任何操作或更改屏幕的代码移动到onPostExecute(),以便可以在正确的时间调用它。这就是它的用途。

    【讨论】:

    • 如何发现 KEY_SUCCESS 存在于 jSon 中?
    • 我这样做是:jSon.has(KEY_SUCCESS) 并且工作正常,谢谢。
    • 您也可以使用optString(),如果密钥不存在,它将简单地返回null,而不是完全炸毁。
    【解决方案2】:

    这很棘手。需要注意的一些事项:

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

    确保登录类的类型在清单中。通常您通过类的名称引用该类,而不是实例化的变量。老实说,它不应该有所作为,但值得一试。

    有时,使用不同的上下文会产生奇怪的副作用。我认为 startActivity 对此非常敏感。您可以尝试 AllNotes.this 来获取正在运行的活动的上下文。这需要在 UI 线程上运行的可能性很小,因此如果它不起作用,您可以尝试 runOnUiThread()。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多