i am new in android and i am making a application to download the file from local server and i almost done.But now i want to add progress bar in this code and i am trying to do it. can anyone help me out. just help me if you can dont leave other comments like grammer mistake and other
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import org.apache.http.util.ByteArrayBuffer;
import android.support.v7.app.ActionBarActivity;
import android.widget.Button;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends ActionBarActivity
{
Button b1;
String FileDownloadPath="http://192.168.1.25/dinesh/di.mp3";
//String FileSavePath="/dinesh2/lecture3.pdf";
//String DownloadUrl = "http://myexample.com/android/";
String fileName = "di.mp3";
//myFile = new File(path,"/mysdfile.xml");
ProgressDialog dialog=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button1);
b1.setOnClickListener(new OnClickListener(){
public void onClick(View arg0)
{
dialog=ProgressDialog.show(MainActivity.this,"", "downloading",true);
new Thread(new Runnable()
{
public void run()
{
downlaodfile(FileDownloadPath,fileName);
}
}).start();
}
});
}
public void downlaodfile(String FileDownloadPath, String fileName) {
try {
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + "/sdcard/myclock/databases");
if(dir.exists() == false){
dir.mkdirs();
}
URL url = new URL("http://192.168.1.25/dinesh/di.mp3");
File file = new File(dir,fileName);
long startTime = System.currentTimeMillis();
Log.d("DownloadManager" , "download url:" +url);
Log.d("DownloadManager" , "download file name:" + fileName);
URLConnection uconn = url.openConnection();
/* uconn.setReadTimeout(TIMEOUT_CONNECTION);
uconn.setConnectTimeout(TIMEOUT_SOCKET);*/
InputStream is = uconn.getInputStream();
BufferedInputStream bufferinstream = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(5000);
int current = 0;
while((current = bufferinstream.read()) != -1){
baf.append((byte) current);
}
FileOutputStream fos = new FileOutputStream( file);
fos.write(baf.toByteArray());
fos.flush();
fos.close();
Log.d("DownloadManager" , "download ready in" + ((System.currentTimeMillis() - startTime)/1000) + "sec");
int dotindex = fileName.lastIndexOf('.');
if(dotindex>=0){
fileName = fileName.substring(0,dotindex);
}
}
catch(IOException e) {
Log.d("DownloadManager" , "Error:" + e);
}
catch(Exception e )
{
e.printStackTrace();
}
}
private void hideProgressIndicator() {
// TODO Auto-generated method stub
runOnUiThread(new Runnable(){
public void run()
{
dialog.dismiss();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
You should use AsyncTask<...> for your downloading process and use ProgressDialog.
private class ClassName extends AsyncTask<String, Void, String>
{
ProgressDialog progressDialog;
#Override
protected void onPreExecute()
{
progressDialog = ProgressDialog.show(context, "Downloading", "Please Wait...");
}
#Override
protected String doInBackground(String... params)
{
//Your downloading code here
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
progressDialog.dismiss();
//dismiss the progress dialog in onPost and do remaining stuff after downloading....
}
}
hope this will help you...
Related
I am new for android.make one video player code the video play from url and user can download the video from the apps. i make until download and push Notification and using service. the issue i is when download one video the user click download another video is overwrite the 1st download. any one can give me solution..
package crazysing.crazyweb.my.fragment;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.NetworkImageView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import crazysing.crazyweb.my.MainActivity;
import crazysing.crazyweb.my.R;
import crazysing.crazyweb.my.adater.CustomListAdapter;
import crazysing.crazyweb.my.app.AppController;
import crazysing.crazyweb.my.model.Movie;
import crazysing.crazyweb.my.service.NLService;
/**
* Created by LENOVO on 14/02/2017.
*/
public class SongPlayerFragment extends Fragment {
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
String videopath = "http://crazysing.crazyweb.my/upload/vid/";
NotificationCompat.Builder mBuilder;
NotificationManager mNotifyManager;
int id = 1;
int counter = 0;
private NotificationReceiver nReceiver;
String sdCard = Environment.getExternalStorageDirectory().toString();
File myDir = new File(sdCard, "Video/CrazySing");
VideoView videov;
MediaController mediaC;
NetworkImageView videothumbNail;
// Movies json url
private static final String url = "http://crazysing.crazyweb.my/api/songlist.php";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
class NotificationReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String event = intent.getExtras().getString(NLService.NOT_EVENT_KEY);
Log.i("NotificationReceiver", "NotificationReceiver onReceive : " + event);
if (event.trim().contentEquals(NLService.NOT_REMOVED)) {
killTasks();
}
}
}
private void killTasks() {
mNotifyManager.cancelAll();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.song_player_fragment, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
videov = (VideoView) view.findViewById(R.id.videov);
mediaC = new MediaController(getActivity());
listView = (ListView) view.findViewById(R.id.list);
adapter = new CustomListAdapter(getActivity(), movieList);
listView.setAdapter(adapter);
// Register the ListView for Context menu
registerForContextMenu(listView);
listView.setOnItemClickListener(new ItemList());
videothumbNail = (NetworkImageView) view.findViewById(R.id.placeholder);
pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("title"));
movie.setFileName(obj.getString("filename"));
movie.setVideoPath(obj.getString("video_path"));
movie.setSingerName(obj.getString("singer_name"));
movie.setSongId(obj.getInt("songId"));
movie.setDuration(obj.getString("duration"));
movie.setThumbnailUrl(obj.getString("image"));
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
videoView(" ", " "," ");
}
public void videoView(String videopath,String fileName, String imageName) {
// videopath = videopath + filename;
if (imageName == " ") {
videothumbNail.setDefaultImageResId(R.drawable.sing);
videothumbNail.setErrorImageResId(R.drawable.sing);
videothumbNail.setVisibility(View.VISIBLE);
videov.setVisibility(View.INVISIBLE);
Log.d(TAG, "empty vedeio");
} else {
videothumbNail.setImageUrl(imageName, imageLoader);
videothumbNail.setVisibility(View.VISIBLE);
videov.setVisibility(View.INVISIBLE);
File file = new File(myDir, fileName);
if (file.exists()){
Uri uri = Uri.parse(myDir+"/"+fileName);
videov.setVideoURI(uri);
videov.setMediaController(mediaC);
mediaC.setAnchorView(videov);
videov.start();
videov.setVisibility(View.VISIBLE);
videov.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
videothumbNail.setVisibility(View.GONE);
}
});
}else {
try {
Uri uri = Uri.parse(videopath);
videov.setVideoURI(uri);
videov.setMediaController(mediaC);
mediaC.setAnchorView(videov);
videov.start();
videov.setVisibility(View.VISIBLE);
videov.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
videothumbNail.setVisibility(View.GONE);
}
});
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getActivity().getMenuInflater();
inflater.inflate(R.menu.song_list_menu, menu);
menu.setHeaderTitle("Options");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
int index = info.position;
View view = info.targetView;
String VideoPath = ((Movie) movieList.get(index)).getVideoPath();
String FileName = ((Movie) movieList.get(index)).getFileName();
String urlsToDownload[] = {VideoPath,FileName};
switch (item.getItemId()) {
case R.id.download:
NotificationManager(urlsToDownload);
Log.d(TAG, "value=" + VideoPath);
return true;
default:
return super.onContextItemSelected(item);
}
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
killTasks();
getActivity().unregisterReceiver(nReceiver);
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
class ItemList implements AdapterView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
view.setSelected(true);
String videoUrl = ((Movie) movieList.get(position)).getVideoPath();
String fileName = ((Movie) movieList.get(position)).getFileName();
String bitmap = ((Movie) movieList.get(position)).getThumbnailUrl();
Toast.makeText(SongPlayerFragment.this.getActivity(), videoUrl, Toast.LENGTH_SHORT).show();
videoView(videoUrl,fileName, bitmap);
}
}
private void downloadImagesToSdCard(String downloadUrl, String videoName) {
FileOutputStream fos;
InputStream inputStream = null;
try {
URL url = new URL(downloadUrl);
/* making a directory in sdcard */
/* if specified not exist create new */
if (!myDir.exists()) {
myDir.mkdir();
Log.v("", "inside mkdir");
}
/* checks the file and if it already exist delete */
String fname = videoName;
File file = new File(myDir, fname);
Log.d("file===========path", "" + file);
if (file.exists())
file.delete();
/* Open a connection */
URLConnection ucon = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) ucon;
httpConn.setRequestMethod("GET");
httpConn.connect();
inputStream = httpConn.getInputStream();
/*
* if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
* inputStream = httpConn.getInputStream(); }
*/
fos = new FileOutputStream(file);
// int totalSize = httpConn.getContentLength();
// int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
fos.write(buffer, 0, bufferLength);
// downloadedSize += bufferLength;
// Log.i("Progress:", "downloadedSize:" + downloadedSize +
// "totalSize:" + totalSize);
}
inputStream.close();
fos.close();
Log.d("test", "Video Saved in sdcard..");
} catch (IOException io) {
inputStream = null;
fos = null;
io.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
private class ImageDownloader extends AsyncTask<String, String, Void> {
#Override
protected Void doInBackground(String... param) {
downloadImagesToSdCard(param[0], param[1]);
return null;
}
protected void onProgressUpdate(String... values) {
}
#Override
protected void onPreExecute() {
Log.i("Async-Example", "onPreExecute Called");
}
#Override
protected void onPostExecute(Void result) {
Log.i("Async-Example", "onPostExecute Called");
mBuilder.setContentTitle("Done.");
mBuilder.setContentText("Download complete")
// Removes the progress bar
.setProgress(0, 0, false);
mNotifyManager.notify(id, mBuilder.build());
}
}
private void NotificationManager(String... param){
mNotifyManager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(getActivity());
mBuilder.setContentTitle("Downloading Video...").setContentText("Download in progress").setSmallIcon(R.mipmap.ic_launcher);
//add sound
Uri nUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
mBuilder.setSound(nUri);
//vibrate
long[] v = {500,1000};
mBuilder.setVibrate(v);
// Start a lengthy operation in a background thread
mBuilder.setProgress(0, 0, true);
mNotifyManager.notify(id, mBuilder.build());
mBuilder.setAutoCancel(true);
ImageDownloader imageDownloader = new ImageDownloader();
imageDownloader.execute(param);
ContentResolver contentResolver = getActivity().getContentResolver();
String enabledNotificationListeners = Settings.Secure.getString(contentResolver, "enabled_notification_listeners");
String packageName = getActivity().getPackageName();
// check to see if the enabledNotificationListeners String contains our
// package name
if (enabledNotificationListeners == null || !enabledNotificationListeners.contains(packageName)) {
// in this situation we know that the user has not granted the app
// the Notification access permission
// Check if notification is enabled for this application
Log.i("ACC", "Dont Have Notification access");
Intent intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
startActivity(intent);
} else {
Log.i("ACC", "Have Notification access");
}
nReceiver = new NotificationReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(NLService.NOT_TAG);
getActivity().registerReceiver(nReceiver, filter);
}
}
Instead of using only
File myDir = new File(sdCard, "Video/CrazySing");
use
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Video" + n + ".mp4";
File file = new File(myDir, fname);
This will generate a unique file name for each time.
Instead .mp4 you can use your video extension
I am working on one project. In this project i download the PDF file it work perfectly but i want progress bar with percentage. Progressbar show but problem is it does't update the progress stuck in 0(zero).What should i do?
See My code
import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity {
// Progress dialog
private ProgressDialog mProgressDialog ;
private int mProgressStatus = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/** Creating a progress dialog window */
mProgressDialog = new ProgressDialog(this);
/** Close the dialog window on pressing back button */
mProgressDialog.setCancelable(true);
/** Setting a horizontal style progress bar */
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
/** Setting a message for this progress dialog
* Use the method setTitle(), for setting a title
* for the dialog window
* */
mProgressDialog.setMessage("Downloading...");
}
public void downloadPDF(View v) {
/** Show the progress dialog window */
mProgressDialog.show();
new DownloadFile().execute("https://letuscsolutions.files.wordpress.com/2015/07/five-point-someone-chetan-bhagat_ebook.pdf", "five-point-someone-chetan-bhagat_ebook.pdf");
}
public void viewPDF(View v) {
File pdfFile = new File(Environment.getExternalStorageDirectory() + "/PDF DOWNLOAD/" + "five-point-someone-chetan-bhagat_ebook.pdf"); // -> filename = maven.pdf
Uri path = Uri.fromFile(pdfFile);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(pdfIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(MainActivity.this, "No Application available to view PDF", Toast.LENGTH_SHORT).show();
}
}
private class DownloadFile extends AsyncTask<String, Integer, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressStatus = 0;
}
#Override
protected Void doInBackground(String... strings) {
publishProgress(mProgressStatus);
String fileUrl = strings[0]; // -> https://letuscsolutions.files.wordpress.com/2015/07/five-point-someone-chetan-bhagat_ebook.pdf
String fileName = strings[1]; // ->five-point-someone-chetan-bhagat_ebook.pdf
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, "PDF DOWNLOAD");
folder.mkdir();
File pdfFile = new File(folder, fileName);
try {
pdfFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
FileDownloader.downloadFile(fileUrl, pdfFile);
return null;
}
/** This callback method is invoked when publishProgress()
* method is called */
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
mProgressDialog.setProgress(mProgressStatus);
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
mProgressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Download PDf successfully", Toast.LENGTH_SHORT).show();
Log.d("Download complete", "----------");
}
}
}
You are not calculating the progress of your download. mProgressStatus will always zero.
First calculate the download size in percentage and store it in mProgressStatus then call publishProgress(mProgressStatus).
You should call
publishProgress(int progress) in doInBackground() method.
like
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
I am trying to upload a sqlite database file to dropbox. This is my code:
public void uploadDb(){
File public_db_file = null;
try {
public_db_file = writeDbToPublicDirectory();
} catch (IOException e2) {
e2.printStackTrace();
}
DbxFileSystem dbxFs = null;
try {
dbxFs = DbxFileSystem.forAccount(mAccount);
} catch (Unauthorized e1) {
e1.printStackTrace();
}
DbxFile testFile = null;
try {
testFile = dbxFs.create(new DbxPath("database_sync.txt"));
} catch (InvalidPathException e1) {
e1.printStackTrace();
} catch (DbxException e1) {
e1.printStackTrace();
}
try {
testFile.writeFromExistingFile(public_db_file, false);
} catch (IOException e) {
e.printStackTrace();
} finally {
testFile.close();
}
}
EDIT (More code)
This function copies my database from the app private dir to a public dir so that I can upload it:
private File writeDbToPublicDirectory() throws IOException {
// TODO Auto-generated method stub
File sd = Environment.getExternalStorageDirectory();
File backupDB = null;
if (sd.canWrite()) {
String backupDBPath = "copied_database.db";
File currentDB = context.getDatabasePath("private_database");
backupDB = new File(sd, backupDBPath);
if (currentDB.exists()) {
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
}
}
return backupDB;
}
The problem is that when I check on my device dropbox, the file size is 0 bytes. The file is created on dropbox, but my database data is not. What am I doing wrong? Thank you in advance
EDIT
I have decided that using Google Drive may be a better option, but I can only upload text files by using the sample applications. Is there any good tutorial or resource that I can use to upload a sqlite database file? I am really badly stuck on this. Please help me with either of these, thank you in advance
I was able to backup the database using Google Drive API. I have used the byte array to copy the contents. Following is the Activity code, which creates a new file on Google Drive root folder and copies the sqlite db content. I've added comments wherever required. Let me know whether it helps.
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.drive.Contents;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.DriveFile;
import com.google.android.gms.drive.DriveApi.ContentsResult;
import com.google.android.gms.drive.DriveFolder.DriveFileResult;
import com.google.android.gms.drive.MetadataChangeSet;
import android.app.Activity;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.webkit.MimeTypeMap;
public class MainActivity extends Activity implements ConnectionCallbacks, OnConnectionFailedListener {
private static final String TAG = "MainActivity";
private GoogleApiClient api;
private boolean mResolvingError = false;
private DriveFile mfile;
private static final int DIALOG_ERROR_CODE =100;
private static final String DATABASE_NAME = "person.db";
private static final String GOOGLE_DRIVE_FILE_NAME = "sqlite_db_backup";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create the Drive API instance
api = new GoogleApiClient.Builder(this).addApi(Drive.API).addScope(Drive.SCOPE_FILE).
addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();
}
#Override
public void onStart() {
super.onStart();
if(!mResolvingError) {
api.connect(); // Connect the client to Google Drive
}
}
#Override
public void onStop() {
super.onStop();
api.disconnect(); // Disconnect the client from Google Drive
}
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.v(TAG, "Connection failed");
if(mResolvingError) { // If already in resolution state, just return.
return;
} else if(result.hasResolution()) { // Error can be resolved by starting an intent with user interaction
mResolvingError = true;
try {
result.startResolutionForResult(this, DIALOG_ERROR_CODE);
} catch (SendIntentException e) {
e.printStackTrace();
}
} else { // Error cannot be resolved. Display Error Dialog stating the reason if possible.
ErrorDialogFragment fragment = new ErrorDialogFragment();
Bundle args = new Bundle();
args.putInt("error", result.getErrorCode());
fragment.setArguments(args);
fragment.show(getFragmentManager(), "errordialog");
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == DIALOG_ERROR_CODE) {
mResolvingError = false;
if(resultCode == RESULT_OK) { // Error was resolved, now connect to the client if not done so.
if(!api.isConnecting() && !api.isConnected()) {
api.connect();
}
}
}
}
#Override
public void onConnected(Bundle connectionHint) {
Log.v(TAG, "Connected successfully");
/* Connection to Google Drive established. Now request for Contents instance, which can be used to provide file contents.
The callback is registered for the same. */
Drive.DriveApi.newContents(api).setResultCallback(contentsCallback);
}
final private ResultCallback<ContentsResult> contentsCallback = new ResultCallback<ContentsResult>() {
#Override
public void onResult(ContentsResult result) {
if (!result.getStatus().isSuccess()) {
Log.v(TAG, "Error while trying to create new file contents");
return;
}
String mimeType = MimeTypeMap.getSingleton().getExtensionFromMimeType("db");
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle(GOOGLE_DRIVE_FILE_NAME) // Google Drive File name
.setMimeType(mimeType)
.setStarred(true).build();
// create a file on root folder
Drive.DriveApi.getRootFolder(api)
.createFile(api, changeSet, result.getContents())
.setResultCallback(fileCallback);
}
};
final private ResultCallback<DriveFileResult> fileCallback = new ResultCallback<DriveFileResult>() {
#Override
public void onResult(DriveFileResult result) {
if (!result.getStatus().isSuccess()) {
Log.v(TAG, "Error while trying to create the file");
return;
}
mfile = result.getDriveFile();
mfile.openContents(api, DriveFile.MODE_WRITE_ONLY, null).setResultCallback(contentsOpenedCallback);
}
};
final private ResultCallback<ContentsResult> contentsOpenedCallback = new ResultCallback<ContentsResult>() {
#Override
public void onResult(ContentsResult result) {
if (!result.getStatus().isSuccess()) {
Log.v(TAG, "Error opening file");
return;
}
try {
FileInputStream is = new FileInputStream(getDbPath());
BufferedInputStream in = new BufferedInputStream(is);
byte[] buffer = new byte[8 * 1024];
Contents content = result.getContents();
BufferedOutputStream out = new BufferedOutputStream(content.getOutputStream());
int n = 0;
while( ( n = in.read(buffer) ) > 0 ) {
out.write(buffer, 0, n);
}
in.close();
mfile.commitAndCloseContents(api, content).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(Status result) {
// Handle the response status
}
});
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
private File getDbPath() {
return this.getDatabasePath(DATABASE_NAME);
}
#Override
public void onConnectionSuspended(int cause) {
// TODO Auto-generated method stub
Log.v(TAG, "Connection suspended");
}
public void onDialogDismissed() {
mResolvingError = false;
}
public static class ErrorDialogFragment extends DialogFragment {
public ErrorDialogFragment() {}
public Dialog onCreateDialog(Bundle savedInstanceState) {
int errorCode = this.getArguments().getInt("error");
return GooglePlayServicesUtil.getErrorDialog(errorCode, this.getActivity(), DIALOG_ERROR_CODE);
}
public void onDismiss(DialogInterface dialog) {
((MainActivity) getActivity()).onDialogDismissed();
}
}
}
I modified #Manish Mulimani's code. I make use of some modules in com.google.android.gms.drive.sample.demo which is available from Google Drive API Website. The modules are BaseDemoActivity, ApiClientAsyncTask and EditContentsActivity. Here are the code.
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.webkit.MimeTypeMap;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.DriveApi;
import com.google.android.gms.drive.DriveContents;
import com.google.android.gms.drive.DriveFile;
import com.google.android.gms.drive.DriveFolder;
import com.google.android.gms.drive.MetadataChangeSet;
import com.google.android.gms.drive.DriveApi.DriveContentsResult;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class gDriveActivity extends BaseDemoActivity {
private final static String TAG = "gDriveActivity";
#Override
public void onConnected(Bundle connectionHint) {
super.onConnected(connectionHint);
// create new contents resource.
Drive.DriveApi.newDriveContents(getGoogleApiClient()).setResultCallback(driveContentsCallback);
}
final private ResultCallback<DriveApi.DriveContentsResult> driveContentsCallback =
new ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(DriveApi.DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
//if failure
showMessage("Error while trying to create new file contents");
return;
}
//change the metadata of the file. by setting title, setMimeType.
String mimeType = MimeTypeMap.getSingleton().getExtensionFromMimeType("db");
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle("mydb")
.setMimeType(mimeType)
.build();
Drive.DriveApi.getAppFolder(getGoogleApiClient())
.createFile(getGoogleApiClient(), changeSet, result.getDriveContents()).setResultCallback(fileCallBack);
}
};
final ResultCallback<DriveFolder.DriveFileResult> fileCallBack = new ResultCallback<DriveFolder.DriveFileResult>() {
#Override
public void onResult(DriveFolder.DriveFileResult driveFileResult) {
if (!driveFileResult.getStatus().isSuccess()) {
Log.v(TAG, "Error while trying to create the file");
return;
}
//Initialize mFile to be processed in AsyncTask
DriveFile mfile = driveFileResult.getDriveFile();
new EditContentsAsyncTask(gDriveActivity .this).execute(mfile);
}
};
public class EditContentsAsyncTask extends ApiClientAsyncTask<DriveFile, Void, Boolean> {
public EditContentsAsyncTask(Context context) {
super(context);
}
#Override
protected Boolean doInBackgroundConnected(DriveFile... args) {
DriveFile file = args[0];
try {
DriveContentsResult driveContentsResult = file.open(
getGoogleApiClient(), DriveFile.MODE_WRITE_ONLY, null).await();
if (!driveContentsResult.getStatus().isSuccess()) {
return false;
}
DriveContents driveContents = driveContentsResult.getDriveContents();
//edit the outputStream
DatabaseHandler db = new DatabaseHandler(gDriveActivity .this);
String inFileName = getApplicationContext().getDatabasePath(db.getDatabaseName()).getPath();
FileInputStream is = new FileInputStream(inFileName);
BufferedInputStream in = new BufferedInputStream(is);
byte[] buffer = new byte[8 * 1024];
BufferedOutputStream out = new BufferedOutputStream(driveContents.getOutputStream());
int n = 0;
while ((n = in.read(buffer)) > 0) {
out.write(buffer, 0, n);
}
in.close();
com.google.android.gms.common.api.Status status =
driveContents.commit(getGoogleApiClient(), null).await();
return status.getStatus().isSuccess();
} catch (IOException e) {
Log.e(TAG, "IOException while appending to the output stream", e);
}
return false;
}
#Override
protected void onPostExecute(Boolean result) {
if (!result) {
showMessage("Error while editing contents");
return;
}
showMessage("Successfully edited contents");
}
}
}
I think you could use the Storage API
https://developer.android.com/guide/topics/providers/document-provider.html
A useful tutorial on
http://www.techotopia.com/index.php/An_Android_Storage_Access_Framework_Example
This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 9 years ago.
I'm novice with web service and i try to create a web service with netbeans, i test it with rest client (mozilla plugin) it work but when i try to use the android client, it's doesn't and i receive this android.os.NetworkOnMainThreadException in my logcat. Here is the code
<pre><code>
package cg.skylab.clientrest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.TargetApi;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import cg.skylab.clientrest.model.Personne;
public class ListePersonnel extends ListActivity {
private ArrayList<Personne> personnes = new ArrayList<Personne>();
private String adresse;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.liste);
startActivityForResult(new Intent(this, ChoixServeur.class), 1);
}
protected void onActivityResult(int requestCode, int resultCode,
Intent intention) {
if (resultCode == RESULT_OK) {
adresse = intention.getStringExtra("adresse");
try {
miseAJour();
} catch (Exception ex) {
Toast.makeText(this, "Reponse incorrecte", Toast.LENGTH_SHORT).show();
String tagException = ex.toString();
String tagAdresse = intention.getStringExtra("adresse");
Log.i(tagException, "Exception");
Log.i(tagAdresse, "Adresse IP");
}
}
}
#Override
protected void onResume() {
super.onResume();
if (adresse != null)
try {
miseAJour();
} catch (Exception ex) {
}
}
#Override
protected void onStop() {
super.onStop();
finish();
}
public void miseAJour() throws IOException, JSONException {
HttpClient client = new DefaultHttpClient();
HttpGet requete = new HttpGet("http://"+adresse+":8080/Personnel/rest/"+1);
HttpResponse reponse = client.execute(requete);
if (reponse.getStatusLine().getStatusCode() == 200) {
Scanner lecture = new Scanner(reponse.getEntity().getContent());
StringBuilder contenu = new StringBuilder();
while (lecture.hasNextLine())
contenu.append(lecture.nextLine() + '\n');
JSONArray tableauJSON = new JSONArray(contenu.toString());
StringBuilder message = new StringBuilder();
personnes.clear();
for (int i = 0; i < tableauJSON.length(); i++) {
JSONObject json = tableauJSON.getJSONObject(i);
Personne personne = new Personne();
personne.setId(json.getLong("id"));
personne.setNom(json.getString("nom"));
personne.setPrenom(json.getString("prenom"));
personne.setNaissance(json.getLong("naissance"));
personne.setTelephone(json.getString("telephone"));
personnes.add(personne);
}
setListAdapter(new ArrayAdapter<Personne>(this,
android.R.layout.simple_list_item_1, personnes));
} else
Toast.makeText(this, "Problème de connexion avec le serveur",
Toast.LENGTH_SHORT).show();
}
public void edition(View v) {
Intent intention = new Intent(this, Personnel.class);
intention.putExtra("id", 0);
intention.putExtra("adresse", adresse);
startActivity(intention);
}
protected void onListItemClick(ListView liste, View v, int position, long id) {
Personne personne = personnes.get(position);
Intent intention = new Intent(this, Personnel.class);
intention.putExtra("id", personne.getId());
intention.putExtra("adresse", adresse);
intention.putExtra("nom", personne.getNom());
intention.putExtra("prenom", personne.getPrenom());
intention.putExtra("naissance", personne.getNaissance());
intention.putExtra("telephone", personne.getTelephone());
startActivity(intention);
}
}
</code></pre>
You are getting NewtworkOnMainThread exception because you are making network calls on the UI thread. This is a bad practice because it can block/bog down your UI thread which would make your app feel slow.
To avoid that error you have to use AsyncTask.
You have to use like this:
public class DowloadTest extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
};
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
// Call your web service here
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
// Update your UI here
return;
}
}
For more detail check out this article
This is the code i am using to download the file:
package com.mynavy;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import java.net.*;
import android.os.*;
import java.io.*;
public class YNrank extends Activity {
Button E4;
String url1 = "http://www.mambazham.com/uploaded_files/downloads/download.pdf";
Button prtbtn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rank_select);
addListenerOnButton();
}
public void addListenerOnButton()
{
E4 = (Button) findViewById(R.id.E4);
E4.setOnClickListener(new OnClickListener()
{
//BIBS BUTTON!
public void onClick(View v){
new download().execute(url1);
DialogFragment newFragment = new open();
newFragment.show(getFragmentManager(), "YN3");
}
class download extends AsyncTask<String, Integer, String>{
protected String doInBackground(String... url1) {
try {
String fileName="E4";
String fileExtension=".pdf";
// download pdf file.
URL url = new URL("http://www.education.gov.yk.ca/pdf/pdf-test.pdf");
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH = Environment.getExternalStorageDirectory() + "/mydownload/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, fileName+fileExtension);
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.flush();
fos.close();
is.close();
System.out.println("--pdf downloaded--ok--"+ url);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
class open extends DialogFragment {
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.YN3open)
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder.setPositiveButton(R.string.open, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
File e4pdf = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/mydownload/E4.pdf");
if(e4pdf.exists()){
Uri path = Uri.fromFile(e4pdf);
Intent pdfintent = new Intent(Intent.ACTION_VIEW);
pdfintent.setDataAndType(path, "application/pdf");
pdfintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try{
startActivity(pdfintent);
} catch(ActivityNotFoundException e) {
Toast.makeText(YNrank.this, "No Application Available To View PDF File.", Toast.LENGTH_LONG).show();
}}
else {
Toast.makeText(YNrank.this, "File Not Found", Toast.LENGTH_LONG).show();
}
}
});
return builder.create();
}};});
}}
The file is created, but it is not written to. It ends up as a blank pdf file that I cannot open because its file size is 0. I have tried several different methods and they either do this or nothing at all.
Also I have the following permissions:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
public void onClick(View v){
new download().execute(url1);
DialogFragment newFragment = new open();
newFragment.show(getFragmentManager(), "YN3");
}
you must wait for the async task to finish. Override the onPostExecute trigger of the asynctask and call the dialog fragment there.