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();
}
}
Related
I use the following code to catch a global uncaught error, the test code System.out.println(s.equals("any string")); will cause an error.
In my mind, one error log file will be created, but in fact, the three error log files were created with same content, what problem are there in my code?
BTW, I test the code in Android 4.0, only one error log file was generated! but when it run under Android 5.0, three error log files was generated!
MainActivity.java
public class MainActivity extends AppCompatActivity {
private String s;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.out.println(s.equals("any string"));
}
}
CrashApplication.java
public class CrashApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
CrashHandler crashHandler = CrashHandler.getInstance();
crashHandler.init(getApplicationContext());
}
}
CrashHandler.java
public class CrashHandler implements UncaughtExceptionHandler {
public static final String TAG = "CrashHandler";
private Thread.UncaughtExceptionHandler mDefaultHandler;
private static CrashHandler INSTANCE = new CrashHandler();
private Context mContext;
private Map<String, String> infos = new HashMap<String, String>();
private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
private CrashHandler() {
}
public static synchronized CrashHandler getInstance() {
return INSTANCE;
}
public void init(Context context) {
mContext = context;
mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(this);
}
#Override
public void uncaughtException(Thread thread, Throwable ex) {
if (!handleException(ex) && mDefaultHandler != null) {
mDefaultHandler.uncaughtException(thread, ex);
} else {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
Log.e(TAG, "error : ", e);
}
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
}
private boolean handleException(Throwable ex) {
if (ex == null) {
return false;
}
new Thread() {
#Override
public void run() {
Looper.prepare();
Toast.makeText(mContext, "Sorry.", Toast.LENGTH_LONG).show();
Looper.loop();
}
}.start();
collectDeviceInfo(mContext);
saveCrashInfo2File(ex);
return true;
}
public void collectDeviceInfo(Context ctx) {
try {
PackageManager pm = ctx.getPackageManager();
PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES);
if (pi != null) {
String versionName = pi.versionName == null ? "null" : pi.versionName;
String versionCode = pi.versionCode + "";
infos.put("versionName", versionName);
infos.put("versionCode", versionCode);
}
} catch (NameNotFoundException e) {
Log.e(TAG, "an error occured when collect package info", e);
}
Field[] fields = Build.class.getDeclaredFields();
for (Field field : fields) {
try {
field.setAccessible(true);
infos.put(field.getName(), field.get(null).toString());
Log.d(TAG, field.getName() + " : " + field.get(null));
} catch (Exception e) {
Log.e(TAG, "an error occured when collect crash info", e);
}
}
}
private String saveCrashInfo2File(Throwable ex) {
StringBuffer sb = new StringBuffer();
for (Map.Entry<String, String> entry : infos.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
sb.append(key + "=" + value + "\n");
}
Writer writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
ex.printStackTrace(printWriter);
Throwable cause = ex.getCause();
while (cause != null) {
cause.printStackTrace(printWriter);
cause = cause.getCause();
}
printWriter.close();
String result = writer.toString();
sb.append(result);
try {
long timestamp = System.currentTimeMillis();
String time = formatter.format(new Date());
String fileName = "crash-" + time + "-" + timestamp + ".txt";
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
String path = Environment.getExternalStorageDirectory() + "/MyCrash/";
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
FileOutputStream fos = new FileOutputStream(path + fileName);
fos.write(sb.toString().getBytes());
fos.close();
}
return fileName;
} catch (Exception e) {
Log.e(TAG, "an error occured while writing file...", e);
}
return null;
}
}
There are different log files in android: Error,Debug,Verbose etc.
And therefore there are different qualifiers for them and they are Log.e,Log.d,Log.v etc. Two of them you are using e and d qualifiers but I don't know about third
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 don't know how to do after this to convert my Java to JSON with Jackson
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ObjectMapper mapper = new ObjectMapper();
Book b = new Book();
ArrayList<Book> listBook = new ArrayList<Book>();
listBook.add(b);
b = new Book();
b.setName("exam");
b.setFileName("res/raw/exam.txt");
b.setCate(0); //4 categories here
b.setSoundFileName("res/raw/exams.mp3");
b.setTranFileName("res/raw/examt.txt");
listBook.add(b);
b = new Book();
b.setName("test");
b.setCate(0);
b.setFileName("res/raw/test.txt");
b.setSoundFileName("res/raw/tests.mp3")
b.setTranFileName("res/raw/textt.txt");
String jsonString = "";
try {
jsonString = mapper.writeValueAsString(listBook);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.d("ttt", "show ans : "+jsonString);
How do I do next to write this to my SD card?
as user Zain has told, Gson is more convenient to use, However, assuming that you are getting the Json string from this line:
jsonString = mapper.writeValueAsString(listBook);
Then use this method to write the string to a file in sdcard.
public static void writeStringToFile(String p_string, String p_fileName)
{
FileOutputStream m_stream = null;
try
{
m_stream = new FileOutputStream(p_fileName);
m_stream.write(p_string.getBytes());
m_stream.flush();
}
catch (Throwable m_th)
{
Log.e(TAG + " Error in writeStringToFile(String p_string, String p_fileName) of FileIO", m_th);
}
finally
{
if (m_stream != null)
{
try
{
m_stream.close();
}
catch (Throwable m_e)
{
Log.e(TAG + " Error in writeStringToFile(String p_string, String p_fileName) of FileIO", m_e);
}
m_stream = null;
}
}
}
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();
}
}
}
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.