I want take the information of a list view made with a hasmap and for this i have made this code:
public class MainActivity extends Activity {
ListView rdv;
HashMap<String, String> map;
ArrayList<HashMap<String, String>> rdvous = new ArrayList<>();
String URL;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
URL = "http://172.16.32.101/?mot=listerrdv&id=5";
rdv = (ListView)findViewById(R.id.listRDV);
new HttpAsyncTask().execute(URL);
rdv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
#SuppressWarnings("unchecked")
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getBaseContext(),map.get("titre"),Toast.LENGTH_LONG).show();
}
});
}
.
.
.
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
return GET(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
try {
JSONArray json = new JSONArray(result);
String str = "";
for(int i = 0 ; i<json.length() ; i++) {
map = new HashMap<String, String>();
str ="";
str += "RDV " + (i+1) + "\n";
str += "jour: " + json.getJSONObject(i).getString("jour") + "\n";
str += "heure: " + json.getJSONObject(i).getString("heure") + "\n";
str += "perso: " + json.getJSONObject(i).getString("perso") + "\n";
str += "acte: " + json.getJSONObject(i).getString("acte") + "\n";
map.put("titre",str);
str = "";
str += json.getJSONObject(i).getString("idrdv");
map.put("description",str);
rdvous.add(map);
}
SimpleAdapter adapt = new SimpleAdapter (getBaseContext(), rdvous, R.layout.list_rdv,
new String[] {"titre", "description"}, new int[] {R.id.titre, R.id.description});
rdv.setAdapter(adapt);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I receive data and listview is Ok but when I click on an item, i only receive the last item...
Can you help me?
Rami found this solution:
Toast.makeText(getBaseContext(), rdvous.get(position).get("titre"),Toast.LENGTH_LONG).show();
And it's work
Thank Rami ;-)
Related
I'm trying to retrieve data from a array to a textfield, which is in a listview, right now i have this
txtDesignacao.setText(position + 1 + todasAsCategorias.toString());
And it's working:
The thing is, I just want the "Designacao" field, which in this case wold be "Azeites & Outros", how can I achieve this?
##########################Edit
TodasAsCategorias.class:
#Override
protected Void doInBackground(Void... params) {
HttpHandler sh = new HttpHandler();
String url1 = "something";
String url2 = "something2";
for (int idCat = 0; idCat <100; idCat++){
final String jsonStr = sh.makeServiceCall(url1 + idCat + url2);
if (jsonStr != null) {
try {
JSONObject jsonObject = new JSONObject(jsonStr);
String K_PRODUTO = jsonObject.getString("K_PRODUTO");
String Designacao = jsonObject.getString("Designacao");
HashMap<String, String> cat = new HashMap<>();
cat.put("K_PRODUTO", K_PRODUTO);
cat.put("Designacao", Designacao);
listaCategorias.add(cat);
} catch (final JSONException e) {
//DO SOMETHING
}
} else {
//DO SOMETHING
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
mAdapter = new ListViewAdapter(mContext);
lv.setAdapter(mAdapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Do Something
}
});
}
}
public static ArrayList<HashMap<String, String>> getListaCategorias() {
return listaCategorias;
}
ListViewAdapter.class:
#Override
public void fillValues(int position, View convertView) {
ArrayList array = TodasAsCategorias.getListaCategorias();
Object todasAsCategorias = array.get(i);
TextView txtDesignacao = (TextView) convertView.findViewById(R.id.Designacao);
txtDesignacao.setText(position + 1 + todasAsCategorias.toString());
}
you have have todasAsCategorias as an object. just todastAsCate.Designacao if it's public property, or todastAsCate.getDesignacao(). All you have to do is check ur todasAsCategorias object
This question already has answers here:
Why is a ConcurrentModificationException thrown and how to debug it
(8 answers)
Closed 6 years ago.
I am writing a piece of code which displays in an expandable list using information from an AsyncTask and a pre defined HashMap. But it is throwing java.util.ConcurrentModificationException. My code is as follows:
AsnycTask
private class BackTask extends AsyncTask<Void, Void, Void> {
ProgressDialog pd;
ArrayList<String> name;
ArrayList<Integer> quantity;
Map<String, Map<String, Integer>> cart_names1 = new HashMap<String, Map<String, Integer>>();
public BackTask(ArrayList<String> name, ArrayList<Integer> quantity) {
this.name = name;
this.quantity = quantity;
}
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(ha);
pd.setTitle("Retrieving data");
pd.setMessage("Please wait.");
pd.setCancelable(true);
pd.setIndeterminate(true);
pd.show();
}
protected Void doInBackground(Void... arg0) {
InputStream is = null;
String result = "";
try {
String link = "http://chutte.co.nf/get_item_prices.php?";
for (int b = 0; b < name.size(); b++) {
link += "names[]" + "=" + name.get(b) + "&";
}
for (int a = 0; a < quantity.size(); a++) {
link += "quantities[]" + "=" + quantity.get(a);
if (a != quantity.size() - 1) {
link += "&";
}
}
Log.e("ERROR", link);
URL url = new URL(link);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
is = urlConnection.getInputStream();
} catch (Exception e) {
if (pd != null) pd.dismiss();
Log.e("ERROR", e.getMessage());
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
builder.append(line + "\n");
}
is.close();
result = builder.toString();
} catch (Exception e) {
Log.e("ERROR", "Error converting result " + e.toString());
}
try {
result = result.substring(result.indexOf("["));
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Map<String, Integer> temmap = new HashMap<>();
String temname = jsonObject.getString("Name");
temmap.put("First", jsonObject.getInt("First"));
temmap.put("Second", jsonObject.getInt("Second"));
temmap.put("Third", jsonObject.getInt("Third"));
Log.e("ERROR", temmap.get("First").toString());
cart_names1.put(temname, temmap);
}
strhold2.clear();
strhold2.add("First");
strhold2.add("Second");
strhold2.add("Third");
String[] strhold1 = new String[strhold2.size()];
for (int i56 = 0; i56 < strhold2.size(); i56++) {
strhold1[i56] = strhold2.get(i56);
}
System.out.println(cart_names1);
Log.e("ERROR", Integer.toString(cart_names1.size()) + "IN LATEST");
if (cart_names1.size() > 1) {
System.out.println(cart_names1.size());
System.out.println(strhold2.size());
Combination.printCombination(cart_names1, strhold1, strhold2.size(), cart_names1.size(), 2);
ArrayList<String> wrong = Permutation.getlist();
System.out.println(wrong + "this is final");
setalldata(wrong);
System.out.println(wrong);
couldthis.clear();
couldthis.addAll(wrong);
} else {
Single_Permutation.getpermute(cart_names1);
System.out.println(Single_Permutation.singlelist);
couldthis.clear();
couldthis.addAll(Single_Permutation.singlelist);
setalldata(Single_Permutation.singlelist);
Log.e("ERROR", "thisis the list 1" + getdataformap());
}
} catch (Exception e) {
Log.e("ERROR", "Error pasting data " + e.toString());
}
return null;
}
#Override
protected void onPostExecute(Void result) {
/*SetMap setMap = new SetMap(getdataformap());
setMap.execute();*/
if (pd != null){ pd.dismiss();}
ListFragment.addtolist(getdataformap());
Log.e("ERROR", "This is putmap i" + getdataformap());
SetMap setMap =new SetMap(getdataformap());
setMap.execute();
}
}
}
Fragment(with expandable list)
public static class ListFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static ExpandableListView expandablelistview;
public static CustomExpandableListAdapter expandableadapter;
public static HashMap<Fitems, List<Fnitems>> datapforput = new HashMap<>();
public static List<Fitems> mainforput = new ArrayList<>();
public static View view;
public static Context getha;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
view = inflater.inflate(R.layout.activity_listfragment, container, false);
//doddata();
expandablelistview = (ExpandableListView) view.findViewById(R.id.expandableListView);
expandableadapter = new CustomExpandableListAdapter(((Result) getActivity()).getha(), mainforput, datapforput);
expandablelistview.setAdapter(expandableadapter);
getha = ((Result) getActivity()).getha();
return view;
}
#Override
public void onStart() {
super.onStart();
Permutation.finallist = new ArrayList<>();
Single_Permutation.singlelist = new ArrayList<>();
/* doddata();
expandablelistview = (ExpandableListView) view.findViewById(R.id.expandableListView);
expandableadapter = new CustomExpandableListAdapter(((Result)getActivity()).getha(),mainforput,datapforput);
expandablelistview.setAdapter(expandableadapter);*/
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static void doddata() {
Fitems fitems1 = new Fitems();
Fitems fitems2 = new Fitems();
Fnitems fnitems1 = new Fnitems();
Fnitems fnitems2 = new Fnitems();
Fnitems fnitems3 = new Fnitems();
Fnitems fnitems4 = new Fnitems();
fitems1.setName("AAA");
fitems2.setName("BBB");
fnitems1.setName("AAAa");
fnitems2.setName("AAAb");
fnitems3.setName("BBBa");
fnitems4.setName("BBBb");
List<Fnitems> listfnitem1 = new ArrayList<>();
List<Fnitems> listfnitem2 = new ArrayList<>();
listfnitem1.add(fnitems1);
listfnitem1.add(fnitems2);
listfnitem2.add(fnitems3);
listfnitem2.add(fnitems4);
datapforput.put(fitems1, listfnitem1);
datapforput.put(fitems2, listfnitem2);
mainforput.add(fitems1);
mainforput.add(fitems2);
//Log.e("ERROR", "thisis the list for god's sake " + Result.couldthis+datapforput.toString());
if (Result.couldthis.size() > 0) {
for (int i = 0; i < (Result.couldthis).size(); i++) {
for (Map.Entry<Fitems, List<Fnitems>> entry : datapforput.entrySet()) {
if (Result.couldthis.get(i).equals(entry.getKey().getName())){
Fnitems fnitems5 = new Fnitems();
fnitems5.setName(Search_multiple.cart_records.get(i).getName());
entry.getValue().add(fnitems5);
}else {
Fitems fitems3 = new Fitems();
fitems3.setName(Result.couldthis.get(i));
Fnitems fnitems5 = new Fnitems();
fnitems5.setName(Search_multiple.cart_records.get(i).getName());
List<Fnitems> listfnitem3 = new ArrayList<>();
listfnitem3.add(fnitems5);
datapforput.put(fitems3, listfnitem3);
mainforput.add(fitems3);
}
}
}
}
}
public static ListFragment newInstance() {
ListFragment fragment = new ListFragment();
Log.e("ERROR", "man .... " + fragment.getTag());
return fragment;
}
public static void addtolist(ArrayList<String> dataforputting) {
// Log.e("ERROR", "thisis the list 3" + (dataforputting));
//if (expandableadapter != null){
expandableadapter.clear();//}
//Log.e("INFO", "This is mainforput" + mainforput + "This is dataforput" + datapforput);
doddata();
//Log.e("INFO", "This is mainforput" + mainforput + "This is dataforput" + datapforput);
expandableadapter = new CustomExpandableListAdapter(getha, mainforput, datapforput);
expandablelistview.setAdapter(expandableadapter);
}
}
Stack
07-13 18:16:11.955 17339-17339/nf.co.riaah.chutte E/ERROR: Inside populate Second
07-13 18:16:11.986 17339-17339/nf.co.riaah.chutte E/AndroidRuntime: FATAL EXCEPTION: main
Process: nf.co.riaah.chutte, PID: 17339
java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(HashMap.java:787)
at java.util.HashMap$EntryIterator.next(HashMap.java:824)
at java.util.HashMap$EntryIterator.next(HashMap.java:822)
at nf.co.riaah.chutte.Result$ListFragment.doddata(Result.java:199)
at nf.co.riaah.chutte.Result$ListFragment.addtolist(Result.java:230)
at nf.co.riaah.chutte.Result$SetMap.onPostExecute(Result.java:1049)
at nf.co.riaah.chutte.Result$SetMap.onPostExecute(Result.java:967)
at android.os.AsyncTask.finish(AsyncTask.java:636)
at android.os.AsyncTask.access$500(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:139)
at android.app.ActivityThread.main(ActivityThread.java:5298)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:950)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:745)
This means that you're modifying a collection while trying to iterate over it. It could be all in the same place or it could be from different threads.
for each loop are generally fail fast , that you can 't change the collection ( as for each internally use iterator ) .
instead of using " for (Map.Entry> entry : datapforput.entrySet()) "
create an iterator and then iterate over map again , don't forget to assign
iterator reference to newly created entrySet . just reassign iterartor reference each time in while / for whichever loop you use to iterate .
}
As the code shows i'm getting JSON from PHP code and add it in a list of type Reservation User and then toast that list in a array Adapter.
but my problem is : i want to get those parameters again from the list view,
(date , time , tarif , stadiumN) when i click on a specific item(just those parameters and nothing else)
any ideas how ?
As shown i typed
`myreservations.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Log.e("aaaaaaaaaaaaa: ",list1.get(i).toString());
}
});
}
but it ouputs the toString with adding text.`
public class UserShowReservation extends ActionBarActivity {
ListView myreservations;
ArrayList<ReservationUser> list1 = new ArrayList<ReservationUser>();
JSONParser parser = new JSONParser();
PreferenceUtils preferenceUtils;
int success=-1;
String id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_show_reservation);
myreservations = (ListView)findViewById(R.id.lisreservationuser);
preferenceUtils = new PreferenceUtils(getApplicationContext());
id=preferenceUtils.getLastId();
list1.clear();
new NetworkRequestTask().execute();
myreservations.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Log.e("aaaaaaaaaaaaa: ",list1.get(i).toString());
}
});
}
private class NetworkRequestTask extends AsyncTask<Void, Void, String> {
protected void onPreExecute() {
}
#Override
protected String doInBackground(Void... params) {
String connect = Utility.getReservationsUser+"userid="+id;
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
JSONObject json = parser.makeHttpRequest(connect, "POST", params1);
try {
success = json.getInt("success");
if (success == 1) {
JSONArray arr = json.getJSONArray("reservations");
for (int i = 0; i < arr.length(); i++) {
ReservationUser ru = new ReservationUser();
ru.date = arr.getJSONObject(i).getString("date");
ru.time = arr.getJSONObject(i).getInt("time");
ru.finaltarif = arr.getJSONObject(i).getDouble("finaltarif");
ru.stadiunN=arr.getJSONObject(i).getString("name");
list1.add(ru);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
if(success==1) {
ArrayAdapter<ReservationUser> adapter = new ArrayAdapter<ReservationUser>(getApplicationContext(),
android.R.layout.simple_list_item_1, list1);
myreservations.setAdapter(adapter);
}
}
}
}
public class ReservationUser {
public String date;
public int time;
public double finaltarif;
public String stadiunN;
public String toString() {
return "DATE : " + date + "\nPrice : " + finaltarif + " $" + "\nTime : " + time + ":00" + "\nStadium : " + stadiunN;
}
}
the code i am using is working very fine for me but the problem is i am not able to fetch that data in main activity
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
final String TAG = "AsyncTaskParseJson.java";
// set your json string url here
String yourJsonStringUrl = "http://demo.codeofaninja.com/tutorials/json-example-with-php/index.php";
// contacts JSONArray
JSONArray dataJsonArr = null;
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(String... arg0) {
try {
// instantiate our json parser
JsonParser jParser = new JsonParser();
// get json string from url
JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);
// get the array of users
dataJsonArr = json.getJSONArray("Users");
// loop through all users
for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(i);
// Storing each json item in variable
String firstname = c.getString("firstname");
String lastname = c.getString("lastname");
String username = c.getString("username");
// show the values in our logcat
Log.e(TAG, "firstname: " + firstname
+ ", lastname: " + lastname
+ ", username: " + username);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String strFromDoInBg) {}
}
this is the code new AsyncTaskParseJson().execute(); to make this thing work
but i need to run
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// we will using AsyncTask during parsing
new AsyncTaskParseJson().execute();
}`
I want to get the data like firstname , lastname , username as variable in main activity .
Is it possible ??
this is my other class IncomingCall.java when i want to get the variables
public class IncomingCall extends BroadcastReceiver {
private String firstname;
private String lastname;
private String username;
public void onReceive (Context context, Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(context, " Calling "+username, Toast.LENGTH_LONG).show();
try {
if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
TelephonyManager.EXTRA_STATE_IDLE)
|| intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
TelephonyManager.EXTRA_STATE_OFFHOOK)) {
notifyuser=true;
}
} catch (Exception e) {
// TODO: handle exception
//Toast.makeText(context, "Error detected 1 "+e, Toast.LENGTH_LONG).show();
}
}
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
final String TAG = "AsyncTaskParseJson.java";
// set your json string url here
String yourJsonStringUrl = "http://demo.codeofaninja.com/tutorials/json-example-with-php/index.php";
// contacts JSONArray
JSONArray dataJsonArr = null;
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(String... arg0) {
try {
// instantiate our json parser
JsonParser jParser = new JsonParser();
// get json string from url
JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);
// get the array of users
dataJsonArr = json.getJSONArray("Users");
// loop through all users
// for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(0);
// Storing each json item in variable
firstname = c.getString("firstname");
lastname = c.getString("lastname");
username = c.getString("username");
// show the values in our logcat
Log.e(TAG, "firstname: " + firstname
+ ", lastname: " + lastname
+ ", username: " + username);
// }
} catch (JSONException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
//Here you use your variables
}
});
return null;
}
protected void onPostExecute(String strFromDoInBg) {
Log.e("TAG1", "firstname: " + firstname
+ ", lastname: " + lastname
+ ", username: " + username);
}
}
this is my code
The method onPostExecute runs on the main thread, You need to use the data once the doInBackground finishes and control return to the main thread.
Better you use these data in the method
protected void onPostExecute(String strFromDoInBg) {
// use the firstname , lastname or username after this method call.
}
Put your code in your Main Activity class, and then use class variables to store what you want, e.g.:
public class MainActivity extends Activity {
private String[] firstname;
private String[] lastname;
private String[] username;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new AsyncTaskParseJson().execute();
}
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
final String TAG = "AsyncTaskParseJson.java";
// set your json string url here
String yourJsonStringUrl = "http://demo.codeofaninja.com/tutorials/json-example-with-php/index.php";
// contacts JSONArray
JSONArray dataJsonArr = null;
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(String... arg0) {
try {
// instantiate our json parser
JsonParser jParser = new JsonParser();
// get json string from url
JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);
// get the array of users
dataJsonArr = json.getJSONArray("Users");
firstname = new String[dataJsonArr.length()];
lastname = new String[dataJsonArr.length()];
username = new String[dataJsonArr.length()];
// loop through all users
for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(i);
// Storing each json item in variable
firstname[i] = c.getString("firstname");
lastname[i] = c.getString("lastname");
username[i] = c.getString("username");
// show the values in our logcat
Log.e(TAG, "firstname: " + firstname
+ ", lastname: " + lastname
+ ", username: " + username);
}
} catch (JSONException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
//Here you use your variables
}
});
return null;
}
#Override
protected void onPostExecute(String strFromDoInBg) {}
}
}
Something like this (it's without error checking, give it a try)
EDIT: be sure to have declared the internet permission in the android manifest:
<uses-permission android:name="android.permission.INTERNET" />
Have the following AsyncTask code:
private class checkChangesTask extends AsyncTask<String, Void, String> {
protected ProgressDialog mProgressDialog2;
protected String _url = "", _idautor="", _idbook="";
#Override
protected void onPreExecute() {
super.onPreExecute();
this.mProgressDialog2 = new ProgressDialog(MainActivity.this);
this.mProgressDialog2.setMessage("Check changes ...");
this.mProgressDialog2.setIndeterminate(false);
this.mProgressDialog2.setCanceledOnTouchOutside(false);
this.mProgressDialog2.setCancelable(true);
this.mProgressDialog2.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
this.mProgressDialog2.setMax(100);
this.mProgressDialog2.setProgress(0);
this.mProgressDialog2.show();
}
#Override
protected String doInBackground(String... params) {
Document doc = null;
String _html = "";
_idautor = params[0];
_idbook = params[1];
_url = params[2];
try {
doc = Jsoup.connect(_url).userAgent("Mozilla").get();
Elements dd = doc.select("dd");
int size = dd.size();
int p = 1;
for (Element src : dd) {
this.mProgressDialog2.setProgress(p*100/size);
if (p <= size-1){
_html += src.outerHtml();
++p;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return Jsoup.clean(_html, Whitelist.basic());
}
#Override
protected void onPostExecute(String result) {
if(!result.equals("")){
String lastfile = readPageFile(_idautor + "_" + _idbook);
if(!lastfile.equals(result)){
savePageToFile(_idautor + "_" + _idbook, result);
}
}else{
Toast.makeText(MainActivity.this, "Error checkChangesTask", Toast.LENGTH_SHORT).show();
}
this.mProgressDialog2.dismiss();
}
the previous code I call in a loop:
public void checkChanges() {
String[][] db_books = db.selectAllBOOKS();
if (db_books.length>0){
for (int j = 0; j < db_books.length; j++){
new checkChangesTask().executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, db_books[j][1], db_books[j][0], db_books[j][2]);
}
}
}
Everything works fine, but the dialog does not display the correct value. First, it is worth it to 0% and then abruptly switches to 100%.
AsyncTask called in sequence (...executeOnExecutor(AsyncTask.SERIAL_EXECUTOR...).
If you run a AsyncTask not in the loop, all the displays are just perfect!
android: targetSdkVersion = "14"
I ask your help.
You need to use onProgressUpdate() inside the AsyncTask. Something like this (at a guess)
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
this.mProgressDialog2.setProgress(progress[0] * 100/progress[1]);
}
And replace this line:
this.mProgressDialog2.setProgress(p*100/size);
With this:
publishProgress(new int[]{p,size})