user3506 user3506 - 2 months ago 7
Android Question

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. 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.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


Could anybody explain why I can't send my intent even though I use 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

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);
}
}

Answer

You are getting an error because your activity is null. 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.

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;

            Intent intent = new Intent(activity, 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();
        }
    }
}