AsyncTask onPostExecute causing crash - java

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");
}
}
}
}

Related

how to show progress bar update for FTP DOWNLOAD in android

I am trying to download an apk file to update my application and apk is placed in ftp server and I am downloading that apk using FTP Client.
Even though I call mProgress.setProgress(percent);
the ProgressBar is not getting updated from the function where I download the apk file by ftp
public class UpdateAppByFTP extends AsyncTask<String,Void,Void> {
private Context context;
CopyStreamAdapter streamListener;
public void setContext(Context mContext){
context = mContext;
}
private ProgressDialog mProgress;
#Override
protected void onPreExecute(){
super.onPreExecute();
mProgress = new ProgressDialog(this.context);
mProgress.setMessage("Downloading new apk .. Please wait...");
mProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
//mProgress.setIndeterminate(true);
mProgress.show();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
mProgress.dismiss(); //Dismiss the above Dialogue
}
#Override
protected Void doInBackground(String... arg0) {
try {
String serverName = arg0[0];
String userName = arg0[1];
String password = arg0[2];
String serverFilePath = arg0[3];
String localFilePath = arg0[4]; if(getFileByFTP(serverName,userName,password,serverFilePath,localFilePath)){
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(localFilePath)), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // without this flag android returned a intent error!
context.startActivity(intent);
}else{
//Do nothing could not download
}
String apkLocation="/download/"+"SmartPOS.apk";
Intent intent1 = new Intent(Intent.ACTION_VIEW);
intent1.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() +apkLocation)), "application/vnd.android.package-archive");
intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // without this flag android returned a intent error!
context.startActivity(intent1);
} catch (Exception e) {
}
return null;
}
//Below code to download using FTP
public boolean getFileByFTP(String serverName, String userName,
String password, String serverFilePath, String localFilePath)
throws Exception {
FTPClient ftp = new FTPClient();
try {
ftp.connect(serverName);
int reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return false;
}
} catch (IOException e) {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException f) {
throw e;
}
}
throw e;
} catch (Exception e) {
throw e;
}
try {
if (!ftp.login(userName, password)) {
ftp.logout();
}
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
ftp.enterLocalPassiveMode();
final int lenghtOfFile =(int)getFileSize(ftp,serverFilePath);
OutputStream output = new FileOutputStream(localFilePath);
CountingOutputStream cos = new CountingOutputStream(output) {
protected void beforeWrite(int n) {
super.beforeWrite(n);
int percent = Math.round((getCount() * 100) / lenghtOfFile);
Log.d("FTP_DOWNLOAD", "bytesTransferred /downloaded"+percent);
System.err.println("Downloaded "+getCount() + "/" + percent);
mProgress.setProgress(percent);
}
};
ftp.setBufferSize(2024*2048);//To increase the download speed
ftp.retrieveFile(serverFilePath, output);
output.close();
ftp.noop(); // check that control connection is working OK
ftp.logout();
return true;
}
catch (FTPConnectionClosedException e) {
Log.d("FTP_DOWNLOAD", "ERROR FTPConnectionClosedException:"+e.toString());
throw e;
} catch (IOException e) {
Log.d("FTP_DOWNLOAD", "ERROR IOException:"+e.toString());
throw e;
} catch (Exception e) {
Log.d("FTP_DOWNLOAD", "ERROR Exception:"+e.toString());
throw e;
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException f) {
throw f;
}
}
}
}
private static long getFileSize(FTPClient ftp, String filePath) throws Exception {
long fileSize = 0;
FTPFile[] files = ftp.listFiles(filePath);
if (files.length == 1 && files[0].isFile()) {
fileSize = files[0].getSize();
}
Log.d("FTP_DOWNLOAD", "File size = " + fileSize);
return fileSize;
}
}
Basically, the UI Does not get updated, also I am not sure whether the CountingOutputStream is the correct method to find the downloaded size of the file.
Thanks in advance.
I changed this retrieveFile section of the code and it is fine now
ftp.retrieveFile(serverFilePath, cos);
I tried your solution, it worked fine for me for file sizes up to 30 MB from FTP, going above, the download crashed every time. So I assumed the getCount() method as it is being called every time would result in some issue.
I even tried running the getCount() on separate thread, but still no use.
So finally I changed percent (for progress) variable to fraction of FileSize of local/FTP file size. So in above case it will be:
int percent = Math.round(output.length() * 100) / lenghtOfFile);
Works fine.

AWS TransferManager returning more bytes transferred than file size, causing hang

I'm using AWS's Java SDK to upload some files (>130 MBs) into an S3 bucket.
The issue I'm having is that during the upload process (using TransferManager), the getBytesTransferred() returns a number greater than that of the file size itself.
This is causing my Progress Dialog to hang at 100%.
Am I missing some sort of configuration?
I should point out that this doesn't happen all the time.
public class PutFileTask extends AsyncTask<Void, Long, UploadZipCode> {
#Override
protected UploadZipCode doInBackground(final Void... params) {
// Initialize S3 Client
BasicAWSCredentials credentials = new BasicAWSCredentials(mS3AccessKey, mS3SecretKey);
AmazonS3Client amazonS3Client = new AmazonS3Client(credentials);
mTransferManager = new TransferManager(credentials);
mUploadStart = new Date(System.currentTimeMillis());
Upload myUpload = mTransferManager.upload(mS3UploadBucket, mFile.getName(), mFile);
myUpload.addProgressListener(new ProgressListener() {
long totalBytesTransferred = 0;
#Override
public void progressChanged(ProgressEvent progressEvent) {
totalBytesTransferred += progressEvent.getBytesTransferred();
Log.d(TAG, "Bytes transferred = " + totalBytesTransferred);
onProgressUpdate(totalBytesTransferred);\
if (progressEvent.getEventCode() == ProgressEvent.COMPLETED_EVENT_CODE) {
cancel(true);
} else if (progressEvent.getEventCode() == ProgressEvent.FAILED_EVENT_CODE
|| progressEvent.getEventCode() == ProgressEvent.CANCELED_EVENT_CODE) {
Log.e(TAG, "Uploaded erred out with AWS Event Code: " + progressEvent.getEventCode());
cancel(true);
}
Log.d(TAG, "Setting completion code to: " + progressEvent.getEventCode());
}
});
try {
myUpload.waitForCompletion();
} catch (InterruptedException e) {
cancel(true);
e.printStackTrace();
return UploadZipCode.CONNECTION_ERROR;
} catch (Exception e) {
cancel(true);
e.printStackTrace();
return UploadZipCode.AWS_ERROR;
}
return UploadZipCode.UPLOAD_SUCCESS;
}
...
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(mActivity);
mProgressDialog.setTitle("Please wait...");
mProgressDialog.setMessage("Uploading your session zip file...");
mProgressDialog.setProgressStyle(mProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setProgress(0);
mProgressDialog.setMax((int) (mFile.length()));
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
...
#Override
protected void onProgressUpdate(Long... values) {
super.onProgressUpdate(values);
for (long value : values) {
mProgressDialog.setProgress((int) value);
}
}
...
#Override
protected void onPostExecute(UploadZipCode resultCode) {
super.onPostExecute(resultCode);
mProgressDialog.dismiss();
mListener.onUploadFinished(resultCode);
}
...
#Override
protected void onCancelled(UploadZipCode resultCode) {
super.onCancelled(resultCode);
if (mProgressDialog != null) {
mProgressDialog.dismiss();
}
mListener.onUploadFinished(resultCode);
}
}

Updating ProgressBar when downloading using FTPClient

I'm using Apache's FTPClient to upload files to my server (images from the gallery if it matters)
I'm having a small and pretty insignificant problem, but I would still like to solve it.
The problem is that the bar is filled and reaches 100% before the upload actually completes, causing the dialog to show 100% for an extra 2-3 seconds on small files (and could be a lot more on files weighing several MBs).
I'm guessing it's because of the conversion from long to int, but that's just a guess.
Here's the code:
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(UploadActivity.this);
dialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
uploadImage.cancel(true);
}
});
dialog.setMessage("Uploading...\nPlease Wait.");
dialog.setIndeterminate(false);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setProgress(0);
dialog.setCancelable(false);
dialog.setMax((int)(file.length()/1024));
dialog.setProgressNumberFormat ("%1dKB/%2dKB");
dialog.show();
}
#Override
protected String doInBackground(Void... params) {
CopyStreamAdapter streamListener = new CopyStreamAdapter() {
#Override // THIS PART IS RESPONSIBLE FOR UPDATING THE PROGRESS
public void bytesTransferred(long totalBytesTransferred, int bytesTransferred, long streamSize) {
int percent = (int) (totalBytesTransferred * 100 / file.length());
publishProgress(percent);
}
};
String name = null;
ftp.setCopyStreamListener(streamListener);
FileInputStream fis = null;
try {
String extension = "";
String fileName = file.getName();
int i = fileName.lastIndexOf('.');
int p = Math.max(fileName.lastIndexOf('/'), fileName.lastIndexOf('\\'));
if (i > p) {
extension = fileName.substring(i + 1);
}
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyy-hhmmss-SSS");
name = String.format("File-%s.%s", sdf.format(new Date()), extension);
ftp.connect(FTP_SERVER);
ftp.enterLocalPassiveMode();
ftp.login(ftpUser, ftpPassword);
ftp.setFileType(FTP.BINARY_FILE_TYPE);
fis = new FileInputStream(file);
if (!ftp.storeFile(name, fis)) {
showToast("Failed uploading");
return null;
}
ftp.logout();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return name;
}
#Override
protected void onProgressUpdate(Integer... values) {
dialog.setProgress(values[0]);
}
Thanks!

Upload progress listener not fired (Google drive API)

I want to show progress by percent of an uploading file using Google drive API.
My menthod has successful upload a file before but It can't see upload progress.
I've seen and added this FileUploadProgressListener but mediaHttpUploader.getProgress() show only 0.0 (start of progress) and 1.0 (when progress finished). I can't get percent of progress in time.
How to make It work?
Here is my Upload code:
public void UploadFile(final DFile uploadFile) {
if (!isLoggedIn()) {
OnUploadGoogleChecked(FALSE, "Not logged in");
return;
}
AsyncTask<Void, Long, String> task = new AsyncTask<Void, Long, String>() {
java.io.File fileContent;
FileContent mediaContent;
com.google.api.services.drive.model.File body;
com.google.api.services.drive.model.File file;
private ProgressDialog mDialog;
long mFileLen;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
mDialog = new ProgressDialog(act);
mDialog.setMax(100);
mDialog.setMessage("Uploading ");
mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mDialog.setProgress(0);
mDialog.setButton("Cancel", new OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
}
});
mDialog.show();
}
class FileUploadProgressListener implements MediaHttpUploaderProgressListener {
#Override
public void progressChanged(MediaHttpUploader uploader) throws IOException {
Log.d("Dolphin got percent", String.valueOf(uploader.getProgress()));
switch (uploader.getUploadState()) {
case INITIATION_STARTED:
System.out.println("Initiation Started");
break;
case INITIATION_COMPLETE:
System.out.println("Initiation Completed");
break;
case MEDIA_IN_PROGRESS:
System.out.println("Upload in progress");
System.out.println("Upload percentage: " + uploader.getProgress());
break;
case MEDIA_COMPLETE:
System.out.println("Upload Completed!");
break;
case NOT_STARTED:
System.out.println("Upload Not Started!");
break;
}
}
}
#Override
protected String doInBackground(Void... arg0) {
try {
java.io.File UPLOAD_FILE = new java.io.File(uploadFile.getNameAndDir());
// File's metadata.
fileContent = new java.io.File(uploadFile.getNameAndDir());
mFileLen = fileContent.length();
InputStreamContent mediaContent2 = new InputStreamContent("image/jpeg", new BufferedInputStream(new FileInputStream(UPLOAD_FILE)));
mediaContent2.setLength(UPLOAD_FILE.length());
body = new com.google.api.services.drive.model.File();
body.setTitle(fileContent.getName());
body.setMimeType("image/jpeg");
String parentId = null;
body.setParents(Arrays.asList(new ParentReference().setId(uploadFile.getFileHostFolderId())));
Drive.Files.Insert mInsert = service.files().insert(body, mediaContent2);
MediaHttpUploader uploader = mInsert.getMediaHttpUploader();
uploader.setDirectUploadEnabled(true);
uploader.setProgressListener(new FileUploadProgressListener());
file = mInsert.execute();
if (file != null) {
}
} catch (UserRecoverableAuthIOException e) {
Log.d("Dolphin got error", "not login " + e);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
mDialog.dismiss();
OnUploadGoogleChecked(TRUE, "Upload complete");
};
};
task.execute();
}
To get progress, you must use uploader.setDirectUploadEnabled(false); (instead of true) and uploader.setChunkSize(MediaHttpUploader.MINIMUM_CHUNK_SIZE); or any value which must be the multiply of MediaHttpUploader.MINIMUM_CHUNK_SIZE, else it will cause error.

Why is FileNotFound being thrown only in Ice Cream Sandwich and JellyBean

I am trying to parse an icalendar file (.ics) using ical4j library, and its working fine with all versions of Android but IceCreamSandwich and JellyBean.
Can someone tell me why its throwing FileNotFound Error only in ICS and JB but not in other versions of android?
Here's my code :
public class MainActivity extends Activity {
String foo = null;
TextView TextView = null;
String fileName = "ical.ics";
String URL = "https://www.google.com/calendar/ical/m0es4hhj4g9d69ibak88tvoup0%40group.calendar.google.com/public/basic.ics";
StringBuilder b = new StringBuilder();
#Override
public void onCreate(Bundle savedInstanceState) {
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView = (TextView)findViewById(R.id.Hello_World);
new Download().execute();
}
final class Download extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute(){
TextView.setText("Downloading");
}
#Override
protected Void doInBackground(Void... arg0) {
try {
URL url = new URL(URL);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
FileOutputStream fos = openFileOutput(fileName, MainActivity.MODE_PRIVATE);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int length = 0;
while ((length = is.read(buffer)) != -1) {
fos.write(buffer, 0, length);
}
fos.close();
is.close();
} catch (IOException e) {
Log.d("log_tag", "Error: " + e);
}
return null;
}
#Override
protected void onPostExecute(Void Result) {
TextView.setText("Saved...Loading Data");
new Loadicaldata().execute();
}
}
final class Loadicaldata extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
FileInputStream fis = null;
try {
fis = openFileInput(fileName);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_UNFOLDING, true);
CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_VALIDATION, true);
CalendarBuilder builder = new CalendarBuilder();
try {
Calendar calendar = builder.build(fis);
b.append(calendar.getProperty("X-WR-CALNAME").getValue());
for (Object event : calendar.getComponents(Component.VEVENT)) {
if (((VEvent) event).getSummary() != null) {
b.append("\n\n");
b.append(((VEvent) event).getSummary().getValue());
b.append(": ");
b.append(((VEvent) event).getStartDate().getDate());
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void Result) {
TextView.setText(b.toString());
}
}
Also, I have noticed that if I use Calendar.load(URL url) it works fine. So it is the saving and loading of file that is going wrong.
Try removing
c.setDoOutput(true);
(as suggested by this blog post)

Categories