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

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

问题描述

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

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 :

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":"u0634u0645u0627 u0647u0646u0648u0632 u0634u0628u0627u0646u0647 u0627u06cc u0646u0646u0648u0634u062au0647 u0627u06ccu062f."}
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);

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

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.

其他一些注意事项:

  1. success == "1" 不是实现字符串相等的正确方法.== 运算符检查对象是否相等(同一对象),如果要检查两个 String 是否相同,则使用 success.equals("1") 代替.
  2. onPostExecute() 总是在主线程上为您调用.您不必从方法中调用 runOnUiThread()...它是多余的.
  3. 从技术上讲,像您一样从后台线程启动 Activity 是可以的,但您不能以这种方式显示 Toast.当您修复异常时,Toast.makeText() 行最终会失败,因为您无法从主线程以外的线程显示 Toast.
  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.

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

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天全站免登陆