I my main activity I want to autosave whenever the user leaves the app or changes to another activity. So I implemented the save function in the activity's OnPause method, which works fine. Problem is the save process can take a few seconds, so I wanted a progressdialog while it happens. So I implenmeted that with an ASyncTask like this:
#Override
public void onPause()
{
super.onPause();
// save sheet when user is leaving activity
SaveTask task = new SaveTask(PlayCharacterActivity.this);
task.execute();
}
private class SaveTask extends AsyncTask <Void, Void, Void> {
private ProgressDialog dialog;
public SaveTask(PlayCharacterActivity activity) {
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(PlayCharacterActivity.this);
dialog.setMessage("Saving...");
dialog.show();
dialog.setIndeterminate(true);
dialog.setCancelable(false);
}
#Override
protected void onPostExecute(Void result) {
if (dialog.isShowing()) {
dialog.dismiss();
}
super.onPostExecute(result);
}
#Override
protected Void doInBackground(Void... params) {
try {
//Log.d("plch:OnPause", "starting save");
Sheet.getInstance().Save();
//Log.d("plch:OnPause", "finished save");
} catch (RuntimeException e) {
e.printStackTrace();
}
return null;
}
}
Problem is, the dialog doesn't appear until after the background task has completed. And I can see in logcat that the main thread is still being blocked. I believe it happens in the middle of the save function when it does the serialisation.
Save is like this:
public void Save()
{
long dtMili = System.currentTimeMillis();
Date d = new Date(dtMili);
CharSequence s = DateFormat.format("hh:mm:ss", d.getTime());
// use this flag to know whether to back up the saved file or not
boolean saveSuccessful = false;
//_xml = new String("");
dtMili = System.currentTimeMillis();
d = new Date(dtMili);
Log.d("Load/Save", "started serialising: " + DateFormat.format("hh:mm:ss", d.getTime()));
_xml = _instance.Serialise();
dtMili = System.currentTimeMillis();
d = new Date(dtMili);
Log.d("Load/Save", "finished serialising: " + DateFormat.format("hh:mm:ss", d.getTime()));
try
{
//---SD Card Storage---
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File (sdCard.getAbsolutePath() + "/RPGenius");
directory.mkdirs();
File file = new File(directory, _name + ".rpg");
FileOutputStream fOut = new FileOutputStream(file);
Log.d("Saving to: ", file.getAbsolutePath());
//---write the string to the file---
OutputStreamWriter osw = new OutputStreamWriter(fOut);
//DebugHelper.DebugMessage("File contents: " + _xml);
dtMili = System.currentTimeMillis();
d = new Date(dtMili);
Log.d("Load/Save", "started writing file: " + DateFormat.format("hh:mm:ss", d.getTime()));
osw.write(_xml);
osw.flush();
osw.close();
dtMili = System.currentTimeMillis();
d = new Date(dtMili);
Log.d("Load/Save", "finished writing file: " + DateFormat.format("hh:mm:ss", d.getTime()));
saveSuccessful = true;
}
catch (NullPointerException npe)
{
npe.printStackTrace();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
// if the save was completely successfully, back it up
if (saveSuccessful)
{
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File (sdCard.getAbsolutePath() + "/RPGenius");
File file = new File(directory, _name + ".rpg");
if (file.exists())
{
// locate backup directory and create if not present
File backupDirectory = new File (sdCard.getAbsolutePath() + "/RPGenius/Backups");
backupDirectory.mkdirs();
// create target file location/name
File backupFile = new File(backupDirectory, _name + ".rpg");
// attempt to copy file
try {
FileInputStream inStream = new FileInputStream(file);
FileOutputStream outStream = new FileOutputStream(backupFile);
FileChannel inChannel = inStream.getChannel();
FileChannel outChannel = outStream.getChannel();
inChannel.transferTo(0, inChannel.size(), outChannel);
inStream.close();
outStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Serialise is like this:
#Override
public String Serialise() {
// produce xml string to represent this object
_indents = 0;
_xml = new String("");
StartXmlItem("Sheet");
//AddSimpleXmlItem("Name", _name);
StartXmlItem("Stats");
for (XmlSerialisable stat: _stats)
{
AddComplexXmlItem(stat);
}
EndXmlItem("Stats");
StartXmlItem("Effects");
for (XmlSerialisable effect: _effects)
{
AddComplexXmlItem(effect);
}
EndXmlItem("Effects");
StartXmlItem("Pages");
for (XmlSerialisable page: _pages)
{
AddComplexXmlItem(page);
}
EndXmlItem("Pages");
EndXmlItem("Sheet");
return _xml;
}
I'm not immediately interested in improvements to the save/serialise methods unless they are relevant to the progressdialog problem. Can anyone help?
I propose the following change of your AsyncTask:
First of all remove the progressbar field and the useless constructor from the AsyncTask:
private ProgressDialog dialog; //should be declared as field in Activity
public SaveTask(PlayCharacterActivity activity) { //don't pass the activity to AsyncTask
}
Then in the onPreExecute() just do:
#Override
protected void onPreExecute() {
showDialog(); //call a method in your Activity that shows your dialog as you want
}
Remember that AsyncTask's onPreExecute method is run in the UI thread so you can deal with views from the Activity here. See documentation: http://developer.android.com/reference/android/os/AsyncTask.html#onPreExecute()
Try moving the dialog to the outer class and opening it outside the AsyncTask and by the static method
dialog = ProgressDialog.show(...)
just before
task.execute();
It should be possible to close it from onPostExecute
Related
Am use this code progress bar show but percentage bar not running
I am fairly new to android development, so what I am trying to make is app that can show pdf from url,
Am use this code progress bar show but percentage bar not running
I am using com.github.barteksc.pdfviewer.PDFView to show pdf
here is my pdf show activity
public class test2 extends AppCompatActivity {
PDFView pdfView; //pdfView object
String URL;
String fileName;
File directory; //path of created File
// Container for all parameters of DownloadAsync
private static class AsyncParameters {
String URL;
File directory;
AsyncParameters(String URL, File directory) {
this.URL = URL;
this.directory = directory;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent(); //whatever calls this activity, gather the intent
URL = intent.getStringExtra("File URL"); // in this case, get the file name of the "extra" passed through
fileName = intent.getStringExtra("File Name");
setContentView(R.layout.activity_test2);
File intDirectory = getFilesDir();
File folder = new File(intDirectory, "pdf");
boolean isDirectoryCreated = folder.exists();
//setDownloadButtonListener();
if (!isDirectoryCreated) {
isDirectoryCreated= folder.mkdir();
}
if(isDirectoryCreated) {
directory = new File(folder, fileName);
try {
directory.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
//See if file already exists (reduces wait time)
boolean empty = directory.length() == 0;
if (empty) {
/**Call class to create parameter container **/
AsyncParameters param = new AsyncParameters(URL, directory);
DownloadAsync Downloader = new DownloadAsync();
Downloader.execute(param);
}
showPdf();
}
}
public void showPdf()
{
pdfView = (PDFView) findViewById(R.id.pdfViewPager);
pdfView.fromFile(directory).load();
}
public class DownloadAsync extends AsyncTask<AsyncParameters, Void, Void> {
// Container for all parameters of DownloadAsync
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
//Create a progress bar that details the program downloading
super.onPreExecute();
pDialog = new ProgressDialog(test2.this);
pDialog.setMessage("Downloading ");
String message= "please wait don't push back";
SpannableString ss2 = new SpannableString(message);
ss2.setSpan(new RelativeSizeSpan(1f), 0, ss2.length(), 0);
ss2.setSpan(new ForegroundColorSpan(Color.BLACK), 0, ss2.length(), 0);
pDialog.setMessage(ss2);
pDialog.setCancelable(false);
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.show();
}
#Override
protected Void doInBackground(AsyncParameters... params) {
int count;
String fileURL = params[0].URL;
File directory = params[0].directory;
try {
FileOutputStream f = new FileOutputStream(directory);
java.net.URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.connect();
InputStream in = c.getInputStream();
int length=c.getContentLength();
byte[] data;
data = new byte[1024];
long total = 0;
while ((count = in.read(data)) != -1) {
total += count;
f.write(data, 0, count);
}
f.flush();
in.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
pDialog.setMessage(new SpannableString("ERROR DOWNLOADING"));
}
onPostExecute();
return null;
}
private void onPostExecute() {
pDialog.dismiss();
showPdf();
}
}
}
I don't see that you are calling publishProgress in doing background to invoke OnProgressUpdate.I don't see that you are setting the percentage in onProgressUpdate.I don't see that you have oveerriden onProgressUpdate anywhere.
OnPostExecute() is automatically called when background execution finishes.You don't need to call explicitly in doInBackGround and should not call it explicitly.
Note: AsyncTask is deprecated for API level 30.
I have a class compositionJSON. The class has a method calls makeJSONObject, that creates a JSON-Object and put stuff in it. Here is the code of the class.
public class CompositionJso extends JSONObject {
public JSONObject makeJSONObject (String title, String desc, ArrayList<String> imgPath, ArrayList<Resources> imgView) {
JSONObject obj = new JSONObject() ;
try {
obj.put("title", title);
obj.put("desc", desc);
obj.put("imgPath", imgPath);
obj.put("imgViewPath", imgView);
} catch (JSONException e) {
e.printStackTrace();
}
return obj;
}
Now I create a instance of this class and call the method in another class. After that I want to write the JSONObject to file and save it on the sd card on device. Here is the code:
saveCompo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setName();
createJSONFolder();
CompositionJso obj = new CompositionJso();
obj.makeJSONObject(compoTitle, compoDesc, imgPaths, imageViewPaths);
MyCompositionsListActivity.buildList();
try {
Writer output = null;
File file = new File("storage/sdcard/MyIdea/MyCompositions/" + compoTitle + ".json");
output = new BufferedWriter(new FileWriter(file));
output.write(obj.toString());
output.close();
Toast.makeText(getApplicationContext(), "Composition saved", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
finish();
}
});
The file is saving successfully but if I open it, there is nothing inside. What is wrong with the code?
makeJSONObject is returning JSONObject
Your code should be
saveCompo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setName();
createJSONFolder();
CompositionJso obj = new CompositionJso();
JSONObject jsonObject = obj.makeJSONObject(compoTitle, compoDesc, imgPaths, imageViewPaths);
MyCompositionsListActivity.buildList();
try {
Writer output = null;
File file = new File("storage/sdcard/MyIdea/MyCompositions/" + compoTitle + ".json");
output = new BufferedWriter(new FileWriter(file));
output.write(jsonObject.toString());
output.close();
Toast.makeText(getApplicationContext(), "Composition saved", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
finish();
}
});
Try this write a simple class with static methods to save and retrieve json object in a file :
CODE :
public class RetriveandSaveJSONdatafromfile {
public static String objectToFile(Object object) throws IOException {
String path = Environment.getExternalStorageDirectory() + File.separator + "/AppName/App_cache" + File.separator;
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
path += "data";
File data = new File(path);
if (!data.createNewFile()) {
data.delete();
data.createNewFile();
}
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(data));
objectOutputStream.writeObject(object);
objectOutputStream.close();
return path;
}
public static Object objectFromFile(String path) throws IOException, ClassNotFoundException {
Object object = null;
File data = new File(path);
if(data.exists()) {
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(data));
object = objectInputStream.readObject();
objectInputStream.close();
}
return object;
}
}
To save json in a file use RetriveandSaveJSONdatafromfile.objectToFile(jsonObj) and to fetch data from file use
path = Environment.getExternalStorageDirectory() + File.separator +
"/AppName/App_cache/data" + File.separator;
RetriveandSaveJSONdatafromfile.objectFromFile(path);
Thanks #Chris Handy! I created a JSONObjectVariable and assign it to the makeJSONObject. Here is my final code:
saveCompo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setName();
createJSONFolder();
CompositionJso compositionJso = new CompositionJso();
JSONObject obj;
obj = compositionJso.makeJSONObject(compoTitle, compoDesc, imgPaths, imageViewPaths);
MyCompositionsListActivity.buildList();
try {
Writer output;
File file = new File("storage/sdcard/MyIdea/MyCompositions/" + compoTitle + ".json");
output = new BufferedWriter(new FileWriter(file));
output.write(obj.toString());
output.close();
Toast.makeText(getApplicationContext(), "Composition saved", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
finish();
}
});
In the method makeJSONObject you instantiate a new JSONObject.
this code should work.
public void makeJSONObject (String title, String desc, ArrayList<String> imgPath, ArrayList<Resources> imgView) {
try {
this.put("title", title);
this.put("desc", desc);
this.put("imgPath", imgPath);
this.put("imgViewPath", imgView);
} catch (JSONException e) {
e.printStackTrace();
}
}
I am new in android. I made a 3 columns in sqlite and I am storing user input in sqlite
I want when device get Wifi(Internet) it will upload all data to google excel sheet accordingly with column on specific user account.
My solution is to convert the sqlite database into csv in first step then in second step is to convert the csv file to xls and it works fine for me, you will need 2 libraries (opencsv-1.7.jar; poi-3.8-20120326.jar)
public class ExportDatabaseCSVTask extends AsyncTask<String, Void, Boolean>
{
private final ProgressDialog dialog = new ProgressDialog(DatabaseExampleActivity.this);
#Override
protected void onPreExecute()
{
this.dialog.setMessage("Exporting database...");
this.dialog.show();
}
protected Boolean doInBackground(final String... args)
{
File dbFile=getDatabasePath("database_name");
//AABDatabaseManager dbhelper = new AABDatabaseManager(getApplicationContext());
AABDatabaseManager dbhelper = new AABDatabaseManager(DatabaseExampleActivity.this) ;
System.out.println(dbFile); // displays the data base path in your logcat
File exportDir = new File(Environment.getExternalStorageDirectory(), "");
if (!exportDir.exists())
{
exportDir.mkdirs();
}
File file = new File(exportDir, "excerDB.csv");
try
{
if (file.createNewFile()){
System.out.println("File is created!");
System.out.println("myfile.csv "+file.getAbsolutePath());
}else{
System.out.println("File already exists.");
}
CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
//SQLiteDatabase db = dbhelper.getWritableDatabase();
Cursor curCSV=db.getdb().rawQuery("select * from " + db.TABLE_NAME,null);
csvWrite.writeNext(curCSV.getColumnNames());
while(curCSV.moveToNext())
{
String arrStr[] ={curCSV.getString(0),curCSV.getString(1),curCSV.getString(2)};
/*curCSV.getString(3),curCSV.getString(4)};*/
csvWrite.writeNext(arrStr);
}
csvWrite.close();
curCSV.close();
/*String data="";
data=readSavedData();
data= data.replace(",", ";");
writeData(data);*/
return true;
}
catch(SQLException sqlEx)
{
Log.e("MainActivity", sqlEx.getMessage(), sqlEx);
return false;
}
catch (IOException e)
{
Log.e("MainActivity", e.getMessage(), e);
return false;
}
}
protected void onPostExecute(final Boolean success)
{
if (this.dialog.isShowing())
{
this.dialog.dismiss();
}
if (success)
{
Toast.makeText(DatabaseExampleActivity.this, "Export succeed", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(DatabaseExampleActivity.this, "Export failed", Toast.LENGTH_SHORT).show();
}
}}
Export CSV to XLS part
public class CSVToExcelConverter extends AsyncTask<String, Void, Boolean> {
private final ProgressDialog dialog = new ProgressDialog(DatabaseExampleActivity.this);
#Override
protected void onPreExecute()
{this.dialog.setMessage("Exporting to excel...");
this.dialog.show();}
#Override
protected Boolean doInBackground(String... params) {
ArrayList arList=null;
ArrayList al=null;
//File dbFile= new File(getDatabasePath("database_name").toString());
File dbFile=getDatabasePath("database_name");
String yes= dbFile.getAbsolutePath();
String inFilePath = Environment.getExternalStorageDirectory().toString()+"/excerDB.csv";
outFilePath = Environment.getExternalStorageDirectory().toString()+"/test.xls";
String thisLine;
int count=0;
try {
FileInputStream fis = new FileInputStream(inFilePath);
DataInputStream myInput = new DataInputStream(fis);
int i=0;
arList = new ArrayList();
while ((thisLine = myInput.readLine()) != null)
{
al = new ArrayList();
String strar[] = thisLine.split(",");
for(int j=0;j<strar.length;j++)
{
al.add(strar[j]);
}
arList.add(al);
System.out.println();
i++;
}} catch (Exception e) {
System.out.println("shit");
}
try
{
HSSFWorkbook hwb = new HSSFWorkbook();
HSSFSheet sheet = hwb.createSheet("new sheet");
for(int k=0;k<arList.size();k++)
{
ArrayList ardata = (ArrayList)arList.get(k);
HSSFRow row = sheet.createRow((short) 0+k);
for(int p=0;p<ardata.size();p++)
{
HSSFCell cell = row.createCell((short) p);
String data = ardata.get(p).toString();
if(data.startsWith("=")){
cell.setCellType(Cell.CELL_TYPE_STRING);
data=data.replaceAll("\"", "");
data=data.replaceAll("=", "");
cell.setCellValue(data);
}else if(data.startsWith("\"")){
data=data.replaceAll("\"", "");
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue(data);
}else{
data=data.replaceAll("\"", "");
cell.setCellType(Cell.CELL_TYPE_NUMERIC);
cell.setCellValue(data);
}
//*/
// cell.setCellValue(ardata.get(p).toString());
}
System.out.println();
}
FileOutputStream fileOut = new FileOutputStream(outFilePath);
hwb.write(fileOut);
fileOut.close();
System.out.println("Your excel file has been generated");
} catch ( Exception ex ) {
ex.printStackTrace();
} //main method ends
return true;
}
protected void onPostExecute(final Boolean success)
{
if (this.dialog.isShowing())
{
this.dialog.dismiss();
}
if (success)
{
Toast.makeText(DatabaseExampleActivity.this, "file is built!", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(DatabaseExampleActivity.this, "file fail to build", Toast.LENGTH_SHORT).show();
}
}
}
I suggest you to study about google spreadsheets APIs
I've build an app for managing transactions and i'm currently adding dropbox backup. I do this by uploading the databasefiles to dropbox (which seems to be appearing correctly). Then i want to download the files again and overwrite the existing databases. When i do this the databases get saved as files ei. get listed by context.fileList(); instead of context.databaseList(); How do i handle the database files to get them in the right place?
Here is the code i thought relevant:
private static class Downloader extends AsyncTask<Integer, Integer, Boolean>{
Context context;
#Override
protected void onPreExecute(){
context = SpendoBase.getContext();
}
#Override
protected Boolean doInBackground(Integer... arg0) {
System.out.println("DoInBackground:");
try {
List<DropboxAPI.Entry> entries = mDBApi.metadata("/", -1, null, true, null).contents;
File file;
FileOutputStream os;
int count = 0;
for(DropboxAPI.Entry entry: entries){
count++;
System.out.println("Entry.path(): " + entry.path + " " + count + "/" + entries.size());
file = new File(entry.path);
System.out.println("1");
os = context.openFileOutput(file.getName(), Context.MODE_PRIVATE);
System.out.println("2");
DropboxFileInfo info = mDBApi.getFile(entry.path, null, os, null);
os.flush();
os.close();
System.out.println("3 " + info);
}
} catch (DropboxException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
private static class Uploader extends AsyncTask<Integer, Integer, Boolean>{
String[] databaseList;
Context context;
#Override
protected void onPreExecute(){
context = SpendoBase.getContext();
databaseList = context.databaseList();
}
#Override
protected Boolean doInBackground(Integer... params) {
for(String dbName: databaseList){
try {
File f = context.getDatabasePath(dbName);
FileInputStream fis = new FileInputStream(f.getPath());
mDBApi.putFileOverwrite("/" + dbName, fis, f.length(), null);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DropboxException e) {
e.printStackTrace();
}
}
return null;
}
}
private static class MetaReader extends AsyncTask<Integer, Integer, List<String>>{
#Override
protected List<String> doInBackground(Integer... arg0) {
try {
List<String> result = new Vector<String>();
DropboxAPI.Entry existingEntry = mDBApi.metadata("/", -1, null, true, null);
List<DropboxAPI.Entry> temp = existingEntry.contents;
for(int i = 0; i < temp.size(); i++){
File f = new File(temp.get(i).path);
result.add(f.getName());
}
return result;
} catch (DropboxException e) {
System.out.println("Something went wrong: " + e);
}
return null;
}
#Override
protected void onPostExecute(List<String> result){
for(String str:result){
System.out.println(str);
}
}
}
I don't do much Android development, so I could be way off base here, but why can't you just use context.getDatabasePath(dbName) again in the Downloader and write the file to that path?
I managed to solve it. My error was simply that I saved the database in the wrong place.
Changing:
file = new File(entry.path);
System.out.println("1");
os = context.openFileOutput(file.getName(), Context.MODE_PRIVATE);
to:
file = new File("/data/data/com.SverkerSbrg.SpendoFull/databases/" + entry.path);
System.out.println("1");
os = new FileOutputStream(file.getPath());
Solved the problem
You need to root your target phone to save your file on /data/data/com.SverkerSbrg.SpendoFull/databases/ this location.
I am going to implement the FTP download function. It works but when it comes to reporting the progress, I have only found that only the message changes but not the numbers and the bar changing
I have screen captured as below
The below is my code:
public void buttonExit(View v) {
System.exit(1);
}
public void doClick(View v){
//ftp
filename = null;
filename = "giant.mp4";
pd = new ProgressDialog(this);
pd.setTitle("EOrder");
pd.setMessage("Downloading file. Please wait...");
pd.setIndeterminate(true);
pd.setMax(100);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setProgress(0);
pd.setCancelable(false);
pd.show();
ad = new AlertDialog.Builder(this);
ad.setTitle("EOrder");
ad.setMessage("Download Finish");
ad.setNeutralButton("OK", null);
new FTPDownload().execute(filename);
}
class FTPDownload extends AsyncTask<String , String , Void>{
boolean running = true;
Date today = Calendar.getInstance().getTime();
Format formatter = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
String reportDate = formatter.format(today);
String fileAndroid = reportDate + "_" + filename;
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
Log.d("******", "Background thread starting......");
FTPClient client = new FTPClient();
try {
Log.d("tag" , "arrived");
client.connect("newaswrissssing.win5.siteonlinetest.com");
boolean successLogin = client.login("newaswrissssing", "newaswrissssing2014cap!");
if(successLogin){
client.changeWorkingDirectory("dummy");
Log.d("tag" , "success");
long fileSize = getFileSize(client , params[0]);
client.setFileType(FTP.BINARY_FILE_TYPE);
client.enterLocalPassiveMode();
File instanceRecordDirectory = new File(Environment.getExternalStorageDirectory() + File.separator + "TVB_Movie");
if(!instanceRecordDirectory.exists()){
instanceRecordDirectory.mkdirs();
}
File instanceRecord = new File(instanceRecordDirectory.getAbsolutePath() + File.separator + fileAndroid);
if(!instanceRecord.exists()){
instanceRecord.createNewFile();
}
BufferedOutputStream desFileStream = new BufferedOutputStream(new FileOutputStream(instanceRecord.getAbsolutePath()),8*1024);
InputStream in = client.retrieveFileStream(params[0]);
Log.d("as" , String.valueOf(in));
byte[] buffer = new byte[1024];
int len1 = 0;
long total = 0;
while ((len1 = in.read(buffer)) > 0) {
total += len1; //total = total + len1
Log.d("aDDs" , String.valueOf(in));
publishProgress("" + (int)((total*100)/fileSize));
desFileStream.write(buffer, 0, len1);
}
desFileStream.flush();
desFileStream.close();
client.completePendingCommand();
in.close();
}else{
Log.d("tag" , "sosad");
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
client.logout();
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
protected void onProgressUpdate(String... progress) {
super.onProgressUpdate(progress);
Log.d("progress","values: "+progress[0]);
pd.incrementProgressBy(Integer.parseInt(progress[0]));
pd.setMessage("Downloading file... Progress at " + progress[0] + "%");
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pd.dismiss();
ad.show();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
Would you please tell me what other steps to do besides using pd.incrementProgressBy(Integer.parseInt(progress[0])); or setProgress?
your ProgressDialog should not be intederminate. You should call setIndeterminate with false instead of true
pd.setIndeterminate(false);
and you should use setProgress instead of incrementProgressBy