how to add progress dialog in inner class fragment - android

I want create progressdialog in fragment but keep showing error is has leaked window com.android.internal.policy.impl.phonewindow that was originally added here. please help and this my code
private class ListDaftarHargaAsync extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("retrieving...");
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(false);
}
#Override
protected String doInBackground(String... params) {
try {
modelPost.setDataVouchers();
} catch (JSONException e) {
e.printStackTrace();
}
String result = modelPost.resultString;
if (result.length() != 0) {
progressDialog.dismiss();
}
return null;
}
#Override
protected void onPostExecute(String result) {
progressDialog.dismiss();
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
fillDaftarHarga();
}
});
}
}

check is progress dialog is showing or not
and you cant touch UI thread in doInBackground
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("retrieving...");
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
try {
modelPost.setDataVouchers();
} catch (JSONException e) {
e.printStackTrace();
}
String result = modelPost.resultString;
return null;
}
#Override
protected void onPostExecute(String result) {
if (null != progressDialog && progressDialog.isShowing()) {
progressDialog.dismiss();
}
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
fillDaftarHarga();
}
});
}
}

leaked window com.android.internal.policy.impl.phonewindow that was originally added here.
Above error showing because you are calling progressDialog.dismiss(); on doInBackground.

Related

How to store or handle the response from AndroidNetworking responce/OkHttp response

public class MainActivity extends AppCompatActivity {
private Map<String,String> ipdetails = new HashMap<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getipDetails();
Log.d("getipdetails", "showingdata after getip fun execute is"+ ipdetails);
//Trying to use AsyncTask for the same operation
new AsyncNetworkoperation().execute();
}
private void getipDetails() {
AndroidNetworking.get("https://freegeoip.live/json/")
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
#Override
public void onResponse(JSONObject response) {
try {
ipdetails.put("Country",response.getString("country_name"));
Log.d("getipdetails", "showingdata in getip fun onResponce is"+ ipdetails);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onError(ANError anError) {
ipdetails.put("Country","Error: "+anError.toString());
}
});
}
private static final class AsyncNetworkoperation extends AsyncTask<Void, Void, String> {
String country;
#Override
protected String doInBackground(Void... params) {
AndroidNetworking.get("https://freegeoip.live/json/")
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
#Override
public void onResponse(JSONObject response) {
try {
country= response.getString("country_name");
Log.d("getipdetails", "showingdata in getip fun in AsyncTask onResponce is "+country);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onError(ANError anError) {
}
});
return country;
}
#Override
protected void onPostExecute(String result) {
Log.d("getipdetails", "showingdata in getip fun onPostExecute is "+result);
}
}
}
above is my code in the android studio I'm trying to call getipDetails() and immediately I want to use the returned data.
but before executing getipDetails(), the returned value is executed and showing null.
I used AsyncTask but I failed.
so help me to implement my logic.
like after calling getipDetails() immediately I want to use the return value. I don't have restrictions in a data type that it returns. but I want it to be used after the function call.
below is my log, which is not executed as mentioned in the code.
D/getipdetails: showingdata after getip fun execute is{}
D/getipdetails: showingdata in getip fun onPostExecute is null
D/getipdetails: showingdata in getip fun onResponce
is{Country=India}
D/getipdetails: showingdata in getip fun in AsyncTask onResponce is
India
Below is an image that has a log.
AsyncTask and all other networking libraries work on background thread in parallel along with the main UI thread. Therefore when the method getipDetails() is called, it starts a new thread and the remaining code is executed along with the getipDetails(), hence the log is giving null output. You have return the response from the doInBackground() and accept in onPostExecute().
public class MainActivity extends AppCompatActivity {
private Map<String, String> ipdetails1 = new HashMap<>();
private Map<String, String> ipdetails2 = new HashMap<>();
private RequestQueue requestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestQueue= Volley.newRequestQueue(this);
execute();
execute2();
}
public void execute() {
Log.i("IP RES", "EXECUTING");
JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET, "https://freegeoip.live/json/", null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
String country=null;
Log.i("Response from volley",response.toString());
try {
country=response.getString("country_name");
} catch (JSONException e) {
e.printStackTrace();
}
ipdetails1.put("country",country);
Log.i("IP Country from volley", ipdetails1.get("country"));
//Do whatever you want here
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
Log.i("Network Error",error.getMessage());
}
});
requestQueue.add(req);
}
public void execute2(){
AndroidNetworking.get("https://freegeoip.live/json/")
.setPriority(Priority.HIGH)
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
#Override
public void onResponse(JSONObject response) {
String country=null;
Log.i("Res Networking",response.toString());
try {
country=response.getString("country_name");
} catch (JSONException e) {
e.printStackTrace();
}
ipdetails2.put("country",country);
Log.i("from Networking", ipdetails2.get("country"));
//Do whatever you want here
}
#Override
public void onError(ANError error) {
// handle error
}
});
}
}
I have given both example using volley and and AndroidNetworking library, please don't use emulator for testing.

Android twitter tweet with images

I am integrating twitter first time in my android application, i am able to post tweet,i want to share image from app,i have URL of images(Which is stored at AmazonS3 server).i want to share this image from my android app ..please anyone can provide steps to achieve this
public class TwitterIntegration extends GlobalActivity {
TwitterAuthClient mTwitterAuthClient;
TwitterApiClient twitterApiClient;
Preferences preferences;
UserHistory userHistory;
StatusesService statusesService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
preferences=HWUtil.getPreferences(this);
userHistory=preferences.getUserHistory();
mTwitterAuthClient=new TwitterAuthClient();
mTwitterAuthClient.authorize(this, new Callback<TwitterSession>() {
#Override
public void success(Result<TwitterSession> result) {
TwitterSession session = result.data;
Log.d("user", session.getUserName());
Log.d("user", session.toString());
HWUtil.showToast(TwitterIntegration.this, session.getUserName());
twitterApiClient = TwitterCore.getInstance().getApiClient(session);
statusesService = twitterApiClient.getStatusesService();
statusesService.update("Hii from android", null, null, null, null,
null, null, null, new Callback<Tweet>() {
#Override
public void success(Result<Tweet> result) {
HWUtil.showToast(TwitterIntegration.this, "Posted SucessFully");
if(Validator.isNotNull(userHistory.getHistoryPictures())&& userHistory.getHistoryPictures().length>0){
shareImage();
}
}
public void failure(TwitterException exception) {
HWUtil.showToast(TwitterIntegration.this, "Failed to post");
}
});
}
#Override
public void failure(TwitterException exception) {
HWUtil.showToast(TwitterIntegration.this, exception.getMessage());
}
});
}
private void shareImage() {
if(Validator.isNotNull(twitterApiClient)){
MediaService mediaService=twitterApiClient.getMediaService();
}
}
#Override
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
// Pass the activity result to the login button.
super.onActivityResult(requestCode,responseCode,intent);
mTwitterAuthClient.onActivityResult(requestCode, responseCode, intent);
}
}
first of all we have to download all the images as said by #amit i used asynctask
public class DownLoadImageAsyncTask extends AsyncTask{
#Override
protected void onPreExecute() {
progressDialog=new ProgressDialog(TwitterIntegration.this);
progressDialog.setCancelable(false);
progressDialog.setMessage(getString(R.string.please_wait));
progressDialog.setIndeterminate(true);
if(Validator.isNotNull(preferences.getImagePath())&& !preferences.getImagePath().isEmpty()){
preferences.getImagePath().clear();
}
filePath=preferences.getImagePath();
}
#Override
protected Object doInBackground(Object[] params) {
File file=new File(Environment.getExternalStorageDirectory(),"/HealthWel");
if(file.exists()==true){
file.delete();
}
file.mkdir();
for (int i=0;i<mURLs.size();i++){
File f=new File(file+"/"+i+".jpg");
if(f.exists()==true){
f.delete();
}
if(f.exists()==false){
HttpClient httpClient=new DefaultHttpClient();
HttpGet httpGet=new HttpGet(mURLs.get(i));
try {
HttpResponse httpResponse=httpClient.execute(httpGet);
if(httpResponse.getStatusLine().getStatusCode()==200){
HttpEntity httpEntity=httpResponse.getEntity();
InputStream is=httpEntity.getContent();
Boolean status=f.createNewFile();
FileOutputStream fileOutputStream=new FileOutputStream(f);
byte[]buffer=new byte[1024];
long total=0;
int count;
while ((count=is.read(buffer))!=-1){
total+=count;
fileOutputStream.write(buffer,0,count);
}
if(!downLoad) {
if (Validator.isNotNull(preferences.getImagePath()) && !preferences.getImagePath().isEmpty()) {
preferences.getImagePath().clear();
}
}
filePath.add(f.getPath());
fileOutputStream.close();
is.close();
runOnUiThread(new Runnable() {
public void run() {
// runs on UI thread
progressDialog.show();
}
});
}
else {
finish();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Object o) {
preferences.setImagePath(filePath);
dismissProgressDialog();
shareImage();
}
}
private void showProgressDialog() {
if(!isFinishing() && progressDialog==null) {
progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
progressDialog.show();
}
}
/**
* dismiss Progress Dialog.
*/
private void dismissProgressDialog() {
if (!isFinishing() &&progressDialog!=null && progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog=null;
}
}
then we have to upload it to twitter using rest api to get media id using status service and after thatwe have to post it along with status with all media id as post. this perfectly works for me.

Trying to dismiss Progress Dialog

I am using Async Task to perform some operations in my database. During the operation, I'm showing a progress dialog and when it operations are finish I want to dismiss it but it doesn't work.
private ProgressDialog progressDialog;
private void showProgressDialog(String title, String message)
{
progressDialog = new ProgressDialog(this);
progressDialog.setTitle(title); //title
progressDialog.setMessage(message); // message
progressDialog.setCancelable(true);
progressDialog.show();
}
private class InsertFoodAsyncTask extends AsyncTask<Void, Integer, String>{
#Override
protected String doInBackground(Void... arg0){
InsertFood p = new InsertFood(Food.this,mBDD);
p.InsertFood();
return "Executed";
}
#Override
protected void onPreExecute() {
showProgressDialog("Please wait...", "Your message");
}
#Override
protected void onPostExecute(String result) {
if(progressDialog != null && progressDialog.isShowing())
{
progressDialog.dismiss();
}
}
}
Can you help me ? Thanks a lot !
Try it,
replace:
progressDialog.show();
for:
progressDialog = progressDialog.show();
It seems all correct in your code. onPostExecute() already make it run on ui thread. But still try to check with this also.
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
if(progressDialog != null && progressDialog.isShowing())
{
progressDialog.dismiss();
}
}
});

Uploading information using AsyncTask in android

Uploading information using AsyncTask in android and notifying user once the task is completed
What am i trying to Do:: I am trying to upload information to server from android
What have i tried:: I have done the image uploading part, I have used Async-task for this & the functionality works
What i am trying to do::
I want to show a Toast message once the file uploading is done as
"File Uploaded"
How can i achieve this ?
MainActivity.java
public class DataAcceptActivity extends Activity {
<----------------------Code-------------->
public class MainTest extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(DataAcceptActivity.this);
pDialog.setMessage("Loading..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
postImageData();
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// data=jobj.toString();
pDialog.dismiss();
}
}
public class ImageAdapter extends BaseAdapter{
<_----------------- code _-------------->
}
Thanks !!
In AsyncTask you have to notified in onPostExecute method:
So use this:
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Toast toast = Toast.makeText(YourActivity.this, "Message Here", duration).show();
pDialog.dismiss();
}
It also depends on your Response that which type of message do you want to display.
If you are not using AsyncTask then you can also use Handler.
You can show the toast message in the onPostExecute() method of your async task.
You can simply display a toast in onPostExecute
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Toast toast = Toast.makeText(context, text, duration);
toast.show();
pDialog.dismiss();
}
on the your asynctask
#Override
protected void onPostExecute() {
Toast toast = Toast.makeText(getApplicationContextt, "File Uploaded", Toast.LENGTH_LONG).show();
}
public class MainTest extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(DataAcceptActivity.this);
pDialog.setMessage("Loading..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Boolean doInBackground(Void... params) {
postImageData();
return true;
}
#Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// data=jobj.toString();
if(result)
{
Toast.makeText(_context , "Image uploaded.." , Toast.LENGTH_LONG).show();
}
/* else
{
Toast.makeText(_context , "Image is not uploaded.." , Toast.LENGTH_LONG).show();
}*/
if(pDialog.isShowing())pDialog.dismiss();
}
}
In your code addding some changes in onPostExecuteMethod
public class MainTest extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(DataAcceptActivity.this);
pDialog.setMessage("Loading..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
postImageData();
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(pDialog.isShowing()){
// data=jobj.toString();
pDialog.dismiss();
}
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}

Android - on post execute in AsyncTask

I currently have an asyncTask which on preexecute begins a loading bar, in background send something to a server, and on post execute dismisses the dialog and enables a button. However, my post execute is not executing due to doInBackground returning null. I'm trying to figure out what I can do do get the postExecute to run. any ideas? thanks
code:
class DatabaseAsync extends AsyncTask<Void,Void,Void>{
#Override
protected void onPreExecute(){
dialog = ProgressDialog.show(MainFeedActivity.this, null, "Posting...");
}
#Override
protected Void doInBackground(Void... arg0) {
Log.d(TAG, "send to databse");
SendToDatabase();
Log.d(TAG, "sent to database - DONE");
//dialog.dismiss();
//sendButton.setEnabled(true);
return null;
}
protected void onPostExecute(){
Log.d(TAG, "p execute");
dialog.dismiss();
sendButton.setEnabled(true);
Log.d(TAG, "done executing");
}
}
It is completely Ok to return null from doInBackground() in your case. Just make sure onPostExecute() looks like this:
#Override
protected void onPostExecute(Void result) {
Log.d(TAG, "p execute");
dialog.dismiss();
sendButton.setEnabled(true);
Log.d(TAG, "done executing");
}
change your DatabaseAsync class like this:
class DatabaseAsync extends AsyncTask<String, Void, String>{
protected void onPreExecute(){
dialog = ProgressDialog.show(MainFeedActivity.this, null, "Posting...");
}
protected String doInBackground(String... arg0) {
Log.d("TAG", "send to databse");
Log.d("", "sent to database - DONE");
//dialog.dismiss();
//sendButton.setEnabled(true);
return null;
}
protected void onPostExecute(String result){
Log.d("TAG", "p execute");
dialog.dismiss();
Log.d("TAG", "done executing");
}
read this link after the code works http://www.vogella.de/articles/AndroidPerformance/article.html

Categories

Resources