Show image gallery in camera intent - android

I'm working on a feature where the user can take a picture and choose from the gallery. This is basically where it starts and goes on to save the images in db.
private void showPictureDialog(){
AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);
pictureDialog.setTitle("Select Action");
String[] pictureDialogItems = {
"Select photo from gallery",
"Capture photo from camera" };
pictureDialog.setItems(pictureDialogItems,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
choosePhotoFromGallary();
break;
case 1:
takePhotoFromCamera();
break;
}
}
});
pictureDialog.show();
}
However, I want to make the user experience better. I want to skip the dialog where the user selects one of the options (from gallery or camera) and instead show the gallery in camera intent. Something similar to this:
I hope you get my point. Thanks :)

Get all image
public List<File> getAllShownImagesPath(Context context) {
//get all images
String[] columns = {MediaStore.Images.Media.DATA, MediaStore.Images.Media.DATE_ADDED, MediaStore.Images.Media.SIZE};
List<File> result = new ArrayList<>();
File f = null;
final Cursor cursor = context.getContentResolver().
query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, // Specify the provider
columns, // The columns we're interested in
null, // A WHERE-filter query
null, // The arguments for the filter-query
MediaStore.Images.Media.DATE_ADDED + " DESC"
);
if (cursor != null) {
cursor.moveToFirst();
for (int r = 0; r < cursor.getCount(); r++, cursor.moveToNext()) {
int i = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.SIZE));
//int l = cursor.getString(1).length();
final int image_path_col = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
if (i > 0) {
f = new File(cursor.getString(image_path_col));
if (f.length() > 0) {
result.add(f);
}
}
}
cursor.close();
}
return result;
}
Add all image into recyclerview or listview

Related

Image not updating from SQLite database

So, I have android application using Sqlite Database. I has a cardview to showing the data. In the table, I have field like, name(text), cost(int) and an image(BLOB). I want to update the data. So, when I change and update the name or the cost, the image not updated and return blank or null. But when I change and update the image, it successfully updated.
First, this is my select query to showing the name, cost and image in update class
public ModelProduk getnama(int selection){
SQLiteDatabase db = this.getReadableDatabase();
String whereclause = KEY_ID_PRODUK + "=?";
String[] whereargs = new String[]{String.valueOf(selection)};
Cursor cursor = db.query(
TABLE_PRODUK,
null,
whereclause,
whereargs,
null,
null,
null
);
ModelProduk modelProduk = new ModelProduk();
if (cursor.moveToFirst()) {
modelProduk.set_id(Integer.parseInt(cursor.getString(0)));
modelProduk.set_nama(cursor.getString(1));
modelProduk.set_harga(Integer.parseInt(cursor.getString(2)));
modelProduk.set_gambar(cursor.getBlob(3));
}
cursor.close();
db.close();
return modelProduk;
}
Here's my database to update
public void update(ModelProduk modelProduk) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAMA_PRODUK, modelProduk.get_nama());
values.put(KEY_HARGA_PRODUK, modelProduk.get_harga());
values.put(KEY_GAMBAR_PRODUK, modelProduk.get_gambar());
String where = "id=?";
String[] whereArgs = new String[] {String.valueOf(modelProduk.get_id())};
// update baris
db.update(TABLE_PRODUK, values, where, whereArgs);
db.close();
}
my java class for update
private void init(){
pilih = getIntent().getIntExtra("id_produk", 0);
db = new Database(this);
modelProduk = db.getnama(pilih);
gambar_produku = (ImageView) findViewById(R.id.pilihgambaru);
tambahgambaru = (Button) findViewById(R.id.btaddu);
simpandatau = (Button) findViewById(R.id.btsimpanu);
deskripsiu = (EditText) findViewById(R.id.etdesku);
harga_produku = (EditText) findViewById(R.id.ethargau);
kembaliu = (Button) findViewById(R.id.btkembaliu);
deskripsiu.setText(modelProduk.get_nama());
harga_produku.setText(String.valueOf(modelProduk.get_harga()));
if (modelProduk.get_gambar() != null) {
gambar_produku.setImageBitmap(bitmap(modelProduk.get_gambar()));
}
}
public void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Pilih Gambar"), 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
gambar_produku.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public byte[] getImageByte(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
byte imageInByte[]=null;
if(bitmap!=null) {
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, stream);
imageInByte=stream.toByteArray();
}
return imageInByte;
}
public Bitmap bitmap (byte[] byteImage){
byte[] outImage = byteImage;
Bitmap image ;
if (outImage != null){
ByteArrayInputStream imageStream = new ByteArrayInputStream(outImage);
image = BitmapFactory.decodeStream(imageStream);
}else {
image= null;
}
return image;
}
my onclick to save the update
simpandatau.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
modelProduk.set_nama(deskripsiu.getText().toString());
modelProduk.set_harga(Integer.parseInt(harga_produku.getText().toString()));
modelProduk.set_gambar(getImageByte(bitmap));
db.update(modelProduk);
Toast.makeText(getApplicationContext(), "Data Berhasil Diubah!", Toast.LENGTH_SHORT).show();
}
});
Please Help! I have read many solutions but it's not same to my problems.
Thank you!
You could try the following. This will attempt to get the row that is to be updated before updating. However, rather than return blank or null or update successful it returns an integer which can be -1, 0 or 1 which indicates three possible outcomes.
If the row doesn't exist then it will return -1 (NOTUPDATED).
Otherwise it will then compare the stored image against the image passed.
If the images are different then it will add the new image to values and set the value to be returned to 1 (IMAGEUPDATED).
Otherwise the new image is not added to the values and the value to be returned will remain as 0 (IMAGENOTUPDATED). By not adding the image to values the gambar column will not be included in the SET clause of the SQL generated by the update method.
:-
public int update(ModelProduk modelProduk) {
final int NOTUPDATED = -1;
final int IMAGENOTUPDATED = 0;
final int IMAGEUPDATED = 1;
String where = "id=?";
String[] whereArgs = new String[] {String.valueOf(modelProduk.get_id())};
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
// get the current row from the database (return -1 if it doesn't exist)
Cursor before_update = db.query(TABLE_PRODUK,null,where,whereArgs,null,null,null);
if (!before_update.moveToFirst) {
before_update.close();
return NOTUPDATED;
}
// Default value to return
rv = IMAGENOTUPDATED;
// Compare the store image against the new image, if not the same
// then include the image in the update
if (!Arrays.equals(before_update.getBlob(3),modelProduk.get_gambar)) {
values.put(KEY_GAMBAR_PRODUK, modelProduk.get_gambar());
rv = IMAGEUPDATED;
}
before_update.close();
values.put(KEY_NAMA_PRODUK, modelProduk.get_nama());
values.put(KEY_HARGA_PRODUK, modelProduk.get_harga());
// Update baris checking to see if an update occurred, if not
// then set return value to -1 (could be a different status code)
if (db.update(TABLE_PRODUK, values, where, whereArgs) = 0) {
rv = NOTUPDATED;
}
db.close();
before_update.close();
return rv;
}
Note the above is in-principle code, it has not been tested and therefore may contain errors.
You may wish to define NOTUPDATED, IMAGENOTUPDATED and IMAGEUPDATED elsewhere with greater scope.

Memory Leaks and GridView

I am using a GridView and universalimageloader (1.8.6) and seem to be encountering a memory leak - though maybe I am misinterpreting DDMS and MAT results? This is code I did not write, but it is pretty basic - we are showing a number of photos and allowing the user to select as many as they want and then storing those for future reference. The code seems to work fine, but in MAT "Leak Suspect" the GridView from below keeps on showing up, chewing upwards of 5 mb each time, even when I have called finish() on the Activity. From what I have read Android can keep the Activity in memory until it wants to release it (and have seen this with other Activities) but it never seems to want to release this one - even when I force GC. The "new thread" allocation looks a bit suspicious, but wouldn't that get dellocated with the calling Activity?
Probably just missing something obvious, but here is the code:
public class PhotoGalleryPickerActivity extends MyActivity {
private Boolean mMultiple = false;
GridView gridGallery;
Handler handler;
GalleryAdapter adapter;
ImageView imgNoMedia;
Button btnGalleryOk;
String action;
private ImageLoader imageLoader;
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photo_gallery_picker);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle("Photo Gallery Capture");
Bundle extras = getIntent().getExtras();
mMultiple = extras.getBoolean("multiple");
initImageLoader();
init();
}
private void initImageLoader() {
try {
String CACHE_DIR = Environment.getExternalStorageDirectory().getAbsolutePath() + "/.temp_tmp";
new File(CACHE_DIR).mkdirs();
File cacheDir = StorageUtils.getOwnCacheDirectory(getBaseContext(), CACHE_DIR);
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheOnDisc(true).imageScaleType(ImageScaleType.EXACTLY)
.bitmapConfig(Bitmap.Config.RGB_565).build();
ImageLoaderConfiguration.Builder builder = new ImageLoaderConfiguration.Builder(
getBaseContext())
.defaultDisplayImageOptions(defaultOptions)
.discCache(new UnlimitedDiscCache(cacheDir))
.memoryCache(new WeakMemoryCache());
ImageLoaderConfiguration config = builder.build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
} catch (Exception e) {
Utilities.logException(e);
}
}
private void init() {
handler = new Handler();
gridGallery = (GridView) findViewById(R.id.gridGallery);
gridGallery.setFastScrollEnabled(true);
adapter = new GalleryAdapter(getApplicationContext(), imageLoader);
PauseOnScrollListener listener = new PauseOnScrollListener(imageLoader, true, true);
gridGallery.setOnScrollListener(listener);
if (mMultiple == true){
findViewById(R.id.llBottomContainer).setVisibility(View.VISIBLE);
gridGallery.setOnItemClickListener(mItemMulClickListener);
adapter.setMultiplePick(true);
}
else {
findViewById(R.id.llBottomContainer).setVisibility(View.GONE);
gridGallery.setOnItemClickListener(mItemSingleClickListener);
adapter.setMultiplePick(false);
}
gridGallery.setAdapter(adapter);
imgNoMedia = (ImageView) findViewById(R.id.imgNoMedia);
btnGalleryOk = (Button) findViewById(R.id.btnGalleryOk);
btnGalleryOk.setOnClickListener(mOkClickListener);
new Thread() {
#Override
public void run() {
Looper.prepare();
handler.post(new Runnable() {
#Override
public void run() {
adapter.addAll(getGalleryPhotos());
checkImageStatus();
}
});
Looper.loop();
};
}.start();
}
private void checkImageStatus() {
if (adapter.isEmpty()) {
imgNoMedia.setVisibility(View.VISIBLE);
} else {
imgNoMedia.setVisibility(View.GONE);
}
}
View.OnClickListener mOkClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<CustomGallery> selected = adapter.getSelected();
String[] photos = new String[selected.size()];
for (int i = 0; i < photos.length; i++) {
photos[i] = selected.get(i).sdcardPath;
}
Intent data = new Intent().putExtra("photos", photos);
if(photos.length == 0) {
data = null;
}
setResult(RESULT_OK, data);
finish();
}
};
AdapterView.OnItemClickListener mItemMulClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> l, View v, int position, long id) {
adapter.changeSelection(v, position);
}
};
AdapterView.OnItemClickListener mItemSingleClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> l, View v, int position, long id) {
CustomGallery item = adapter.getItem(position);
String[] photos = new String[1];
photos[0] = item.sdcardPath;
Intent data = new Intent().putExtra("photos", photos);
setResult(RESULT_OK, data);
finish();
}
};
private ArrayList<CustomGallery> getGalleryPhotos() {
ArrayList<CustomGallery> galleryList = new ArrayList<CustomGallery>();
try {
String[] dirs = new String[1];
final String where = MediaStore.Images.Media.DATA + " not like ? ";
String mediaDir = GlobalState.getInstance().currentForm.mediaDirectory();
if (mediaDir != null) {
int slash = mediaDir.lastIndexOf("/");
dirs[0] = mediaDir.substring(0, slash) + "%";
}
final String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID };
final String orderBy = MediaStore.Images.Media._ID;
Cursor imagecursor = null;
try {
if (mediaDir != null && mediaDir.trim().length() > 0) {
imagecursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, where, dirs, orderBy);
}
else {
imagecursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null, null, orderBy);
}
if (imagecursor != null && imagecursor.getCount() > 0) {
while (imagecursor.moveToNext()) {
CustomGallery item = new CustomGallery();
int dataColumnIndex = imagecursor
.getColumnIndex(MediaStore.Images.Media.DATA);
item.sdcardPath = imagecursor.getString(dataColumnIndex);
galleryList.add(item);
}
}
}
catch (Exception ex) {
Utilities.logException(ex);
Utilities.logError("PhotoGalleryPickerActivity", "getGalleryPhotos : " + ex.getMessage());
}
finally {
if (imagecursor != null) {
imagecursor.close();
}
}
} catch (Exception e) {
Utilities.logException(e);
e.printStackTrace();
}
// show newest photo at beginning of the list
Collections.reverse(galleryList);
return galleryList;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
PhotoGalleryPickerActivity.this.finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
The MAT results, run from Eclipse, look like this. It shows all the various calls I have made to this Activity, as though none of them have been actually released:
The normal memory for the application hangs around 11-15mb, but as you can see it is now at ~50mb, and grows each time I call the activity. If all the memory for the suspects was reclaimed I think I would be right where I should be:
Finally, could this be a result of running from Eclipse remotely to the device? I saw something similar with another control and was not able to replicate. Whereas I am definitely able to replicate this.
Thanks!
Just to wrap this one up, the issue was the new Thread(), which was holding onto the resources and specifically the GridView (at +4mb per hit). My final solution was to just get rid of the thread and looper, and just call the two methods directly in the init() of the Activity. I have no idea why it was coded into a looping thread to begin with, though I suspect it may have been to update the list of images on the fly (or cut and pasted code that was not really understood). Anyway seems to be working and the memory is being successfully garage collected. Thanks to #dharms you the help!

Facing issue to Draw the image on Box using PdfJet library in Android

I am creating Pdf file using PdfJet Library in Android. All the things are going good but I face some problem to draw the Image on Box . When I execute the program Pdf is created and the box is also created but the Image is not place in the Box.
Here is my code.
File file = new File(Environment.getExternalStorageDirectory(),
"Images.pdf");
FileOutputStream fos = new FileOutputStream(file);
PDF pdf = new PDF(fos);
Page page = new Page(pdf, A3.PORTRAIT);
Font f1 = new Font(pdf, CoreFont.HELVETICA);
f1.setSize(12.0f);
InputStream is = getAssets().open("myImage.jpg");
Image image1 = new Image(pdf, is, ImageType.JPG);
Box bo = new Box();
bo.setPosition(10,10);
bo.setSize(page.getWidth()-50.0f, page.getHeight()-50.0f);
image1.placeIn(bo);
bo.drawOn(page);
pdf.flush();
fos.close();
Any one with the good suggestion and answer regarding to this Question is Welcome here.
Please find the below example to get image from sdcard and past using pdfJet. Sure its helps you
public class PdfDemo extends Activity {
String exportDir;
int SELECT_PICTURE = 0;
String selectedImagePath;
#SuppressLint("SdCardPath")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
exportDir = Environment.getExternalStorageDirectory() + File.separator
+ "firstPdf.pdf";
((Button) findViewById(R.id.btnChangeDate))
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
getImage();
}
});
((Button) findViewById(R.id.btn_gen_pdf))
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
GeneratePdf();
}
});
}
private void GeneratePdf() {
try {
FileOutputStream fos = new FileOutputStream(exportDir);
BufferedOutputStream bos = new BufferedOutputStream(fos);
PDF pdf = new PDF(bos);
Page page = new Page(pdf, Letter.PORTRAIT);
InputStream is = new FileInputStream(selectedImagePath);
BufferedInputStream bis1 = new BufferedInputStream(is);
Image image1 = new Image(pdf, bis1, ImageType.JPG);
image1.setPosition(10, 52);
// image1.scaleBy(.4)
image1.scaleBy(0.3f, 0.4f);
// image1.setRotateCW90(true);
image1.drawOn(page);
// Adding Text View
Font f4 = new Font(pdf, CoreFont.HELVETICA_OBLIQUE);
TextLine text = new TextLine(f4);
text.setPosition(100.0, 100.0);
text.setText("Even so, unemployment has remained at less than half the EU average.");
text.setColor(Color.black);
text.drawOn(page);
Box flag = new Box();
flag.setPosition(100.0, 100.0);
flag.setSize(190.0, 100.0);
flag.setColor(Color.white);
flag.drawOn(page);
double sw = 7.69; // stripe width
Line stripe = new Line(0.0, sw / 2, 190.0, sw / 2);
stripe.setWidth(sw);
stripe.setColor(Color.oldgloryred);
for (int row = 0; row < 7; row++) {
stripe.placeIn(flag, 0.0, row * 2 * sw);
stripe.drawOn(page);
}
Box union = new Box();
union.setSize(76.0, 53.85);
union.setColor(Color.oldgloryblue);
union.setFillShape(true);
union.placeIn(flag, 0.0, 0.0);
union.drawOn(page);
double h_si = 12.6; // horizontal star interval
double v_si = 10.8; // vertical star interval
Point star = new Point(h_si / 2, v_si / 2);
star.setShape(Point.BOX);
star.setRadius(3.0);
star.setColor(Color.white);
star.setFillShape(true);
for (int row = 0; row < 6; row++) {
for (int col = 0; col < 5; col++) {
star.placeIn(union, row * h_si, col * v_si);
star.drawOn(page);
}
}
star.setPosition(h_si, v_si);
for (int row = 0; row < 5; row++) {
for (int col = 0; col < 4; col++) {
star.placeIn(union, row * h_si, col * v_si);
star.drawOn(page);
}
}
pdf.flush();
bos.close();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "" + e, Toast.LENGTH_SHORT)
.show();
System.out.println("ERRORLOG::" + e);
e.printStackTrace();
}
}
private void getImage() {
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, SELECT_PICTURE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SELECT_PICTURE && resultCode == RESULT_OK
&& data != null) {
Uri pickedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(pickedImage, filePath,
null, null, null);
cursor.moveToFirst();
selectedImagePath = cursor.getString(cursor
.getColumnIndex(filePath[0]));
cursor.close();
}
}
/**
*
* #param uri
* #return
*/
public String getPathBelowOs(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
/**
* Getting image from Uri
*
* #param contentUri
* #return
*/
public String getPathUpperOs(Uri contentUri) {// Will return "image:x*"
String wholeID = DocumentsContract.getDocumentId(contentUri);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = { MediaStore.Images.Media.DATA };
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, column, sel,
new String[] { id }, null);
String filePath = "";
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
return filePath;
}
public static InputStream bitmapToInputStream(Bitmap bitmap) {
int size = bitmap.getHeight() * bitmap.getRowBytes();
ByteBuffer buffer = ByteBuffer.allocate(size);
bitmap.copyPixelsToBuffer(buffer);
return new ByteArrayInputStream(buffer.array());
}
}

I get repeated numbers in the ContactPicker

I've a problem using the ContactPicker in Android. My code is the next
public void showContacts(View v){
phoneNumber.setText("");
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
startActivityForResult(contactPickerIntent, 1001);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case 1001:
Cursor cursor = null;
String[] numeros = null;
try {
Uri result = data.getData();
String id = result.getLastPathSegment();
cursor = getContentResolver().query(Phone.CONTENT_URI,
null,
Phone.CONTACT_ID + "=?", new String[] {id}, null);
int phoneIdx = cursor.getColumnIndex(Phone.NUMBER);
if(cursor.getCount() > 0){
numeros = new String[cursor.getCount()];
if (cursor.moveToFirst()) {
int cont = 0;
do{
numeros[cont] = cursor.getString(phoneIdx);
cont++;
}while(cursor.moveToNext());
}
}
} catch (Exception e) {
Log.e("Exception", "Failed to get email data", e);
} finally {
if (cursor != null) {
cursor.close();
}
if(numeros != null){
if(numeros.length > 1){
showNumbers(numeros);
}else{
phoneNumber.setText(numeros[0]);
}
}
}
break;
}
}
}
private void showNumbers(final String[] numeros){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setSingleChoiceItems(numeros, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogo, int item) {
phoneNumber.setText(numeros[item]);
dialogo.cancel();
}
});
builder.create().show();
}
Basically in the first method I call the ContactPicker, in the second I receive the answer of this, I process that and validate if the user have more than one phone.
The problem is, the algorithm return me six times the numbers. I don't know why occur that.

Android - getting back to menu from filepicker/browsing screen

I found this file picker online, which the developer said that people could use if they wanted to.
Since I thought the code was easy to understand - I decided to use it and change it a bit for my application.
All credit goes to the original developer (https://github.com/mburman/Android-File-Explore)
loadFileList();
showDialog(DIALOG_LOAD_FILE);
Log.d(TAG, path.getAbsolutePath());
}
private void loadFileList() {
try {
path.mkdirs();
} catch (SecurityException e) {
Log.e(TAG, "unable to write on the sd card ");
}
// Checks whether path exists
if (path.exists()) {
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String filename) {
File sel = new File(dir, filename);
// Filters based on whether the file is hidden or not
return (sel.isFile() || sel.isDirectory())
&& !sel.isHidden();
}
};
String[] fList = path.list(filter);
fileList = new Item[fList.length];
for (int i = 0; i < fList.length; i++) {
fileList[i] = new Item(fList[i], R.drawable.file_icon);
// Convert into file path
File sel = new File(path, fList[i]);
// Set drawables
if (sel.isDirectory()) {
fileList[i].icon = R.drawable.directory_icon;
Log.d("DIRECTORY", fileList[i].file);
} else {
Log.d("FILE", fileList[i].file);
}
}
if (!firstLvl) {
Item temp[] = new Item[fileList.length + 1];
for (int i = 0; i < fileList.length; i++) {
temp[i + 1] = fileList[i];
}
temp[0] = new Item("Up", R.drawable.directory_up);
fileList = temp;
}
} else {
Log.e(TAG, "path does not exist");
}
adapter = new ArrayAdapter<Item>(this,
android.R.layout.select_dialog_item, android.R.id.text1,
fileList) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// creates view
View view = super.getView(position, convertView, parent);
TextView textView = (TextView) view
.findViewById(android.R.id.text1);
// put the image on the text view
textView.setCompoundDrawablesWithIntrinsicBounds(
fileList[position].icon, 0, 0, 0);
// add margin between image and text (support various screen
// densities)
int dp5 = (int) (5 * getResources().getDisplayMetrics().density + 0.5f);
textView.setCompoundDrawablePadding(dp5);
return view;
}
};
}
private class Item {
public String file;
public int icon;
public Item(String file, Integer icon) {
this.file = file;
this.icon = icon;
}
#Override
public String toString() {
return file;
}
}
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
AlertDialog.Builder builder = new Builder(this);
if (fileList == null) {
Log.e(TAG, "No files loaded");
dialog = builder.create();
return dialog;
}
switch (id) {
case DIALOG_LOAD_FILE:
builder.setTitle("Choose your file");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
chosenFile = fileList[which].file;
File sel = new File(path + "/" + chosenFile);
if (sel.isDirectory()) {
firstLvl = false;
// Adds chosen directory to list
str.add(chosenFile);
fileList = null;
path = new File(sel + "");
loadFileList();
removeDialog(DIALOG_LOAD_FILE);
showDialog(DIALOG_LOAD_FILE);
Log.d(TAG, path.getAbsolutePath());
}
// Checks if 'up' was clicked
else if (chosenFile.equalsIgnoreCase("up") && !sel.exists()) {
// present directory removed from list
String s = str.remove(str.size() - 1);
// path modified to exclude present directory
path = new File(path.toString().substring(0,
path.toString().lastIndexOf(s)));
fileList = null;
// if there are no more directories in the list, then
// its the first level
if (str.isEmpty()) {
firstLvl = true;
}
loadFileList();
removeDialog(DIALOG_LOAD_FILE);
showDialog(DIALOG_LOAD_FILE);
Log.d(TAG, path.getAbsolutePath());
}
// File picked
else {
chosenFile = fileList[which].file;
File test = new File(path + "/" + chosenFile);
sendback(test);
}
}
});
break;
}
dialog = builder.show();
return dialog;
}
Sorry, if it's a bit too long. But that's the entire file picker which is in the onCreate().
I open it by using this code:
Bundle b = new Bundle();
b.putInt("tallet", 1);
Intent i = new Intent(getApplicationContext(), FileExplore.class);
i.putExtras(b);
startActivityForResult(i, 0);
The code works perfectly. But when I press "back" (onBackPressed), it gives me blank (black) screen if I say finish(); .
Right now I'm using this code:
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
Intent backIntent = new Intent(FileExplore.this, AndroidTabLayoutActivity.class);
startActivity(backIntent);
}
Which actually works, but it gives me black screen if I press back once, and then the menu, when I hit the back button again. EDIT: it goes INTO the onBackPressed code on second back-press, not the first.
Here's my onActivityResult code in PhotosActivity (it's a tablayout - photosactivity is just one of the screens):
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
// Bundle b = getIntent().getExtras();
if (resultCode == -1)
{
Bundle b = data.getBundleExtra("FiletoPhoto");
int knappen = b.getInt("number");
String titlen = b.getString("title");
{
Listofsounds los = new Listofsounds();
String shortname = los.puttextonit(titlen, knappen);
putnameinit(shortname,knappen);
}
}
else if (resultCode == 0)
{
//If I press "back" i've made the resultCode to be 0 in the onBackPressed. What should I do here then?
}
}
What should I do so I could just press it once and get back to the menu?
The issue is that when you use this code:
Intent backIntent = new Intent(FileExplore.this, AndroidTabLayoutActivity.class);
startActivity(backIntent);
You are basically creating and starting a new activity of AndroidTabLayoutActivity which already exists, so now there will be two copies of this activity running simultaneously. However, the original activity will be expecting a result as you've called startActivityForResult(). I think the solution to your problem is probably to do a check if the resultCode you are getting back as a onActivityResult is RESULT_OK or whatever successful resultCode you are setting in setResult(...) in FileExplore.
This is really strange because in all of my apps I don't override onBackPressed and yet, I am able to finish the activity without causing any weird side effects.

Categories

Resources