通过 (From) AsyncTask 向 MainActivity 发送意图
Sending intent to MainActivity through (From) AsyncTask
我在 Stack Overflow 上查找了几个关于将 int 发送到我的 MainActivity 并将其显示在我的 TextView[ 上的问题=30=]。但是尝试初始化 activity 或上下文不起作用..
我得到的最新错误是:
FATAL EXCEPTION: AsyncTask #1
Process: com.dahlstore.jsonparsingdemo, PID: 32123
java.lang.RuntimeException: An error occurred while executing
doInBackground()
at android.os.AsyncTask.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.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.java:21)
at android.os.AsyncTask.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor.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
任何人都可以解释为什么即使我使用 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);
}
}
主要Activity
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);
}
}
已更新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();
}
}
}
更新的主要活动
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);
}
}
我认为错误是您在异步中使用了 getIntExtra。而不是使用 putIntExtra 将变量保存在意图中。
Put是存储值,getIntent函数是用来获取intent中的数据。
使用这一行,
intent = new Intent(getApplicationContext(),MainActivity.class);
或
intent = new Intent(YourClassName.class,MainActivity.class);
您实际上不必使用意图将您的 "code" 发送到 activity。在您的 doInBackground 中,将您的 "code" 放入一个字符串变量(您需要正确解析它),然后将该字符串作为您的 return.
的参数
然后在 postExecute(String result) 中,变量 result 应该是您从 doInBackground return编辑的值。 dataSendToActivity.sendData(结果)现在应该可以正常工作了。
您收到错误消息,因为您的 activity
为空。发生这种情况是因为您有两个构造函数。
// 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;
}
因此您的 activity
变量从未被初始化。
查看我的更改,
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();
}
}
}
在你的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);
}
}
您的 OnDataSendToActivity
界面将变为,
public interface OnDataSendToActivity {
void sendData(String str, String code);
}
我在 Stack Overflow 上查找了几个关于将 int 发送到我的 MainActivity 并将其显示在我的 TextView[ 上的问题=30=]。但是尝试初始化 activity 或上下文不起作用.. 我得到的最新错误是:
FATAL EXCEPTION: AsyncTask #1 Process: com.dahlstore.jsonparsingdemo, PID: 32123 java.lang.RuntimeException: An error occurred while executing doInBackground() at android.os.AsyncTask.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.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.java:21) at android.os.AsyncTask.call(AsyncTask.java:295) at java.util.concurrent.FutureTask.run(FutureTask.java:237) at android.os.AsyncTask$SerialExecutor.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
任何人都可以解释为什么即使我使用 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);
}
}
主要Activity
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);
}
}
已更新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();
}
}
}
更新的主要活动
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);
}
}
我认为错误是您在异步中使用了 getIntExtra。而不是使用 putIntExtra 将变量保存在意图中。
Put是存储值,getIntent函数是用来获取intent中的数据。
使用这一行,
intent = new Intent(getApplicationContext(),MainActivity.class);
或
intent = new Intent(YourClassName.class,MainActivity.class);
您实际上不必使用意图将您的 "code" 发送到 activity。在您的 doInBackground 中,将您的 "code" 放入一个字符串变量(您需要正确解析它),然后将该字符串作为您的 return.
的参数然后在 postExecute(String result) 中,变量 result 应该是您从 doInBackground return编辑的值。 dataSendToActivity.sendData(结果)现在应该可以正常工作了。
您收到错误消息,因为您的 activity
为空。发生这种情况是因为您有两个构造函数。
// 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;
}
因此您的 activity
变量从未被初始化。
查看我的更改,
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();
}
}
}
在你的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);
}
}
您的 OnDataSendToActivity
界面将变为,
public interface OnDataSendToActivity {
void sendData(String str, String code);
}