This question already has answers here:
Updating progress dialog in Activity from AsyncTask
(2 answers)
How to use AsyncTask to show a ProgressDialog while doing background work in Android? [duplicate]
(2 answers)
Closed 8 years ago.
I want to add progressbar while new activity is not opened.
on next activity I am also fetching data so I want to add a progress bar on next activity also.
Here is my code.
login=(Button)dialog.findViewById(R.id.buttonLogin);
login.setOnClickListener(new OnClickListener() {
#SuppressLint("DefaultLocale")
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(LoginUsername.getText()==null||LoginUsername.getText().toString().equals(""))
{
LoginUsername.setHint("Enter Username");
LoginUsername.setHintTextColor(Color.RED);
}
else if(LoginPassword.getText()==null||LoginPassword.getText().toString().equals("")||LoginPassword.getText().toString().length()<6)
{
LoginPassword.setText("");
LoginPassword.setHint("Enter Password");
LoginPassword.setHintTextColor(Color.RED);
}
else
{
String username=LoginUsername.getText().toString();
String password=LoginPassword.getText().toString();
username1=username.toLowerCase();
// fetch the Password form database for respective user name
//String loginentries=database.getSingleEntry(username1);
//type=database.getType(username1);
try{
HttpClient client=new DefaultHttpClient();
HttpPost post=new HttpPost("http://www.universal-cinemas.com/android/login.php");
JSONObject jobj=new JSONObject();
jobj.put("username",username1);
jobj.put("password", password);
post.setEntity(new StringEntity(jobj.toString()));
Log.i("Info", "Sending request");
HttpResponse res=client.execute(post);
Log.i("Info", "Executed");
InputStream inp=res.getEntity().getContent();
BufferedReader bf = new BufferedReader(new InputStreamReader(inp));
StringBuilder sb= new StringBuilder();
sb.append(bf.readLine()+"\n");
String tmp="0";
while((tmp=bf.readLine())!=null)
{
sb.append(tmp+"\n");
}
String result= sb.toString();
JSONArray jarray=new JSONArray(result);
for(int i=0;i<jarray.length();i++)
{
a=1;
JSONObject job=jarray.getJSONObject(i);
type=job.getString("type");
currency=job.getString("currency");
}
}
catch(Exception e)
{
e.printStackTrace();
}
if(a==1)
{
i=new Intent(getApplicationContext(),User_MainOptions_List.class);
startActivity(i);
finish();
Toast.makeText(getApplicationContext(), "Welcome "+username, Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(), "Username and Password is not correct", Toast.LENGTH_SHORT).show();
}
}
}
});
dialog.show();
WindowManager.LayoutParams lp = dialog.getWindow().getAttributes(); // retrieves the windows attributes
lp.dimAmount=0.7f;// sets the dimming amount to zero
dialog.getWindow().setAttributes(lp); // sets the updated windows attributes
dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND); // adds the flag to blur bg
}
});
class MyLodingAsycTask extends AsyncTask<Void, Void, Void>{
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
runOnUiThread(new Runnable() {
public void run() {
progressDialog = new ProgressDialog(CameraActivity.this);
progressDialog.setMessage("Loding...");
progressDialog.setCancelable(false);
progressDialog.show();
}
});
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
runOnUiThread(new Runnable() {
public void run() {
if(progressDialog.isShowing())
progressDialog.dismiss();
}
});
}
#Override
protected Void doInBackground(Void... params) {
//call HTTP service
return null;
}
}
try this
private class MyAsync extends AsyncTask {
ProgressDialog PD;
#Override
protected void onPreExecute() {
super.onPreExecute();
PD = new ProgressDialog(MainActivity.this);
PD.setTitle("Please Wait..");
PD.setMessage("Loading...");
PD.setCancelable(false);
PD.show();
}
#Override
protected Void doInBackground(Void... params) {
//do what u want
return result;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
PD.dismiss();
}
}
}
Related
I am trying to download file using AsyncTask and also wanted to implement cancel button in progress dialog to cancel the download.
i think the problem is in "doInBackground" method. here is my asynctask:
public class Download_result extends AsyncTask<String,Integer,Void>{
ProgressDialog progressDialog;
Context context;
String pdfFile;
Download_result(Context context, String pdfFile){
this.context=context;
this.pdfFile=pdfFile;
}
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(context);
progressDialog.setTitle("Downloading...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMax(200);
progressDialog.setCancelable(false);
progressDialog.setProgress(0);
progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Download_result.this.cancel(true); //cancel asynctask here
dialog.dismiss();
}
});
progressDialog.show();
}
#Override
protected Void doInBackground(String... params) {
//given below
}
#Override
protected void onProgressUpdate(Integer... values) {
progressDialog.setProgress(values[0]);
}
#Override
protected void onPostExecute(Void result) {
progressDialog.cancel();
}
}
"doInBackground" method:
#Override
protected Void doInBackground(String... params) {
String url_1=params[0];
int file_length=0;
try {
URL url = new URL(url_1);
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
file_length=urlConnection.getContentLength();
filesize=file_length;
File sdCard = Environment.getExternalStorageDirectory();
File new_folder = new File (sdCard.getAbsolutePath() + "/xxx");
File input_file = new File(new_folder,pdfFile);
InputStream inputStream = new BufferedInputStream(url.openStream(),8192);
byte[] data=new byte[1024];
int total=0,count=0;
OutputStream outputStream = new FileOutputStream(input_file);
while ((count=inputStream.read(data))!=-1){
total+=count;
outputStream.write(data,0,count);
int progress= (total*200)/file_length;
downloadedsize=total;
publishProgress(progress);
if(isCancelled()){
break; or return null; // same result
}
}
inputStream.close();
outputStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
try this:
boolean downloadstatus = true;
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(context);
progressDialog.setTitle("Downloading...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMax(200);
progressDialog.setCancelable(false);
progressDialog.setProgress(0);
progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
download.cancel(true);
downloadstatus=false; //add boolean check
dialog.dismiss();
}
});
progressDialog.show();
}
Now in your doInbackGround()
while ((count=inputStream.read(data))!=-1){
if(!your_AsyncTask.isCancelled() || downloadstatus !=false){
total+=count;
outputStream.write(data,0,count);
int progress= (total*200)/file_length;
downloadedsize=total;
publishProgress(progress);
}else{
break;
}
}
This is a reply to my own post(may be in future someone need this):
Actualy my asynctask get cancel, but i didn't know because i thought that when we cancel the asynctask the file should not be there. But actualy when we cancel async task the file is stored but with the smaller size.
eg. Suppose the file is 1mb and i have cancel asynctask while progress dialog shows 50% then only 500kb file is stored, and i thought this is the actual file. sorry for my mistake.
So the logic is when someone press cancel you need to delete the half downloaded file too.
and sorry for my English, it's terrible i know.
I'm trying to show a ProgressDialog from an AsyncTask but is not showing... if I delete the 'dialog.dismiss()' of the PostExecute, this task works like a 'post()', it shows the Dialog in the end of the task. I'm getting crazy with this!
private static class Experimento extends AsyncTask<String, Void, String>
{
ProgressDialog dialog;
#Override
protected void onPreExecute()
{
super.onPreExecute();
dialog = new ProgressDialog(Config.getCurrent_Context());
dialog.setMessage("Cargando...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
protected String doInBackground(String... params)
{
try
{
Config.getCurrent_Context().runOnUiThread(new Runnable()
{
#Override
public void run()
{
try
{
//Work, work, work...
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result)
{
super.onPostExecute(result);
dialog.dismiss();
}
}
Now tried giving the Activity in the constructor but still not working...
private static ProgressDialog dialog;
public Experimento(Activity act)
{
Log.w("Experimento", "Experimento");
dialog = new ProgressDialog(act);
dialog.setMessage("Cargando...");
dialog.setCancelable(false);
dialog.show();
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
You should remove setIntermidiate(true);
Try this, it works for me:
Override
protected void onPreExecute()
{
dialog = new ProgressDialog(Config.getCurrent_Context());
dialog.setMessage("Cargando...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
protected String doInBackground(String... params)
{
String result = " ";
try
{
Config.getCurrent_Context().runOnUiThread(new Runnable()
{
#Override
public void run()
{
try
{
//Work, work, work...
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
}
catch(Exception e)
{
e.printStackTrace();
}
return result;
}
protected void onPostExecute(String result)
{
dialog.dismiss();
}
I'm using URLEncoder in my activity. but i have a error in MyTask. I have marked the error with Error in my code.
public class Search_Ringtone extends SherlockActivity{
ListView lsv_latest;
List<ItemRingCategoryItem> arrayOfRingcatItem;
RingCateItemAdapter objAdapterringitemitem;
AlertDialogManager alert = new AlertDialogManager();
private ItemRingCategoryItem objAllBean;
JsonUtils util;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.ringcatitem_activity);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
lsv_latest=(ListView)findViewById(R.id.latest_list);
arrayOfRingcatItem=new ArrayList<ItemRingCategoryItem>();
if (JsonUtils.isNetworkAvailable(Search_Ringtone.this)) {
String str = Constant.SEARCH_RINGTONE_URL+Constant.SEARCH.replace(" ", "%20");
String myUrl = URLEncoder.encode(str, "UTF-8");
MyTask().execute(myUrl); //*Error*
} else {
showToast("No Network Connection!!!");
alert.showAlertDialog(Search_Ringtone.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
}
lsv_latest.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
objAllBean=arrayOfRingcatItem.get(position);
Intent intplay=new Intent(getApplicationContext(),SingleRingtone.class);
Constant.RINGTONE_ITEMID=objAllBean.getRingItemId();
startActivity(intplay);
}
});
}
private class MyTask extends AsyncTask<String, Void, String> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Search_Ringtone.this);
pDialog.setMessage("لطفا صبر کنید...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
return JsonUtils.getJSONString(params[0]);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (null != pDialog && pDialog.isShowing()) {
pDialog.dismiss();
}
if (null == result || result.length() == 0) {
showToast("Server Connection Error");
alert.showAlertDialog(getApplicationContext(), "Server Connection Error",
"May Server Under Maintaines Or Low Network", false);
} else {
try {
JSONObject mainJson = new JSONObject(result);
JSONArray jsonArray = mainJson.getJSONArray(Constant.LATEST_ARRAY_NAME);
JSONObject objJson = null;
if(jsonArray.length()==0)
{
showToast("موردی پیدا نشد!");
}
else
{
for (int i = 0; i < jsonArray.length(); i++) {
objJson = jsonArray.getJSONObject(i);
ItemRingCategoryItem objItem = new ItemRingCategoryItem();
objItem.setRingItemId(objJson.getString(Constant.CATEITEMRING_RINDID));
objItem.setRingItemCatId(objJson.getString(Constant.CATEITEMRING_RINDCATID));
objItem.setRingItemCatName(objJson.getString(Constant.CATEITEMRING_CATENAME));
objItem.setRingItemName(objJson.getString(Constant.CATEITEMRING_RINGNAME));
objItem.setRingItemUrl(objJson.getString(Constant.CATEITEMRING_RINDURL));
objItem.setRingItemDownCount(objJson.getString(Constant.CATEITEMRING_RINDDOWNCOUNT));
objItem.setRingItemUser(objJson.getString(Constant.CATEITEMRING_RINDUSER));
objItem.setRingItemTag(objJson.getString(Constant.CATEITEMRING_RINDTAG));
objItem.setRingItemSize(objJson.getString(Constant.CATEITEMRING_RINDSIZE));
objItem.setRingStar(objJson.getString(Constant.LATESTRING_RINGSTAR));
objItem.setRingImage(objJson.getString(Constant.LATESTRING_RINGIMAGE));
arrayOfRingcatItem.add(objItem);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
setAdapterToListview();
}
}
}
Shouldn't it be new MyTask().execute(myURL);?
Also because it's an AsyncTask you need to retain a reference to it until it's finished or else the garbage collector destroys it.
i write like this and solved thank you everyone:
if (JsonUtils.isNetworkAvailable(Search_Ringtone.this)) {
String str = Constant.SEARCH_RINGTONE_URL+Constant.SEARCH.replace(" ", "%20");
String myUrl = null;
try {
myUrl = URLEncoder.encode(str, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new MyTask().execute(myUrl);
I used Facebook SDK in Android App for Login. I can login with Facebook. I want to insert AccessToken and Email to my database. I solved get Email but I can get email from user with Async. Then I use AsyncTask For Insert data to database. When I used AsyncTask with Facebook SDK, I got exception.
AsyncTask #5 java.lang.RuntimeException: An error occured while executing doInBackground()
And My Code
private JSONParser jParser = new JSONParser();
private String AccessToken;
public String Email;
private LoginAPI api = new LoginAPI();
#Override
protected void onCreate(Bundle savedInstanceState) {
FacebookSdk.sdkInitialize(getApplicationContext());
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loginButton = (LoginButton)findViewById(R.id.login_button);
if(Profile.getCurrentProfile()!=null){
user = Profile.getCurrentProfile();
new LoginAPI().execute();
}
loginButton.setReadPermissions("public_profile");
loginButton.setReadPermissions("email");
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
user = Profile.getCurrentProfile();
AccessToken = loginResult.getAccessToken().getToken();
GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject user, GraphResponse graphResponse) {
Email = user.optString("email");
api.execute();
}
}).executeAsync();
}
#Override
public void onCancel() {
AlertDialog alertMessage = new AlertDialog.Builder(Login.this).create();
alertMessage.setMessage("Iptal");
alertMessage.show();
}
#Override
public void onError(FacebookException exception) {
AlertDialog alertMessage = new AlertDialog.Builder(Login.this).create();
alertMessage.setMessage(exception.toString());
alertMessage.show();
}
});
}
class LoginAPI extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(final String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new NameValuePair() {
#Override
public String getName() {
return "Email";
}
#Override
public String getValue() {
return Email;
}
});
params.add(new NameValuePair() {
#Override
public String getName() {
return "AccessToken";
}
#Override
public String getValue() {
return AccessToken;
}
});
JSONObject json = jParser.makeHttpRequest("WebServiceURL", "POST", params); //Exception Line
try {
if (json != null) {
Sonuc = json.getBoolean("Result");
Mesaj = json.getString("Message");
JSONObject _uye = json.getJSONObject("Data");
if(_uye!=null){
localUser = new User(_uye.getInt("UserID"),
_uye.getString("FacebookID"),
_uye.getString("NameSurname"),
_uye.getString("Email"),
_uye.getString("ProfileImage"));
}
else{
localUser = new User(1,"","","","");
}
}
} catch (JSONException e) {
return e.getMessage().toString();
}
return null;
}
protected void onPostExecute(String file_url) {
runOnUiThread(new Runnable() {
public void run() {
if(Sonuc){
Intent welcomeAct = new Intent(getBaseContext(), Welcome.class);
welcomeAct.putExtra("User",localUser);
Login.this.startActivity(welcomeAct);
}
else{
AlertDialog alertMessage = new AlertDialog.Builder(Login.this).create();
alertMessage.setMessage(Mesaj);
alertMessage.show();
}
}
});
}
}
I solved this problem. I wrote AsyncTask code in OnActivityResult event. When Authenticate process finished, I call AsyncTask.
I'm trying to retrieve data from JSON but it crashes whenever I try to retrieve data from my Android app.
// Intent i = new Intent(this,MainMenu.class);
// startActivity(i);
new AsyncTask<Void, Void, Void>()
{
ProgressDialog progressDialog;
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = new ProgressDialog(JobScreen.this);
progressDialog.setMessage("Getting Items..");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... voids)
{
try
{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet post = new HttpGet("http://users.abdullahadhaim.com/users/WebServiceResturant.asmx/login?userName=abood&Password=123");
HttpResponse response = httpClient.execute(post);
String responseString = EntityUtils.toString(response.getEntity());
JSONArray jsonArray = new JSONArray(responseString);
JSONObject jsonObject = jsonArray.getJSONObject(0);
ed1.setText(jsonObject.getString("UserName"));
Log.e("Done", "Done");
}
catch (Exception e)
{
e.printStackTrace();
Toast.makeText(JobScreen.this, "Faild", Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid)
{
super.onPostExecute(aVoid);
progressDialog.dismiss();
}
}.execute();
It looks like the problem is that you're calling ed1.setText() in the background thread.
Just move that call to onPostExecute(), and return the String value that you need from doInBackground().
Also remove the Toast from doInBackground(), and move it to onPostExecute() to be displayed if the return value of doInBackground() is null;
I just ran this, and it worked fine, and set the text to abood:
//use String for last parameter here:
new AsyncTask<Void, Void, String>() {
ProgressDialog progressDialog;
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(JobScreen.this);
progressDialog.setMessage("Getting Items..");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
progressDialog.show();
}
//String return value:
protected String doInBackground(Void... unused) {
try
{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet post = new HttpGet("http://users.abdullahadhaim.com/users/WebServiceResturant.asmx/login?userName=abood&Password=123");
HttpResponse response = httpClient.execute(post);
String responseString = EntityUtils.toString(response.getEntity());
JSONArray jsonArray = new JSONArray(responseString);
JSONObject jsonObject = jsonArray.getJSONObject(0);
Log.e("Done", "Done");
//return the String you need:
return jsonObject.getString("UserName");
}
catch (Exception e)
{
e.printStackTrace();
//remove this Toast:
//Toast.makeText(MainActivity.this, "Faild", Toast.LENGTH_SHORT).show();
}
return null;
}
//String parameter
protected void onPostExecute(String username) {
super.onPostExecute(username);
if (username == null){
//Toast if username is null
Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
else{
//Set the text here with the String received:
ed1.setText(username);
}
progressDialog.dismiss();
}
}.execute();