简体   繁体   English

通过(从)AsyncTask发送意图到MainActivity

[英]Sending intent to MainActivity through (From) AsyncTask

I looked for a couple of questions asked on Stack Overflow for sending a int to my MainActivity and displaying it on my TextView . 我在Stack Overflow上询问了几个问题,该问题将int发送给MainActivity并将其显示在TextView上 But trying to initialize activity or context don't work.. The latest error I get is this: 但是尝试初始化活动或上下文无效。.我得到的最新错误是:

FATAL EXCEPTION: AsyncTask #1 Process: com.dahlstore.jsonparsingdemo, PID: 32123 java.lang.RuntimeException: An error occurred while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:309) at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354) at java.util.concurrent.FutureTask.setException(FutureTask.java:223) at java.util.concurrent.FutureTask.run(FutureTask.java:242) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) at java.lang.Thread.run(Thread.java:818) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.app.Activity.getApplicationContext()' on a null object reference at com.dahlstore.jsonparsingdemo.JSONTask.doInBackground(JSONTask.java:63) at com.dahlstore.jsonparsingdemo.JSONTask.doInBackground(JSONTask. 致命异常:AsyncTask#1进程:com.dahlstore.jsonparsingdemo,PID:32123 java.lang.RuntimeException:在Java上执行android.os.AsyncTask $ 3.done(AsyncTask.java:309)的doInBackground()时发生错误。 android上的util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)在java.util.concurrent.FutureTask.setException(FutureTask.java:223)在java.util.concurrent.FutureTask.run(FutureTask.java:242)在Android .os.AsyncTask $ SerialExecutor $ 1.run(AsyncTask.java:234)在java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)在java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java: 588)at java.lang.Thread.run(Thread.java:818)原因:java.lang.NullPointerException:尝试在null上调用虚拟方法'android.content.Context android.app.Activity.getApplicationContext()' com.dahlstore.jsonparsingdemo.JSONTask.doInBackground(JSONTask.com.dahlstore.jsonparsingdemo.JSONTask.doInBackground(JSONTask.java:63)上的对象引用 java:21) at android.os.AsyncTask$2.call(AsyncTask.java:295) at java.util.concurrent.FutureTask.run(FutureTask.java:237) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) at java.lang.Thread.run(Thread.java:818) 09-17 18:31:37.015 32123-32152/com.dahlstore.jsonparsingdemo E/Surface: getSlotFromBufferLocked: unknown buffer: 0xabea80a0 的android.os.AsyncTask $ 2.call(AsyncTask.java:295)的java:21)的android.os.AsyncTask $ SerialExecutor $ 1.run(AsyncTask的java.util.concurrent.FutureTask.run(FutureTask.java:237)的android.os.AsyncTask $ 2.call .java:234)at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)at java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java:588)at java.lang.Thread.run( Thread.java:818)09-17 18:31:37.015 32123-32152 / com.dahlstore.jsonparsingdemo E / Surface:getSlotFromBufferLocked:未知缓冲区:0xabea80a0

Could anybody explain why I can't send my intent even though I use Activity. 任何人都可以解释为什么即使使用Activity也无法发送意图。

/*ROW21*/      public class JSONTask extends AsyncTask<String,String, String>{

    OnDataSendToActivity dataSendToActivity;
    Activity activity;
    Intent intent;

    public JSONTask(MainActivity mainActivity) {
        dataSendToActivity = (OnDataSendToActivity)mainActivity;
    }

    public JSONTask(Activity activity){
        this.activity = activity;
    }

    @Override
    protected String doInBackground(String... params) {

        HttpURLConnection connection = null;
        BufferedReader reader = null;

        try {
            URL url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            InputStream stream = connection.getInputStream();

            reader = new BufferedReader(new InputStreamReader(stream));
            StringBuffer buffer = new StringBuffer();

            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            JSONObject parentObject = new JSONObject(buffer.toString());
            JSONObject query = parentObject.getJSONObject("query").optJSONObject("results").optJSONObject("channel").optJSONObject("item");
            String temperature = query.getJSONObject("condition").optString("temp");
            String text = query.getJSONObject("condition").optString("text");

            int code = query.getJSONObject("condition").optInt("code");
           **//ROW 63**  intent = new Intent(activity.getApplicationContext(),MainActivity.class); 

            intent.putExtra("code",code);

            return temperature + " °C " +" and "+ text;

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        activity.startActivity(intent);
        dataSendToActivity.sendData(result);
    }

}

MainActivity 主要活动

public class MainActivity extends AppCompatActivity implements OnDataSendToActivity{

    public TextView temperatureTextView,textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        temperatureTextView = (TextView) findViewById(R.id.temperatureTextView);
        textView = (TextView) findViewById(R.id.textView);

        new JSONTask(this).execute("https://query.yahooapis.com/v1/public/yql?q=select%20item%20from%20weather.forecast%20where%20woeid%3D906057%20and%20u%3D%27c%27&format=json");

        Intent intent = getIntent();
        if(intent!= null) {
            int code = getIntent().getIntExtra("code", 0);
            String codeToString = String.valueOf(code);
            textView.setText(codeToString);
        } else {
            Toast.makeText(MainActivity.this, "Intent is null", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void sendData(String str) {
        temperatureTextView.setText(str);
    }
}

UPDATED JSONTASK.JAVA 更新的JSONTASK.JAVA

public class JSONTask extends AsyncTask<String,String, String>{
    OnDataSendToActivity dataSendToActivity;
    Context context;

    // single constructor to initialize both the context and dataSendToActivity
    public JSONTask(Context context){
        this.context = context;
        dataSendToActivity = (OnDataSendToActivity) ((Activity) context);
    }

    @Override
    protected String doInBackground(String... params) {
        HttpURLConnection connection = null;
        BufferedReader reader = null;
        StringBuffer buffer = new StringBuffer();

        try {
            URL url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            InputStream stream = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(stream));
            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return buffer.toString();
    }

    @Override
    protected void onPostExecute(String result) {
        try {
            JSONObject parentObject = new JSONObject(result);
            JSONObject query = parentObject.getJSONObject("query").optJSONObject("results").optJSONObject("channel").optJSONObject("item");
            String temperature = query.getJSONObject("condition").optString("temp");
            String text = query.getJSONObject("condition").optString("text");
            int code = query.getJSONObject("condition").optInt("code");
            temperature += " °C " +" and "+ text;

            Intent intent = new Intent(context, MainActivity.class);
            intent.putExtra("code", code);
            context.startActivity(intent);
            if(dataSendToActivity != null){
                dataSendToActivity.sendData(temperature);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

UPDATED MAINACTIVITY 更新的维护性

public class MainActivity extends AppCompatActivity implements OnDataSendToActivity{

    public TextView temperatureTextView,textView;
    Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        temperatureTextView = (TextView) findViewById(R.id.temperatureTextView);
        textView = (TextView) findViewById(R.id.textView);
        intent = getIntent();
        new JSONTask(this).execute("https://query.yahooapis.com/v1/public/yql?q=select%20item%20from%20weather.forecast%20where%20woeid%3D906057%20and%20u%3D%27c%27&format=json");

    }


    @Override
    public void sendData(String str) {
        temperatureTextView.setText(str);
    }
}

You are getting an error because your activity is null. 您收到错误消息,因为您的activity为空。 This happends because you have two constructors. 发生这种情况是因为您有两个构造函数。

// this is the constructor that is called
public JSONTask(MainActivity mainActivity) {
    dataSendToActivity = (OnDataSendToActivity)mainActivity;
}

// this is not called
public JSONTask(Activity activity){
    this.activity = activity;
}

So your activity variable is never initialized. 因此,您的activity变量永远不会初始化。

See my changes, 看看我的变化,

public class JSONTask extends AsyncTask<String,String, String>{
    OnDataSendToActivity dataSendToActivity;
    Context context;

    // single constructor to initialize both the context and dataSendToActivity
    public JSONTask(Context context){
        this.context = context;
        dataSendToActivity = (OnDataSendToActivity) ((Activity) context);
    }

    @Override
    protected String doInBackground(String... params) {
        HttpURLConnection connection = null;
        BufferedReader reader = null;
        StringBuffer buffer = new StringBuffer();

        try {
            URL url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            InputStream stream = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(stream));
            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return buffer.toString();
    }

    @Override
    protected void onPostExecute(String result) {
        try {
            JSONObject parentObject = new JSONObject(result);
            JSONObject query = parentObject.getJSONObject("query").optJSONObject("results").optJSONObject("channel").optJSONObject("item");
            String temperature = query.getJSONObject("condition").optString("temp");
            String text = query.getJSONObject("condition").optString("text");
            int code = query.getJSONObject("condition").optInt("code");
            temperature += " °C " +" and "+ text;

            if(dataSendToActivity != null){
                dataSendToActivity.sendData(temperature, code);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

In your MainActivity , 在您的MainActivity

public class MainActivity extends AppCompatActivity implements OnDataSendToActivity {

    public TextView temperatureTextView,textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        temperatureTextView = (TextView) findViewById(R.id.temperatureTextView);
        textView = (TextView) findViewById(R.id.textView);

        new JSONTask(this).execute("https://query.yahooapis.com/v1/public/yql?q=select%20item%20from%20weather.forecast%20where%20woeid%3D906057%20and%20u%3D%27c%27&format=json");
    }

    @Override
    public void sendData(String str, String code) {
        temperatureTextView.setText(str);
        textView.setText(code);
    }
}

Your OnDataSendToActivity interface will become, 您的OnDataSendToActivity接口将变为

public interface OnDataSendToActivity {
    void sendData(String str, String code);
}

I think the mistake is you are using getIntExtra in the Async. 我认为错误是您在Async中使用getIntExtra。 Instead of that use putIntExtra to save the variable in the intent. 而不是使用putIntExtra将变量保存在意图中。

Put is to store the value and getIntent functions are used to get the data from the intent. Put是存储值,而getIntent函数用于从intent中获取数据。

Use this line, 使用此行,

intent = new Intent(getApplicationContext(),MainActivity.class); 

or 要么

intent = new Intent(YourClassName.class,MainActivity.class); 

You do not really have to use intent to send your "code" to the activity. 您实际上不必使用意图将“代码”发送到活动。 In your doInBackground, put your "code" into a string variable (you need to properly parse it) then put that string as an argument to your return. 在您的doInBackground中,将“代码”放入字符串变量(需要正确解析),然后将该字符串作为返回值的参数。

Then in postExecute(String result), the variable result should be the value your returned from doInBackground. 然后在postExecute(String result)中,变量result应该是您从doInBackground返回的值。 The dataSendToActivity.sendData(result) should work fine now. dataSendToActivity.sendData(result)现在应该可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM