I am trying to post a toast from an async task and was reading this answer on stack:
Raising a Toast From AsyncTask
Quick summary of that questions leads to this:
Get the Context object by calling getApplicationContext() from MainActivity and pass it as a parameter to your AsyncTask
I am confused on how to pass a context through async task and how to call it:
my async task is:
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();
}
}
And I call it with this:
new ReadLogInJSON().execute(url);