My toast doesn't show up and I am confused because I think I made it correctly, I don't understand. As you can see its a program that shows three buttons, the first one activates a download which is supposed to open the PDFs file automatically - if there is no pdf reader a toast should pop up saying there isn't a reader. the other buttons take to a new screen and operate as a back button.
public class myactivity extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn;
private ProgressDialog mProgressDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myactivity);
mProgressDialog = new ProgressDialog(myactivity.this);
mProgressDialog.setMessage("Please be patient, file downloading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
Button Section = (Button) findViewById(R.id.Section);
Section.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// TODO Auto-generated method stub
Intent Section = new Intent(view.getContext(),
Section.class);
startActivity(Section);
}
});
Button Back = (Button) findViewById(R.id.Back);
Back.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
setResult(RESULT_OK);
finish();
}
});
startBtn = (Button) findViewById(R.id.Search);
startBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startDownload();
}
});
}
private void startDownload() {
DownloadFile downloadFile = new DownloadFile();
downloadFile
.execute("http://www.website.com/document.pdf");
}
class DownloadFile extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
mProgressDialog.setProgress(progress[0]);
}
#Override
protected String doInBackground(String... aurl) {
try {
URL url = new URL(aurl[0]);
URLConnection connection = url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
int tickSize = 2 * fileLength / 100;
int nextProgress = tickSize;
Log.d(
"ANDRO_ASYNC", "Lenght of file: " + fileLength);
InputStream input = new BufferedInputStream(url.openStream());
String path = Environment.getExternalStorageDirectory()
+ "/Android/Data/"
+ getApplicationContext().getPackageName() + "/files";
File file = new File(path);
file.mkdirs();
File outputFile = new File(file, "test1.pdf");
OutputStream output = new FileOutputStream(outputFile);
byte data[] = new byte[1024 * 1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
if (total >= nextProgress) {
nextProgress = (int) ((total / tickSize + 1) * tickSize);
this.publishProgress((int) (total * 100 / fileLength));
}
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
showPdf();
} catch (Exception e) {
}
return null;
}
}
private void showPdf() {
// TODO Auto-generated method stub
mProgressDialog.dismiss();
File file = new File(Environment.getExternalStorageDirectory()
+ "/Android/Data/" + getApplicationContext().getPackageName()
+ "/files/test1.pdf");
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(myactivity .this,
"No Application Available to View PDF", Toast.LENGTH_LONG).show();
}
}
}
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(myactivity .this,
"No Application Available to View PDF", Toast.LENGTH_LONG).show();
}
The above code show toast only if you have not declared the activity in your manifeast file but not when the pdf is not present. You must use FileNotFoundException for your requirement.
Updated:::
try{
File file = new File(Environment.getExternalStorageDirectory()
+ "/Android/Data/" + getApplicationContext().getPackageName()
+ "/files/test1.pdf");
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(myactivity .this,
"No Application Available to View PDF", Toast.LENGTH_LONG).show();
}
} catch (FileNotFoundException e) {
Toast.makeText(myactivity .this,
"No Application Available to View PDF", Toast.LENGTH_LONG).show();
}
Related
In my Project I want to download the link the user enter.
when user enter link to download I want to show progress bar to show the percentage of downloading.
In this code I can show the progress bar but it doesn't show the progress of download.How I can show the percentage or progress of downloading.
and how to finish it after download has finished successfully?
here is my code:
public class MyActivity extends Activity {
private long enqueue;
private DownloadManager dm;
final Context context = this;
public Button star_download, view_downlod;
private ProgressDialog pDialog;
public static final int progress_bar_type = 0;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
star_download = (Button) findViewById(R.id.start_download);
view_downlod = (Button) findViewById(R.id.view_download);
star_download.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.alert_custom);
dialog.setTitle("Downloading ...");
// set the custom dialog components - text, image and button
final EditText text = (EditText) dialog.findViewById(R.id.text);
final String link = text.getText().toString();
Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(text.getText().toString()));
enqueue = dm.enqueue(request);
showDialog(progress_bar_type);
}
});
dialog.show();
}
});
view_downlod.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent();
i.setAction(DownloadManager.ACTION_VIEW_DOWNLOADS);
startActivity(i);
}
});
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
long downloadId = intent.getLongExtra(
DownloadManager.EXTRA_DOWNLOAD_ID, 0);
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(enqueue);
Cursor c = dm.query(query);
if (c.moveToFirst()) {
int columnIndex = c
.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c
.getInt(columnIndex)) {
ImageView view = (ImageView) findViewById(R.id.imageView1);
String uriString = c
.getString(c
.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
view.setImageURI(Uri.parse(uriString));
}
}
}
}
};
registerReceiver(receiver, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type:
pDialog = new ProgressDialog(this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
pDialog.show();
return pDialog;
default:
return null;
}
}
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
}
I am new with android,and I am really confused, Can anyone help me?
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Before starting background thread
* Show Progress Bar Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(false);
pDialog.show();
getActivity().showDialog(progress_bar_type);
}
/**
* Downloading file in background thread
*/
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
Log.d("URl","Url====="+f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
extn=f_url[0].split("XYZ/");
Log.d("URlextn","Urlextn====="+extn[1]);
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// File file = new File(Environment.DIRECTORY_DOCUMENTS /);
// Output stream to write file
//OutputStream output = new FileOutputStream(Environment.getExternalStoragePublicDirectory() +extn[1]);
OutputStream output = null;
File mydir = new File(Environment.getExternalStorageDirectory() + "/xyz/");
if(!mydir.exists())
mydir.mkdirs();
output = new FileOutputStream(mydir+"/"+extn[1]);
Log.d("EXTERNAL PATH","EXTERNAL PATH===="+ Environment.getExternalStorageDirectory()+"/xyz/");
byte data[] = new byte[4096];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
/**
* Updating progress bar
*/
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
/**
* After completing background task
* Dismiss the progress dialog
**/
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
// dismissDialog(progress_bar_type);
pDialog.dismiss();
try{
imagePath = Environment.getExternalStorageDirectory()+"/"+"xyz"+"/" + extn[1];
}
catch (ArrayIndexOutOfBoundsException | NullPointerException ne)
{
System.out.println("ArrayError:" + ne);
}
System.out.println("imagePath==" + imagePath);
imgFile = new File(imagePath);
galleryAddPic(imgFile, getActivity());
}
}
After I take a picture I store the picture into ImageView, So if anyone has an idea or suggestion in how to store the picture after it shown on the ImageView into phone stage without user interaction
Thanks in advance
public class MainActivity extends Activity {
ImageView viewpict;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewpict=(ImageView) findViewById(R.id.pict_result);
Button btn= (Button)findViewById(R.id.camera);
btn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
Intent intent = new Intent (android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
// Intent intent = new Intent (getApplicationContext(),MainActivity2.class);
//startActivity(intent);
startActivityForResult(intent,0);
}
});
}
protected void onActivityResult( int requestCode, int resultCode,Intent data)
{
if (requestCode==0)
{
Bitmap theimage = (Bitmap) data.getExtras().get("data");
viewpict.setImageBitmap(theimage);
}
}
}
Try:
viewpict.buildDrawingCache();
Bitmap bm=viewpict.getDrawingCache();
And save:
OutputStream fOut = null;
Uri outputFileUri;
try {
File root = new File(Environment.getExternalStorageDirectory()
+ File.separator + "folder_name" + File.separator);
root.mkdirs();
File sdImageMainDirectory = new File(root, "myPicName.jpg");
outputFileUri = Uri.fromFile(sdImageMainDirectory);
fOut = new FileOutputStream(sdImageMainDirectory);
} catch (Exception e) {
Toast.makeText(this, "Error occured. Please try again later.",
Toast.LENGTH_SHORT).show();
}
try {
bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
}
And permission in AndroidManifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
On my android app, I have my own BaseAdapter, in this I have a click button listener with the following code:
btnShareFacebook.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
videoMoreLayout.setVisibility(View.GONE);
final String id = videoIDs[position];
videoActions = new VideoActions();
hfu = new HttpFileUpload(videoPathURL[position], token);
final ProgressDialog pDialog = new ProgressDialog(activity);
pDialog.setMessage("Preparing video to share...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
if (!isOnline()) {
Toast.makeText(activity,
activity.getString(R.string.noInternetConnection),
Toast.LENGTH_SHORT).show();
} else {
try {
String arr[] = videoPathURL[position].split("/upload/videos/");
final String finalVideoName = (arr[arr.length-1]);
File DoutFile = new File(
Environment.getExternalStorageDirectory() +
File.separator + "vidytape_shared" + File.separator + finalVideoName);
if(!DoutFile.exists()){
pDialog.show();
String downloadResult = videoActions.downloadToShare(token, activity, id, videoPathURL[position], finalVideoName);
if (downloadResult.equalsIgnoreCase("POST_FAILURE") || downloadResult.equalsIgnoreCase("FAILURE_102")) {
Toast.makeText(
activity,
activity.getString(R.string.someErrorOccurred),
Toast.LENGTH_SHORT).show();
}
/*if(hfu.Download_File_To_Share(finalVideoName, videoPathURL[position])){
Toast.makeText(activity, "OK", Toast.LENGTH_LONG).show();
//pDialog.dismiss();
} else {
Toast.makeText(activity, "ERRO", Toast.LENGTH_LONG).show();
}*/
}
pDialog.dismiss();
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("video/*");
share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(DoutFile));
share.putExtra(Intent.EXTRA_TEXT,
"" + activity.getResources().getString(R.string.app_name));
share.setPackage("com.facebook.katana");
activity.startActivity(share);
} catch (Exception e) {
pDialog.dismiss();
Toast.makeText(
activity,
activity.getString(R.string.facebookNotInstalled),
Toast.LENGTH_LONG).show();
}
}
}
});
Now here you have the function downloadToShare from the class VideoActions:
public String downloadToShare(String token, Activity activity, String videoID, String videoPath, String videoName) {
this.token = token;
this.activity = activity;
this.videoId = videoID;
this.videoPath = videoPath;
this.videoName = videoName;
DownloadToShareClass downloadAction = new DownloadToShareClass();
try {
return downloadAction.execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return null;
} // Close download
And now the downloadToShare class:
class DownloadToShareClass extends AsyncTask<String, String, String> {
String response = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(activity);
pDialog.setMessage("Preparing video to share...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
HttpFileUpload hfu = new HttpFileUpload(videoPath, token);
hfu.Download_File_To_Share(videoName, videoPath);
return "SUCESSFULLY";
}
} // Close DownloadClass
Now the download_file_to_share:
boolean Download_File_To_Share(String fileName, String urlToDownload) {
boolean downloadResult;
try {
downloadResult = DownloadFileToShare(fileName, urlToDownload);
return downloadResult;
} catch (MalformedURLException e) {
return false;
} catch (IOException e) {
return false;
}
}
And for the last the DownloadFileToShare:
// Download video
boolean DownloadFileToShare(String filename, String urlToDownload)
throws MalformedURLException, IOException {
BufferedInputStream in = null;
FileOutputStream fout = null;
try {
URL url = new URL(urlToDownload);
in = new BufferedInputStream(url.openStream());
fout = new FileOutputStream(
Environment.getExternalStorageDirectory() +
File.separator + "vidytape_shared" + File.separator + filename);
byte data[] = new byte[1024];
int count;
while ((count = in.read(data, 0, 1024)) != -1) {
fout.write(data, 0, count);
System.out.println(count);
}
} finally {
if (in != null)
in.close();
if (fout != null)
fout.close();
}
return true;
}
My Problem is as you can see on my BaseAdapter code, I'm showing a progress dialog, but it only is shown after all the rest finish (the video download). What is the problem here ? I want that the progressDialog shows when the video is being downloaded...
Thanks in advance
I've found a solution to my own problem. From my BaseAdapter I changed my click listener code to the following and it's working perfectly now:
btnShareFacebook.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
videoMoreLayout.setVisibility(View.GONE);
hfu = new HttpFileUpload(videoPathURL[position], token);
final ProgressDialog pDialog = new ProgressDialog(activity);
pDialog.setMessage(activity.getResources().getString(R.string.preparingVideoToShare));
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
if (!isOnline()) {
Toast.makeText(activity,
activity.getString(R.string.noInternetConnection),
Toast.LENGTH_SHORT).show();
} else {
try {
String arr[] = videoPathURL[position].split("/upload/videos/");
final String finalVideoName = (arr[arr.length-1]);
final File DoutFile = new File(
Environment.getExternalStorageDirectory() +
File.separator + "vidytape_shared" + File.separator + finalVideoName);
if(!DoutFile.exists()){
pDialog.show();
(new Thread(new Runnable() {
#Override
public void run() {
final String a = hfu.Download_File_To_Share(finalVideoName, videoPathURL[position]);
activity.runOnUiThread(new Runnable() {
public void run() {
if (!a.equalsIgnoreCase("ok")){
pDialog.dismiss();
Toast.makeText(activity,
activity.getResources().getString(R.string.someErrorOccurred),
Toast.LENGTH_LONG).show();
} else {
pDialog.dismiss();
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("video/*");
share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(DoutFile));
share.putExtra(Intent.EXTRA_TEXT,
"" + activity.getResources().getString(R.string.app_name));
share.setPackage("com.facebook.katana");
activity.startActivity(share);
}
}
});
}
})).start();
} else {
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("video/*");
share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(DoutFile));
share.putExtra(Intent.EXTRA_TEXT,
"" + activity.getResources().getString(R.string.app_name));
share.setPackage("com.facebook.katana");
activity.startActivity(share);
}
} catch (Exception e) {
if(pDialog.isShowing()){
pDialog.dismiss();
}
e.printStackTrace();
Toast.makeText(
activity,
activity.getString(R.string.facebookNotInstalled),
Toast.LENGTH_LONG).show();
}
}
}
});
I hope it can help someone too.
Can you add code to show progressbar in onPreExecute in class DownloadToShareClass which extends AsyncTask ?
Please refer to http://developer.android.com/reference/android/os/AsyncTask.html
From the above link --
onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
class DownloadToShareClass extends AsyncTask<String, String, String> {
private ProgressDialog mdialog;
public DownloadToShareClass(yourActivity activity) {
mdialog = new ProgressDialog(activity);
}
#Override
protected void onPreExecute() {
mdialog.show();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPostExecute(Void result) {
if (mdialog.isShowing()) {
mdialog.dismiss();
}
}
}
I cannot figure out why this is occurring. It is probably a silly mistake that I cannot identify. Again the error is:
getOutputMediaFile(int) is undefined for the type new Camera.PictureCallback(){}
my code:
public static final int MEDIA_TYPE_IMAGE = 1;
private PictureCallback mPicture = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
//Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
// Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
};
If you arrived here because of the camera example scroll down further into the documentation the method is written at the last as it's common to both video and the image capture
http://developer.android.com/guide/topics/media/camera.html#saving-media
See Camera Android Code
public class MainActivity extends Activity {
public static final int MEDIA_TYPE_IMAGE = 1;
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
Uri fileUri ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bt=(Button)findViewById(R.id.button1);
bt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri= getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
});
}
private static Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
#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;
}
private static File getOutputMediaFile(int type){
File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), "MyCameraApp");
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
TextView tv=(TextView)findViewById(R.id.textView2);
if (resultCode == RESULT_OK) {
tv.setText("Image saved to:\n"+data.getData());
ImageView img=(ImageView)findViewById(R.id.imageView1);
img.setImageURI(fileUri);
//tv.setText(fileUri.toString());
} else if (resultCode == RESULT_CANCELED) {
tv.setText("Cancelled");
} else {
// Image capture failed, advise user
tv.setText("Can con be captured");
}
}
}
}
Edit
Try importing android.provider.MediaStore.Files.FileColumns and change MEDIA_TYPE_IMAGE to FileColumns.MEDIA_TYPE_IMAGE.
if you are calling Camera like
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
// create a file to save the image
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
// start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
Uploading image from android phone to Ftp server, It is not uploading my image into Ftp server it shows windows leaked error,it shows sdcard path but the image is not uploading into the ftp folder can anyone please help me.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ivImage = (ImageView) findViewById(R.id.ivImage);
btnSetImage = (Button) findViewById(R.id.btnSelectPhoto);
upload = (Button) findViewById(R.id.upload_btn);
btnSetImage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
upload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialog = ProgressDialog.show(MainActivity.this, "Uploading",
"Please wait...", true);
dialog.setCancelable(true);
//File f = new File("file:///android_asset/launcher.png");
// Log.i("do in image ", tempPath);
new doFileUpload().execute();
}
});
}
class doFileUpload extends AsyncTask<Void, Void, String> {
// Log.i("do in image ", path);
String hostName = "xxxxx";
String username = "dsdadg";
String password = "adasdh";
InputStream in = null;
protected String doInBackground(Void... unsued) {
String loc = tempPath.toString();
Log.i("location in async ", loc);
try {
FTPClient ftp = new FTPClient();
ftp.connect(hostName);
ftp.login(username, password);
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.changeWorkingDirectory("/ftp/gallery/"); // FTP folder path
int reply = ftp.getReplyCode();
System.out.println("Received Reply from FTP Connection:" + reply);
if (FTPReply.isPositiveCompletion(reply)) {
System.out.println("Connected Success");
}
File f1 = new File("/sdcard/Image/003.JPG");
in = new FileInputStream(f1);
ftp.storeFile("/ftp/gallery/", in);
ftp.enterLocalPassiveMode();
System.out.println("SUCCESS");
ftp.logout();
ftp.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return hostName;
}
}
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment
.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, REQUEST_CAMERA);
} else if (items[item].equals("Choose from Library")) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(
Intent.createChooser(intent, "Select File"),
SELECT_FILE);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_CAMERA) {
File f = new File(Environment.getExternalStorageDirectory()
.toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bm;
BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
bm = BitmapFactory.decodeFile(f.getAbsolutePath(),
btmapOptions);
// bm = Bitmap.createScaledBitmap(bm, 70, 70, true);
ivImage.setImageBitmap(bm);
path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
f.delete();
OutputStream fOut = null;
File file = new File(path, String.valueOf(System
.currentTimeMillis()) + ".jpg");
try {
fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.flush();
fOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == SELECT_FILE) {
Uri selectedImageUri = data.getData();
tempPath = getPath(selectedImageUri, MainActivity.this);
Log.i("temporary path", tempPath);
Bitmap bm;
BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
bm = BitmapFactory.decodeFile(tempPath, btmapOptions);
ivImage.setImageBitmap(bm);
}
}
//return urlPosting;
}
public String getPath(Uri uri, Activity activity) {
String[] projection = { MediaColumns.DATA };
Cursor cursor = activity
.managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}