I am trying to pass a string from AsyncTask back to my Activity. Browsing through other similar questions (eg. here), I decided to use an interface listener.
Interface:
package com.example.myapplication;
public interface GetListener {
void passJSONGet(String s);
}
AsyncTask class:
package com.example.myapplication;
import android.content.Context;
import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class DataGetter extends AsyncTask<String, Void, String> {
Context context;
private GetListener GetListener;
public String jsonString;
DataGetter(Context ctx, GetListener listener) {
this.context = ctx;
this.GetListener = listener;
}
@Override
protected String doInBackground(String... params) {
String ip = params[0];
String scriptname = params[1];
String db = params[2];
String urladress = "http://" + ip + "/"+ scriptname +".php";
try {
URL url = new URL(urladress);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
OutputStream os = connection.getOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(os, "UTF-8");
String data = URLEncoder.encode("database", "UTF-8") + "=" + URLEncoder.encode(db, "UTF-8");
writer.write(data);
writer.flush();
writer.close();
BufferedReader reader = new BufferedReader(new
InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
break;
}
return sb.toString();
} catch (Exception e) {
return e.getMessage();
}
}
@Override
protected void onPostExecute(String result) {
GetListener.passJSONGet(result);
}
}
My Activity:
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import org.json.JSONArray;
import org.json.JSONException;
public class WeatherDisplay extends AppCompatActivity implements GetListener {
private JSONArray jsonArray;
private String jsonString;
@Override
protected void onCreate(Bundle savedInstanceState) {
// other code
DataGetter dataGetter = new DataGetter(this, WeatherDisplay.this);
dataGetter.execute(ip, "readLatestOutside", "weather");
Toast.makeText(this, this.jsonString, Toast.LENGTH_LONG).show();
this.jsonArray = new JSONArray(this.jsonString);
// furter code
}
@Override
public void passJSONGet(String jsonstring) {
this.jsonString = jsonstring;
}
The JSON is properly get from server and is seen in onPostExecute
normally, however, it isn't visible later on in WeatherDisplay
(the Toast is displayed empty, variable is still a nullpointer).
How do I resolve this issue? I am inexperienced and might've missed some trivial stuff.