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();
}}
Related
I want to show string from another string in my MainActivity, but the string is getting printed in console. Here is my code:
public class MainActivity extends AppCompatActivity {
Button start;
public TextView showText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showText= (TextView)findViewById(R.id.textView);
start = (Button)findViewById(R.id.button);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RetrieveFeedTask click1 = new RetrieveFeedTask();
click1.execute();
showText.setText(click1.getString());
}
});
}
}
And the class:
class RetrieveFeedTask extends AsyncTask<Void, Void, String> {
static final String API_URL = "http://numbersapi.com/random/trivia?json";
private Exception exception;
public String finalString;
protected void onPreExecute() { }
protected String doInBackground(Void... urls) {
try {
URL url = new URL(API_URL );
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
while ((finalString = bufferedReader.readLine()) != null) {
stringBuilder.append(finalString).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
protected void onPostExecute(String response) {
if(response == null) {
response = "THERE WAS AN ERROR";
}
try {
JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
finalString = object.getString("text");
Log.i("Here",finalString);
} catch (JSONException e) {
}
}
public String getString() {
return this.finalString;
}
}
You require the finalString before it's populated with your data. the onPostExecute is executed after the doInBackground so you should pass your text view to your task and set it's value in the onPostExecute
public TextView showText;
public RetrieveFeedTask(TextView showText) { this.showText = showText; }
protected void onPostExecute(String response) {
if(response == null) {
response = "THERE WAS AN ERROR";
}
try {
JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
finalString = object.getString("text");
showText.setText(finalString ); // add this
Log.i("Here",finalString);
} catch (JSONException e) {
}
}
The problem is that showText.setText(click1.getString()); of your activity is called earlier than finalString = object.getString("text"); of your task.
Solution:
Create an interface:
public interface DataCallback {
void onNewData(String data);
}
and implement it in your activity:
public class MainActivity extends ... implements DataCallback
public void onNewData(String data) {
showText.setText(data);
}
Pass the interface to your asynctask when you create it:
RetrieveFeedTask click1 = new RetrieveFeedTask(this);
Call the interface inside the task in onPostExecute() to notify the activity that there is new data:
JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
finalString = object.getString("text");
callback.onNewData(finalString);
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 am trying to use pagination in an android project.There are 60 pieces of data which i want to display 10 at a time in a listview.But the problem is i am getting duplicates in the list that loads, i.e the first 10 are followed by the same 10 again:
The code:
public class VideoActivity extends Activity {
private ConnectionDetector cd;
public HttpResponse video_respons;
public String video_string_response1;
public ArrayList<NameValuePair> nameValuePairs_Video;
ArrayList<Ice_data> ice_list;
String URL="http://footballultimate.com/icebucket/index.php/api/getVideo";
String URL1="http://footballultimate.com/icebucket/index.php/api/getVideoByLimit";
JSONObject jsonobj;
JSONArray jsonarr;
Ice_data iceobj;
CustomIceAdapter ciadp;
ListView list;
int start = 1;
int limit = 10;
boolean loadingMore = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
ice_list=new ArrayList<Ice_data>();
// GEt all Data for Video
cd = new ConnectionDetector(VideoActivity.this);
Config.isInternetPresent = cd.isConnectingToInternet();
if (!Config.isInternetPresent) {
AlertDialog.Builder builder = new AlertDialog.Builder(VideoActivity.this);
// Shuld be fail icon
builder.setIcon(R.drawable.ic_launcher);
builder.setMessage("Connection Not Available !" + "\n"
+ "Please enable your Internet Connection");
builder.setTitle("INTERNET CONNECTION");
builder.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
} else {
new GetVideos().execute();
}
// Get all Data for Video
list= (ListView) findViewById(R.id.videoList);
list.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView arg0, int arg1) {
// TODO Auto-generated method stub
}
#Override
public void onScroll(AbsListView arg0, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
int lastInScreen = firstVisibleItem + visibleItemCount;
if((lastInScreen == totalItemCount) && !(loadingMore)){
new GetVideos().execute();
}
}
});
}
class GetVideos extends AsyncTask<String, String, String> {
private ProgressDialog pDialog;
private HttpResponse vip_respons;
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(VideoActivity.this);
pDialog.setTitle("Processing...");
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
loadingMore = true;
// TODO Auto-generated method stub
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL1);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("start",String.valueOf(start)));
nameValuePairs.add(new BasicNameValuePair("limit",String.valueOf(limit)));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
video_respons = httpclient.execute(httppost);
//video_string_response1 = getResponseBody(video_respons);
video_string_response1=responsetostring.getResponseBody(video_respons);
//Log.d("Store_Response", the_string_response1);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String video_string) {
try{
if(pDialog.isShowing()){
pDialog.dismiss();
}
}
catch(Exception e){
e.printStackTrace();
}
finally
{
pDialog.dismiss();
}
if (video_string_response1!=null) {
//displayjsonstring();
geticevalues(video_string_response1);
}
}
}
public void geticevalues(String result)
{
try {
jsonobj=new JSONObject(result);
//ice_list=new ArrayList<Ice_data>();
jsonarr=jsonobj.getJSONArray("video_data");
for(int i=0;i<jsonarr.length();i++)
{
JSONObject jso=jsonarr.getJSONObject(i);
iceobj=new Ice_data();
iceobj.title=jso.getString("title");
iceobj.image_URL=jso.getString("image");
iceobj.video_URL=jso.getString("url");
ice_list.add(iceobj);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ciadp=new CustomIceAdapter(VideoActivity.this,ice_list);
ciadp.notifyDataSetChanged();
loadingMore = false;
list.setAdapter(ciadp);
start+=10;
}
The start and limit are the values which show the starting and the number of items in each request.I have also increamented the start value as start+=10.I am passing the start and limit values to the webservice in the async class.
Is there a more elegant way to do the above?Or can you fix the above code.Please help!!
initialization of ice_list inside doInBackground will eliminate duplicates
protected String doInBackground(String... arg0) {
loadingMore = true;
ice_list=new ArrayList<Ice_data>();
// TODO Auto-generated method stub
try {......................
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.