Async json parsing- What am i doing wrong? - java

I have been trying to work on an app in which after clicking ,a new activity opens up and loads the data from the url.
Here is the new activity code
ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
}
private class MyTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
dialog.setMessage("Processing");
dialog.setIndeterminate(true);
dialog.show();
dialog.getWindow().setLayout(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
try {
JSONObject jsonObject = new JSONObject();
String url = " http://www.trailermag.com/tsappapis/?request=featuredAdList";
JSONArray trailersJSON = jsonObject.getJSONArray(url);
for (int i = 0; i < trailersJSON.length(); i++) {
Trail aTrail = new Trail();
JSONObject contactObject = trailersJSON.getJSONObject(i);
aTrail.id = contactObject.getString(V_Id);
aTrail.image = contactObject.getString(V_Image);
aTrail.title = contactObject.getString(V_Title);
aTrail.price = contactObject.getString(V_Price);
webData.add(aTrail);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (dialog.isShowing()) {
System.out.println("IN POST EXE");
dialog.dismiss();
}
}
}

Once try and replace this code with your code this will work and i have tested it.
JSONArray mJsonArray = new JSONArray(response);
for (int i = 0; i < mJsonArray.length(); i++) {
JSONObject mJsonObject = mJsonArray.getJSONObject(i);
String idStr = mJsonObject.getString("id");
String imageStr = mJsonObject.getString("image");
String titleStr = mJsonObject.getString("title");
String priceStr = mJsonObject.getString("price");
}
Happeee...Programming....

Related

Need help to retrieve all the data to listview

I'm trying to make an android application that can read data from a database. but when I try to display some rows in the listview, only the bottom row of the code that I make is displayed.
this is my code for MainActivity
public class MainActivity extends AppCompatActivity {
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listView);
getJSON("http://192.168.137.234/librenms/getdata.php");
}
private void getJSON(final String urlWebService) {
class GetJSON extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
loadIntoListView(s);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(urlWebService);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) !=null) {
sb.append(json).append("\n");
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
GetJSON getJSON = new GetJSON();
getJSON.execute();
}
private void loadIntoListView(String json) throws JSONException {
JSONArray jsonArray = new JSONArray(json);
String[] alerts = new String[jsonArray.length()];
this is the part to showing the atribute on listview
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
alerts[i] = object.getString("Rule ID");
alerts[i] = object.getString("Device ID");
alerts[i] = object.getString("Time logged");
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, alerts);
listView.setAdapter(arrayAdapter);
}
}

ArrayList.size function doesnt reflect changes of first try but if i run the method again solves that

I have a array list that takes changes on a AsyncTask that is called on a button click, after that i want to loop through the arraylist
for (int f = 0; f < getid.size();f++){
teste[f] = getid.get(f);
Log.d("teste", "welelelelelele ?");
}
but it cant because getid.size returns 0 so it doesnt execute(only on the first time i clicked the button), but why ? If i press back then click the button again it works, it returns the correct size and executes the for cycle.
ButtonClick
btnCriar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SparseBooleanArray checked = listView.getCheckedItemPositions();
ArrayList<String> selectedItems = new ArrayList<String>();
for (int i = 0; i < checked.size(); i++) {
// Item position in adapter
int position = checked.keyAt(i);
// Add sport if it is checked i.e.) == TRUE!
if (checked.valueAt(i))
selectedItems.add((String) adapter.getItem(position));
}
final String[] outputStrArr = new String[selectedItems.size()];
for (int i = 0; i < selectedItems.size(); i++) {
outputStrArr[i] = selectedItems.get(i);
Log.d("teste", String.valueOf(i));
}
Log.e("teste", "chega aqui ?===??");
new Get(outputStrArr).execute();
Log.e("teste", String.valueOf(getid.size()));
String[] teste = new String[getid.size()];
Log.e("teste", "chega aqui ?===??");
for (int f = 0; f < getid.size();f++){
teste[f] = getid.get(f);
Log.d("teste", "welelelelelele ?");
}
for (int va = 0; va < teste.length;va++){
Log.d("teste", "adadada ?");
pls +=teste[va];
}
editText.setText(pls);
Intent x = new Intent(AddCenario.this, GerirCenario.class);
Bundle b = new Bundle();
b.putStringArray("selectedItems", outputStrArr);
String text = editText.getText().toString();
x.putExtra("ola" , text);
x.putExtras(b);
startActivity(x);
listView.getSelectedItem();
}
});
Asynctask:
private class Get extends AsyncTask<String, Void, Void> {
private final String[] outputStrArr;
Get(String[] outputStrArr)
{
this.outputStrArr = outputStrArr;
}
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(String... integers) {
for (x = 0; x < outputStrArr.length; x++) {
try {
RequestQueue queue = Volley.newRequestQueue(AddCenario.this);
String url = "http://brunos.000webhostapp.com/teste/obter_id.php?descricao=" + outputStrArr[x];
JsonArrayRequest jsonRequest = new JsonArrayRequest
(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); ++i) {
JSONObject obj = response.getJSONObject(i);
id[0] = obj.getString("id");
getid.add(id[0]);
Log.d("teste", "chega aqui ?");
Log.e("teste", String.valueOf(getid.size()));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
queue.add(jsonRequest);
} catch (Exception ex) {
}
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
Complete code:
public class AddCenario extends AppCompatActivity {
String input,pls, kappa;
Integer podeIR = 0,x;
EditText editText,esc;
String idDivisao;
private String my_sel_items;
ArrayAdapter adapter;
String[] id = new String[1];
ArrayList<String> getid = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
final ArrayList<String> divisoes = new ArrayList<>();
my_sel_items=new String();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_cenario);
editText = (EditText) findViewById(R.id.editText4);
final ListView listView = (ListView) findViewById(R.id.listview);
Button btnCriar = (Button) findViewById(R.id.button_criarr);
RequestQueue queue = Volley.newRequestQueue(AddCenario.this.getApplicationContext());
try {
String url = "http://brunos.000webhostapp.com/teste/listar_divisoes.php";
JsonArrayRequest jsonRequest = new JsonArrayRequest
(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
public void onResponse(JSONArray response) {
try {
adapter = new ArrayAdapter(getApplicationContext(),R.layout.custom_divi_mult,divisoes);
Integer i = 0;
String divisao;
while (i!= response.length()){
JSONObject obj = response.getJSONObject(i);
idDivisao = obj.getString("id");
divisao = obj.getString("descricao");
divisoes.add(divisao);i++;
}
listView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
queue.add(jsonRequest);
} catch (Exception ex) {
} finally {
}
btnCriar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SparseBooleanArray checked = listView.getCheckedItemPositions();
ArrayList<String> selectedItems = new ArrayList<String>();
for (int i = 0; i < checked.size(); i++) {
// Item position in adapter
int position = checked.keyAt(i);
// Add sport if it is checked i.e.) == TRUE!
if (checked.valueAt(i))
selectedItems.add((String) adapter.getItem(position));
}
final String[] outputStrArr = new String[selectedItems.size()];
for (int i = 0; i < selectedItems.size(); i++) {
outputStrArr[i] = selectedItems.get(i);
Log.d("teste", String.valueOf(i));
}
Log.e("teste", "chega aqui ?===??");
new Get(outputStrArr).execute();
Log.e("teste", String.valueOf(getid.size()));
String[] teste = new String[getid.size()];
Log.e("teste", "chega aqui ?===??");
for (int f = 0; f < getid.size();f++){
teste[f] = getid.get(f);
Log.d("teste", "welelelelelele ?");
}
for (int va = 0; va < teste.length;va++){
Log.d("teste", "adadada ?");
pls +=teste[va];
}
editText.setText(pls);
Intent x = new Intent(AddCenario.this, GerirCenario.class);
Bundle b = new Bundle();
b.putStringArray("selectedItems", outputStrArr);
String text = editText.getText().toString();
x.putExtra("ola" , text);
x.putExtras(b);
startActivity(x);
listView.getSelectedItem();
}
});
}
private class Get extends AsyncTask<String, Void, Void> {
private final String[] outputStrArr;
Get(String[] outputStrArr)
{
this.outputStrArr = outputStrArr;
}
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(String... integers) {
for (x = 0; x < outputStrArr.length; x++) {
try {
RequestQueue queue = Volley.newRequestQueue(AddCenario.this);
String url = "" + outputStrArr[x];
JsonArrayRequest jsonRequest = new JsonArrayRequest
(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); ++i) {
JSONObject obj = response.getJSONObject(i);
id[0] = obj.getString("id");
getid.add(id[0]);
Log.d("teste", "chega aqui ?");
Log.e("teste", String.valueOf(getid.size()));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
queue.add(jsonRequest);
} catch (Exception ex) {
}
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
}

How to set the arraylist to object after the postExecute of asyncTask?

I have 2 asyncTasks. One for GetCheckLists another for GetCheckListItems.
In CheckList class, it has checkListId,Title,etc and arrayList of checkListItems.
First I get all the checkLists using GetCheckListAsyncTask. Now for each checkList I am calling GetCheckListItemsAsync task to get all the checkListItems.
Now onPostExecute method of GetCheckListItemsAsyncTask I want to set the checkListItemArrayList.
How can I make sure to add checkListItemArrayList to checkList item's object?
CheckListActivity:
public class CheckListActivity extends AppCompatActivity implements CheckListAdapter.OnItemClickListener{
private ProgressDialog progressDialog;
private RecyclerView recyclerView;
private ArrayList<CheckList> checkLists = new ArrayList<>();
private CheckList mCheckList;
private ArrayList<CheckListItem> itemList;
private ArrayList<CheckList> checkListArrayList;
private CheckListAdapter mAdapter;
JSONArray checkListsItemArray,checkListArray;
public int iterationCount = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check_list);
checkListArrayList = new ArrayList<>();
mEventId = mIntent.getStringExtra("eventId");
mCheckList = new CheckList();
progressDialog = new ProgressDialog(CheckListActivity.this);
recyclerView = (RecyclerView)findViewById(R.id.recycler_view);
mAdapter = new CheckListAdapter(checkListArrayList,CheckListActivity.this,CheckListActivity.this);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
GetCheckListAsyncTask getCheckListAsyncTask = new GetCheckListAsyncTask();
getCheckListAsyncTask.execute(mEventId);
}
}
#Override
public class GetCheckListsItemAsyncTask extends AsyncTask<String, Void, JSONObject> {
private String api;
private JSONObject jsonParams;
public GetCheckListsItemAsyncTask(){}
#Override
protected JSONObject doInBackground(String... params) {
try {
api = getResources().getString(R.string.server_url) + "api/checklist_items/getChecklistItems.php";
jsonParams = new JSONObject();
String checklistId = params[0]; // params[0] is username
jsonParams.put("checklistId", checklistId);
ServerRequest request = new ServerRequest(api, jsonParams);
return request.sendRequest();
} catch(JSONException je) {
return Excpetion2JSON.getJSON(je);
}
} //end of doInBackground
#Override
protected void onPostExecute(JSONObject response) {
super.onPostExecute(response);
Log.e("ServerResponse", response.toString());
try {
int result = response.getInt("result");
String message = response.getString("message");
if (result == 1) {
Toast.makeText(CheckListActivity.this, message, Toast.LENGTH_LONG).show();
//code after getting profile details goes here
checkListsItemArray = response.getJSONArray("checklistItems");
for (int i = 0; i < checkListsItemArray.length(); i++) {
int pendingTasks = 0,completedTasks = 0;
itemList = new ArrayList<>();
CheckListItem checkListItem = new CheckListItem();
JSONObject subObject = checkListsItemArray.getJSONObject(i);
String checkListItemName = subObject.getString("text");//name of the attribute in response
String checkListItemBudget = subObject.getString("budget");//name of the attribute in response
String checkListItemTimedate = subObject.getString("time_due");
String checkListItemReminder = subObject.getString("reminder");
String checkListItemId = subObject.getString("checklistItemId");
String checkListItemStatus = subObject.getString("status");
if (checkListItemStatus.equals("1")) {
completedTasks++;
}
if (checkListItemStatus.equals("0")) {
pendingTasks++;
}
checkListItem.setTitle(checkListItemName);
checkListItem.setBudget(checkListItemBudget);
checkListItem.setDateTime(checkListItemTimedate);
checkListItem.setReminder(checkListItemReminder);
checkListItem.setCheckListItemId(checkListItemId);
checkListItem.setStatus(checkListItemStatus);
checkListItem.setPendingItem(pendingTasks);
checkListItem.setCompletedItem(completedTasks);
itemList.add(checkListItem);//adding string to arraylist
}
if(checkListArrayList.size() < iterationCount) {
iterationCount++;
String checkListId =
checkListArrayList.get(iterationCount).getCheckListId();
CheckList checkList1 = checkListArrayList.get(iterationCount);
checkList1.setCheckListItemArrayList(itemList);
}
mAdapter.notifyDataSetChanged();
}
else {
Toast.makeText(CheckListActivity.this, message, Toast.LENGTH_LONG).show();
//code after failed getting profile details goes here
}
} catch(JSONException je) {
je.printStackTrace();
Toast.makeText(CheckListActivity.this, je.getMessage(), Toast.LENGTH_LONG).show();
}
} //end of onPostExecute
}
public class GetCheckListAsyncTask extends AsyncTask<String, Void, JSONObject> {
private String api;
private JSONObject jsonParams;
public GetCheckListAsyncTask(){}
#Override
protected JSONObject doInBackground(String... params) {
try {
api = getResources().getString(R.string.server_url) + "api/checklist/getChecklists.php";
jsonParams = new JSONObject();
String eventId = params[0]; // params[0] is username
jsonParams.put("eventId", eventId);
ServerRequest request = new ServerRequest(api, jsonParams);
return request.sendRequest();
} catch(JSONException je) {
return Excpetion2JSON.getJSON(je);
}
} //end of doInBackground
#Override
protected void onPostExecute(JSONObject response) {
super.onPostExecute(response);
//Log.e("ServerResponse", response.toString());
try {
int result = response.getInt("result");
String message = response.getString("message");
if (result == 1 ) {
Toast.makeText(CheckListActivity.this, message, Toast.LENGTH_LONG).show();
//code after getting profile details goes here
checkListArray = response.getJSONArray("checklists");
for (int i = 0; i < checkListArray.length(); i++) {
CheckList checkList = new CheckList();
JSONObject subObject = checkListArray.getJSONObject(i);
String checkListName = subObject.getString("checklist");//name of the attribute in response
String checkListBudget = subObject.getString("budget");//name of the attribute in response
String checkListIcon = subObject.getString("icon");
String checkListId = subObject.getString("checklistId");
checkList.setCheckListTitle(checkListName);
checkList.setBudget(checkListBudget);
checkList.setImageIcon(checkListIcon);
checkList.setCheckListId(checkListId);
checkListArrayList.add(checkList);
iterationCount++;
new GetCheckListsItemAsyncTask().execute(checkListId);
mAdapter.notifyDataSetChanged();
}
if ((progressDialog != null) && progressDialog.isShowing()) {
progressDialog.dismiss();
}
} else {
Toast.makeText(CheckListActivity.this, message, Toast.LENGTH_LONG).show();
//code after failed getting profile details goes here
if ((progressDialog != null) && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
} catch(JSONException je) {
je.printStackTrace();
Toast.makeText(CheckListActivity.this, je.getMessage(), Toast.LENGTH_LONG).show();
}
} //end of onPostExecute
#Override
protected void onPreExecute(){
super.onPreExecute();
progressDialog.setMessage("Loading...");
progressDialog.show();
}
}
}
How to set CheckListItemsArrayList to the objects of checkListArrayList sequence wise? Please help. Thank you..
You need to elaborate your question. It is very confusing.
But I think that you want to add items to your AsyncTask class.
You can use the Constructor Method for this.
GetCheckListAsyncTask getCheckListAsyncTask = new GetCheckListAsyncTask(checkListsItemArray);
getCheckListAsyncTask.execute(mEventId);
And for AsyncTask Just Add:
JSONArray m_checkListsItemArray;
public GetCheckListsItemAsyncTask(JSONArray checkListsItemArray){
m_checkListsItemArray = checkListsItemArray;
//Do something here with checkListsItemArray;
}
And use m_checkListsItemArray anywhere in the AsycTask class.
Each time you start a task, you have no control when it ends. The tasks are running Asynchronously so they won't end in the order you start them. Maybe have a field level Array or ArrayList that adds results each time a task ends and then when everyhthing has ended you can work with the array results.

How to put 2 parameters in doInBackground asynctask ?

I use Asynctask to load and get data from php. And I have to pass 2 parameters to php.
But I don't know how.
Here is the java code :
public class info extends Activity{
ProgressDialog pDialog;
TextView movie_tittle, studio, date;
int std;
String movie, reservation, ttl, dt;
private String URL_CATEGORIES = "http://10.0.2.2/cinemainfo/info.php";
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> accountsList;
JSONArray accounts = null;
private static final String TAG_SUCCESS = "success";
private static final String TAG_ACCOUNT = "message";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.info);
movie = getIntent().getStringExtra("kode_intent");
reservation = getIntent().getStringExtra("kode_intent2");
movie_tittle=(TextView)findViewById(R.id.tv_tittle);
date=(TextView)findViewById(R.id.tv_date);
studio=(TextView)findViewById(R.id.tv_studio);
new GetCategories().execute();
}
private class GetCategories extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(info.this);
pDialog.setMessage("Please Wait..");
pDialog.setCancelable(false);
pDialog.show();
}
protected Void doInBackground(Void... arg0) {
List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
params.add(new BasicNameValuePair("id_movie", movie));
params.add(new BasicNameValuePair("id_reservation", reservation));
JSONObject json = jParser.makeHttpRequest(URL_CATEGORIES, "GET", params);
Log.d("All Accounts: ", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
accounts = json.getJSONArray(TAG_ACCOUNT);
for (int i = 0; i < accounts.length(); i++) {
JSONObject json_data = accounts.getJSONObject(i);
ttl=json_data.getString("movie_tittle");
dt=json_data.getString("date");
std = json_data.getInt("studio");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
result();
}
}
private void result() {
try{
movie_tittle.setText(ttl);
date.setText(dt);
studio.setText(String.valueOf(std));
}
catch(Exception e){
Log.e("log_tag","Error in Display!" + e.toString());;
}
}
}
I want to pass id_movie and id_reservation to php code..Both is getting from movie = getIntent().getStringExtra("kode_intent"); and reservation = getIntent().getStringExtra("kode_intent2");
But when I run the code in emulator, It displays nothing..The php code is fine..But I'm not sure with my java code. How to pass 2 parameters in doInBackground asynctask? Did I do something wrong ?
String curloc = current.toString();
String itemdesc = item.mDescription;
ArrayList<String> passing = new ArrayList<String>();
passing.add(itemdesc);
passing.add(curloc);
new calc_stanica().execute(passing); //no need to pass in result list
And change your async task implementation
public class calc_stanica extends AsyncTask<ArrayList<String>, Void, ArrayList<String>> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(baraj_mapa.this);
dialog.setTitle("Calculating...");
dialog.setMessage("Please wait...");
dialog.setIndeterminate(true);
dialog.show();
}
protected ArrayList<String> doInBackground(ArrayList<String>... passing) {
ArrayList<String> result = new ArrayList<String>();
ArrayList<String> passed = passing[0]; //get passed arraylist
//Some calculations...
return result; //return result
}
protected void onPostExecute(ArrayList<String> result) {
dialog.dismiss();
String minim = result.get(0);
int min = Integer.parseInt(minim);
String glons = result.get(1);
String glats = result.get(2);
double glon = Double.parseDouble(glons);
double glat = Double.parseDouble(glats);
GeoPoint g = new GeoPoint(glon, glat);
String korisni_linii = result.get(3);
}
Calling:
String[] arrayOfValue = new String[2];
arrayOfValue[0] = movie;
arrayOfValue[1] = reservation;
new GetCategories().execute(arrayOfValue);
Usage:
protected ArrayList<String> doInBackground(String... passing){
String movie = passing[0];
String reservation = passing[1];
}

android AsyncTask in foreach

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})

Categories

Resources