**我有这三个课程。我的Mainactivity,newactivity和一个扩展AsyncTask的活动,现在在一个扩展Asynctask的活动中,我需要在AsyncTask的OnPostExecute()上启动新的活动。我怎样才能做到这一点?我已经完成了上下文操作,但是我从执行后台任务行的mainactivity中出错,但是应用程序崩溃了,请帮助**
这是mainactivity类
import pandas as pd
from sklearn import datasets, linear_model
from sklearn.model_selection import train_test_split
from matplotlib import pyplot as plt
columns = "age sex bmi map tc ldl hdl tch ltg glu".split() # Declare the columns names
diabetes = datasets.load_diabetes() # Call the diabetes dataset from sklearn
df = pd.DataFrame(diabetes.data, columns=columns) # load the dataset as a pandas data frame
y = diabetes.target # define the target variable (dependent variable) as y
答案 0 :(得分:1)
您必须使用上下文创建构造函数
public class fetchdata extends AsyncTask<Void,Void,Void> {
String data="";
String dataparsed="";
String singleparsed="";
List<Entry> x;
List<String> y;
boolean flag=false;
private WeakReference<Context> contextRef;
public fetchdata(Context context) {
contextRef = new WeakReference<>(context);
}
@Override
protected Void doInBackground(Void... voids) {
x = new ArrayList<Entry>();
y = new ArrayList<String>();
try {
URL url=new URL("https://io.adafruit.com/api/v2/Yarev/feeds/pir-sensor/data");
HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();
InputStream inputStream=httpURLConnection.getInputStream();
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
String line="";
while (line!=null)
{
line=bufferedReader.readLine();
data=data+line;
}
JSONArray JA=new JSONArray(data);
for(int i=0;i<JA.length();i++)
{
JSONObject JO= (JSONObject) JA.get(i);
singleparsed="Value:"+JO.get("value")+"\n"+
"Feed key:"+JO.get("feed_key")+"\n"+
"Created:"+JO.get("created_at")+"\n";
int value=JO.getInt("value");
float v1=value;
x.add(new Entry(i,v1));
dataparsed=dataparsed+singleparsed;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (context != null) {
// start new activity with context
Intent intent=new Intent(context,NewActivity.class);
context.startActivity(intent);
}
}
public List<Entry> getList() {
return x;
}
}
开始努力:
new fetchdata(this).execute();