Sqlite database saved as file - android

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.

Related

how to store data from sqlite to google excel sheet

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

Populate Android SQLite Dat Records into Excel

I create my Project . but I sucked in final mode.. My Table has been generated but for attaching Purpose, I have to create that Table into EXCEL.. PLease give me link. I also tried for pdf but API is not free for commercial use. so give me guide lines , links or GitHub...
Solution is to convert the sqlite database into csv then convert the csv file to xls.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();
}
}
}

Android JSON image download throw MalformedURLException that is already caught

I am downloading images from url's provided by a JSON document. At first my app seems to be working correctly, pulling in and placing images and catching the exceptions when there is no image url in the array element but suddenly it crashes and my error log is showing something to the tune of
Caused by: java.lang.RuntimeException: java.net.MalformedURLException: Protocol not found:
The thing is I have already caught this error as shown below.
If someone could explain to me why this is happening to me and point me in the right direction I will be much obliged.
Image DwnLdr class
public Drawable loadImage (BaseAdapter adapt, ImageView view)
{
this.adapter = adapt;
String url = (String) view.getTag();
if (imageCache.containsKey(url))
{
return imageCache.get(url);
}
else {
new ImageTask().execute(url);
return DEFAULT_ICON;
}
}
private class ImageTask extends AsyncTask<String, Void, Drawable>
{
private String s_url;
#Override
protected Drawable doInBackground(String... params) {
s_url = params[0];
InputStream inStream;
try {
Log.v(debugTag, "Fetching: " + s_url);
URL url = new URL(s_url);
inStream = url.openStream();
} catch (MalformedURLException e) {
Log.v(debugTag, "Malformed: " + e.getMessage());
throw new RuntimeException(e);
} catch (IOException e)
{
Log.d(debugTag, "I/O : " + e.getMessage());
throw new RuntimeException(e);
}
return Drawable.createFromStream(inStream, "src");
}
#Override
protected void onPostExecute(Drawable result) {
super.onPostExecute(result);
synchronized (this) {
imageCache.put(s_url, result);
}
adapter.notifyDataSetChanged();
}
}
View Adapter Class
ListData data = topics.get(position);
try {
long lg = Long.valueOf(data.getPostTime())*1000;
Date date = new Date(lg);
String postTime = new SimpleDateFormat("MM dd, yyyy hh:mma").format(date);
holder.data = data;
holder.listName.setText(data.getTitle());
holder.authorName.setText(data.getAuthor());
holder.postTime.setText(postTime);
holder.redditScore.setText(data.getrScore());
Log.v(DEBUG_TAG, "Cell Created");
}catch (Exception e){
e.printStackTrace();
Log.v(DEBUG_TAG,"Cell Not Created Due to: ",e);
}
if(data.getImageUrl()!=null){
try {
holder.thumbnail.setTag(data.getImageUrl());
Drawable drawable = imgGet.loadImage(this, holder.thumbnail);
if (drawable != null) {
holder.thumbnail.setImageDrawable(drawable);
} else {
holder.thumbnail.setImageResource(R.drawable.filler_icon);
}
}catch (Exception e){
e.printStackTrace();
Log.v(DEBUG_TAG,"no image: ",e);
}
return convertView;
}
Main Class Adapter Set
public static class MyViewHolder {
public TextView listName, authorName, redditScore, postTime;
public Button goButton;
public ImageView thumbnail;
public ListData data;
}
public void setTopics(ArrayList<ListData> data) {
this.data = data;
this.postList.setAdapter(new RedditDataAdapter(this, this.getImg, this.layoutInflater,this.data));
}
Error Log
Caused by: java.lang.RuntimeException: java.net.MalformedURLException: Protocol not found:
at Tasks.RedditIconTask$ImageTask.doInBackground(RedditIconTask.java:60)
at Tasks.RedditIconTask$ImageTask.doInBackground(RedditIconTask.java:46)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
Looks like the image URL is an empty string. Debug your code to learn why is it so. The code you posted doesn't really show where the URL value comes from.
Why you're getting the exception is because you're re-throwing it, wrapped in a RuntimeException:
throw new RuntimeException(e);
I was able to solve my problem by using what laatlto said and changing the code to the following.
protected Drawable doInBackground(String... params) {
s_url = params[0];
InputStream inStream;
Drawable picture=null;
try {
Log.v(debugTag, "Fetching: " + s_url);
URL url = new URL(s_url);
inStream = url.openStream();
picture= Drawable.createFromStream(inStream, "src");
} catch (MalformedURLException e) {
Log.v(debugTag, "Malformed: " + e.getMessage());
} catch (IOException e)
{
Log.d(debugTag, "I/O : " + e.getMessage());
}
return picture;
}

AsyncTask is still blocking UI thread

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

PDF is not getting download form url

I am very new with android and doing this first time. I am trying to download pdf form url in my app but its not getting downloaded. I really got messed up with this. I don't what i am missing ,why this is not working for me. Please help me to do this.
Here i am pasting my code:
public class ProductBrochureActivity extends Activity {
private static String cookie;
private static String nid;
WebView webViewForBrochureAndVideo;
private String prodBrochureURL;
private String prodVideoURL;
private static int clickedItemId;
ActionBar actionBar;
private static HashMap<String, String> cookieWithRequest = new HashMap<String, String>();
static Object json;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.product_brochure);
actionBar = getActionBar();
actionBar.hide();
Intent intent = getIntent();
cookie = intent.getStringExtra(BsharpConstant.WEB_SERVICES_COOKIES);
nid = intent.getStringExtra(BsharpConstant.PRODUCT_NODE_ID);
clickedItemId = intent.getIntExtra(BsharpConstant.CLICKED_ITEM_ID, 0);
String jsonResponseFromWebservices = WebserviceBsharpUtil
.callWebServicesToGetTheProductBrochureAndVideo(cookie, nid);
urlFromResponse(jsonResponseFromWebservices);
cookieWithRequest.put(BsharpConstant.WEB_SERVICES_COOKIES, cookie);
switch (clickedItemId) {
case 0:
if (!prodBrochureURL.isEmpty()) {
try {
new DownloadFile();
} catch (ActivityNotFoundException e) {
Toast.makeText(this,
"No Application Available to View PDF",
Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "No PDF is Attached with this Product",
Toast.LENGTH_SHORT).show();
}
break;
case 1:
if (!prodVideoURL.isEmpty()) {
try {
new DownloadFile();
} catch (ActivityNotFoundException e) {
Toast.makeText(this,
"No Application Available to View PDF",
Toast.LENGTH_SHORT).show();
}
break;
} else {
Toast.makeText(this, "No Video is Attached with this Product",
Toast.LENGTH_SHORT).show();
}
}
}
/**
* GetTheBrochureAndAttachedVideoURL
*
* #param jsonResponse
*/
public void urlFromResponse(String jsonResponse) {
try {
json = new JSONTokener(jsonResponse).nextValue();
if (json instanceof JSONArray) {
JSONArray jsonArray = (JSONArray) json;
prodBrochureURL = jsonArray.getJSONObject(0).getString(
BsharpConstant.PRODUCT_BROCHURE_URL);
prodVideoURL = jsonArray.getJSONObject(0).getString(
BsharpConstant.PRODUCT_VIDEO_URL);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private class DownloadFile extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
String filename = "brochure.pdf";
HttpURLConnection connection;
try {
URL url = new URL(prodBrochureURL);
connection = (HttpURLConnection) url.openConnection();
connection.addRequestProperty(
BsharpConstant.WEB_SERVICES_COOKIES, cookie);
connection.setDoOutput(true);
connection.connect();
} catch (IOException e1) {
return e1.getMessage();
}
File folderDir = new File(getExternalFilesDir("Bsharp_PDF")
+ "/Download");
File file = new File(folderDir, filename);
if (file.exists()) {
file.delete();
}
if ((folderDir.mkdirs() || folderDir.isDirectory())) {
try {
InputStream inputStream = connection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(
folderDir + "/" + filename);
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, len1);
}
fileOutputStream.close();
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(),
"Unable to create folder", Toast.LENGTH_LONG).show();
}
return "Done";
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG)
.show();
super.onPostExecute(result);
}
}
}
In order for an AsyncTask (DownloadFile in your case) to be executed one has to explicitly call its execute(Params... params) method. In your case in addition to instantiating your task call execute without providing any parameters, i.e.
DownloadFile task = new DownloadFile();
task.execute();
Hope this helps.

Categories

Resources