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.
Related
When apps installed, copy database work just fine. But when i tried to copy database in onUpgrade. the apps crashed even i left it empty in onPostExecute. But the database successfully copied and apps work just fine. Please help me.
LoginActivity
public class AsyncCopyDatabase extends AsyncTask<String, String, String> {
DatabaseHelper db;
ProgressDialog progress;
protected void onPreExecute(){
super.onPreExecute();
db = new DatabaseHelper(LoginActivity.this);
progress = new ProgressDialog(LoginActivity.this);
progress.setMessage("Preparing data. Please wait..");
progress.setCancelable(false);
progress.show();
}
#Override
protected String doInBackground(String... strings) {
//return null;
try {
db.createDatabase();
} catch (IOException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
}
db.openDataBase();
return null;
}
#Override
protected void onPostExecute(String result) {
//Toast.makeText(LoginActivity.this, result, Toast.LENGTH_SHORT).show();
progress.dismiss();
}
}
DatabaseHelper
public void CopyDataBaseFromAsset() throws IOException{
InputStream in = ctx.getAssets().open(DATABASE_NAME);
Log.e("sample", "Starting copying" );
String outputFileName = DATABASE_PATH+DATABASE_NAME;
File databaseFile = new File(DATABASE_PATH);
// check if databases folder exists, if not create one and its subfolders
if (!databaseFile.exists()){
databaseFile.mkdir();
}
OutputStream out = new FileOutputStream(outputFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer))>0){
out.write(buffer,0,length);
}
Log.e("sample", "Completed" );
//db_delete();
out.flush();
out.close();
in.close();
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
if (newVersion > oldVersion) {
db.close();
boolean b = ctx.deleteDatabase(DATABASE_NAME);
if(b){
try{
CopyDataBaseFromAsset();
}
catch (IOException e){
throw new Error("Error copying database");
}
}
}
}
its my codes for send data to server i want cancel Asynctask when click back button i try a lot of way but i could not cancel Asynctask how do that??
public class sendcomment extends AsyncTask{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pr = ProgressDialog.show(sendques.this, null, null, true);
pr.setContentView(R.layout.progressdialog);
pr.getWindow().setBackgroundDrawable(newColorDrawable(android.graphics.Color.TRANSPARENT));
pr.setCancelable(true);
pr.show();
pr.setOnCancelListener(new ProgressDialog.OnCancelListener() {
#Override
public void onCancel(DialogInterface arg0) {
pr.cancel();
new sendcomment().cancel(true);
}
});
}
#Override
protected Object doInBackground(Object... arg0) {
// TODO Auto-generated method stub
try{
String data=URLEncoder.encode("name","utf8")+"="+URLEncoder.encode(ename.getText().toString()+"","utf8");
data+="&"+URLEncoder.encode("email","utf8")+"="+URLEncoder.encode(eemail.getText().toString()+"","utf8");
data+="&"+URLEncoder.encode("phone","utf8")+"="+URLEncoder.encode(ephone.getText().toString()+"","utf8");
data+="&"+URLEncoder.encode("question","utf8")+"="+URLEncoder.encode(equestion.getText().toString()+"","utf8");
data+="&"+URLEncoder.encode("serial","utf8")+"="+URLEncoder.encode(phoneserialnumber+"","utf8");
data+="&"+URLEncoder.encode("model","utf8")+"="+URLEncoder.encode(devicemodel+"","utf8");
data+="&"+URLEncoder.encode("androidv","utf8")+"="+URLEncoder.encode(androidOS+"","utf8");
URL link=new URL(Main.url+"getquestion.php");
URLConnection connect=link.openConnection();
//send data
connect.setDoOutput(true);
OutputStreamWriter wr=new OutputStreamWriter(connect.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader=new BufferedReader(new InputStreamReader(connect.getInputStream()));
StringBuilder sb=new StringBuilder();
String line=null;
while((line=reader.readLine()) != null){
sb.append(line);
}
res=sb.toString();
}catch(Exception e){
res=e.toString();
}
return "";
}
#Override
protected void onPostExecute(Object result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(res.equals("ok")){
Builder alert = new AlertDialog.Builder(sendques.this);
alert.setTitle("your code: "+pnom+"");
alert.setMessage("your comment recieved!");
alert.setPositiveButton("ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Finish activity
finish();
}
});;
alert.show();
pr.cancel();
}
}
}`
its all of my code for send data and data send by press button
Thank you
Cancelling an AsyncTask can be a pain -
Instead of new sendcomment().cancel(true); try sendcomment.this.cancel(true);
And to test it, know that if AsyncTask is successfully cancelled, onPostExecute() won't run but onCancelled() will run instead, so put something in onCancelled() so you can tell if it's called, and if it is that means the AsyncTask is cancelled.
new sendcomment().cancel(true);
You try to cancel new task.
mySendCommentTask = new sendcomment();
mySendCommentTask.cancel(true);
P.S Don't use AsyncTask.
Try this
// Initialize and execute
sendcomment mySendCommentTask = new sendcomment();
mySendCommentTask.execute();
// and when you need to cancel
mySendCommentTask.cancel(true);
I am trying to develop an app that can check if an update of itself is available, and then prompt the user to upgrade or not. One of the things I am having trouble with it being able to pull a the applications version number from online. Assuming that my url is correct and the div class actually exists, which is safe to assume, where is the issue in my code? Here is my code below:
Update called from a button click
public String url = "http://www.myurl.com"
UPDATE.setOnClickListener(new View.OnClickListener() {
String versionString = "";
#Override
public void onClick(View v) {
ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(connManager.TYPE_WIFI);
if (mWifi.isConnected()) {
new VersionCheck().execute();
}
}
});
//If wifi is connected then try to pull the version from offline.
private class VersionCheck extends AsyncTask<Void, Void, Void>{
String stringVersion;
int convertedString;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(UpdateActivity.this);
progressDialog.setTitle("Checking Current Version Number");
progressDialog.setMessage("Loading...");
progressDialog.setIndeterminate(false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try{
Document document = Jsoup.connect(URL1).get();
Elements element = document.select("div.VERSION_NUM");
stringVersion = element.toString();
convertedString = Integer.parseInt(stringVersion);
}catch (IOException ex){
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
String versionName = "";
int cVersion;
try {
versionName = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
try{
cVersion = Integer.parseInt(versionName);
if(convertedString > cVersion){
Toast.makeText(getApplicationContext(), "NEW Version :D", Toast.LENGTH_SHORT).show();
//Ideally create new dialog here to download the new version
}
}catch (NumberFormatException i){
i.printStackTrace();
}
} catch (PackageManager.NameNotFoundException e) {
}
}
}
Any questions please ask, I will post as much information as I am allowed to.
Thank everyone!
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();
}
}
}
Dear stackOverflow members i have recently started a new project called "RootBox" and it is an app that needs "su" perms and i have successfully allowed the app "su" or "root" access and im trying to download and replace a system file in "/system/media and i have setup my downloader but the download progress dialog pops up and closes which im guessing is the result of the file not being able to written to the system directory and i have Re-mounted the system as r-w before starting the download an i have searched all over the internet and was unable to find help thats why i have come here.
This is the activity executing the download
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn;
private ProgressDialog mProgressDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bootmation);
startBtn = (Button)findViewById(R.id.startBtn);
startBtn.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
startDownload();
RootTools.remount("/system/", "rw");
}
});
}
private void startDownload() {
String url = "http://www.filehosting.org/file/details/430746/bootanimation.zip";
new DownloadFileAsync().execute(url);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading file..");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
class DownloadFileAsync extends AsyncTask {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/system/media/bootanimation.zip");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC",progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
}
for this u have to allow in manifest for permission for writing as
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
URL u = new URL(fUrls[i]);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();