I have made an asynctask for getting some Json response from a webservice.I have used a progress bar when background processing done it displays,and have finished that progress Dialog in onPostExecute method of my asynctask.Thing is that i got successful response as per needed,But myl progress Dialog remains visible after that,Please can any one tell me how to dismiss it.My code is as below:
main.java
private class DoFavourite extends AsyncTask {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(ProductDetailActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
String favUrl = Const.API_DO_FAVOURITE + "?product_id=" + pid + "&customer_id=" + Pref.getValue(ProductDetailActivity.this, Const.PREF_CUSTOMER_ID, "");
System.out.println(":::::::::my FAVOURITE URL::::::::::::::" + favUrl);
// Creating service handler class instance
BackendAPIService sh = new BackendAPIService();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(favUrl, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
System.out.println("=============MY RESPONSE==========" + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
if (jsonObj.has(Const.TAG_STATUS)) {
if (jsonObj.getString(Const.TAG_STATUS).equalsIgnoreCase("success")) {
if (jsonObj.getString(Const.TAG_FAVOURITE).equalsIgnoreCase("1")) {
flag = 1;
} else {
flag = 2;
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
}
}
You are not using the progress dialog right. You'll notice the IDE shows a neat little warning sign next to your pd.show(...) line.
What you are doing is
Create an (invisible, irrelevant) progress dialog using new ProgressDialog()
Create another progress dialog with the desired text using pd.Show(), without storing a reference to it.
Dismiss the first dialog. The dialog from (2) remains.
If you replace your code with:
//pd = new ProgressDialog(this);
pd = ProgressDialog.show(this, "Waiting...", "Please wait five seconds...");
Related
Progress dialog should appear before display Alert dialog in Android app . I am using android studio.
Alert dialog content will be from Async task in separate class file. So excuting Progress dialog from async task.
But i am not able to see progress dialog screen before AlertDialog opens.
here is my async task code below.
public class ResidentsPaymentInfoHttpResponse extends AsyncTask<String,
Void, List<paymentInfo>> {
ProgressDialog pDialog;
private Context MSAContext;
public ResidentsPaymentInfoHttpResponse(Context context) {
MSAContext = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = ProgressDialog.show(MSAContext,"Autenticando", "Contactando o
servidor, por favor, aguarde alguns instantes.", true, false);
}
#Override
protected List<UserPaymentInfo> doInBackground(String... params){
String flatNo = params[0];
String urls = "https://script.google.com/macros/s/;"
List<UserPaymentInfo> residentsMonthlyPayments = new ArrayList<>();
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(urls)
.build();
Response responses = null;
try
{
responses = client.newCall(request).execute();
String jsonData = responses.body().string();
JSONObject jobject = new JSONObject(jsonData);
JSONArray jarray = jobject.getJSONArray("ResidentsInfo");
int limit = jarray.length();
for(int i=0;i<limit; i++)
{
JSONObject object = jarray.getJSONObject(i);
if(object.getString("FlatNo").equals(flatNo) &&
object.getString("PaymentStatus").equals("notpaid")) {
UserPaymentInfo residentMaintePayment = new
UserPaymentInfo();
UserInfo residentInfo = new UserInfo();
residentInfo.setUserFlatNo(object.getString("FlatNo"));
residentsMonthlyPayments.add(residentMaintePayment);
}
}
}
catch (IOException e)
{
// e.printStackTrace();
}
pDialog.dismiss();
}
catch (Exception ex)
{
// ex.printStackTrace();
}
return residentsMonthlyPayments;
}
protected void onPostExecute(List<UserPaymentInfo> rusult){
super.onPostExecute(rusult);
pDialog.dismiss();
}
}
Am i missing something???
You should not update UI elements (which belong to main/UI thread) inside doInBackground(). May be removing pDialog.dismiss(); from end lines of doInBackground() change the situation.
Check below link.
How to show progress dialog in Android?
you are not calling show() method on progress dialog. You should do it inside preExecute then dismiss it in postExecute method of async task.
Also as said by VSB you should not update UI elements from doInBackground method.
Hi i need to save json data in sqlite. But iam getting following error.
Can't create handler inside thread that has not called
Looper.prepare().
This is my code. It is shwoing database open/database created...
/**
* Async task class to get json by making HTTP call
* */
private class GetDetails extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#SuppressLint("NewApi")
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Create an array to populate the spinner
branchlist = new ArrayList<String>();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
// System.out.println("response"+jsonStr);
if (jsonStr != null) {
try {
// jsonString is a string variable that holds the JSON
JSONArray itemArray=new JSONArray(jsonStr);
for (int i = 0; i < itemArray.length(); i++) {
value=itemArray.getString(i);
Log.e("json", i+"="+value);
dbhelper=new DataBaseHepler(getApplicationContext());
sqLiteDatabase=dbhelper.getWritableDatabase();
dbhelper.addinnformation(value,sqLiteDatabase);
Toast.makeText(getBaseContext(),"Data saved",Toast.LENGTH_LONG).show();
dbhelper.close();
branchlist.add(itemArray.getString(i));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ArrayAdapter<String> stringadapter = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_spinner_dropdown_item,
branchlist);
spinner1.setAdapter(stringadapter);
// spinner1
// .setAdapter(new ArrayAdapter<String>(MainActivity.this,
// android.R.layout.simple_spinner_dropdown_item,
// branchlist));
}
}
This error is due to Toast inside doInBackground(Void... arg0) method:
Toast.makeText(getBaseContext(),"Data saved",Toast.LENGTH_LONG).show();
Clearly the Android OS wont let threads other than the main thread change UI elements. Follow this link for more details on this: https://dzone.com/articles/android-%E2%80%93-multithreading-ui
I have implemented an AsyncTask to get values of a web service and store them into an array, but something I am doing wrong because it says that "Invalid index 0, size is 0". The object "dia" is not well created. Here is my code:
private class GetValue extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
metereologia = new ArrayList<DiaTemperatura>();
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
eventos = jsonObj.getJSONArray("list");
// looping through All Contacts
for (int i = 0; i < eventos.length(); i++) {
JSONObject c = eventos.getJSONObject(i);
JSONObject temp = c.getJSONObject(TAG_TEMP);
String max = temp.getString(TAG_MAX);
String min = temp.getString(TAG_MIN);
String humedad = c.getString(TAG_HUMIDITY);
JSONObject weather = c.getJSONObject(TAG_WEATHER);
//String main = weather.getString(TAG_MAIN);
//String description = weather.getString(TAG_DESCRIPTION);
DiaTemperatura dia= new DiaTemperatura();
dia.setMyText(max);
metereologia.add(dia);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
TextView mitext = (TextView) getView().findViewById(R.id.temperatura);
mitext.setText(metereologia.get(0).getMyText());
}
}
It looks like you must be declaring metereologia outside your AsyncTask, then initialising and populating it in the task. This is not quite the correct way to use it. Your AsyncTask should return the result of its computation. You'll need to declare your task as:
private class GetValue extends AsyncTask<Void, Void, List<DiaTemperatura>> {
...
#Override
protected List<DiaTemperatura> doInBackground(Void... arg0) {
List<DiaTemperatura> metereologia = new ArrayList<DiaTemperatura>();
...
return metereologia;
}
and thus onPostExecute becomes:
#Override
protected void onPostExecute(List<DiaTemperatura> metereologia) {
I think that's right, it's off the top of my head...
Your error must be in the line mitext.setText(metereologia.get(0).getMyText()); Its will go for finding the value at the index 0 in your metereologia which its is not getting.
You can not directly set the value of your whole arraylist in such a way. You need to loop for the value whichever you want to set in your TextView.
There is nothing in the metereologia so when you try to get it with (metereologia.get(0).getMyText(), it results in an error, "Invalid index 0, size is 0".
1) For doing check work -
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
TextView mitext = (TextView) getView().findViewById(R.id.temperatura);
String content = "";
if(metereologia.size() == 0)
{
//a check that your metereologia size is 0.
}
for(int i=0;i<metereologia.size();i++)
content = content + metereologia.get(i).getMyText();
mitext.setText(content);
}
}
2) To get the value right-
More convenient way is to return the object metereologia from background and pass it to postExecute method and then process.This is explained by #dave.c.
protected void onPostExecute(List<DiaTemperatura> metereologia) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
TextView mitext = (TextView) getView().findViewById(R.id.temperatura);
String content = "";
if(metereologia.size() == 0)
{
//a check that your metereologia size is 0.
}
for(int i=0;i<metereologia.size();i++)
content = content + metereologia.get(i).getMyText();
mitext.setText(content);
}
}
I want to get an url from this link:
"http://graph.facebook.com/10202459285618351/picture?type=large&redirect=false"
it gives result:
{
"data": {
"url": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xap1/t1.0- 1/s200x200/10342822_10202261537234765_3194866551853134720_n.jpg",
"is_silhouette": false
}
}
I tried,
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(AccountActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
String jsonStr = sh.makeServiceCall(fbPicURL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
fbRealURL = jsonObj.getString("url");
// Phone node is JSON Object
Toast.makeText(AccountActivity.this, fbRealURL,
Toast.LENGTH_LONG).show();
// tmp hashmap for single contact
}
catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
Toast.makeText(AccountActivity.this, fbRealURL,
Toast.LENGTH_LONG).show();
}
}
But returning null and its not crashing..
You have to get the data object first like this:
try {
JSONObject jsonObj = new JSONObject(jsonStr);
fbRealURLObj = jsonObj.getJSONObject("data");
fbRealURL = fbRealURLObj.getString("url");
// Phone node is JSON Object
Toast.makeText(AccountActivity.this, fbRealURL,
Toast.LENGTH_LONG).show();
// tmp hashmap for single contact
}
I want to show ProgressDialog when http connection request.
there is request method.
protected Result request(String urlStr, String postData) {
ProgressDialog dialog = ProgressDialog.show(activity, "", "Loading...",true);
Result result = new Result();
String message = "";
try {
message = HttpRequest.postURL(urlStr, postData);
result = new Result(message);
} catch (Exception e) {
Log.e(TAG,"Failed to request data from " + urlStr + "\n" + e.getMessage());
}
dialog.dismiss();
return result;
}
but when this method running. the ProgressDialog not showing.
how to solve this problem?
You need to call dialog.show()
Start the dialog and display it on screen. The window is placed in the
application layer and opaque. Note that you should not override this
method to do initialization when the dialog is shown, instead
implement that in onStart().
Also, what I do suggest is that you do this in AsyncTask class' doInBackground().
In the onPreExecute(), display the ProgressDialog and in the onPostExecute() dismiss it.
protected Result request(String urlStr, String postData) {
ProgressDialog dialog = ProgressDialog.show(activity, "", "Loading...",true);
Result result = new Result();
String message = "";
try {
message = HttpRequest.postURL(urlStr, postData);
result = new Result(message);
} catch (Exception e) {
Log.e(TAG,"Failed to request data from " + urlStr + "\n" + e.getMessage());
}
dialog.show();
return result;
}
don't forget to call dialog.dismiss(); with a button
There are many reasons for the progress dialog not showing, but in your case, i guess it's because you passing the wrong Context to show the ProgessDialog, please check your Activity context. Make sure you use proper Contextfor that or just change it to ApplicationContext
ProgressDialog dialog = ProgressDialog.show(activity, "", "Loading...",true);
Check this line, especially the activity. Hope this helps.