Show image on screen from ftp server - android

I almost build my android application, but i have some troubles. My app use a ftp connection to upload photos on a server and display on screen this photos. With "upload part" i have no problems, but when i choose a photo and i want to display it on screen, I encounter some problems. Seems like my image is blurred or fragmented. I think that is from redimensioning, but in this way i tried many algorithms ...unsuccessful
Please tell me how can I display on screen an image from this ftp server, image displayed at good quality without "blurred or fragmented" part, thank you
This is my "show image" class...
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
#SuppressLint("NewApi")
public class FaceDetection extends Activity {
public String o;
public ImageView viu;
public Bitmap bit;
public Bitmap myBitmap;
File file;
InputStream a=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.poza);
a=NextActivity.aa;
viu=(ImageView)findViewById(R.id.imageView1);
o=getIntent().getStringExtra("CaleOptiune");
setData(o);
initData();
bit=getBit();
viu.setImageBitmap(bit);
}
public Bitmap getBit(){
BitmapFactory.Options BitmapFactoryOptionsbfo = new BitmapFactory.Options();
BitmapFactoryOptionsbfo.inPreferredConfig = Bitmap.Config.RGB_565;
myBitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.index, BitmapFactoryOptionsbfo);
if(a!=null){Log.e("asdasdsadsadas","Streamul este incarcat");}else{Log.e("asdasdsadsadas","E nullllllll");}
myBitmap = BitmapFactory.decodeStream(new BufferedInputStream(a));
return myBitmap;
}
public void initData(){
File file=new File(o);
try {
Log.e("Fisierul curent este",""+Logare.ftpClient.getWorkingDirectory());
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
Log.e("File","Fisier creat din calea "+o);
Log.e("File name",""+file.getName());
try {
a = Logare.ftpClient.ftpClient.retrieveFileStream(file.getName());
Logare.ftpClient.ftpClient.completePendingCommand();
} catch (Exception e1) {
Log.e("asdasdsadsadas","Nu s-a instantiat InputSteamul");
}
}
public void setData(String o) {
this.o = o;
}
}

Decoding and showing images seems to be OK. You could improve it by Loading Large Bitmaps Efficiently.
I'm not sure, but I think your problem should be this issue: https://code.google.com/p/android/issues/detail?id=6066
Try to create class:
public class FlushedInputStream extends FilterInputStream {
public FlushedInputStream(InputStream inputStream) {
super(inputStream);
}
#Override
public long skip(long n) throws IOException {
long totalBytesSkipped = 0L;
while (totalBytesSkipped < n) {
long bytesSkipped = in.skip(n - totalBytesSkipped);
if (bytesSkipped == 0L) {
int by_te = read();
if (by_te < 0) {
break; // we reached EOF
} else {
bytesSkipped = 1; // we read one byte
}
}
totalBytesSkipped += bytesSkipped;
}
return totalBytesSkipped;
}
}
and use:
bm = BitmapFactory.decodeStream(new FlushedInputStream(entity.getContent()));

Related

Bitmap saved as black image sometimes for same bitmap

I know this was a common issue, but I have tried different suggestion, and still no solution.
My issue is that the bitmap is being displayed correctly, however SOMETIMES it saves as a black bitmap, while other times it saves correctly.
Can anyone see what I have done and tell me where I can be going wrong?
I have looked at most of the other StackOverflow questions.
The following is my code, which encodes the clip board text into a QR code and attempts to save the qr code generated.
Thank you!
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.text.ClipboardManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import java.io.File;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
//import android.content.ClipboardManager;
public class BarcodeWriter extends AppCompatActivity {
ImageLoader imgLoader;
ImageView qrImg;
String copiedStr;
TextView qrTxt;
ClipboardManager clipboard;
String BASE_QR_URL = "http://chart.apis.google.com/chart?cht=qr&chs=400x400&chld=M&choe=UTF-8&chl=";
String fullUrl = BASE_QR_URL;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.barcode_writer);
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
.defaultDisplayImageOptions(defaultOptions)
.build();
imgLoader = ImageLoader.getInstance(); // Do it on Application start
imgLoader.init(config);
qrImg = (ImageView)findViewById(R.id.qrImg);
qrTxt = (TextView)findViewById(R.id.qrTxt);
clipboard = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
/*
* clipboard.getText() is now deprecated. But I am going to use it here
* because the new way of doing the same thing only works on API lvl 11+
* Since I want this application to support API lvl 4+ we have to use
* the old method.
*/
CharSequence clipTxt = clipboard.getText();
//This is the new, non-deprecated way of getting text from the Clipboard.
//CharSequence clipTxt = clipboard.getPrimaryClip().getItemAt(0).getText();
//If the clipboard has text, and it is more than 0 characters.
if((null != clipTxt) && (clipTxt.length() > 0)){
try {
qrTxt.setText(clipTxt);
copiedStr = clipTxt.toString();
fullUrl += URLEncoder.encode(copiedStr, "UTF-8");
//imgLoader.displayImage(fullUrl, qrImg);
ImageLoader.getInstance().displayImage(fullUrl, qrImg, defaultOptions); // Incoming options will be used
qrImg.setDrawingCacheEnabled(true);
qrImg.measure(View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.EXACTLY));
qrImg.layout(0, 0, qrImg.getMeasuredWidth(), qrImg.getMeasuredHeight());
qrImg.buildDrawingCache();
Bitmap bm = Bitmap.createBitmap(qrImg.getDrawingCache());
qrImg.setDrawingCacheEnabled(false); // clear drawing cache
try {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/DCIM/QR codes");
myDir.mkdirs();
String fname = clipTxt+".png";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, out);
Toast.makeText(BarcodeWriter.this, "Image Saved", Toast.LENGTH_SHORT).show();
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
getApplicationContext().sendBroadcast(mediaScanIntent);
Toast.makeText(this,"QR Code showing "+clipTxt,Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(this, "Error occurred. Please try again later.",
Toast.LENGTH_SHORT).show();
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{ //If no text display a dialog.
Toast.makeText(this,"No text in clipboard",Toast.LENGTH_SHORT).show();
}
}
}
Your code seems to be fine, the only thing that I saw is that you are getting you Bitmap from and external URL with Universal Image Loader instantly after calling displayImage. So is possible that for some delay in the network sometimes your ImageView still doesn't have the entire image and can make your bitmap saved as black.
Please try moving your all code bellow ImageLoader.getInstance().displayImage inside the onLoadingComplete like this:
ImageLoader.getInstance().displayImage(fullUrl, qrImg, defaultOptions, new SimpleImageLoadingListener()
{
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
ImageLoader.getInstance().displayImage(fullUrl, qrImg, defaultOptions,null);
qrImg.setDrawingCacheEnabled(true);
...
catch (Exception e) {
Toast.makeText(this, "Error occurred. Please try again later.",
Toast.LENGTH_SHORT).show();
}
}
});
Hope this help!!

Disable back button in Android(Not working)

package com.my.app ;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Comparator;
import com.my.app .R;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;
public class ImageInfo extends Activity {
private static final int CAMERA_PIC_REQUEST = 1111;
private ImageView mImage;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mImage = (ImageView) findViewById(R.id.camera_image);
//1
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode != RESULT_CANCELED) {
if(requestCode == CAMERA_PIC_REQUEST){
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
// mImage.setImageBitmap(thumbnail);
//3
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
//4
File file = new File("data/data/com.my.app /photo.jpg");
File myDir=new File("data/data/com.my.app /");
try {
String encodedPhotoImage;
file.createNewFile();
FileOutputStream fo = new FileOutputStream(file);
//5
fo.write(bytes.toByteArray());
fo.close();
deleteLatest() ;
byte[] photoImgBytes=readPhotoFile();
ByteArrayOutputStream bao1 = new ByteArrayOutputStream();
Bitmap bitmapPhoto = BitmapFactory.decodeByteArray(photoImgBytes, 0, photoImgBytes.length);
bitmapPhoto.compress(Bitmap.CompressFormat.JPEG, 100,bao1);
byte[] by = bao1.toByteArray();
String by1 = Base64.encodeToString(by, 0);
encodedPhotoImage = URLEncoder.encode(by1);
file.delete();
if (!myDir.exists()) {
myDir.mkdirs();
}
File encryptedFile=new File("data/data/com.my.app /photo.txt");
encryptedFile.createNewFile();
FileWriter writer = new FileWriter(encryptedFile);
writer.append(encodedPhotoImage);
writer.close();
//Base64.encodeToString(ba1, Base64.DEFAULT);
Intent intent=new Intent(ImageInfo.this,Info.class);
startActivity(intent);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
private byte[] readPhotoFile(){
String url="data/data/com.my.app /photo.jpg";
Log.e("","Image is"+url);
Bitmap bm = BitmapFactory.decodeFile(url);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
return b;
}
#Override
public void onBackPressed() {
// do nothing.
}
private void deleteLatest() {
File f = new File(Environment.getExternalStorageDirectory() + "/DCIM/Camera" );
File [] files = f.listFiles();
Arrays.sort( files, new Comparator<Object>()
{
public int compare(Object o1, Object o2) {
if (((File)o1).lastModified() > ((File)o2).lastModified()) {
return -1;
} else if (((File)o1).lastModified() < ((File)o2).lastModified()) {
return 1;
} else {
return 0;
}
}
});
files[0].delete();
}
}
This is my java file. I have already disabled the back button using
public void onBackPressed() {
// do nothing.
}
But when back button is pressed in the app, the entire screen becomes black. Please find screen shot . The app hangs and the only way it can be accessed by terminating it through task manager and then restarting it.
try this code for disable back button
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if(keyCode==KeyEvent.KEYCODE_BACK)
{
return true;
}
else
{
return super.onKeyDown(keyCode, event);
}
}
Capture Image from Camera and Display in Activity
I can't see a problem with your back button disabling. But there is another problem that may cause a part of this issue you are doing File IO in the UI Thread of your App.
Android has one UI Thread that does all the painting of your UI. If you block this thread through writing large files to the disk or reading bitmaps from the disk the phone UI will freeze and not react on user input until the heavy work is done.
I recommend to read this article on responsiveness to learn more about not blocking the UI Thread.
You can intercept the BackButton inside your own App, ONLY! As I see, you are starting some kind of CameraApp, that should pick a picture for you. You have NO control over the CameraActivity's BackButton. Your screen Has an ImageView, but you never set a Bitmap to it.
The disabling of the BackButton works, as you could NOT go out of your screen and have to "kill" it via a TaskManager. The BackButton has no functionality inside your Activity.

using puelocesar / android-lib-magick

I am a beginner in Android. I want a sample app which uses this library: https://github.com/puelocesar/android-lib-magick. I tried to use https://github.com/lilac/Android-ImageMagick before - I made lots of changes to make it work but the result I got was not satisfactory.
I just want to know which class to call for a particular thing.
These are the effects i am getting using https://github.com/lilac/Android-ImageMagick
blur, charcoal and no effect looks exactly same. when i select edge it shows blur image.
and the noise effects appear but they look like red and green dots are drawn manually on that image.
below is the code which runs application.
it searches for images in sd card with hard coded name and extention. it gets all the ibages but i am unable to understand wha it does with those images because it shows only one image on screen.
also dont know test.txt is created. this code is present in library as AndroidMagickActivity
i did some changes in android.mk file after searching for long time and now its running but the output is not that good.
please anybody help me to improve results of lilac library or help me to understand how to use https://github.com/puelocesar/android-lib-magick
i am beginner and i don't know how to use NDK and how to create JNI and .so files
package magick;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.magick.R;
import magick.util.DisplayImageMetaData;
import magick.util.MagickBitmap;
import android.util.Log;
import android.view.*;
public class AndroidMagickActivity extends Activity {
static final int PROGRESS_DIALOG = 0;
ProgressDialog progressDialog = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// InputStream stream = getResources().openRawResource(R.raw.app_notes);
try {
final MagickImage img = new MagickImage(new ImageInfo("/sdcard/1.jpg"));
/*
* ImageView iv = new ImageView(this);
* iv.setImageBitmap(MagickBitmap.ToBitmap(img));
* setContentView(iv);
*/
// setContentView(R.layout.main);
Spinner s = (Spinner) findViewById(R.id.spinner);
ArrayAdapter adapter = ArrayAdapter.createFromResource(this,R.array.effects, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s.setAdapter(adapter);
s.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
ProgressThread t = new ProgressThread(img, pos);
//runOnUiThread(t);
t.run();
}
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing.
}
});
ImageView iv = (ImageView) findViewById(R.id.imageView);
iv.setImageBitmap(MagickBitmap.ToBitmap(img));
} catch (MagickApiException e) {
e.printStackTrace();
} catch (MagickException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
* TextView tv = new TextView(this);
* tv.setText(DisplayImageMetaData.displayMagickImage(img));
* setContentView(tv);
*/
int count = 2;
MagickImage images[] = new MagickImage[count];
for (int i = 0; i < count; i++) {
String path = "/sdcard/" + String.valueOf(i + 1) + ".jpg";
try {
images[i] = new MagickImage(new ImageInfo(path));
} catch (MagickException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
MagickImage image = new MagickImage(images);
image.setImageFormat("gif");
String fn = Environment.getExternalStorageDirectory() + "/Pictures/test.gif";
image.setFileName(fn);
ImageInfo info = new ImageInfo(fn);
info.setMagick("gif");
//image.writeImage(info);
byte blob[] = image.imageToBlob(info);
FileOutputStream fos = new FileOutputStream(fn);
fos.write(blob);
fos.close();
FileOutputStream testOS = new FileOutputStream("/mnt/sdcard/test.txt");
testOS.write("abc".getBytes());
testOS.close();
} catch (MagickException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected Dialog onCreateDialog(int id, Bundle bundle) {
switch (id) {
case PROGRESS_DIALOG:
/*
* ProgressDialog dialog =
* ProgressDialog.show(AndroidMagickActivity.this, "",
* "Loading. Please wait...", true);
*/
progressDialog = new ProgressDialog(AndroidMagickActivity.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("Loading...");
return progressDialog;
// return dialog;
default:
return null;
}
}
/** Nested class that performs progress calculations (counting) */
private class ProgressThread extends Thread {
MagickImage img;
int pos;
ProgressThread(MagickImage image, int pos) {
this.img = image;
this.pos = pos;
}
public void run() {
int effect = 0;
AndroidMagickActivity.this.showDialog(PROGRESS_DIALOG);
switch (pos) {
case 1:
effect = NoiseType.UndefinedNoise;
break;
case 2:
effect = NoiseType.UniformNoise;
break;
case 3:
effect = NoiseType.GaussianNoise;
break;
case 4:
effect = NoiseType.MultiplicativeGaussianNoise;
break;
case 5:
effect = NoiseType.ImpulseNoise;
break;
case 6:
effect = NoiseType.LaplacianNoise;
break;
case 7:
effect = NoiseType.PoissonNoise;
break;
}
Bitmap bitmap = null;
try {
ImageView iv = (ImageView) findViewById(R.id.imageView);
MagickImage image = null;
if (pos < 8)
image = img.addNoiseImage(effect);
else if (pos == 9)
image = img.blurImage(5, 1);
else if (pos == 10)
image = img.charcoalImage(5, 1);
else if (pos == 11)
image = img.edgeImage(0);
if (image != null) {
bitmap = MagickBitmap.ToBitmap(image);
iv.setImageBitmap(bitmap);
}
// bitmap.recycle(); we can't do that.
AndroidMagickActivity.this.dismissDialog(PROGRESS_DIALOG);
} catch (MagickException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

How create a folder on SdCard and how to copy files from one to another

In this Project i am trying to copy files from sdcard (for eg images in DICM) to Recycle Folder whenever user click delete button. But, i am facing problem. I am able to delete files but but unable to copy thing.
C.Java - Using for assigning directories.
package com.haha.recyclebin;
public class C
{
public static String SDCARD = "/mnt/sdcard";
public static String RECYCLE_BIN_ROOT = SDCARD+"/.Recycle";
}
U.Java - Using for copying file from one folder on Sdcard to Recycle Folder.
package com.haha.recyclebin;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class U
{
public static void copyFile(File sourceLocation, File targetLocation)
throws FileNotFoundException, IOException
{
U.debug("copying from "+sourceLocation.getAbsolutePath()+" to "+targetLocation.getAbsolutePath());
String destDirPath = targetLocation.getParent();
File destDir = new File(destDirPath);
if(!destDir.exists()){
destDir.mkdirs();
}
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024*512];
int len;
while ((len = in.read(buf)) > 0) {
System.out.println("papa");
out.write(buf, 0, len);
System.out.println(">");
}
System.out.println(".");
in.close();
out.close();
}
public static void debug(Object msg){
System.out.println(msg);
}
}
RecycleActivity - using U.java and C.java in this code :-
package com.haha.recyclebin;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.Set;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Toast;
public class RecycleActivity extends Activity {
private OnClickListener exitListener = new OnClickListener()
{
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt)
{
RecycleActivity.this.finish();
}
};
/**
* need a standalone class to hold data (file name)
*/
private final class DeleteFileListener implements OnClickListener
{
String file = null;
/**
* #param file the file to set
*/
public void setFile(String file)
{
this.file = file;
}
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt)
{
RecycleActivity.this.prepareRecyclebin();
File src = new File(file);
String destPath = C.RECYCLE_BIN_ROOT+file;
File dest = new File(destPath);
try
{
U.copyFile(src, dest); /* using U.java here */
src.delete();
String msg = RecycleActivity.this.getResources().getString(R.string.deleted) + destPath;
Toast.makeText(RecycleActivity.this, msg, Toast.LENGTH_SHORT).show();
} catch (Exception e)
{
e.printStackTrace();
Toast.makeText(RecycleActivity.this, R.string.delete_failed, Toast.LENGTH_SHORT).show();
}
RecycleActivity.this.finish();
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent intent = getIntent();
debugIntent(intent);
Bundle extras = intent.getExtras();
/* For File Explorer */
Object obj = extras.get(Intent.EXTRA_INTENT);
if(null!=obj){
Intent it2 = (Intent) obj;
Bundle ex2 = it2.getExtras();
Object obj2 = ex2.get(Intent.EXTRA_STREAM);
if(null!=obj2){
Uri uri = (Uri) obj2;
String file = uri.getPath();
System.out.println("file: "+file);
toRecyclebin(file);
}
}
}
/**
* #param file
*/
private void toRecyclebin(String file)
{
if(!file.startsWith(C.SDCARD))
{
promptLimit();
return;
}
String conf = this.getResources().getString(R.string.confirm_delete);
conf+="\n\n"+file;
DeleteFileListener listener = new DeleteFileListener();
listener.setFile(file);
new AlertDialog.Builder(this)
.setMessage(conf)
.setPositiveButton(R.string.yes, listener)
.setNegativeButton(R.string.no, exitListener)
.show();
}
/**
*
*/
private void promptLimit()
{
new AlertDialog.Builder(this)
.setMessage(R.string.limit)
.setPositiveButton(R.string.ok, exitListener)
.show();
}
/**
* #param intent
*/
private void debugIntent(Intent intent)
{
System.out.println("intent: "+intent);
Bundle extras = intent.getExtras();
Set<String> keys = extras.keySet();
for(String key:keys){
Object value = extras.get(key);
System.out.println("-["+key+"]:["+value+"]");
if(value instanceof Intent){
Intent intent2 = (Intent) value;
Bundle ext2 = intent2.getExtras();
Set<String> ks2 = ext2.keySet();
for(String k:ks2){
Object v2 = ext2.get(k);
System.out.println("--["+k+"]:["+v2+"]");
if(v2 instanceof Intent){
Intent i3 = (Intent) v2;
Bundle e3 = i3.getExtras();
Set<String> ks3 = e3.keySet();
for(String kk:ks3){
Object v3 = e3.get(kk);
System.out.println("---["+kk+"]:["+v3+"]");
}
}
}
}
}
Uri data = intent.getData();
System.out.println("data: "+data);
}
void prepareRecyclebin(){
File root = new File(C.RECYCLE_BIN_ROOT);
if(!root.exists()){
root.mkdirs();
}
}
}
I have file explorer which is working fine, I can see images and music on sdcard and i am able to delete then also. But after deletion they should go to Recycle folder (as stated in C.java ). I have created Recycle Folder (/mnt/sdcard/Recycle) manually using file explorer in eclipse.
But i don't see files in recycle folder.
Is there any problem with the Code ?
Any kind of Help will be appreciated.
Thanks !!
Have you Debug and make sure the copyfile has been executed?
And this is My CopyFile function, and they are quite the same:
public static boolean copyFile(String from, String to) {
try {
int bytesum = 0;
int byteread = 0;
File oldfile = new File(from);
if (oldfile.exists()) {
InputStream inStream = new FileInputStream(from);
FileOutputStream fs = new FileOutputStream(to);
byte[] buffer = new byte[1444];
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread;
fs.write(buffer, 0, byteread);
}
inStream.close();
fs.close();
}
return true;
} catch (Exception e) {
return false;
}
}
Try following Code, it will Work.
public void Save_To_Phone(Bitmap bitmap){
try {
FileOutputStream os = new FileOutputStream(YourSDCardPath);
bitmap.compress(CompressFormat.JPEG, 80, os);
os.close();
} catch (Exception e) {
Log.w("ExternalStorage", "Error writing file", e);
}
}

Turn FTP command into ASync Task?

First off, don't flame me for not searching, I've looked for answers to this and while there are answers out there, I can't understand any of them.
Now, with that aside, I'm trying to put my ftp command into an ASync task for Android.
Code:
package com.dronnoc.ftp;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.io.CopyStreamEvent;
import org.apache.commons.net.io.CopyStreamListener;
import org.apache.commons.net.io.Util;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
public class Main extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
FTPTransfer ftp = new FTPTransfer("hostname", "user", "pass");
String data = Environment.getDataDirectory().toString();
data += "/data/com.dronnoc.ftp/databases/test.db";
boolean result = ftp.upload(data, "/ftp_dir/test.db");
if(result)
{
Log.d("message", "Upload Successful.");
}
else
{
Log.e("message", ftp.error());
}
ftp.close();
}
}
FTPTransfer.java
package com.dronnoc.ftp;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.SocketException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPConnectionClosedException;
public class FTPTransfer {
final FTPClient ftp = new FTPClient();
private String error = null;
private boolean connected = false;
public FTPTransfer(String host, String username, String pass) {
// TODO Auto-generated constructor stub
try {
ftp.connect(host);
if(ftp.login(username, pass))
{
ftp.enterLocalPassiveMode();
connected = true;
}
}
catch (FTPConnectionClosedException e) { error = e.getMessage(); }
catch (SocketException e) { error = e.getMessage(); }
catch (IOException e) { error = e.getMessage(); }
}
public boolean upload(String localName, String remoteName)
{
if(ftp.isConnected() && connected)
{
try {
FileInputStream file = new FileInputStream(localName);
boolean result = ftp.storeFile(remoteName, file);
if(result) { return true; }
else { return false; }
}
catch (FileNotFoundException e) { error = e.getMessage(); return false; }
catch (IOException e) { error = e.getMessage(); return false; }
}
return false;
}
public boolean upload(File localName, String remoteName)
{
if(ftp.isConnected() && connected)
{
try {
FileInputStream file = new FileInputStream(localName.getAbsolutePath());
boolean result = ftp.storeFile(remoteName, file);
if(result) { return true; }
else { return false; }
}
catch (FileNotFoundException e) { error = e.getMessage(); return false; }
catch (IOException e) { error = e.getMessage(); return false; }
}
return false;
}
public boolean download(String remote, String local)
{
//TODO Put appropriate code here
return false;
}
public boolean close()
{
try {
ftp.disconnect();
return true;
} catch (IOException e) {
error = e.getMessage();
return false;
}
}
public String error()
{
return error;
}
}
What I want to know is how I can put my FTP function into an ASync task so that I can run it in a background activity and update a progress bar, and also indicate how many bytes its uploaded so far?
Cheers
EDIT
The code itself works at the moment, I just need to know how to make it into an Async task
Not sure if you're asking how to use the AsyncTask but in case you are here's a tutorial about using AsyncTask to make requests to a web service. This can be extended easily to perform FTP in the background. AsyncTask can also support Progress though I don't think it's mentioned in the tutorial.
Basically your upload function needs to move to doInBackground and so does the connection code. See http://geekjamboree.wordpress.com/2011/11/22/asynctask-call-web-services-in-android/

Categories

Resources