Unable to save photo in my android app - android

This is my first time for asking question in stackoverflow and to make an android application using camera app.
I tried to use the source code in android development page, but it failed.
Thank you for reading my post.
package com.examplehoon.gnibnumb;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
static final int REQUEST_IMAGE_CAPTURE = 1;
String mCurrentPhotoPath;
static final int REQUEST_TAKE_PHOTO = 1;
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent() {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri outputFileUri = Uri.fromFile(photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
public void startClicked(View view) throws IOException, InterruptedException{
for(int i = 0; i<10; i++){
thd.run();
thd.sleep(5000);
}
}
public class Top implements Runnable{
public void run() {
dispatchTakePictureIntent();
}
}
Top t = new Top();
Thread thd = new Thread(t);
}

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!!

Create, write and display PDF file in android app

I have an android app which is basically a form to accept user input. This input is stored in a database. But I want to create a pdf file with the information a user enters and and display it so that the user can print the file or save the file to their android note tab. What is the best way to go about it. I have seen iText around but this does not render the file. I found this code online and I tested it to understand the concept of pdf creation. This uses Lowagie 2.1.7
package com.example.sweetiean.androidpdfdemo;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Environment;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Font;
import com.lowagie.text.HeaderFooter;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.Image;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class MainActivity extends ActionBarActivity {
private Button createPDF , openPDF;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createPDF = (Button)findViewById(R.id.button1);
createPDF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
createPDF();
}
});
openPDF = (Button)findViewById(R.id.button2);
openPDF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
openPdf();
}
});
}
public void createPDF()
{
Document doc = new Document();
try {
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/PDF";
File dir = new File(path);
if(!dir.exists())
dir.mkdirs();
Log.d("PDFCreator", "PDF Path: " + path);
File file = new File(dir, "demo.pdf");
FileOutputStream fOut = new FileOutputStream(file);
PdfWriter.getInstance(doc, fOut);
//open the document
doc.open();
/* Create Paragraph and S`enter code here`et Font */
Paragraph p1 = new Paragraph("Hi! I am Generating my first PDF using DroidText");
/* Create Set Font and its Size */
Font paraFont= new Font(Font.HELVETICA);
paraFont.setSize(16);
p1.setAlignment(Paragraph.ALIGN_CENTER);
p1.setFont(paraFont);
//add paragraph to document
doc.add(p1);
Paragraph p2 = new Paragraph("This is an example of a simple paragraph");
/* You can also SET FONT and SIZE like this */
Font paraFont2= new Font(Font.COURIER,14.0f, Color.GREEN);
p2.setAlignment(Paragraph.ALIGN_CENTER);
p2.setFont(paraFont2);
doc.add(p2);
/* Inserting Image in PDF */
/*ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap bitmap = BitmapFactory.decodeResource(getBaseContext().getResources(), R.drawable.android);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100 , stream);
Image myImg = Image.getInstance(stream.toByteArray());
myImg.setAlignment(Image.MIDDLE);
//add image to document
doc.add(myImg);*/
//set footer
Phrase footerText = new Phrase("This is an example of a footer");
HeaderFooter pdfFooter = new HeaderFooter(footerText, false);
doc.setFooter(pdfFooter);
Toast.makeText(getApplicationContext(), "Created...", Toast.LENGTH_LONG).show();
} catch (DocumentException de) {
Log.e("PDFCreator", "DocumentException:" + de);
} catch (IOException e) {
Log.e("PDFCreator", "ioException:" + e);
}
finally
{
doc.close();
}
}
void openPdf()
{
Intent intent = new Intent(Intent.ACTION_VIEW);
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/PDF";
File file = new File(path, "demo.pdf");
intent.setDataAndType( Uri.fromFile(file), "application/pdf" );
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
And this is the main activity.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<Button
android:id="#+id/button2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_marginTop="100dp"
android:text="Open PDF" />
<Button
android:id="#+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"
android:layout_marginTop="44dp"
android:text="Generate PDF" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="#string/hello_world" />
Do it this way:
import com.cete.dynamicpdf.*;
import com.cete.dynamicpdf.pageelements.Label;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.widget.Toast;
public class DynamicPDFHelloWorld extends Activity {
private static String FILE = Environment.getExternalStorageDirectory()
+ "/HelloWorld.pdf";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Create a document and set it's properties
Document objDocument = new Document();
objDocument.setCreator("DynamicPDFHelloWorld.java");
objDocument.setAuthor("Your Name");
objDocument.setTitle("Hello World");
// Create a page to add to the document
Page objPage = new Page(PageSize.LETTER, PageOrientation.PORTRAIT,
54.0f);
// Create a Label to add to the page
String strText = "Hello World...\nFrom DynamicPDF Generator "
+ "for Java\nDynamicPDF.com";
Label objLabel = new Label(strText, 0, 0, 504, 100,
Font.getHelvetica(), 18, TextAlign.CENTER);
// Add label to page
objPage.getElements().add(objLabel);
// Add page to document
objDocument.getPages().add(objPage);
try {
// Outputs the document to file
objDocument.draw(FILE);
Toast.makeText(this, "File has been written to :" + FILE,
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this,
"Error, unable to write to file\n" + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}
Also check these links. They will help you to fulfill your requirement.
http://www.dynamicpdf.com/Blog/post/2012/06/15/Generating-PDFs-Dynamically-on-Android.aspx
https://github.com/JoanZapata/android-pdfview
How to create PDFs in an Android app?
Render a PDF file using Java on Android
you'll find the correct code that actually works right.for creating a pdf file, putting some content in it, saving in and the opening the newly created file.
For this you'll need to add the jar of iTextG to your project:
OR
if you WANT TO convert your layout or view into pdf then you have to create image from your layout and then add into pdf.Perfect tutorial of that Go Through this Link . Hope this will help you guys.Thank you.
For Simple Create and Open pdf:
// Method for creating a pdf file from text, saving it then opening it for display
public void createandDisplayPdf(String text) {
Document doc = new Document();
try {
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/PDF";
File dir = new File(path);
if(!dir.exists())
dir.mkdirs();
File file = new File(dir, "mypdffile.pdf");
FileOutputStream fOut = new FileOutputStream(file);
PdfWriter.getInstance(doc, fOut);
//open the document
doc.open();
Paragraph p1 = new Paragraph(text);
Font paraFont= new Font(Font.FontFamily.COURIER);
p1.setAlignment(Paragraph.ALIGN_CENTER);
p1.setFont(paraFont);
//add paragraph to document
doc.add(p1);
} catch (DocumentException de) {
Log.e("PDFCreator", "DocumentException:" + de);
} catch (IOException e) {
Log.e("PDFCreator", "ioException:" + e);
}
finally {
doc.close();
}
viewPdf("mypdffile.pdf", "PDF");
}
// Method for opening a pdf file
private void viewPdf(String file, String directory) {
File pdfFile = new File(Environment.getExternalStorageDirectory() + "/" + directory + "/" + file);
Uri path = Uri.fromFile(pdfFile);
// Setting the intent for pdf reader
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(this, "Can't read pdf file", Toast.LENGTH_SHORT).show();
}
}
Check this link,it requires you to download a jar file.(more description in the link).Here is a part of code to generate pdf.
package com.cete.androidexamples.dynamicpdf.helloworld;
import com.cete.dynamicpdf.*;
import com.cete.dynamicpdf.pageelements.Label;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.widget.Toast;
public class DynamicPDFHelloWorld extends Activity {
private static String FILE = Environment.getExternalStorageDirectory()
+ "/HelloWorld.pdf";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Create a document and set it's properties
Document objDocument = new Document();
objDocument.setCreator("DynamicPDFHelloWorld.java");
objDocument.setAuthor("Your Name");
objDocument.setTitle("Hello World");
// Create a page to add to the document
Page objPage = new Page(PageSize.LETTER, PageOrientation.PORTRAIT,
54.0f);
// Create a Label to add to the page
String strText = "Hello World...\nFrom DynamicPDF Generator "
+ "for Java\nDynamicPDF.com";
Label objLabel = new Label(strText, 0, 0, 504, 100,
Font.getHelvetica(), 18, TextAlign.CENTER);
// Add label to page
objPage.getElements().add(objLabel);
// Add page to document
objDocument.getPages().add(objPage);
try {
// Outputs the document to file
objDocument.draw(FILE);
Toast.makeText(this, "File has been written to :" + FILE,
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this,
"Error, unable to write to file\n" + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}

Open gallery in specific video, without playing it

I have a camera application that can also record video. (Im developing on samsung S3)
I want to be able to open the gallery on the last recorded video.
I use this code:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(file.getAbsolutePath()), "video/3gpp");
startActivity(intent);
The problem with that code is that the video immediately starts, and when it ends
the gallery activity close.
I want to be able to open the video without playing it, exactly like in my samsung S3.
thanks in advance!
To open particular image we can use this .. and its worked .
so please check with your requirement. Hope this will helps you..
import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.MediaScannerConnectionClient;
import android.net.Uri;
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;
public class SDCARD123Activity extends Activity implements MediaScannerConnectionClient{
public String[] allFiles;
private String SCAN_PATH ;
private static final String FILE_TYPE="image/*";
private MediaScannerConnection conn;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
File folder = new File("/sdcard/Photo/");
allFiles = folder.list();
// uriAllFiles= new Uri[allFiles.length];
for(int i=0;i<allFiles.length;i++)
{
Log.d("all file path"+i, allFiles[i]+allFiles.length);
}
// Uri uri= Uri.fromFile(new File(Environment.getExternalStorageDirectory().toString()+"/yourfoldername/"+allFiles[0]));
SCAN_PATH=Environment.getExternalStorageDirectory().toString()+"/Photo/"+allFiles[0];
System.out.println(" SCAN_PATH " +SCAN_PATH);
Log.d("SCAN PATH", "Scan Path " + SCAN_PATH);
Button scanBtn = (Button)findViewById(R.id.scanBtn);
scanBtn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
startScan();
}});
}
private void startScan()
{
Log.d("Connected","success"+conn);
if(conn!=null)
{
conn.disconnect();
}
conn = new MediaScannerConnection(this,this);
conn.connect();
}
#Override
public void onMediaScannerConnected() {
Log.d("onMediaScannerConnected","success"+conn);
conn.scanFile(SCAN_PATH, FILE_TYPE);
}
#Override
public void onScanCompleted(String path, Uri uri) {
try {
Log.d("onScanCompleted",uri + "success"+conn);
System.out.println("URI " + uri);
if (uri != null)
{
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(uri);
startActivity(intent);
}
} finally
{
conn.disconnect();
conn = null;
}
}
}

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);
}
}

Android UNZIP Inputstream problem

I am trying to unzip a file located on SDCARD of Android device.
If the ZIP file only contains files NOT FOLDERS everything is fine. However the production file that I want the app to unzip contains multiple directories and sub-directories. This is where I run into issues.
The code isnt creating the folder structure required. If I manually create the folders prior to running the class it unzips as planned, but in the future I wont know the directory structure and need the code to create the proper folder structure.
Here is the code I'm working with
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;
public class HomeActivity extends Activity
{
private TextView tv;
private static final String ROOT_FOLDER = Environment.getExternalStorageDirectory()
+ File.separator + "FacebookPhotos";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.tv);
tv.append("Reading zip file from assets folder...");
// Start the unzipping process
thread.start();
}
private Thread thread = new Thread()
{
#Override
public void run()
{
sendMessage("-----------------------------------------------");
// Create a directory in the SDCard to store the files
File file = new File(ROOT_FOLDER);
if (!file.exists())
{
file.mkdirs();
}
else
{
file.delete();
}
try
{
// Open the ZipInputStream
ZipInputStream inputStream = new ZipInputStream(new FileInputStream("/sdcard/Photos/photos.zip"));
// Loop through all the files and folders
for (ZipEntry entry = inputStream.getNextEntry(); entry != null; entry = inputStream
.getNextEntry())
{
sendMessage("Extracting: " + entry.getName() + "...");
String innerFileName = ROOT_FOLDER + File.separator + entry.getName();
File innerFile = new File(innerFileName);
if (innerFile.exists())
{
innerFile.delete();
}
// Check if it is a folder
if (entry.isDirectory())
{
// Its a folder, create that folder
innerFile.mkdirs();
}
else
{
// Create a file output stream
FileOutputStream outputStream = new FileOutputStream(innerFileName);
final int BUFFER = 2048;
// Buffer the output to the file
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream,
BUFFER);
// Write the contents
int count = 0;
byte[] data = new byte[BUFFER];
while ((count = inputStream.read(data, 0, BUFFER)) != -1)
{
bufferedOutputStream.write(data, 0, count);
}
// Flush and close the buffers
bufferedOutputStream.flush();
bufferedOutputStream.close();
}
sendMessage("DONE");
// Close the current entry
inputStream.closeEntry();
}
inputStream.close();
sendMessage("-----------------------------------------------");
sendMessage("Unzipping complete");
}
catch (IOException e)
{
sendMessage("Exception occured: " + e.getMessage());
e.printStackTrace();
}
}
};
private Handler handler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
tv.append("\n" + msg.getData().getString("data"));
super.handleMessage(msg);
}
};
private void sendMessage(String text)
{
Message message = new Message();
Bundle data = new Bundle();
data.putString("data", text);
message.setData(data);
handler.sendMessage(message);
}
}
Check out this answer
Android - Unzip a folder?
I think sometimes in ZIP files, the directory entries may be added after their files. In this case, you won't get the directory before the file. The linked example calls file.getParentFile().exists() for regular files and creates that directory if it doesn't eixst.

Categories

Resources