Syntax error on token "extends", throws expected - when implementing AsyncTask - java

I'm attempting to implement asynctask into my existing source code but I'm getting an error stating Syntax error on token "extends", throws expected
If I change
public void run() extends AsyncTask {
to
public void run() throws AsyncTask {
as eclipse seems to be asking me to do - I end up with:
No exception of type AsyncTask can be thrown; an exception type must be a subclass of Throwable
I simply need to figure out what I've done wrong in my asyncTask implementation.
JAVA
public class GetYouTubeUserVideosTask implements Runnable {
public static final String LIBRARY = "Library";
private final Handler replyTo;
private final String username;
public GetYouTubeUserVideosTask(Handler replyTo, String username) {
this.replyTo = replyTo;
this.username = username;
}
#Override
public void run() extends AsyncTask {
try {
HttpClient client = new DefaultHttpClient();
HttpUriRequest request = new HttpGet("https://gdata.youtube.com/feeds/api/videos?author="+username+"&v=2&alt=jsonc");
HttpResponse response = client.execute(request);
String jsonString = StreamUtils.convertToString(response.getEntity().getContent());
JSONObject json = new JSONObject(jsonString);
JSONArray jsonArray = json.getJSONObject("data").getJSONArray("items");
List<Video> videos = new ArrayList<Video>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String title = jsonObject.getString("title");
String url;
try {
url = jsonObject.getJSONObject("player").getString("mobile");
} catch (JSONException ignore) {
url = jsonObject.getJSONObject("player").getString("default");
}
String thumbUrl = jsonObject.getJSONObject("thumbnail").getString("sqDefault");
videos.add(new Video(title, url, thumbUrl));
}
Library lib = new Library(username, videos);
Bundle data = new Bundle();
data.putSerializable(LIBRARY, lib);
Message msg = Message.obtain();
msg.setData(data);
replyTo.sendMessage(msg);
} catch (ClientProtocolException e) {
Log.e("Feck", e);
} catch (IOException e) {
Log.e("Feck", e);
} catch (JSONException e) {
Log.e("Feck", e);
}
}
protected void onPostExecute(String result) {
// do something
}
protected void onPreExecute() {
// do something
}
protected void onProgressUpdate(String... text) {
// do something
}
}

Your asyncTask should be like the following, the class should extends AsyncTask not implements Runnable:
public final class GetYouTubeUserVideosTask extends AsyncTask<Void, Void, Void> {
public static final String LIBRARY = "Library";
private final Handler replyTo;
private final String username;
public GetYouTubeUserVideosTask(Handler replyTo, String username) {
this.replyTo = replyTo;
this.username = username;
}
/*
* #see android.os.AsyncTask#doInBackground(Params[])
*/
#Override
protected Void doInBackground(Void... arg0) {
try {
HttpClient client = new DefaultHttpClient();
HttpUriRequest request = new HttpGet("https://gdata.youtube.com/feeds/api/videos?author="+username+"&v=2&alt=jsonc");
HttpResponse response = client.execute(request);
String jsonString = StreamUtils.convertToString(response.getEntity().getContent());
JSONObject json = new JSONObject(jsonString);
JSONArray jsonArray = json.getJSONObject("data").getJSONArray("items");
List<Video> videos = new ArrayList<Video>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String title = jsonObject.getString("title");
String url;
try {
url = jsonObject.getJSONObject("player").getString("mobile");
} catch (JSONException ignore) {
url = jsonObject.getJSONObject("player").getString("default");
}
String thumbUrl = jsonObject.getJSONObject("thumbnail").getString("sqDefault");
videos.add(new Video(title, url, thumbUrl));
}
Library lib = new Library(username, videos);
Bundle data = new Bundle();
data.putSerializable(LIBRARY, lib);
Message msg = Message.obtain();
msg.setData(data);
replyTo.sendMessage(msg);
} catch (ClientProtocolException e) {
Log.e("Feck", e);
} catch (IOException e) {
Log.e("Feck", e);
} catch (JSONException e) {
Log.e("Feck", e);
}
return null;
}
/*
* #see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
#Override
protected void onPostExecute(Void result) {
}
}

Related

Retrieve data to ListView from API in android

I need to retrieve data to listview from this link http://www.autotrack.rs/android_juzna_backa/get_voznja.php?. I need to send key, with value-POST method, to get something like this: http://www.autotrack.rs/android_juzna_backa/get_voznja.php?voznja_id=42. My code is bellow: Thanks. ERROR Value null at data of type org.json.JSONObject$1 cannot be converted to JSONArray
public class fetchData extends AsyncTask<String, String, String> {
#Override
public void onPreExecute() {
super.onPreExecute();
swipeRefresh.setRefreshing(true);
}
#Override
protected String doInBackground(String... params) {
arrayList.clear();
String result = null;
try {
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("text/plain");
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("voznja_id", "42")
.build();
Request request = new Request.Builder()
.url("http://www.autotrack.rs/android_juzna_backa/get_voznja.php")
.method("POST", body)
.build();
try {
response = client.newCall(request).execute();
// System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
return "";
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
#Override
public void onPostExecute(String rezultat) {
try {
rezultat = response.body().string();
}catch (Exception m)
{
m.printStackTrace();
}
Intent intent;
Gson gson = new Gson();
Type type = new TypeToken<Voznja>() {
}.getType();
Voznja voznja = gson.fromJson(rezultat, type);
Intent im = new Intent(getApplicationContext(), Unos.class);
im.putExtra("voznja", voznja);
// startActivity(im);
swipeRefresh.setRefreshing(false);
try {
JSONObject object = new JSONObject(rezultat);
JSONArray array = object.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
String id = jsonObject.getString("id");
String vozilo_id = jsonObject.getString("vozilo_id");
String vozac_id = jsonObject.getString("vozac_id");
String pocetna_kilometraza = jsonObject.getString("pocetna_kilometraza");
String pocetno_vreme = jsonObject.getString("pocetno_vreme");
String razlog = jsonObject.getString("razlog");
String zavrsna_kilometraza = jsonObject.getString("zavrsna_kilometraza");
String zavrsno_vreme = jsonObject.getString("zavrsno_vreme");
String moto_sati = jsonObject.getString("moto_sati");
String id_projekat_jb = jsonObject.getString("id_projekat_jb");
ItemModel model = new ItemModel();
model.setVoznja_id(id);
model.setVoziloId(vozilo_id);
model.setVozac_id(vozac_id);
model.setPocetnaKilometraza(pocetna_kilometraza);
model.setPocetnoVreme(pocetno_vreme);
model.setRazlog(razlog);
model.setZavrsnaKilometraza(zavrsna_kilometraza);
model.setZavrsnoVreme(zavrsno_vreme);
model.setMotoSati(moto_sati);
model.setProjekatId(id_projekat_jb);
arrayList.add(model);
}
} catch (JSONException e) {
e.printStackTrace();
}
VoznjaAdapter adapter = new VoznjaAdapter(ListaVoznji.this, arrayList);
listView.setAdapter(adapter);
Your api response is JSONObject.
{"data":{"id":"42","vozilo_id":"777777003561","vozac_id":"2","pocetna_kilometraza":"50000","pocetno_vreme":"2020-12-25 07:15:00","projekat":null,"razlog":"Sastanak","zavrsna_kilometraza":"50150","zavrsno_vreme":"2020-12-25 10:45:00","moto_sati":"3","insert_time":"2021-01-08 10:47:33.683885","id_projekat_jb":"330"}}
So you should use JSONObject instead JSONArray
try {
JSONObject object = new JSONObject(rezultat);
JSONObject jsonObject = object.getJSONObject("data");
String id = jsonObject.getString("id");
String vozilo_id = jsonObject.getString("vozilo_id");
String vozac_id = jsonObject.getString("vozac_id");
String pocetna_kilometraza = jsonObject.getString("pocetna_kilometraza");
String pocetno_vreme = jsonObject.getString("pocetno_vreme");
String razlog = jsonObject.getString("razlog");
String zavrsna_kilometraza = jsonObject.getString("zavrsna_kilometraza");
String zavrsno_vreme = jsonObject.getString("zavrsno_vreme");
String moto_sati = jsonObject.getString("moto_sati");
String id_projekat_jb = jsonObject.getString("id_projekat_jb");
ItemModel model = new ItemModel();
model.setVoznja_id(id);
model.setVoziloId(vozilo_id);
model.setVozac_id(vozac_id);
model.setPocetnaKilometraza(pocetna_kilometraza);
model.setPocetnoVreme(pocetno_vreme);
model.setRazlog(razlog);
model.setZavrsnaKilometraza(zavrsna_kilometraza);
model.setZavrsnoVreme(zavrsno_vreme);
model.setMotoSati(moto_sati);
model.setProjekatId(id_projekat_jb);
arrayList.add(model);
} catch (JSONException e) {
e.printStackTrace();
}

How do I make a call OK HttpRequest post from an isolated class using async?

I was using this in another place as async but I wanted to refactor to make it reusable, how can I reorganize the code in order to work as a consumable class?. It doesn't work if it's not async and the ip of the backend is well defined so it's not that. Any ideas?
public class HTTPRequestManager {
public static JSONArray fetchData(){
return null;
}
public static String postData(Context context, String url, String JSONData) {
return null;
}
/* #Override
protected Integer doInBackground(String... strings) {
try {
//1.create client Object
OkHttpClient client = new OkHttpClient();
//2.Define request being sent to server
RequestBody postData = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), JSONData);
Request request = new Request.Builder()
.url(context.getResources().getString(R.string.backend_base_url) + url)
.post(postData)
.build();
//3.Transport the request and wait for response to process next
Response response = client.newCall(request).execute();
String resultData = response.body().string();
if (resultData.equals("OK")) {
} else {
//post failed
return "FAILED";
}
return resultData;
} catch (Exception e) {
Log.d("API_CONNECTION_ERROR", "Couldn't connect to the API");
return "API_CONNECTION_ERROR";
}
}*/
}
I used to have this annonymous class embeeded in another class and it works(it's a get request) but the problem is that it's not reusable in that way:
public class AsyncHttpTask extends AsyncTask<String, Void, Integer> {
URL url = null;
#Override
protected void onPreExecute() {
getActivity().setProgressBarIndeterminateVisibility(true);
}
#Override
protected Integer doInBackground(String... params) {
Integer result = 0;
HttpURLConnection urlConnection;
try {
url = new URL (getResources().getString(R.string.backend_base_url) +
"api/flrcks/user/id/0/latitude/3000/longitude/300/within/9999999999999999999999999");
urlConnection = (HttpURLConnection) url.openConnection();
int statusCode = urlConnection.getResponseCode();
// 200 represents HTTP OK
if (statusCode == 200) {
BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
response.append(line);
}
parseResult(response.toString());
result = 1; // Successful
} else {
result = 0; //"Failed to fetch data!";
}
} catch (Exception e) {
Log.d(TAG, e.getLocalizedMessage());
}
return result; //"Failed to fetch data!";
}
#Override
protected void onPostExecute(Integer result) {
// Download complete. Let us update UI
progressBar.setVisibility(View.GONE);
if (result == 1) {
adapter = new MyRecyclerAdapter_Nearby(getActivity(), feedsList);
mRecyclerView.setAdapter(adapter);
checkAdapterIsEmpty();
} else {
Toast.makeText(getActivity(), "Failed to fetch data!", Toast.LENGTH_SHORT).show();
t.setVisibility(View.VISIBLE);
}
}
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONArray posts = response.getJSONArray("rows");
feedsList = new ArrayList<>();
JSONArray members;
for (int i = 0; i < posts.length(); i++) {
memberList = new ArrayList<>();
final JSONObject post = posts.optJSONObject(i);
members=post.getJSONArray("members");
final FeedItem item = new FeedItem();
//for (int i = 0; i < posts.length(); i++) {
//JSONObject post = posts.optJSONObject(i);
//FeedItem item = new FeedItem();
item.setId(post.optString("id"));
item.setTitle(post.optString("name"));
item.setDescription(post.optString("description"));
item.setPrivacy(post.optString("privacy_mode_description"));
item.setInitial_date(post.optString("initial_date"));
item.setThumbnail(post.optString("thumbnail"));
item.setColor_hex(post.optString("color_hex"));
item.setTag(post.optString("tag"));
item.setDistance(post.optInt("st_distance"));
//item.setThumbnail(post.optString("thumbnail"));
for(int k=0; k <members.length();k++)
{
MemberItem memberItem = new MemberItem();
JSONObject member = members.optJSONObject(k);
memberItem.setName(member.optString("name"));
memberItem.setUsername(member.optString("username"));
memberItem.setProfile_pic(member.optString("profile_pic"));
memberItem.setIs_moderator(member.optBoolean("is_moderator"));
memberItem.setFacebookId(member.optString("facebook_id"));
memberList.add(memberItem);
}
item.setMemberList(memberList);
feedsList.add(item);
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
}
What changes do I need to make to put it in an isolated file to be consumed by the whole app like for example in a file called OkHTTPRequests.class???
Create an interface
public interface OnWebResponseListener {
void onWebResponse(CommonUtilities.services service, String result);
}
create a public enum for identifying service. in my case i created a CommonUtilities java where i declared
public enum services {
LOGIN
}
Your Common File
public class CallAddr extends AsyncTask<String, Void, String> {
CommonUtilities.services service;
OnWebResponseListener onWebResponseListener;
String url;
FormBody.Builder body;
Request request;
OkHttpClient client;
final static String TAG = "CallAddr";
public CallAddr(Map<String, String> data, CommonUtilities.services service, OnWebResponseListener onWebResponseListener, String url) {
this.service = service;
this.onWebResponseListener = onWebResponseListener;
this.url = url;
body = new FormBody.Builder();
for (String key : data.keySet()) {
body.add(key, data.get(key));
}
client = new OkHttpClient();
}
#Override
protected String doInBackground(String... strings) {
String result = "";
request = new Request.Builder().url(url).post(body.build()).build();
try {
Response response = client.newCall(request).execute();
result = response.body().string();
} catch (Exception e) {
Log.e(TAG,Log.getStackTraceString(e));
}
return result;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (onWebResponseListener != null) {
onWebResponseListener.onWebResponse(service, s);
}
}
}

how to parse a json file when starts with

I want to parse the following JSON file but is starting with [ indicating to me that is an array, and then continues with { objects, my current parser is returning a JSON object.
My question is: how to modify the parser to parse this file? So that the parser will serve me for other JSON files, starting with objects or arrangements.
JSON FILE:
[{"codigo":1,"contenido":[{"codigo":1,"descripcion":"Lomo completo"},{"codigo":2,"descripcion":"Cerveza 1 Lt."}],"descripcion":"1 lomo completo y 1 cerveza de lt","precio":100.0},{"codigo":2,"contenido":[{"codigo":1,"descripcion":"Lomo completo"},{"codigo":2,"descripcion":"Cerveza 1 Lt."}],"descripcion":"2 lomo completo y 2 cerveza de lt","precio":190.0},{"codigo":3,"contenido":[{"codigo":1,"descripcion":"Lomo completo"},{"codigo":2,"descripcion":"Cerveza 1 Lt."}],"descripcion":"3 lomo completo y 3 cerveza de lt","precio":280.0},{"codigo":4,"contenido":[{"codigo":1,"descripcion":"Lomo completo"},{"codigo":2,"descripcion":"Cerveza 1 Lt."}],"descripcion":"4 lomo completo y 4 cerveza de lt","precio":370.0}]
JSON PARSER
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Try to parser JSON FILE
public class OfertaService extends Service {
private static final String URL = "http://192.168.0.13:8080/ofertas/listado";
private static final String TAG_CODIGO = "codigo";
private static final String TAG_CONTENIDO = "contenido";
private static final String TAG_DESCRIPCION = "descripcion";
private static final String TAG_PRECIO = "precio";
private static final String TAG_CODIGO_PRODUCTO = "codigo";
private static final String TAG_DESCRIPCION_PRODUCTO = "descripcion";
#SuppressWarnings("rawtypes")
private List listaOfertas = new ArrayList();
public List getListaOfertas() {
return listaOfertas;
}
public void setListaOfertas(List listaOfertas) {
this.listaOfertas = listaOfertas;
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#SuppressWarnings("unchecked")
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
new DoInBack().execute();
} catch (Exception e) {
System.out.println("error en proceso de segundo plano DoInBack");
}
return 0;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
private class DoInBack extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
JSONParser jParser = new JSONParser();
JSONArray ofertasArray = null;
JSONArray productos = null;
JSONObject json = jParser.getJSONFromUrl(URL);
try {
String codigo = json.getString(TAG_CODIGO);
for (int i = 0; i < ofertasArray.length(); i++) {
JSONObject of;
of = ofertasArray.getJSONObject(i);
String id = of.getString(TAG_CODIGO);
// productos = json.getJSONArray(0);
List listaProductos = new ArrayList();
for (int j = 0; j < productos.length(); j++) {
JSONObject pro = productos.getJSONObject(j);
String idProducto = pro.getString(TAG_CODIGO_PRODUCTO);
String descProducto = pro
.getString(TAG_DESCRIPCION_PRODUCTO);
Hashtable<String, String> producto = new Hashtable<String, String>();
producto.put(TAG_CODIGO_PRODUCTO, idProducto);
producto.put(TAG_DESCRIPCION_PRODUCTO, descProducto);
listaProductos.add(producto);
}
String descripcionOferta = of.getString(TAG_DESCRIPCION);
String precio = of.getString("precio");
Hashtable ht = new Hashtable();
ht.put(TAG_CODIGO, id);
ht.put(TAG_CONTENIDO, listaProductos);
ht.put(TAG_DESCRIPCION, descripcionOferta);
ht.put(TAG_PRECIO, precio);
listaOfertas.add(ht);
}
System.out.println("parseo finalizado");
} catch (Exception e) {
}
return null;
}
}
I want to parse the following JSON file but is starting with [
indicating to me that is an array
When json string starting with [ means string is JSONArray
how to modify the parser to parse this file?
1. Convert json String to JSONArray instead of JSONObject:
JSONArray jsonArray = new JSONArray(json);
2. Change return type of getJSONFromUrl method to JSONArray from JSONObject
3. In doInBackground get response from getJSONFromUrl method in JSONArray:
JSONArray jsonArray = jParser.getJSONFromUrl(URL);

Multiple if else statement with parameter in doGet() servlet

I am having some problem when trying to execute different method in servlet doGet(). So when my button on click, it will pass along the eventID:
viewDtlEventBtn.setOnClickListener(new OnClickListener(){
public void onClick(View v){
Intent eventDtlIntent = new Intent(context, EventDetail.class);
eventDtlIntent.putExtra("eventID", eventIDTV.getText());
startActivity(eventDtlIntent);
}
});
Then in my EventDetail class, I am executing the method in AsyncTask class:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.event_detail);
context = this;
Bundle extras = getIntent().getExtras();
if (extras != null) {
eventID = extras.getString("eventID");
}
eventModel.setEventID(eventID);
new GetEventDetailAsyncTask(context).execute(eventModel);
}
And in my AsyncTask class, I am calling the method in my controller which retrieving the JSON returned from servlet:
#Override
protected Double doInBackground(Event... params) {
try {
eventCtrl.getEventDetailByID(params[0]);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
And in my controller class:
public Event getEventDetailByID(Event event) throws JSONException {
Event eventModel = new Event();
String page;
JSONArray jsonArray;
String eventID = event.getEventID();
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(ENeighbourhoodActivity.URL
+ "?getEventDetailByID&eventID=" + eventID +"");
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity, "UTF-8");
page = "{\'EventDetail\':" + responseString + "}";
try {
JSONObject jsonObject = new JSONObject(page);
jsonArray = jsonObject.getJSONArray("EventDetail");
int length = jsonArray.length();
for (int i = 0; i < length; i++) {
JSONObject attribute = jsonArray.getJSONObject(i);
String eventName = attribute.getString("eventName");
eventModel.setEventName(eventName);
}
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return event;
}
And basically from here, I am accessing the servlet. And in my doGet() in serlvet class:
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
JSONArray jsonArray = new JSONArray();
PrintWriter out = response.getWriter();
if (request.getParameter("getAllEvent") != null) {
}
catch (JSONException je) {
System.out.println(je.getMessage());
} catch (Exception exc) {
System.out.println(exc.getMessage());
}
out.println(jsonArray.toString());
}
}
I already have one if statement for some other methods. I wonder how should I pass the getEventDetailByID and the eventID parameter into servlet so that it knows which method to runs.
Thanks in advance.
Here is a example of how you can get the eventID value.
//gets value from getEventDetailByID parameter.
String detail = request.getParameter("getEventDetailByID");
if (detail != null && !detail.equals("")) {
int eventId = Integer.parseInt(request.getParameter("eventID"));
//get event detail by id with id
//e.g resultObject = myMethod(detail, eventId);
}
Update 1:
A better way of doing what is required:
String action = request.getParameter("action");
if (action.equalsIgnoreCase("GetById")) {
int eventId = Integer.parseInt(request.getParameter("eventID"));
//get event detail by id with id
//e.g resultObject = getById(eventId);
} else if (action.equalsIgnoreCase("GetAllEvents")) {
//Get all events
//e.g resultObject = GetAllEvents();
} else {
}
The URL usage:
to get event by id:
http://localhost:8080/WebService/EventDetailServlet?action=GetById&eventID=46
to get all event details
http://localhost:8080/WebService/EventDetailServlet?action=GetAllEvents

Return data from AsyncTask class

How do I get the data from my AsyncTask? My MainActivity is calling the DataCall.getJSON function that triggers the AsyncTask but I am not sure how to get the data back to the original Activity.
MainActivity with call to DataCall that should return a string and save it in state_data
String state_data = DataCall.getJSON(spinnerURL,spinnerContentType);
DataCall:
public class DataCall extends Activity {
private static final String TAG = "MyApp";
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
protected void onPostExecute(String result) {
//THIS IS WHERE I NEED TO RETURN MY DATA TO THE MAIN ACTIVITY. (I am guessing)
}
}
public void getJSON(String myUrlString, String contentType) {
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://www.mywebsite.com/" + myUrlString });
}
}
modify your AsyncTask as below:
public class GetData extends AsyncTask<String, Void, String>
{
DataDownloadListener dataDownloadListener;
public GetData()
{
//Constructor may be parametric
}
public void setDataDownloadListener(DataDownloadListener dataDownloadListener) {
this.dataDownloadListener = dataDownloadListener;
}
#Override
protected Object doInBackground(Object... param)
{
// do your task...
return null;
}
#Override
protected void onPostExecute(Object results)
{
if(results != null)
{
dataDownloadListener.dataDownloadedSuccessfully(results);
}
else
dataDownloadListener.dataDownloadFailed();
}
public static interface DataDownloadListener {
void dataDownloadedSuccessfully(Object data);
void dataDownloadFailed();
}
}
and use it in your Activity
GetData getdata = new GetData();
getdata.setDataDownloadListener(new DataDownloadListener()
{
#SuppressWarnings("unchecked")
#Override
public void dataDownloadedSuccessfully(Object data) {
// handler result
}
#Override
public void dataDownloadFailed() {
// handler failure (e.g network not available etc.)
}
});
getdata.execute("");
NOTE: For the people who are reading this.
Please consider this post for the best and perhaps right implementation.
The key for me was to create a class called URLWithParams or something because AsyncTask will allow only 1 type to be sent IN, and I needed both the URL and the params for the HTTP request.
public class URLWithParams {
public String url;
public List<NameValuePair> nameValuePairs;
public URLWithParams()
{
nameValuePairs = new ArrayList<NameValuePair>();
}
}
and then I send it to a JSONClient:
public class JSONClient extends AsyncTask<URLWithParams, Void, String> {
private final static String TAG = "JSONClient";
ProgressDialog progressDialog ;
GetJSONListener getJSONListener;
public JSONClient(GetJSONListener listener){
this.getJSONListener = listener;
}
#Override
protected String doInBackground(URLWithParams... urls) {
return connect(urls[0].url, urls[0].nameValuePairs);
}
public static String connect(String url, List<NameValuePair> pairs)
{
HttpClient httpclient = new DefaultHttpClient();
if(url == null)
{
Log.d(TAG, "want to connect, but url is null");
}
else
{
Log.d(TAG, "starting connect with url " + url);
}
if(pairs == null)
{
Log.d(TAG, "want to connect, though pairs is null");
}
else
{
Log.d(TAG, "starting connect with this many pairs: " + pairs.size());
for(NameValuePair dog : pairs)
{
Log.d(TAG, "example: " + dog.toString());
}
}
// Execute the request
HttpResponse response;
try {
// Prepare a request object
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(pairs));
response = httpclient.execute(httpPost);
// Examine the response status
Log.i(TAG,response.getStatusLine().toString());
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
return json;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String json ) {
getJSONListener.onRemoteCallComplete(json);
}
public interface GetJSONListener {
public void onRemoteCallComplete(String jsonFromNet);
}
}
Then call it from my main class like this
public class BookCatalog implements GetJSONListener {
private final String TAG = this.getClass().getSimpleName();
private String catalog_url = "URL";
private void getCatalogFromServer() {
URLWithParams mURLWithParams = new URLWithParams();
mURLWithParams.url = catalog_url;
try {
JSONClient asyncPoster = new JSONClient(this);
asyncPoster.execute(mURLWithParams);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onRemoteCallComplete(String jsonBookCatalogList) {
Log.d(TAG, "received json catalog:");
Log.d(TAG, jsonBookCatalogList);
JSONObject bookCatalogResult;
try {
bookCatalogResult = (JSONObject) new JSONTokener(jsonBookCatalogList).nextValue();
JSONArray books = bookCatalogResult.getJSONArray("books");
if(books != null) {
ArrayList<String> newBookOrdering = new ArrayList<String>();
int num_books = books.length();
BookCatalogEntry temp;
DebugLog.d(TAG, "apparently we found " + Integer.toString(num_books) + " books.");
for(int book_id = 0; book_id < num_books; book_id++) {
JSONObject book = books.getJSONObject(book_id);
String title = book.getString("title");
int version = book.getInt("price");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Although i disagree creating a new activity for that simple task there is
startActivityForResult()
to get data from another activity.
Check this. You can store your data to the Intent's extras. But still if you have a large amount of data you better off write it to a file get the result from the other activity that is done downloading and then read the file.
Serialize it and then read it. The only way I'm aware of.
Some options:
a) Make your bean implement Serializable interface, you can then pass your bean through Intent.
b) Implement Application interface (you need to make an entry in manifest), Have setter\getter method in your Application class. You can set your bean in Application from AsyncTask and later retrieve from Activity.
Sorry for answering so late, i think by this time you might have solved this problem. when i was searching for something else, i came across your question. I'm pasting a link here which might of some help for others.

Categories