我正在尝试从异步任务中发布祝酒词,并在堆栈上阅读此答案:
对这些问题的快速总结导致了这一点:
通过从 MainActivity 调用 getApplicationContext() 获取 Context 对象并将其作为参数传递给您的 AsyncTask
我对如何通过异步任务传递上下文以及如何调用它感到困惑:
我的异步任务是:
public class ReadLogInJSON extends AsyncTask<String, Void, String>
{
@Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return readJSONFeed(arg0[0]);
}
protected void onPostExecute(String result)
{
//decode json here
try{
JSONObject json = new JSONObject(result);
String status = json.getString("status");
if(status == "no"){
//toast logIN failed
String message = "Log In Failed";
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
else {
//get userName
//get user ID
//set preferences
//launch normal activity
}
}
catch(Exception e){
}
}
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
}
我用这个来称呼它:
new ReadLogInJSON().execute(url);