Reputation: 117
I need to yield a JsonObject
in a class MainActivity
from a method doInBackground()
in a class Post
.
I instantiated the class Post
, called the method in it which is being passed parameters into, and tried to assign it to a variable of type JSONObject
.
This is the class Post
:
class Post extends AsyncTask<String, Void, JSONObject> {
@Override
protected JSONObject doInBackground(String... args) {
JSONObject jsonObject = null;
try {
//Connect to the website
Connection.Response response =
Jsoup.connect(args[0])
.method(Connection.Method.POST)
.data("text", args[1])
.data("language", args[2])
.ignoreContentType(true)
.execute();
Document document = response.parse();
jsonObject = new JSONObject(document.text());
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException err) {
Log.d("Error", err.toString());
}
return jsonObject;
}
}
And this is how I tried to retrieve the object in the class MainActivity
:
Post post = new Post();
JSONObject object = post.execute(stringurl, text, "en");
The Java error I get is incompatible types. Required is org.json.JSONObject
and found is android.os.AsyncTask <java.lang.String, java.lang.Void, org.json.JSONObject>
.
I should be able to capture the JSONObject
... how?
Upvotes: 0
Views: 63
Reputation: 13009
You can declare a method in MainActivity
which can be called from the AsyncTask
once it has fetched the JSONObject
:
private onObtainJSONObject(JSONObject jsonObject){
if(jsonObject != null){
// do something with the JSONObject
} else{
// something went wrong - maybe show an error message?
}
}
And you need to override onPostExecute()
in the AsyncTask
:
public void onPostExecute(JSONObject jsonObject){
// Note: this will be executed on the main thread
MainActivity.this.onObtainJSONObject(jsonObject);
}
If the AsyncTask
is not an inner class of your Activity
, you can use a callback (a simple interface) as follows
public interface PostCallback{
void onSuccess(JSONObject data);
void onError(Exception exception);
}
Then you let the AsyncTask
have a field of type PostCallback
and a setter setCallback(PostCallback)
.
In MainActivity
:
Post post = new Post();
post.setPostCallback(new PostCallback(){
@Override
onSuccess((JSONObject data){
onObtainJSONObject(data);
}
@Override
onError(Exception exception){
// exception handling ...
}
});
JSONObject object = post.execute(stringurl, text, "en");
In Post
:
private PostCallback callback;
private Exception exception;
public setPostCallback(PostCallback callback){
this.callback = callback;
}
@Override
protected JSONObject doInBackground(String... args){
// keep everything as before but when an Exception occurs,
// assign it to *exception* in the catch block
}
@Override
public void onPostExecute(JSONObject jsonObject){
// Note: this will be executed on the main thread
if(exception == null){
callback.onSuccess(jsonObject);
} else {
callback.onError(exception);
}
}
Upvotes: 1