This code is running an apkfile after download from webserver.
But..
When the apkfile runs, it prints this message.
-Parse error
"There is a problem parsing the package."
When i run apkfile after copy to device, it did not print message.
How can I solve this ?
p.s) starting method is skinDownload(filename).
String File_Name = "";
String File_extend = "";
String fileURL = "http://URL/";
String Save_Path = "/data/data/kr.appsol.util.calc.formcalc/themes";
DownloadThread dThread;
ProgressDialog downDialog = null;
private void skinDownload(String filename){
File_Name = filename + ".apk";
File_extend = "apk";
File dir = new File(Save_Path);
if (!dir.exists()) {
dir.mkdir();
}
if (new File(Save_Path + "/" + File_Name).exists() == false) {
downDialog = ProgressDialog.show(Activity_SkinList.this, "", getString(R.string.setting_skin_downloading));
downDialog.show();
dThread = new DownloadThread(fileURL + "/" + File_Name,
Save_Path + "/" + File_Name);
dThread.start();
} else {
showDownloadFile();
}
}
class DownloadThread extends Thread {
String ServerUrl;
String LocalPath;
DownloadThread(String serverPath, String localPath) {
ServerUrl = serverPath;
LocalPath = localPath;
}
#Override
public void run() {
URL imgurl;
int Read;
try {
imgurl = new URL(ServerUrl);
HttpURLConnection conn = (HttpURLConnection) imgurl
.openConnection();
int len = conn.getContentLength();
byte[] tmpByte = new byte[len];
InputStream is = conn.getInputStream();
File file = new File(LocalPath);
FileOutputStream fos = new FileOutputStream(file);
for (;;) {
Read = is.read(tmpByte);
if (Read <= 0) {
break;
}
fos.write(tmpByte, 0, Read);
}
is.close();
fos.close();
conn.disconnect();
} catch (MalformedURLException e) {
Log.e("ERROR1", e.getMessage());
} catch (IOException e) {
Log.e("ERROR2", e.getMessage());
e.printStackTrace();
}
mAfterDown.sendEmptyMessage(0);
}
}
Handler mAfterDown = new Handler() {
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
downDialog.dismiss();
// run
showDownloadFile();
}
};
private void showDownloadFile() {
File apkFile = new File(Save_Path + "/" + File_Name);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
startActivity(intent);
}
You probably need to flush the stream before closing it:
fos.flush();
fos.close();
Related
i m trying to download image and audio using jsonObject
but the problem is when i close my app in background it not work well
code
public class downloadData extends AsyncTask<JSONObject, Void, ArrayList<modelCBlips>> {
Context context;
String cId;
Utils utils;
private DownloadManager mgr = null;
public downloadData(Context context, String cId) {
this.context = context;
this.cId = cId;
utils = new Utils(context);
mgr = (DownloadManager) context.getSystemService(context.DOWNLOAD_SERVICE);
context.registerReceiver(onComplete,
new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
#Override
protected ArrayList<modelCBlips> doInBackground(JSONObject... params) {
ArrayList<modelCBlips> list = new ArrayList<>();
try {
JSONArray blipArray = params[0].getJSONArray("Blips");
for (int i = 0; i < blipArray.length(); i++) {
modelCBlips mcblips = new modelCBlips();
JSONObject jObjBlip = blipArray.getJSONObject(i);
String imagePath = jObjBlip.getString("imagePath");
String audioPath = jObjBlip.getString("audioPath");
mcblips.setImagePath(SaveFile(imagePath));
mcblips.setAudioPath(SaveFile(audioPath));
list.add(mcblips);
if (isCancelled())
System.out.println("istrue");
else
System.out.println("not");
}
} catch (JSONException e) {
e.printStackTrace();
}
return list;
}
#Override
protected void onPreExecute() {
utils.editor.putString("status" + cId, "Downloading...").commit();
}
#Override
protected void onPostExecute(ArrayList<modelCBlips> list) {
for (int i = 0; i < list.size(); i++) {
modelCBlips mcb = list.get(i);
utils.con.insertCBlips(mcb.getImagePath(), mcb.getAudioPath());
}
utils.editor.putString("status" + cId, "Downloaded").commit();
utils.editor.putBoolean("download" + cId, true).commit();
}
BroadcastReceiver onComplete = new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
}
};
public String SaveFile(String path) {
String startdownloadurl = null;
try {
ContextWrapper cw = new ContextWrapper(context);
File directory = cw.getDir("channel" + cId, Context.MODE_PRIVATE);
if (!directory.exists()) {
directory.mkdir();
}
DownloadManager mgr = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
/* Uri downloadUri = Uri.parse(path);
DownloadManager.Request request = new DownloadManager.Request(
downloadUri);
String imgnm = path.substring(path.lastIndexOf("/") + 1);
startdownloadurl = directory + "/";
System.out.println(" directory " + startdownloadurl);
request.setAllowedNetworkTypes(
DownloadManager.Request.NETWORK_WIFI
| DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false).setTitle("Demo")
.setDescription("Something useful. No, really.")
.setDestinationInExternalPublicDir(startdownloadurl, imgnm);
mgr.enqueue(request);
startdownloadurl = directory + "/" + imgnm;
*/
URL url = new URL(path);
String imgnm = path.substring(path.lastIndexOf("/") + 1);
URLConnection connection = url.openConnection();
connection.connect();
InputStream input = new BufferedInputStream(url.openStream(), 2048);
startdownloadurl = directory + "/" + imgnm;
FileOutputStream output = new FileOutputStream(startdownloadurl);
byte data[] = new byte[2048];
int bytesRead = 0;
while ((bytesRead = input.read(data, 0, data.length)) >= 0) {
output.write(data, 0, bytesRead);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
System.out.println("Exception " + e);
}
return startdownloadurl;
}
}
using this code i m try to download Image and audio file when all image and audio file downloaded successfully and then i ll try to insert in my database
Try to run it in a service as service runs even if app is closed
I have used a videoview to play the video from raw folder locally, but now im trying to download a list of videos first on sdcard and after to play it to media player. Here is my videoview.
public class MainActivity extends Activity {
/* Full Screen Mode-Sticky */
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
View decorView = getWindow().getDecorView();
if (hasFocus) {
decorView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);}
}
public void downloadVideoFile(String url, String dest_file_name) {
try {
URL domain = new URL("http://192.168.0.22");
String video_folder = "video";
String sdcard_path = Environment.getExternalStorageDirectory().getAbsolutePath();
String dest_video_path = sdcard_path + File.separator + video_folder + File.separator + dest_file_name;
File dest_file = new File(dest_video_path);
URL u = new URL(domain + "/files/video/");
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(dest_file));
fos.write(buffer);
fos.flush();
fos.close();
} catch(FileNotFoundException e) {
return;
} catch (IOException e) {
return;
}
}
private VideoView myVideo1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().setFormat(PixelFormat.TRANSLUCENT);
setContentView(R.layout.activity_main);
String video_folder = "myvideos";
String sdcard_path = Environment.getExternalStorageDirectory().getAbsolutePath();
File fvideo_path = new File(sdcard_path + File.separator + video_folder);
File videolist[] = fvideo_path.listFiles();
String play_path = videolist[0].getAbsolutePath();
myVideo1=(VideoView)findViewById(R.id.myvideoview);
myVideo1.setVideoPath(play_path);
myVideo1.start();
myVideo1.requestFocus();
myVideo1.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.setLooping(true);
}
});
}
}
Step 1: build video list from a specific path on sdcard
String video_folder = "myvideos";
String sdcard_path = Environment.getExternalStorageDirectory();
File fvideo_path = new File(sdcard_path + File.separator + video_folder);
File videolist[] = fvideo_path.listFiles();
Step 2: play any video in list by index
//you can next or prev index from 0 - list lenght;
String play_path = videolist[0].getAbsolutePath();
Step 3: you set play_path to media player
myVideo1.setVideoPath(play_path);
myVideo1.start();
myVideo1.requestFocus();
Example code to download file from server:
public void downloadVideoFile(String url, String dest_file_name) {
try {
String video_folder = "myvideos";
String sdcard_path = nvironment.getExternalStorageDirectory();
String dest_video_path = sdcard_path + File.separator + video_folder + File.separator + dest_file_name;
File dest_file = new File(dest_video_path);
URL u = new URL(url);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(dest_file));
fos.write(buffer);
fos.flush();
fos.close();
} catch(FileNotFoundException e) {
return;
} catch (IOException e) {
return;
}
}
I am using below code to get download videos from Server
class DownloadFileFromURL extends AsyncTask<Object, String, Integer> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onCancelled() {
super.onCancelled();
}
/**
* Downloading file in background thread
* */
#Override
protected Integer doInBackground(Object... params) {
try {
URL url = new URL((String) params[1]);
name = ((String) params[1]).substring(((String) params[1])
.lastIndexOf("/") + 1);
// Log.v("log_tag", "name Substring ::: " + name);
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(),
8192);
File download = new File(Environment.getExternalStorageDirectory()
+ "/download/");
if (!download.exists()) {
download.mkdir();
}
String strDownloaDuRL = download + "/" + name;
Log.v("log_tag", " down url " + strDownloaDuRL);
FileOutputStream output = new FileOutputStream(strDownloaDuRL);
byte data[] = new byte[1024];
long total = 0;
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return 0;
}
protected void onPostExecute(String file_url) {
// Do after downloaded file
}
}
I'm trying to create internal db file when data submit to database.when user enter values to textfields and click on the button,'SAMPLE.db' db file should create inside 'MYTEST' file on internal storage.this is my code.but it's not working.
-Main Activity oncreate-
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String Id=mEDitTxt.getText().toString();
String Unm=mEDitTxt2.getText().toString();
insertconfig(Id, Unm);
DbBackup.copyDatabase(getApplicationContext());
}
});
-DBbackup-
public class DbBackup {
public static void copyDatabase(Context c) {
String DATABASE_NAME = "SAMPLE.db";
String databasePath = c.getDatabasePath(DATABASE_NAME).getPath();
File f = new File(databasePath);
OutputStream myOutput = null;
OutputStream myOutputInternal = null;
InputStream myInput = null;
Log.d("testing", " lots db path " + databasePath);
Log.d("testing", " lots db exist " + f.exists());
if (f.exists()) {
try {
File directoryIntenal = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/MYTEST/");
if (!directoryIntenal.exists())
directoryIntenal.mkdir();
myOutputInternal = new FileOutputStream(directoryIntenal.getAbsolutePath()
+ "/" + DATABASE_NAME);
myInput = new FileInputStream(databasePath);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutputInternal.write(buffer, 0, length);
}
myOutputInternal.flush();
} catch (Exception e) {
} finally {
try {
if (myOutputInternal != null) {
myOutputInternal.close();
myOutputInternal = null;
}
if (myInput != null) {
myInput.close();
myInput = null;
}
} catch (Exception e) {
}
}
}
}
}
Call this method when you want to export OR import your database ,
public class DbExportImport {
public static final String TAG = DbExportImport.class.getName();
/**
* Directory that files are to be read from and written to *
*/
public static final String PACKAGE_NAME = "com.vcs.androiddatabaseexample";
public static final String DATABASE_NAME = "crud.db";
public static final File DATA_DIRECTORY_DATABASE = new File(
Environment.getDataDirectory() + "/data/" + PACKAGE_NAME
+ "/databases/" + DATABASE_NAME);
public static final String DATA_DIRECTORY_DATABASE_PATH =
Environment.getDataDirectory() + "/data/" + PACKAGE_NAME
+ "/databases/" + DATABASE_NAME;
public static boolean exportSyncDbNew(String Filename, String FolderPath) {
if (!SdIsPresent())
return false;
File dbFile = DATA_DIRECTORY_DATABASE;
if (dbFile.exists()) {
// String filename = Filename+"_SAT.db";
File exportDir = new File(FolderPath);
if (!exportDir.exists()) {
exportDir.mkdirs();
}
File file = new File(exportDir, Filename);
Utils.printLoge(5, "#### exportDir", "-->" + FolderPath);
Utils.printLoge(5, "#### Filename", "-->" + Filename);
Utils.printLoge(5, "DATA_DIRECTORY_DATABASE", "-->" + DATA_DIRECTORY_DATABASE);
try {
if (!file.exists()) {
file.createNewFile();
copyFile(dbFile, file);
return true;
} else {
return false;
}
} catch (IOException e) {
//e.printStackTrace();
Constant.isFielCopeError = true;
Constant.fileCopeException = "Upload: " + Utils.ConvertExceptionToString(e);
return false;
}
} else {
Constant.isFielCopeError = true;
Constant.fileCopeException = "Upload: DB not available";
return false;
}
}
public static boolean restoreDownloadedDb(String FileName) {
if (!SdIsPresent())
return false;
File exportFile = DATA_DIRECTORY_DATABASE;
//File importFile = IMPORT_Downloaded_FILE;
File importFile = new File(Constant.ECTERNAL_STORAGE_APP_USER1, FileName);
if (exportFile.exists()) {
exportFile.delete();
// Log.e(TAG, "exportFile delete");
}
if (!importFile.exists()) {
// Log.d(TAG, "File does not exist");
return false;
}
try {
exportFile.createNewFile();
//copyFile(importFile, exportFile);
copyDataBase(importFile, exportFile);
return true;
} catch (IOException e) {
Utils.printLoge(5, "restoreDownloadedDb", "error-->" + e.getMessage().toString());
e.printStackTrace();
return false;
}
}
i have build an application the user can download with one button click an image and attachments text file (in two separate folder one folder for store image and the other for text file )
now I would like build an listview for display this data, each row contain image (ImageView) and name of image (textView) and when user click on it i would like display the attachments text file
DownloadFile code :
#Override
protected Void doInBackground(String... strings) {
String filetxtUrl = strings[0];
String filetxtName = strings[1];
String fileImageUrl = strings[2];
String fileImageName = strings[3];
String extStorageDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString(); //(Environment.DIRECTORY_DOWNLOADS)
File folder = new File(extStorageDirectory, "folder");
if (!folder.exists()) {
folder.mkdirs();
}
File folder1 = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/"
+ "folder" , "txt");
if (!folder1.exists()) {
folder1.mkdirs();
}
File TxtFile = new File(folder1, filetxtName);
File folder3 = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/"
+ "folder" , "Image");
if (!folder3.exists()) {
folder3.mkdirs();
}
File ImageFile = new File(folder3, fileImageName);
try{
TxtFile.createNewFile();
ImageFile.createNewFile();
}catch (IOException e){
e.printStackTrace();
}
FileDownloader.downloadFile(filetxtUrl, TxtFile);
FileDownloader.downloadFile(fileImageUrl, ImageFile);
L.m("File Download successufuly in Sdcard0 ");
return null;
}
FileDownloader code :
private static final int MEGABYTE = 1024 * 1024;
public static void downloadFile(String fileUrl, File directory){
try {
URL url = new URL(fileUrl);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(directory);
byte[] buffer = new byte[MEGABYTE];
int bufferLength = 0;
while((bufferLength = inputStream.read(buffer))>0 ){
fileOutputStream.write(buffer, 0, bufferLength);
}
fileOutputStream.close();
} catch (FileNotFoundException e) {
L.m(""+e);
} catch (MalformedURLException e) {
L.m(""+e);
} catch (IOException e) {
L.m(""+e);
}
}
}
I want use the code below to read the the txt files attachment
public void displayOutput()
{
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,"/TextFile.txt");
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
}
catch (IOException e) {
Toast.makeText(getApplicationContext(),"Error reading file!",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
catch (FileNotFoundException e) {
Toast.makeText(getApplicationContext(),"File not found!",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
TextView output=(TextView) findViewById(R.id.output);
// Assuming that 'output' is the id of your TextView
output.setText(text);
}
I want to download different types of file and there is possibility of link like
https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcRpDmM-KiKgR-wcFtJnXUYVua-2409t5z7pjqski5wQ9pYZfOJG7nklFnc
where I don't know the file name, type and any of the description. then How to get those information. so I make that file name as default?
Thank You.
You have to use async task for downloading file
Call it with
String Your_Url = "https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcRpDmM-KiKgR-wcFtJnXUYVua-2409t5z7pjqski5wQ9pYZfOJG7nklFnc";
new downloadProcess(Your_Url, Your_Context).execute();
public downLoadProcess(String Url , Context context)
{
context.Url = Url ;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected void onPostExecute(ArrayList<String> result)
{
super.onPostExecute(result);
}
#Override
protected ArrayList<String> doInBackground(Void... Params)
{
ArrayList<String> Data = new ArrayList<String>();
boolean flag = false;
URL url;
URLConnection conn;
int fileSize, lastSlash;
String fileName, path = null;
BufferedInputStream inStream;
BufferedOutputStream outStream;
File outFile;
FileOutputStream fileStream;
WebServiceMethods objWSMethod = new WebServiceMethods();
String downloadUrl = Url ;
try
{
url = new URL(downloadUrl);
conn = url.openConnection();
conn.setUseCaches(false);
fileSize = conn.getContentLength();
// get the filename
lastSlash = url.toString().lastIndexOf('/');
fileName = "file.bin";
if(lastSlash >=0)
{
fileName = url.toString().substring(lastSlash + 1);
}
if(fileName.equals(""))
{
fileName = "file.bin";
}
int DOWNLOAD_BUFFER_SIZE = fileSize;
// start download
inStream = new BufferedInputStream(conn.getInputStream());
path = Environment.getExternalStorageDirectory().toString() ;
File file = new File(path + "/Download");
file.mkdir();
path = Environment.getExternalStorageDirectory() + "/Download/" + fileName;
outFile = new File(path);
fileStream = new FileOutputStream(outFile);
outStream = new BufferedOutputStream(fileStream, DOWNLOAD_BUFFER_SIZE);
byte[] data = new byte[DOWNLOAD_BUFFER_SIZE];
int bytesRead = 0, totalRead = 0;
while((bytesRead = inStream.read(data, 0, data.length)) >= 0)
{
if(Check_your_Internet_is_on?)
{
outStream.write(data, 0, bytesRead);
totalRead += bytesRead;
flag = true;
}
else
{
flag = outFile.delete();
flag = false;
}
}
outStream.close();
fileStream.close();
inStream.close();
}
catch(MalformedURLException e)
{
}
catch(FileNotFoundException e)
{
}
catch(Exception e)
{
}
return Data;
}
}
Hope it will help you..!