I use asynctask to show data from json but asynctask show loading never dies, no error but loading and loading this code doInBackground function
#Override
protected void onPreExecute() {
progressDialog.show();
}
#Override
protected Integer doInBackground(String... arg0) {
// check for login response
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
//DatabaseHandler db = new DatabaseHandler(
// activity.getApplicationContext());
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(URL+id_user);
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// Getting Array of Following
user = json.getJSONArray(KEY_USER);
// looping through All Following
for (int i = 0; i < user.length(); i++) {
JSONObject c = user.getJSONObject(i);
// Storing each json item in variable
nama = c.getString(KEY_NAMA);
instansi = c.getString(KEY_INSTANSI);
status = c.getString(KEY_STATUS);
responseCode = 1;
}
} else{
responseCode = 0;
}
}
} catch (NullPointerException e) {
e.printStackTrace();
}
catch (JSONException e) {
e.printStackTrace();
}
return responseCode;
}
#Override
protected void onPostExecute(Integer responseCode) {
if (responseCode == 1) {
headerNama = (TextView)activity.findViewById(R.id.headerNama);
headerInstansi = (TextView)activity.findViewById(R.id.headerInstansi);
buttonStatus = (Button)activity.findViewById(R.id.buttonStatus);
headerNama.setText(nama);
headerInstansi.setText(instansi);
buttonStatus.setText(status);
}else {
progressDialog.dismiss();
activity.showDashboardError(responseCode);
}
}
i think no probleme in doinbackground, please help thanks
You should dismiss your dialog like:
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
Related
I´m did a register activity, in this activity I've two spinner one to state and other to city,the activity send the string of the spinner of state to phpfile and this return all the cities of this state and in the java fill the spinner with this cities, I use AsyncTask with a class to do the query to my php file in http server and I get this error in all the class 'android.os.AsyncTask' is deprecated.
Someone can help me or orientedme to fix that.
private class GetModelFromServer extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(registro.this);
pDialog.setMessage("Fetching Data");
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
estado = spinnerEstado.getSelectedItem().toString();
Handler jsonParser = new Handler();
String json = null;
try {
json = jsonParser.makeServiceCall("https://chilaquilesenterprise.com/localidades/get_model.php?nombre_estado="+ URLEncoder.encode(estado,"UTF-8"), Handler.GET);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray model = jsonObj
.getJSONArray("nombre");
for (int i = 0; i < model.length(); i++) {
JSONObject modObj = (JSONObject) model.get(i);
Nombre nom = new Nombre(modObj.getString("nombre"));
nombreList.add(nom);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
populateSpinnerModel();
}
}
I have a little problem with make a toast when my table database is null based on parsing json. I mean, when data is no result or no data found then make a toast " Sorry no data found". Any help would be greatly appreciated.
here my code for show the data
private void showEmployee(){
JSONObject jsonObject = null;
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String, String>>();
try {
jsonObject = new JSONObject(JSON_STRING);
JSONArray result = jsonObject.getJSONArray(konfigurasi.TAG_JSON_ARRAY);
for(int i = 0; i<result.length(); i++){
JSONObject jo = result.getJSONObject(i);
String id = jo.getString(konfigurasi.TAG_ID);
String nama = jo.getString(konfigurasi.TAG_NAMA);
String pyg = jo.getString(konfigurasi.TAG_PENYELENGGARA);
String tmpt = jo.getString(konfigurasi.TAG_TEMPAT);
String tgl = jo.getString(konfigurasi.TAG_TGL);
String jam = jo.getString(konfigurasi.TAG_JAM);
String email = jo.getString(konfigurasi.TAG_EMAIL);
HashMap<String,String> employees = new HashMap<>();
employees.put(konfigurasi.TAG_ID,id);
employees.put(konfigurasi.TAG_NAMA,nama);
employees.put(konfigurasi.TAG_PENYELENGGARA,pyg);
employees.put(konfigurasi.TAG_TEMPAT,tmpt);
employees.put(konfigurasi.TAG_TGL,tgl);
employees.put(konfigurasi.TAG_JAM,jam);
employees.put(konfigurasi.TAG_EMAIL,email);
list.add(employees);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new MySimpleArrayAdapter(this, list);
listView.setAdapter(adapter);
}
And this for postexcetude code :
private void getJSON(){
class GetJSON extends AsyncTask<Void,Void,String>{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(TampilSemuaPgw.this,"Mengambil Data","Mohon Tunggu...",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if(s == null || s.length() == 0){
Toast.makeText(getApplicationContext(), "No Data",Toast.LENGTH_LONG).show();
}
// Dismiss the progress dialog
if (loading.isShowing())
loading.dismiss();
JSON_STRING = s;
showEmployee();
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequest(konfigurasi.URL_GET_ALL);
return s;
}
}
GetJSON gj = new GetJSON();
gj.execute();
}
Update Code by KeLiuyue :
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequest(konfigurasi.URL_GET_ALL);
return s;
}
#Override
protected void onPostExecute(String s) {
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("result");
if(jsonArray.length() == 0){
Toast.makeText(getApplicationContext(), "No Data", Toast.LENGTH_LONG).show();
if (loading.isShowing()){
loading.dismiss();
}
return;
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("TAG",s);
// Dismiss the progress dialog
if (loading.isShowing())
loading.dismiss();
JSON_STRING = s;
showEmployee();
}
Try this in your code .
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequest(konfigurasi.URL_GET_ALL);
return s;
}
#Override
protected void onPostExecute(String s) {
// edited here
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("result");
if(jsonArray.length() == 0){
Toast.makeText(getApplicationContext(), "No Data", Toast.LENGTH_LONG).show();
if (loading.isShowing()){
loading.dismiss();
}
return;
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("TAG",s);
// Dismiss the progress dialog
if (loading.isShowing())
loading.dismiss();
JSON_STRING = s;
showEmployee();
}
1.Determine return value whether is empty in doInBackground method
2.Determine param value whether is empty in onPostExecute method
You need to Debug this issue why your toast is not showing:
You have correctly put show Toast code in onPostExecute
Now to debug , first put a Log to know the value of s , whether it is ever null or empty.
If yes and still toast is not showing, move the dialog dismiss dialog before Toast and check.
If Toast still does not show debug your showEmployee() method as what it does.
In my App I am hitting a service which can have no result to n number of results(basically some barcodes). As of now I am using default circular progressbar when json is parsed and result is being saved in local DB(using sqlite). But if the json has large number of data it sometimes takes 30-45 min to parse and simultaneously saving that data in DB, which makes the interface unresponsive for that period of time and that makes user think the app has broken/hanged. For this problem I want to show a progressbar with the percentage stating how much data is parsed and saved so that user get to know the App is still working and not dead. I took help from this link but couldn't find how to achieve. Here's my Asynctask,
class BackGroundTasks extends AsyncTask<String, String, Void> {
private String operation, itemRef;
private ArrayList<Model_BarcodeDetail> changedBarcodeList, barcodeList;
private ArrayList<String> changeRefList;
String page;
public BackGroundTasks(String operation, String itemRef, String page) {
this.operation = operation;
this.itemRef = itemRef;
this.page = page;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
if (dialog == null) {
dialog = ProgressDialog.show(mActivity, null,
"Please wait ...", true);
}
}
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
try{
if (!connection.HaveNetworkConnection()) {
dialog.dismiss();
connection.showToast(screenSize, "No Internet Connection.");
return null;
}
if (operation.equalsIgnoreCase("DownloadChangeItemRef")) {
changeRefList = DownloadChangeItemRef(params[1]);
if (changeRefList != null && !changeRefList.isEmpty()) {
RefList1.addAll(changeRefList);
}
}
if ((changeRefList != null && changeRefList.size() >0)) {
setUpdatedBarcodes(changedBarcodeList);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#SuppressLint("SimpleDateFormat")
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
ArrayList<String> DownloadChangeItemRef(String api_token) {
ArrayList<String> changedRefList = null;
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(thoth_url + "/" + todaysDate
+ "?&return=json");
String url = thoth_url + "/" + todaysDate + "?&return=json";
String result = "";
try {
changedRefList = new ArrayList<String>();
ResponseHandler<String> responseHandler = new BasicResponseHandler();
result = httpClient.execute(postRequest, responseHandler);
JSONObject jsonObj = new JSONObject(result);
JSONArray jsonarray = jsonObj.getJSONArray("changes");
if (jsonarray.length() == 0) {
return null;
}
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject obj = jsonarray.getJSONObject(i);
changedRefList.add(obj.getString("ref"));
}
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
// when there is no thoth url
Log.i("inclient: ", e.getMessage());
return null;
} catch (Exception e) {
// when there are no itemref
return null;
}
return changedRefList;
}
private boolean setUpdatedBarcodes(
final ArrayList<Model_BarcodeDetail> changedBarcodeList2) {
try {
BarcodeDatabase barcodeDatabase = new BarcodeDatabase(mActivity);
barcodeDatabase.open();
for (Model_BarcodeDetail model : changedBarcodeList2) {
barcodeDatabase.updateEntry(model, userId);
}
n++;
barcodeDatabase.close();
if (RefList1.equals(RefList)) {
if (dialog != null) {
dialog.dismiss();
}
connection.showToast(screenSize, "Barcodes updated successfully");
}
} catch (Exception e) {
Log.i("Exception caught in: ", "setDownloadedBarcodes method");
e.printStackTrace();
return false;
}
return true;
}
I am trying to fetch some data from Web Server through JSON. I am using asynctask to do so. Normally it is taking 5-10 seconds to be shown in my ListView.
Hence I want to put spinner progress bar. My code is working fine only problem is the progress bar is not visible.
MyActivity code to call asyntask
try{
JSONObject output = new AsyncTaskJsonParse(this,status, A, B, city).execute().get();
try {
JSONObject output = new AsyncTaskJsonParse(ListViewDisplay.this,status, bgrp, antigen, city).execute().get();
JSONObject src = output.getJSONObject("data");
String flag = output.getString("success");
String flagmsg = output.getString("message");
if (flag == "1") {
JSONArray jarr_name = new JSONArray(src.getString("name"));
JSONArray jarr_fathername = new JSONArray(src.getString("fathername"));
JSONArray jarr_moh = new JSONArray(src.getString("moh"));
JSONArray jarr_city = new JSONArray(src.getString("city"));
JSONArray jarr_phone = new JSONArray(src.getString("phone"));
int n = jarr_name.length();
name_array = new String[n];
fathername_array = new String[n];
moh_array = new String[n];
phone_array = new String[n];
city_array = new String[n];
for (int i = 0; i < n; i++) {
name_array[i] = (String) jarr_name.get(i);
fathername_array[i] = (String) jarr_fathername.get(i);
moh_array[i] = (String) jarr_moh.get(i);
phone_array[i] = (String) jarr_phone.get(i);
city_array[i] = "Vadodara";
Log.d("Inside StringArray", i + "");
}
String msg = src.getString("name");
list = (ListView) findViewById(R.id.listView);
CustomListAdapter custAdaptor = new CustomListAdapter(this, name_array, fathername_array, mohalla_array, city_array, phone_array);
list.setAdapter(custAdaptor);
}else
{
Toast.makeText(this, "Data not found" + flagmsg, Toast.LENGTH_LONG).show();
}
}catch(ExecutionException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(InterruptedException e)
{
e.printStackTrace();
}catch(JSONException je)
{
}
Standalone asyntask with progressbar code
public class AsyncTaskJsonParse extends AsyncTask<String, String, JSONObject>
{
String A,B;
private String url = "abc.com/check.php";
List<NameValuePair> param=new ArrayList<NameValuePair>();
private Context context;
private ProgressDialog progress;
public AsyncTaskJsonParse(Context context,String A,String B,String antigen,String city)
{
this.A=A;
this.B=B;
this.city=city;
this.context=context;
progress=new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.e("In preexecution ", "Preexecution 1");
progress.setMessage("Processing...");
progress.setIndeterminate(true);
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setCancelable(true);
Log.e("In preexecution azam", "Preexecution 2");
progress.show();
if(progress.isShowing())
{
Log.d("In preexecution ", "Showing 2");
}
}
//rest of code i.e. doInBackground and postexecute come after this.
#Override
protected JSONObject doInBackground(String... arg0) {
// TODO Auto-generated method stub
try
{
JsonParsor parse=new JsonParsor();
Log.d("diInbackgrnd ","Dialog box");
jsonobj = parse.getJSONFromUrl(url, param);
}
catch(Exception e)
{
Log.e(TAG, " "+e );
}
return jsonobj;
}
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//pDialog.dismiss();
if(progress.isShowing())
{
Log.e("In onPost ", "Showing 2");
}
progress.dismiss();
}
}
In my log I can see the message "In preexecution Showing 2". And the appliaction is working as expected but the Spinner progressbar is not visible.
Note: I did not add any progressbar component in any xml file. Does i need to add it? if yes then where and how?
class JsonParser.java
public class JsonParsor {
final String TAG = "JsonParser.java";
static InputStream is = null;
static JSONObject jObj = null;
static String str = "";
public JSONObject getJSONFromUrl(String url,List<NameValuePair> params) {
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
post.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try
{
BufferedReader br=new BufferedReader(new InputStreamReader(is,"iso-8859-1"), 8);
StringBuilder builder=new StringBuilder();
String line=null;
while((line=br.readLine())!=null)
{
builder.append(line + "\n");
}
is.close();
str=builder.toString();
}
catch(Exception e)
{
}
try {
jObj=new JSONObject(str);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jObj;
}
}
I suspect your problem is that your AsyncTask finishes immediately as parse.getJSONFromUrl... is also Async. So whats happening is that progress.dismiss(); in onPostExecute invoked also immediately.
Try removing progress.dismiss(); from onPostExecute and see what happens
This should work. But without the progress.setMessage("Processing...");
You can still set that.
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(getActivity(),R.style.MyTheme);
dialog.setCancelable(false);
dialog.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
dialog.show();
}
I try to update the autocomplete textview data from the web service based text typed in the textbox. It's working fine but i put the progressbar at the time of web service call because it will take some time in this case autocomplete text view is not showing the drop down menu. I guess autocomplete textview is dissmissed at the time of progressbar dissmissed. How should we put the progress bar in this case.
Code
class GetFundNames extends AsyncTask {
ProgressDialog progress = new ProgressDialog(BasicAutoText.this);
#Override
protected void onPreExecute() {
Log.d("TAG", "onPreExecute()");
progress.setMessage("Please wait...");
progress.setCanceledOnTouchOutside(false);
progress.show();
}
#Override
// three dots is java for an array of strings
protected String doInBackground(Void... args) {
try {
response = getNames(strKeyword);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
;
return response;
}
// then our post
#Override
protected void onPostExecute(String response) {
if(progress.isShowing())
{
progress.dismiss();
}
if (ETF_Constants.registerResponsevalue == 200) {
JSONArray arObjects;
try {
arObjects = new JSONArray(response);
arProducts = new ArrayList<ProductData>();
arProducts.clear();
for (int i = 0; i < arObjects.length(); i++) {
JSONObject jOb = arObjects.getJSONObject(i);
ProductData pd = new ProductData();
int fundId = jOb.getInt("fundId");
String con = "" + fundId;
String fundName = jOb.getString("fundName");
String priceAndDate = jOb.getString("priceAndDate");
String recentGain = jOb.getString("recentGain");
String recentGrowth = jOb.getString("recentGrowth");
String tickerName = jOb.getString("tickerName");
pd.fundId = con;
pd.fundName = fundName;
pd.priceAndDate = priceAndDate;
pd.recentGain = recentGain;
pd.recentGrowth = recentGrowth;
pd.tickerName = tickerName;
arProducts.add(pd);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// autocomplete
adapter = new ArrayAdapter<String>(BasicAutoText.this,
R.layout.advancelist);
adapter.setNotifyOnChange(true);
AUTO_View.setAdapter(adapter);
System.out.println("adapter" + adapter);
for (int i = 0; i < arProducts.size(); i++) {
adapter.add(arProducts.get(i).fundName);
System.out.println("Fund Name:"
+ arProducts.get(i).fundName);
}
System.out.println("arProducts count:" + arProducts.size());
System.out.println("adapter count:" + adapter.getCount());
adapter.notifyDataSetChanged();
}
}
}