In my AsyncTask I do a quite a long operation inside doInBackground() which assigns a value to a variable after completion of doInBackground().
I use the value of that variable to setup a part of the user interface in postExecute().
The problem is that doinbackground() is quite a long operation and postExecute() finishes first. That way I fail to obtain the value.
Here's what the problem is
private class bigwork extends AsyncTask<String, Void, Boolean> {
String foo = null;
#Override
protected void onPreExecute() {
}
#Override
protected Boolean doInBackground(final String... args) {
// Long operation sets variable 'foo' a new value
}
#Override
protected void onPostExecute(final Boolean success) {
// Make use of foo here
}
The problem is the value of foo I get in postExecute() is still null.
Usually you would pass the String directly to onPostExecute:
private class bigwork extends AsyncTask<String, Void, String>
{
#Override
protected void onPreExecute() {
}
#Override
protected Boolean doInBackground(final String... args) {
// Long operation
set variable 'foo' a new value
return foo;
}
#Override
protected void onPostExecute(String foo) {
if (foo != null) {
// success
}
// Make use of foo here
}
Override onPostExecute() function to perform some task after doInBackground() function has finished.Like this:
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
ServiceHandler sh = new ServiceHandler();
jsonStr=sh.makeServiceCall(arg0[0], ServiceHandler.GET);
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Log.i("jsin", jsonStr);
if(pd.isShowing()){
pd.dismiss();
}
try {
js = new JSONObject(jsonStr);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray results =null;
try {
results = js.getJSONArray("results");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int i = 0; i< results.length();i++)
{
JSONObject c = null;
try {
c = results.getJSONObject(i);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
placeName = c.getString(TAG_NAME);
ratings = c.getDouble(TAG_RATING);
HashMap<String, String> rest = new HashMap<String, String>();
rest.put(TAG_NAME, placeName);
rest.put(TAG_RATING, ratings+"");
placeList.add(rest);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ListAdapter adapter = new SimpleAdapter(getActivity().getApplicationContext(), placeList, R.layout.list_item, new String[]{TAG_NAME}, new int[]{R.id.list_text});
lv.setAdapter(adapter);
}
I am making http request in my doInBackground and after successful reply i am parsing json in onPostExecute() and displaying in a listview and obviously this code is in class extending AsyncTask class.
You should pass the parameter directly to onPostExecute. Quoting from the Android Developer Reference:
protected void onPostExecute (Result result)
Runs on the UI thread after doInBackground(Params...). The specified result is the value returned by doInBackground(Params...).
In case you need to pass more than one parameter wrap them in a class like:
public class MyClass
{
public String string1;
public String string2;
public MyClass(String a, String b){
string1 = a;
string2 = b;
}
}
Hope this helps.
Best regards.
Related
I'm currently studying this tutorial http://www.android-examples.com/android-json-parsing-retrieve-from-url-and-set-mysql-db-data/
It runs perfectly but now I would like to display all of the JSON values in the text view. I am new to JSON and only has a bit of experience in android.
Here is my MainActivity.java. I modified it a bit from the tutorial
public class MainActivity extends Activity {
TextView textview;
JSONObject json = null;
String str = "";
HttpResponse response;
Context context;
ProgressBar progressbar;
Button button;
JSONArray jArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressbar = (ProgressBar)findViewById(R.id.progressBar1);
textview = (TextView)findViewById(R.id.textView1);
button = (Button)findViewById(R.id.button1);
progressbar.setVisibility(View.GONE);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
progressbar.setVisibility(View.VISIBLE);
new GetTextViewData(context).execute();
}
});
}
public static Map<String,String> parse(JSONObject json , Map<String,String> out) throws JSONException{
Iterator<String> keys = json.keys();
while(keys.hasNext()){
String key = keys.next();
String val = null;
try{
JSONObject value = json.getJSONObject(key);
parse(value,out);
}catch(Exception e){
val = json.getString(key);
}
if(val != null){
out.put(key,val);
}
}
return out;
}
private class GetTextViewData extends AsyncTask<Void, Void, Void>
{
public Context context;
public GetTextViewData(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost("http://192.168.1.9:80/test-androidex/send-data.php");
try {
response = myClient.execute(myConnection);
str = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try{
JSONArray jArray = new JSONArray(str);
json = jArray.getJSONObject(0);
} catch ( JSONException e) {
e.printStackTrace();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result)
{
try {
textview.setText(json.getString("name"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
progressbar.setVisibility(View.GONE);
}
}
and this is my JSON. It is a lot different from the tutorial
[{"id":"1","name":"white","status":"0"},{"id":"2","name":"red","status":"10"},{"id":"5","name":"blue","status":"15"}]
So obviously my code only displays the first name "white". I can't understand how to iterate the JSONObject to display all the values. I tried the answers in other questions but I can't quite incorporate them in my code.
That's because you're just getting the first element from JSONArray. (Index 0)
You should iterate over JSONArray to get all the JSONObject within an array.
Like this,
JSONArray jArray = new JSONArray(str);
int total=jArray.length();
for(int i=0;i<total;i++) {
JSONObject json = jArray.getJSONObject(i); // Replace 0 with i'th index.
// use this json object to iterate over individual objects.
}
Here's example of json parsing and insert , update , delete or get data from server with source you should try this !
Happy Coding!
The problem of your code is what Alok Patel stated. But I see that the logic of your code needs some changes to do what you want (according to sample json that you posted). You called parse method on values which are in fact simple data while you should call it on jsonObjects.
I refactored your code as below to do what you want:
public class MainActivity extends Activity {
TextView textview;
JSONObject json = null;
String str = "";
HttpResponse response;
Context context;
ProgressBar progressbar;
Button button;
JSONArray jArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressbar = (ProgressBar)findViewById(R.id.progressBar1);
textview = (TextView)findViewById(R.id.textView1);
button = (Button)findViewById(R.id.button1);
progressbar.setVisibility(View.GONE);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
progressbar.setVisibility(View.VISIBLE);
new GetTextViewData(context).execute();
}
});
}
private class GetTextViewData extends AsyncTask<Void, Void, Void>
{
public Context context;
Map<String,String> out = new Map<String, String>();
public GetTextViewData(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost("http://192.168.1.9:80/test-androidex/send-data.php");
try {
response = myClient.execute(myConnection);
str = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try{
JSONArray jArray = new JSONArray(str);
int total=jArray.length();
for(int i=0;i<total;i++) {
JSONObject json = jArray.getJSONObject(i);
parse(json, out);
}
} catch ( JSONException e) {
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result)
{
try {
// print "out" object to console here by iterating over its keys
// or do any needed process on it here.
textview.setText(json.getString("name"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
progressbar.setVisibility(View.GONE);
}
Map<String,String> parse(JSONObject json , Map<String,String> out) throws JSONException{
Iterator<String> keys = json.keys();
while(keys.hasNext()){
String key = keys.next();
String val = null;
try{
val = json.getString(key);
}catch(Exception e){
}
if(val != null){
out.put(key,val);
}
}
return out;
}
}
I'm Using inner AsyncTask to Calculate the Average from remote DB,
I get the result but
The problem is : The value of Average available only in "onPostExecute" , I want this value to be accessible in "On Create ()" so I can send it to another AsyncTask in the same Activity
public class Place_details extends Activity {
RatingBar PlaceRatingBar;
UserSessionManager session;
String ID;
Double [] Place_rates;
int Total_place_rates;
float Average_place_rates;
// JSON
JSONParser jsonparser;
JSONObject JSONObject;
ProgressDialog ProgressDialog;
JSONArray jsonArray1;
int value;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_place_details);
PlaceRatingBar = (RatingBar) findViewById (R.id.Place_rating);
jsonparser = new JSONParser();
//Session
session = new UserSessionManager(Place_details.this);
new getPlaceRating().execute() ;
// Here I get 0.0 and not the correct Average
Toast.makeText(Place_details.this, ""+Average_place_rates, Toast.LENGTH_SHORT).show();
} // End Of OnCreate
public class getPlaceRating extends AsyncTask<String,String,String>{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
ProgressDialog = new ProgressDialog(Place_details.this);
ProgressDialog.setTitle("Wait....");
ProgressDialog.setIndeterminate(false);
ProgressDialog.setCancelable(true);
ProgressDialog.show();
}
#Override
protected String doInBackground(String...parma) {
// TODO Auto-generated method stub
List<NameValuePair> list = new ArrayList<NameValuePair>();
// passing place_id value
list.add(new BasicNameValuePair("id",String_Place_id));
try {
JSONObject = jsonparser.makeHttpRequest("http://192.168.1.2/Yourguideapplication/Place_rating2.php", "POST", list);
Log.e("pass 1", "connection success ");
}
catch (Exception e) {
Log.e("Fail 1", "Fail connection");
}
try {
value = JSONObject.getInt("value");
if (value==1){
//Place Rating
jsonArray1 = JSONObject.getJSONArray("Place_rating");
Place_rates = new Double[jsonArray1.length()];
Total_place_rates =0;
for (int i = 0 ; i < jsonArray1.length() ; i++)
{
JSONObject object = jsonArray1.getJSONObject(i);
Place_rates[i] = object.getDouble("Rating_box");
Total_place_rates+= Place_rates[i];
}
} else {
value = 0;
}
} catch (Exception e){
Log.d("ERORR",e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (value == 1){
//Place Rating
Average_place_rates = (float) (Total_place_rates/jsonArray1.length());
PlaceRatingBar.setRating((float) Average_place_rates);
} else {
Toast.makeText(Place_details.this, "Error", Toast.LENGTH_LONG).show();
}
ProgressDialog.dismiss();
}
}
}
Thank you
You can create something like
private interface CallbackListener<T> {
void onComputingFinished(T arg);
}
Make your activity implement this interface.
public class Place_details extends Activity implements CallbackListener<String> {
#Override
public void onComputingFinished(String arg) {
//do your stuff here
}
And register it as listener in your AsynTask class (create field and constructor in you AsyncTask class):
public class GetPlaceRating extends AsyncTask<String,String,String>{
private CallbackListener<String> mListener;
public GetPlaceRating(CallbackListener<String> listener) {
mListener = listener;
}
And when starting task
new GetPlaceRating(this).execute() ;
And in onPostExecute call
if (mListener != null) mListener.onComputingFinished(*your arg*);
I used String to replace generic T in this example, hope you understand you can use whatever you want.
EDITED:
If arguments are of the same type you can change signature of interface to:
private interface CallbackListener<T> {
void onComputingFinished(T ...args);
}
And access them as an array: args[0], args[1].
Or just specify what concrete arguments you want to pass, for example String, int and SomeClass:
private interface CallbackListener {
void onComputingFinished(String str, int value, SomeClass obj);
}
I'm using Android SDK 4.0 API14 and I want to run multiple AsyncTask in one class, I want the called async task to wait while the one before it is finished, but is seems I can't accomplish this, even if I test the status of the one currently being executed. this is my code :
if(isNetworkAvailable()){
new SpinnerTask().execute();
new RiderTask().execute();
new BankTask().execute();
}
//spinner bank
public class BankTask extends AsyncTask<Void, Void, String>{
String url="http://128.21.30.37:8080/E-Policy/ios/spaj_bank.htm?type=pusat";
public BankTask(){
this.url=url;
System.out.println(url);}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog=new ProgressDialog(Menu_SPPAJ.this);
dialog = ProgressDialog.show(Menu_SPPAJ.this, "Mohon Menunggu", "Penarikan data Rider..");}
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
String result = "";
try {
result = Connection.get(url);
System.out.println("tes " + result);
} catch (Exception e) {
// TODO: handle exception
result = "";
}
return result;
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
// TODO Auto-generated method stub
super.onPostExecute(result);
// Response(result.replace("\n", "").trim());
System.out.println("done for Bank");
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray PRODUK = jsonObject.getJSONArray("BANK PUSAT");
for (int i=0; i<PRODUK.length();i++){
JSONObject spinner = PRODUK.getJSONObject(i);
String LSBP_NAMA = spinner.optString("LSBP_NAMA");
int LSBP_ID = spinner.optInt("LSBP_ID");
helper.InsertBank(LSBP_ID, LSBP_NAMA);
// ListSpinner.add(VarSpinner);
System.out.println("tes VarSpinner");
}
}catch (Exception e) {
Log.d("TES", e.getMessage());
}
}
}
//spinner bank
public class CabBankTask extends AsyncTask<Void, Void, String>{
String url="http://128.21.30.37:8080/E-Policy/ios/spaj_bank.htm?type=cabang";
public CabBankTask(){
this.url=url;
System.out.println(url);}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog=new ProgressDialog(Menu_SPPAJ.this);
dialog = ProgressDialog.show(Menu_SPPAJ.this, "Mohon Menunggu", "Penarikan data Rider..");}
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
String result = "";
try {
result = Connection.get(url);
System.out.println("tes " + result);
} catch (Exception e) {
// TODO: handle exception
result = "";
}
return result;
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
// TODO Auto-generated method stub
super.onPostExecute(result);
// Response(result.replace("\n", "").trim());
System.out.println("done for Cabang");
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray PRODUK = jsonObject.getJSONArray("BANK CABANG");
for (int i=0; i<PRODUK.length();i++){
JSONObject spinner = PRODUK.getJSONObject(i);
int LSBP_ID = spinner.optInt("LSBP_ID");
int LBN_ID = spinner.optInt("LBN_ID");
String LBN_NAMA = spinner.optString("LBN_NAMA");
helper.InsertCabBank(LSBP_ID, LBN_ID, LBN_NAMA);
// ListSpinner.add(VarSpinner);
System.out.println("tes VarSpinner");
}
}catch (Exception e) {
Log.d("TES", e.getMessage());
}
}
}
//spinner produk
public class SpinnerTask extends AsyncTask<Void, Void, String>{
// String url="http://epolicy.sinarmasmsiglife.co.id/ios/spaj_prod.htm?model=1";
String url="http://128.21.30.37:8080/E-Policy/ios/spaj_prod.htm?type=bancass";
public SpinnerTask(){
this.url=url;
System.out.println(url);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog=new ProgressDialog(Menu_SPPAJ.this);
// dialog = ProgressDialog.show(Menu_SPPAJ.this, "Mohon Menunggu", "Penarikan data Produk..");
}
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
String result = "";
try {
result = Connection.get(url);
System.out.println("tes " + result);
} catch (Exception e) {
// TODO: handle exception
result = "";
}
return result;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
// dialog.dismiss();
super.onPostExecute(result);
fetchResponse(result.replace("\n", "").trim());
System.out.println("done for product");
}
}
private void fetchResponse(String result) {
if (!result.equals("")) {
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray PRODUK = jsonObject.getJSONArray("PRODUK");
for (int i=0; i<PRODUK.length();i++){
JSONObject spinner = PRODUK.getJSONObject(i);
String LSBS_ID = spinner.optString("LSBS_ID");
String LSBS_NAME = spinner.optString("LSBS_NAME");
helper.InsertSpin_Produk(LSBS_ID, LSBS_NAME);
// ListSpinner.add(VarSpinner);
System.out.println("tes VarSpinner");
JSONArray PRODUK1 = spinner.getJSONArray("SUB_PRODUK");
for (int j=0; j<PRODUK1.length();j++){
JSONObject sub = PRODUK1.getJSONObject(j);
String LSDBS_NUMBER = sub.optString("LSDBS_NUMBER");
String LSDBS_NAME = sub.optString("LSDBS_NAME");
helper.InsertSpin_SubProduk(LSBS_ID,LSBS_NAME,LSDBS_NUMBER, LSDBS_NAME);
System.out.println("tes VarSpinner 1\2");
}
}
}
catch (Exception e) {
Log.d("TES", e.getMessage());
}
}
}
//Rider
public class RiderTask extends AsyncTask<Void, Void, String>{
String url="http://128.21.30.37:8080/E-Policy/ios/spaj_prod.htm?type=rider";
public RiderTask(){
this.url=url;
System.out.println(url);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog=new ProgressDialog(Menu_SPPAJ.this);
dialog = ProgressDialog.show(Menu_SPPAJ.this, "Mohon Menunggu", "Penarikan data Rider..");
}
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
String result = "";
try {
result = Connection.get(url);
System.out.println("tes " + result);
} catch (Exception e) {
// TODO: handle exception
result = "";
}
return result;
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
// TODO Auto-generated method stub
super.onPostExecute(result);
Response(result.replace("\n", "").trim());
System.out.println("done for ridern");
}
}
is there any way to run multiple Asynctask in one class? thank u very much
Have a look on the AsyncTask.executeOnExecutor() method. It will run AsyncTasks in parallel. But make sure that the Tasks you run are independent from each other. As mentioned in the docs there is no given order in which the Tasks will be executed.
Call your Tasks like this:
new SpinnerTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
What you can do is, you can call second AsyncTask on onPostExecute() of first AsyncTask and so on.
e.g
public class FirstAsyncTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// your code
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// new SecondAsyncTask().execute();
}}
I am trying to implement simple internal data storage code.In it I want to show ProgressDialog for some background process which will increment by 5 while calling publishProgress(). But it gives me error like the following,
The method publishProgress(R.integer...) in the type AsyncTask<String,R.integer,String> is not applicable for the arguments (int)
following is the code.
public class loadSomeStuff extends AsyncTask<String, integer, String>
{
ProgressDialog dailog;
protected void onPreExecute()
{
//example of setting up something
dailog=new ProgressDialog(MainActivity.this);
dailog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dailog.setMax(100);
dailog.show();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String collected=null;
FileInputStream fis=null;
for(int i=1; i<=20; i++)
{
publishProgress(5);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
dailog.dismiss();
try {
fis=openFileInput(FileName);
byte[] dataArray = new byte[fis.available()];
while(fis.read(dataArray)!= -1)
{
collected=new String(dataArray);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
fis.close();
return collected;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
protected void onProgressUpdate(Integer...progress)
{
dailog.incrementProgressBy(5);
}
protected void onPostExecute(String result)
{
DataResults.setText(result);
}
}
Generics cannot use value types so your AsyncTask needs to use Integer:
extends AsyncTask<String, Integer, String>
try this :
extends AsyncTask<String, Integer, String>
Integer with a capital I
I have tried your code on my machine and its working fine without any error.
You can check now with my code.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadSomeStuff objSomeStuff = new loadSomeStuff();
objSomeStuff.execute();
}
public class loadSomeStuff extends AsyncTask<String, Integer, String>
{
ProgressDialog dailog;
protected void onPreExecute()
{
//example of setting up something
dailog=new ProgressDialog(MainActivity.this);
dailog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dailog.setMax(100);
dailog.show();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String collected=null;
FileInputStream fis=null;
for(int i=1; i<=20; i++)
{
publishProgress(5);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
dailog.dismiss();
try {
fis=openFileInput("");
byte[] dataArray = new byte[fis.available()];
while(fis.read(dataArray)!= -1)
{
collected=new String(dataArray);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
fis.close();
return collected;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
protected void onProgressUpdate(Integer...progress)
{
dailog.incrementProgressBy(5);
}
protected void onPostExecute(String result)
{
//DataResults.setText(result);
Toast.makeText(getApplicationContext(), "", Toast.LENGTH_LONG).show();
}
}
}
Alright I think you may have messed up with some namespaces. Here is what you need to do
Organize your imports Ctrl+Shift+O. make sure there is no invalid import. it may have happned if you copy & paste code from any other source.
Clean your project.
AsyncTask should look like this:
public class LoadSomeStuff extends AsyncTask<String, Integer, String>
Let me know if you still cant resolve it .
simple answer is that
in the Question Code Mention is
AsyncTask< String, integer, String>
But change that for progress updated
AsyncTask< String, Integer, String>
if use AsyncTask**< String, String, String>** then should be Cast into Interger for
progress update.
I am creating an Online Dictionary Android App.
I am using JSON to request for definitions for a word which the user inputs.
This input is into the variable "text" everytime the search button is clicked.
The Inputted word is then appended into the API request URL which returns the definition......which is stored in variable "result" in the bottom method OnPost Execute()
My TextView should then be set to this String.
I Therefore put the entire JSON and HTTPrequest code within the onClickLIstener because the user input always changes and requests everytime, but im getting an error at the "throws ClientProtocolException" after the "public JSONObject lastTweet(String word)" the error is "Syntax error on tokens, delete these tokens" I am Using Enclipse Indigo.
Here Is my Code:
public class Dictionary extends Activity {
String finalresult;
HttpClient client = new DefaultHttpClient();
TextView ansa;
JSONObject json;
Button Search;
EditText input;
String text;
final static String URL = "http://api.wordnik.com/v4/word.json/";
final static String URL2 = "/definitions?api_key=<MY API KEY>";
String fresult;
Dictionary dic = new Dictionary();
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.dictionary);
ansa = (TextView) findViewById(R.id.ansa);
input = (EditText) findViewById(R.id.input);
Search = (Button) findViewById(R.id.search);
Search.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
text = input.getText().toString();
public JSONObject lastTweet(String word)
throws ClientProtocolException, IOException, JSONException{
new Read().execute("text");
StringBuffer strBuff = new StringBuffer();
strBuff.append(URL);
strBuff.append(word);
strBuff.append(URL2);
HttpGet get = new HttpGet(strBuff.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if (status == 200){
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONArray timeline = new JSONArray(data);
JSONObject last = timeline.getJSONObject(0);
return last;
}else{
Toast.makeText(Dictionary.this, "error", Toast.LENGTH_LONG);
return null;
}
}
class Read extends AsyncTask<String, Integer, String>{
#Override
public String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
json = lastTweet(text);
return json.getString(params[0]);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
fresult = result;
// TODO Auto-generated method stub
}
}
ansa.setText(fresult);
}
});
}
public JSONObject lastTweet(String word)
throws ClientProtocolException, IOException, JSONException{
new Read().execute("text");
StringBuffer strBuff = new StringBuffer();
strBuff.append(URL);
strBuff.append(word);
strBuff.append(URL2);
HttpGet get = new HttpGet(strBuff.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if (status == 200){
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONArray timeline = new JSONArray(data);
JSONObject last = timeline.getJSONObject(0);
return last;
}else{
Toast.makeText(Dictionary.this, "error", Toast.LENGTH_LONG);
return null;
}
}
class Read extends AsyncTask<String, Integer, String>{
#Override
public String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
json = lastTweet(text);
return json.getString(params[0]);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
fresult = result;
// TODO Auto-generated method stub
}
}
}
Any Suggestions?
Have you tried moving the request code to another class?