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.
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.
In my application i take an image and data from server. When internet connection is there image loaded properly. When internet connection slow down an application keeps on running and after sometime it stops suddenly.
This is AsyncTask to get image and data from server:
public void getPendingList() {
new AsyncTask<Void, Void, String>() {
protected void onPreExecute() {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setTitle("Loading....");
progressDialog.setMessage("Please Wait...");
progressDialog.setCancelable(true);
progressDialog.show();
}
protected String doInBackground(Void... params) {
prepareList();
getRegistrationDetails();
getStateList();
for (int i = 0; i < districts.size(); i++) {
JSONObject jsonObject;
try {
jsonObject = new JSONObject(districts.get(i));
String val1 = jsonObject.getString("OptionalParameter");
int val2 = jsonObject.getInt("ItemID");
String val3 = jsonObject.getString("Item_Description");
double val4 = jsonObject.getDouble("Item_Price");
String val5 = jsonObject.getString("Item_Code");
String val6 = jsonObject.getString("Item_Name");
String val7 = jsonObject.getString("ImageFinal");
String ItemCode = jsonObject.getString("Item_Code");
val7.replace("/", "");
listmodel.add(new Item_Master(val2, val3, val4, val6, val7, ItemCode));
listCountry.add("\u20B9" + val4);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return "response";
}
protected void onPostExecute(String result) {
if (result != null) {
if (!result.equals("NO_NETWORK")) {
mAdapter = new GridviewAdapter_Item_Master(FaramentView.getContext(), listmodel);
gridview.setAdapter(mAdapter);
}
dismissDialog();
}
}.execute(null, null);
}
}
After getting this data, I set GridView adapter in this data and image are set. I use Picasso library to download image and set with following code:
Picasso.with(context).load(list.get(position).getImagePath()).centerCrop()
.resize(150, 150).error(R.drawable.ic_launcher).into(view.imgViewFlag);
How to load image even in slow internet connection?
You get an ANR probably and that means you catch a UI Timeout, that because you trying to update an application component of UI in and AsyncTask (however keep in mind to manage background network processing in doInBackground() method); to update a UI application component you can use Handlers or updating it by runOnUiThread()
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...");
This is code
StatusUpdate status = new StatusUpdate(msg);
twitter.updateStatus(status);
it work fine.
but i want share my image by url
please help me.
Try following :
Get the path of the image you wish to upload, if it is already on sd-card. If not then download it first, save to sd card and then get the path.
Then create a file using that filepath (picFilePath) as follows :
File imgFile = new File(picFilePath);
Set this file as media in statusupdate object,
// the txt message
StatusUpdate status = new StatusUpdate(Msg);
// set the image file as media with the message.
status.setMedia(imgFile);
Upload the message with image using an AsyncTask
twitter.updateStatus(status);
Hope this helps you.
try this:
T4JTwitterFunctions.postToTwitter
(your_class.this.getApplicationContext(),your_class.this, twitter_consumer_key, twitter_consumer_secret,
Your_URL, new T4JTwitterFunctions.TwitterPostResponse()
{ #Override public void OnResult(Boolean success)
{
if(success)
{
//success
}
else
{
//not success
}
}
});
you can do this with the help of the twitPic4j API. Just add the API for twitPic4j and write below code to upload the photo.
first you have to download the picture from url, save it to temp folder then upload it and after uploading delete this temporary image.
File picture = new File(APP_FILE_PATH + "/"+filename+".jpg");
// Create TwitPic object and allocate TwitPicResponse object
TwitPic tpRequest = new TwitPic(TWITTER_NAME, TWITTER_PASSWORD);
TwitPicResponse tpResponse = null;
// Make request and handle exceptions
try {
tpResponse = tpRequest.uploadAndPost(picture, customMessageEditText.getText()+" http://www.twsbi.com/");
}
catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Please enter valid username and password.", Toast.LENGTH_SHORT).show();
}
catch (TwitPicException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Invalid username and password.", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "Please enter valid Username and Password.", Toast.LENGTH_SHORT).show();
}
// If we got a response back, print out response variables
if(tpResponse != null) {
tpResponse.dumpVars();
System.out.println(tpResponse.getStatus());
if(tpResponse.getStatus().equals("ok")){
Toast.makeText(getApplicationContext(), "Photo posted on Twitter.",Toast.LENGTH_SHORT).show();
//picture.delete();
}
}
I think this code will help you:
class updateTwitterStatus extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Updating to twitter...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Places JSON
* */
protected String doInBackground(String... args) {
Log.d("Tweet Text", "> " + args[0]);
String status = args[0];
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
// Access Token
String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
// Access Token Secret
String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");
System.out.println(access_token+access_token_secret+"....."+PREF_KEY_OAUTH_TOKEN);
AccessToken accessToken = new AccessToken(access_token, access_token_secret);
Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
StatusUpdate ad=new StatusUpdate("mala ruparel...........");
// The InputStream opens the resourceId and sends it to the buffer
InputStream is = getResources().openRawResource(R.drawable.f1);
ad.setMedia("Malvika",is);
// Update status
twitter4j.Status response = twitter.updateStatus(ad);
Log.d("Status", "> " + response.getText());
} catch (TwitterException e) {
// Error in updating status
Log.d("Twitter Update Error", e.getMessage());
}
return null;
}
/**
* After completing background task Dismiss the progress dialog and show
* the data in UI Always use runOnUiThread(new Runnable()) to update UI
* from background thread, otherwise you will get error
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Status tweeted successfully", Toast.LENGTH_SHORT)
.show();
// Clearing EditText field
txtUpdate.setText("");
}
});
}
}
Here is my issue:
I have a list of values which I retrieve from server.
These values fill ListView in the UI.
I cannot continue loading the View and showing it to user until the list is full.
Since Android forces me to make http calls in separate thread, my question is how do I create 1 class that does the httprequests and in the calling class I wait until I get response from the HttpRequest and only then I proceed loading the View?
Right now I have this class that does the requests:
public class WapConnector extends AsyncTask<String, String, String>{
private static final String TAG = "WapConnector";
private String html = "";
private Handler mHandler;
private String server = "http://....whatever";
private String callUrl = "/api/";
private String params = "login?u=Admin&pw=234234&format=json";
private int _callstate = 1;
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
String fullUrl = "";
Log.i(TAG,fullUrl);
if(params.length() > 0){
fullUrl = server + callUrl + params + "&alf_ticket=" + Globals.getInstance().getTicket() + "&udid=" + Globals.getInstance().udid() + "&phoneNumber=" + Globals.getInstance().phoneNumber();
}
else{
fullUrl = server + callUrl + "?udid=" + Globals.getInstance().udid() + "&alf_ticket=" + Globals.getInstance().getTicket() + "&phoneNumber=" + Globals.getInstance().phoneNumber();
}
Log.i(TAG,fullUrl);
response = httpclient.execute(new HttpGet(fullUrl));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
Log.i(TAG,responseString);
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
e.printStackTrace();
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
e.printStackTrace();
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.i(TAG + "onPostExecute",result);
activity.getClass().handleResponse();
//main load
JSONObject jobj;
JSONObject jvalue;
try {
jobj = new JSONObject(result);
if(_callstate == 1){
jvalue = jobj.getJSONObject("data");
String ticket = jvalue.getString("ticket");
Log.i("loginwap",ticket);
Globals.getInstance().setTicket(ticket);
_callstate = 2;
}
else{
jvalue = jobj.getJSONObject("countries");
JSONArray countries = jvalue.getJSONArray("countries");
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And this is how I make calls from Parent classes:
WapConnector wap = new WapConnector();
wap.setCallUrl("/anyurl/");
wap.callstate(3);
wap.setParams("");
wap.execute("");
Now my issue is that since the request runs in thread, once I call wap.execute(), my Activity continues to load, but I want it to wait until I get response, parse the response and only then continue to load.
thanks everyone for replies.!!!
Pass in a context to your class from the activity you are calling it from. Overload the onPreExecute() to show a ProgressDialog and then overload onPostExecute() to hide the ProgressDialog. This gives you blocking while letting the user you are loading.
There is a kinda hacky way to get more control. If you want to keep the AsyncTask as a separate class but allow it to update UI elements in another Activity, define a Handler in that Activity and then pass it in the constructor of the the AsyncTask. You can then send a message in the onPostExecute() method of your AsyncTask to the handler to tell it to update the UI. You will need to make sure the handler is properly handling the message your AsyncTask is sending back. Could be a little cleaner, but it works and will allow you to reuse an asyncTask that makes a network call across activities.