medo medo - 3 months ago 16
Android Question

Android AsyncTask error when execute

this is my class for get Json f rom url

public class Json extends AsyncTask<Void , Void, JSONObject > {

String theUrl;
public AsyncResponse delegate = null;
InputStream is = null;
String result = "";
JSONObject jsonObject = null;
StringBuilder stringBuilder;
URLConnection urlConnection;
BufferedReader reader;

public Json(String theUrl , AsyncResponse delegate) {
this.theUrl = theUrl;
this.delegate = delegate;
}


public interface AsyncResponse {
void processFinish(JSONObject output);
}


@Override
protected JSONObject doInBackground(Void... params) {
try {
URL url = new URL(theUrl);
urlConnection = url.openConnection();

} catch(Exception e) {
Log.d("Fff22", " " +e);
return null;
}
// Read response to string
try {
reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}

result = sb.toString();

} catch(Exception e) {

return null;
}

// Convert string to object
try {
jsonObject = new JSONObject(result);
} catch(JSONException e) {
return null;
}

return jsonObject;
}

@Override
protected void onPreExecute() {
delegate.processFinish(jsonObject);
}

@Override
protected void onPostExecute(JSONObject jsonObject) {
super.onPostExecute(jsonObject);
}

@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}

@Override
protected void onCancelled(JSONObject jsonObject) {
super.onCancelled(jsonObject);
}

@Override
protected void onCancelled() {
super.onCancelled();
}


}


and on my actiivty i call it like this

String s = "http://192.168.0.106/json/259616167dfea1870e4d0330caa0323b.json";

Json fs = new Json(s, new Json.AsyncResponse(){
@Override
public void processFinish(JSONObject output) {
Log.d("fwwwwwww "," "+output);
}
}).execute();


but its be all on red color and show

incompatible types

required myjson class

found Anroid.os.asyncTask java.lang.void , java.lang.void , org.json.JSONObject

i have problem on asyncTask any help also i dont know if its good idea for get json file if there are another one and its better please write it

Answer

The return type of the AsyncTask.execute() method is always AsyncTask type, not your child class Json - that's why you get your error.

So it should be

AsyncTask<Void, Void, JSONObject> fs = new Json(s, new Json.AsyncResponse(){
...