I can't load image from gallery and set it into ImageView - android

I try set image into ImageView from gallery.
public class CollageCreateActivity extends AppCompatActivity {
private static final String TAG ="MyLogs" ;
Draw2d draw2d;
static final int GALLERY_REQUEST = 1;
private final int TAKE_PICTURE_CAMERA = 2;
private Uri mOutputFileUri;
ArrayList<CollageView> collageViewList1;
ArrayList<CollageView> collageViewList2;
float width;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.collage_creator);
collageViewList1 = new ArrayList<>();
collageViewList2 = new ArrayList<>();
Data data = new Data();
draw2d = new Draw2d(this);
LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
FrameLayout frameLayout = (FrameLayout) findViewById(R.id.frame_1);
if (frameLayout != null) {
frameLayout.addView(draw2d);
}
createCollage(data, layout);
if (layout != null) {
layout.bringToFront();
}
click();
}
public void createCollage(Data data, LinearLayout layout) {
ArrayList<Integer> list = new ArrayList<>();
list.add((int) data.getMap().get("mainLayout"));
list.add((int) data.getMap().get("firstLayout"));
list.add((int) data.getMap().get("secondLayout"));
final LinearLayout layout1 = new LinearLayout(this);
final LinearLayout layout2 = new LinearLayout(this);
LinearLayout[] massLay = {layout, layout1, layout2};
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
params.weight = 1;
layout1.setLayoutParams(params);
layout2.setLayoutParams(params);
for (int i = 0; i < (int) data.getMap().get("layButt1"); i++) {
final Button button = new Button(this);
button.setLayoutParams(params);
button.setTextSize(50);
button.setId(i);
button.setPadding(16, 16, 16, 16);
button.setText(R.string.plus);
layout1.addView(button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
layout1.removeView(v);
CollageView collageView = new CollageView(CollageCreateActivity.this);
saveFromGallery();
layout1.addView(collageView);
collageView.setOnTouchListener(new MultiTouchListener());
collageViewList1.add(collageView);
}
});
}
for (int j = 0; j < (int) data.getMap().get("layButt2"); j++) {
Button button2 = new Button(this);
button2.setLayoutParams(params);
button2.setTextSize(50);
button2.setId(j);
button2.setPadding(16, 16, 16, 16);
button2.setText(R.string.plus);
layout2.addView(button2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
layout2.removeView(v);
CollageView collageView = new CollageView(CollageCreateActivity.this);
layout2.addView(collageView);
collageView.setOnTouchListener(new MultiTouchListener());
width = layout2.getWidth();
collageViewList2.add(collageView);
}
});
}
for (int x = 0; x < list.size(); x++) {
if (list.get(x) == 0) {
massLay[x].setOrientation(LinearLayout.HORIZONTAL);
} else {
massLay[x].setOrientation(LinearLayout.VERTICAL);
}
}
layout.addView(layout1);
layout.addView(layout2);
}
public void click() {
Button button = (Button) findViewById(R.id.butt);
if (button != null) {
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < collageViewList1.size(); i++) {
collageViewList1.get(i).setDrawingCacheEnabled(true);
Bitmap bitmap1 = Bitmap.createBitmap(collageViewList1.get(i).getDrawingCache());
collageViewList1.get(i).setDrawingCacheEnabled(false);
draw2d.listBitmap.add(bitmap1);
draw2d.listX.add(collageViewList1.get(i).getX());
draw2d.listY.add(collageViewList1.get(i).getY());
Log.d("TAG", collageViewList1.get(i).getX() + " " + collageViewList1.get(i).getY());
}
for (int i = 0; i < collageViewList2.size(); i++) {
collageViewList2.get(i).setDrawingCacheEnabled(true);
Bitmap bitmap2 = Bitmap.createBitmap(collageViewList2.get(i).getDrawingCache());
collageViewList2.get(i).setDrawingCacheEnabled(false);
draw2d.listBitmap.add(bitmap2);
draw2d.listX.add(collageViewList2.get(i).getX() + width);
draw2d.listY.add(collageViewList2.get(i).getY());
Log.d("TAG", collageViewList1.get(i).getX() + " " + collageViewList1.get(i).getY());
}
draw2d.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(draw2d.getDrawingCache());
draw2d.setDrawingCacheEnabled(false);
draw2d.invalidate();
}
});
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap bitmap = null;
InputStream imageStream = null;
CollageView collageView = new CollageView(CollageCreateActivity.this);
switch(requestCode) {
case GALLERY_REQUEST:
if(resultCode == RESULT_OK){
Uri selectedImage = data.getData();
try {
imageStream=getContentResolver().openInputStream(selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
bitmap= BitmapFactory.decodeStream(imageStream);
Log.d(TAG, "сетим з галереї1");
collageView.setImageBitmap(bitmap);
Log.d(TAG, "сетим з галереї");
}
break;
case TAKE_PICTURE_CAMERA:
if (data != null) {
if (data.hasExtra("data")) {
Bitmap thumbnailBitmap = data.getParcelableExtra("data");
collageView.setImageBitmap(thumbnailBitmap);
}
} else {
collageView.setImageURI(mOutputFileUri);
}
}
}
private void saveFromGallery(){
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, GALLERY_REQUEST);
}
}
When i try set image from folder "drawrable" it's work, but if i try load image and set from gallery it's don't work, all i have "W/EGL_genymotion: eglSurfaceAttrib not implemented" in logs

In this case you will have to create a content provider which will use to share your local (Application's internal) file to the camera activity.when you try to take picture from camera
try this code:
Content provider class
public class MyFileContentProvider extends ContentProvider {
public static final Uri CONTENT_URI =
Uri.parse("content://com.example.camerademo/");
private static final HashMap<String, String> MIME_TYPES = new
HashMap<String, String>();
static {
MIME_TYPES.put(".jpg", "image/jpeg");
MIME_TYPES.put(".jpeg", "image/jpeg");
}
#Override
public boolean onCreate() {
try {
File mFile = new File(getContext().getFilesDir(), "newImage.jpg");
if(!mFile.exists()) {
mFile.createNewFile();
}
getContext().getContentResolver().notifyChange(CONTENT_URI, null);
return (true);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
#Override
public String getType(Uri uri) {
String path = uri.toString();
for (String extension : MIME_TYPES.keySet()) {
if (path.endsWith(extension)) {
return (MIME_TYPES.get(extension));
}
}
return (null);
}
#Override
public ParcelFileDescriptor openFile(Uri uri, String mode)
throws FileNotFoundException {
File f = new File(getContext().getFilesDir(), "newImage.jpg");
if (f.exists()) {
return (ParcelFileDescriptor.open(f,
ParcelFileDescriptor.MODE_READ_WRITE));
}
throw new FileNotFoundException(uri.getPath());
}
#Override
public Cursor query(Uri url, String[] projection, String selection,
String[] selectionArgs, String sort) {
throw new RuntimeException("Operation not supported");
}
#Override
public Uri insert(Uri uri, ContentValues initialValues) {
throw new RuntimeException("Operation not supported");
}
#Override
public int update(Uri uri, ContentValues values, String where,
String[] whereArgs) {
throw new RuntimeException("Operation not supported");
}
#Override
public int delete(Uri uri, String where, String[] whereArgs) {
throw new RuntimeException("Operation not supported");
}
}
Home.java:
public class Home extends Activity implements OnClickListener{
/** Called when the activity is first created. */
private final int CAMERA_RESULT = 1;
private final String Tag = getClass().getName();
Button button1;
ImageView imageView1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button1 = (Button)findViewById(R.id.button1);
imageView1 = (ImageView)findViewById(R.id.imageView1);
button1.setOnClickListener(this);
}
public void onClick(View v) {
PackageManager pm = getPackageManager();
if (pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, MyFileContentProvider.CONTENT_URI);
startActivityForResult(i, CAMERA_RESULT);
} else {
Toast.makeText(getBaseContext(), "Camera is not available",
Toast.LENGTH_LONG).show();
} }
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
super.onActivityResult(requestCode, resultCode, data);
Log.i(Tag, "Receive the camera result");
if (resultCode == RESULT_OK && requestCode == CAMERA_RESULT) {
File out = new File(getFilesDir(), "newImage.jpg");
if(!out.exists()) {
Toast.makeText(getBaseContext(),
"Error while capturing image", Toast.LENGTH_LONG)
.show();
return;
}
Bitmap mBitmap = BitmapFactory.decodeFile(out.getAbsolutePath());
imageView1.setImageBitmap(mBitmap);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
imageView1 = null;
}
}
hope it will help you,otherwise u will contact me my email
id:daminimehra28#gmail.com

Related

Use onActivityResult

I try to get an image what i pick in my gallery.
I cast startActivityForResult because my class not extendess an Activity and i need use onActivityResult for set imageview with the selected image.
My code...
Intent getIntent = new Intent(Intent.ACTION_GET_CONTENT);
getIntent.setType("image/*");
Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
pickIntent.setType("image/*");
Intent chooserIntent = Intent.createChooser(getIntent, "Elegir imagen");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[]{pickIntent});
((Activity)context).startActivityForResult(chooserIntent, INTENT_ELEGIR_IMAGEN);
My onActivityResult
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case INTENT_ELEGIR_IMAGEN:
Uri selectedImageUri = data.getData();
if(selectedImageUri !=null) {
try {
fotoJugador.setImageBitmap(decodeUri(selectedImageUri));
imageSelected = true;
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
break;
}
}
}
If dont have a solution, give a an advice please!!
Thanks!!!
I add complete code
public class SeccionAdapterJugadorEquipoInfo extends RecyclerView.Adapter<com.followup.arielverdugo.followup.SeccionAdapterJugadorEquipoInfo.SeccionJugadorInfoViewHolder> {
private List<Jugador> jugadores;
public Equipo equipo;
private static RecyclerViewClickListener itemListener;
private Context c;
public static class SeccionJugadorInfoViewHolder extends
RecyclerView.ViewHolder{
// each data item is just a string in this case
public ImageView fotoJugador;
//public ImageView escudo;
public TextView nombreJugador;
public TextView nombreEquipo;
public TextView posicion;
public TextView altura;
public CardView cv;
public ImageView menu;
public SeccionJugadorInfoViewHolder(View v) {
super(v);
//fotoJugador = (ImageView) v.findViewById(R.id.fotoEquipoJugadorInfo);
fotoJugador = (ImageView) v.findViewById(R.id.fotoJugador);
nombreJugador = (TextView) v.findViewById(R.id.nombreJugadorInfo);
posicion = (TextView) v.findViewById(R.id.posicionJugadorEquipoInfo);
//nombreEquipo = (TextView) v.findViewById(R.id.nombreEquipoJugadorInfo);
//nombreEquipo = (TextView) v.findViewById(R.id.nombreEquipoJugadorInfo);
cv = (CardView) v.findViewById(R.id.cardViewJugadorEquipoInfo);
menu =(ImageView) v.findViewById(R.id.menu);
final CheckBox checkBox = (CheckBox) v.findViewById(R.id.star);
}
}
public SeccionAdapterJugadorEquipoInfo(Equipo e, List<Jugador> jugadores ,Context c) {
this.equipo = equipo;
this.jugadores = jugadores;
this.c=c;
}
#Override
public com.followup.arielverdugo.followup.SeccionAdapterJugadorEquipoInfo.SeccionJugadorInfoViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.activity_card_jugadorequipoinfo, parent, false);
return new com.followup.arielverdugo.followup.SeccionAdapterJugadorEquipoInfo.SeccionJugadorInfoViewHolder(v);
}
#Override
public void onBindViewHolder(final com.followup.arielverdugo.followup.SeccionAdapterJugadorEquipoInfo.SeccionJugadorInfoViewHolder viewHolder, final int i) {
final int id = jugadores.get(i).getId();
if(jugadores.get(i).getFoto() != null){
Bitmap fotoJugador = BitmapFactory.decodeByteArray(jugadores.get(i).getFoto(), 0, jugadores.get(i).getFoto().length);
viewHolder.fotoJugador.setImageBitmap(fotoJugador);
} else {
viewHolder.fotoJugador.setImageResource(R.drawable.sinimagen);
}
viewHolder.nombreJugador.setText(jugadores.get(i).getNombre() + " " +jugadores.get(i).getApellido());
viewHolder.posicion.setText(jugadores.get(i).getPosicion());
viewHolder.menu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showPopupMenu(viewHolder.menu,i,c,id);
}
});
}
private void showPopupMenu(View view,int position,Context context,int id) {
// inflate menu
PopupMenu popUp = new PopupMenu(view.getContext(),view);
MenuInflater inflater = popUp.getMenuInflater();
inflater.inflate(R.menu.delete_edit_jugadorequipoinfo, popUp.getMenu());
popUp.setOnMenuItemClickListener(new com.followup.arielverdugo.followup.MyMenuItemClickListener(position,c,id));
popUp.show();
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return jugadores.size();
}
}
class MyMenuItemClickListener implements PopupMenu.OnMenuItemClickListener{
private RecyclerView.Adapter lastmAdapter;
private int position;
private Context context;
private int id;
private ImageView fotoJugador;
public static final int INTENT_ELEGIR_IMAGEN = 1;
private Boolean imageSelected = false;
public MyMenuItemClickListener(int positon,Context context,int id) {
this.position=positon;
this.context = context;
this.id = id;
}
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.editarJugadorEquipo:
final Jugador jugadorEditar = JugadorRepository.getInstance(context).findJugadorById(id);
LayoutInflater inflater = (LayoutInflater) context.getSystemService( context.LAYOUT_INFLATER_SERVICE);
final ViewGroup popupViewEditar = (ViewGroup) inflater.inflate(R.layout.dialog_editar_jugador, null);
String nombreAnterior = jugadorEditar.getNombre();
String apellidoAnterior = jugadorEditar.getApellido();
byte[] fotoAnterior = jugadorEditar.getFoto();
EditText nombre = (EditText) popupViewEditar.findViewById(R.id.editarNombreJugador);
nombre.setText(nombreAnterior);
EditText apellido = (EditText) popupViewEditar.findViewById(R.id.editarApellidoJugador);
apellido.setText(apellidoAnterior);
if (fotoAnterior == null)
{
fotoJugador = (ImageView) popupViewEditar.findViewById(R.id.editarFotoJugador);
fotoJugador.setImageResource(R.drawable.anadirimagen);
fotoJugador.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//para ir a la galeria
Intent getIntent = new Intent(Intent.ACTION_GET_CONTENT);
getIntent.setType("image/*");
Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
pickIntent.setType("image/*");
Intent chooserIntent = Intent.createChooser(getIntent, "Elegir imagen");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[]{pickIntent});
//utiliza la constante INTENT_ELEGIR_IMAGEN en onActivityResult
((Activity) context).startActivityForResult(chooserIntent, INTENT_ELEGIR_IMAGEN);
onActivityResult(chooserIntent);
}
});
}
else
{
fotoJugador = (ImageView) popupViewEditar.findViewById(R.id.editarFotoJugador);
Bitmap bitmap = BitmapFactory.decodeByteArray(fotoAnterior, 0, fotoAnterior.length);
fotoJugador.setImageBitmap(bitmap);
fotoJugador.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//para ir a la galeria
Intent getIntent = new Intent(Intent.ACTION_GET_CONTENT);
getIntent.setType("image/*");
Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
pickIntent.setType("image/*");
Intent chooserIntent = Intent.createChooser(getIntent, "Elegir imagen");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[]{pickIntent});
//utiliza la constante INTENT_ELEGIR_IMAGEN en onActivityResult
((Activity) context).startActivityForResult(chooserIntent, INTENT_ELEGIR_IMAGEN);
onActivityResult(chooserIntent);
}
});
}
//se crea y llena el spiner de equipos
List<Equipo> equipos = EquipoRepository.getInstance(context).getEquipos();
ArrayList<String> equiposNombre = new ArrayList<>();
for (int i = 0; i < equipos.size(); i++)
{
equiposNombre.add(equipos.get(i).getNombre());
}
final Spinner spinnerEquipos = (Spinner) popupViewEditar.findViewById(R.id.editarEquipoJugador);
ArrayAdapter<String> adapter;
adapter = new ArrayAdapter<String>(context,R.layout.spinner_equipos, equiposNombre);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Cree una clase NothingSelectedSpinnerAdapter y un xml Spinner_row_selected
spinnerEquipos.setAdapter(adapter);
String compareValue = jugadorEditar.getEquipo().getNombre();
if (!compareValue.equals(null)) {
int spinnerPosition = adapter.getPosition(compareValue);
spinnerEquipos.setSelection(spinnerPosition);
}
//se crea y llena el spinner de posciones
ArrayList<String> posicionesJugadores = new ArrayList<>();
posicionesJugadores.add("Base");
posicionesJugadores.add("Ayuda Base");
posicionesJugadores.add("Alero");
posicionesJugadores.add("Ala Pivot");
posicionesJugadores.add("Pivot");
final Spinner spinnerPosiciones = (Spinner) popupViewEditar.findViewById(R.id.editarPosicionJugador);
ArrayAdapter<String>adapterPosiciones;
adapterPosiciones = new ArrayAdapter<String>(context,R.layout.spinner_posicion, posicionesJugadores);
adapterPosiciones.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerPosiciones.setAdapter(adapterPosiciones);
String compareValuePosicion = jugadorEditar.getPosicion();
if (!compareValuePosicion.equals(null)) {
int spinnerPosition = adapterPosiciones.getPosition(compareValuePosicion);
spinnerPosiciones.setSelection(spinnerPosition);
}
//se crea y llena el spinner de altura
Integer alturaMinima = 160;
Integer alturaMaxima = 221;
Integer step = 1;
String[] myValues = getArrayWithSteps(alturaMinima, alturaMaxima, step);
NumberPicker picker = new NumberPicker(context);
picker.setDisplayedValues(myValues);
picker.setWrapSelectorWheel(false);
final Spinner spinnerAlturas = (Spinner) popupViewEditar.findViewById(R.id.editarAlturaJugador);
ArrayAdapter<String> adapterAltura;
adapterAltura = new ArrayAdapter<String>(context,R.layout.spinner_altura, myValues);
adapterAltura.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerAlturas.setAdapter(adapterAltura);
int alturaJugador = jugadorEditar.getAltura();
String compareValueAltura = Integer.toString(alturaJugador);
if (!compareValueAltura.equals(null)) {
int spinnerPosition = adapterAltura.getPosition(compareValueAltura);
spinnerAlturas.setSelection(spinnerPosition);
}
AlertDialog.Builder builderEditar =
new AlertDialog.Builder(context)
.setTitle("Editar Jugador")
.setPositiveButton("Editar", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// capturar y gaurdadr en bd
final String NOMBRE = (((TextView) popupViewEditar.findViewById(R.id.editarNombreJugador)).getText().toString());
final String APELLIDO = (((TextView) popupViewEditar.findViewById(R.id.editarApellidoJugador)).getText().toString());
Bitmap FOTO = null;
FOTO = ((BitmapDrawable) ((ImageView) popupViewEditar.findViewById(R.id.editarFotoJugador)).getDrawable()).getBitmap();
jugadorEditar.setNombre(NOMBRE);
jugadorEditar.setApellido(APELLIDO);
jugadorEditar.setFoto(Utils.getByteArrayFromBitmap(FOTO));
JugadorRepository.getInstance(context).updateJugador(jugadorEditar);
Toast.makeText(context, "Jugador editado", Toast.LENGTH_SHORT).show();
//se refresca el cardview
dialog.dismiss();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builderEditar.setView(popupViewEditar);
builderEditar.show();
break;
case R.id.eliminarJugadorEquipo:
AlertDialog.Builder builderEliminar;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builderEliminar = new AlertDialog.Builder(context, android.R.style.Theme_Material_Dialog_Alert);
} else {
builderEliminar = new AlertDialog.Builder(context);
}
builderEliminar.setTitle("Delete entry")
.setMessage("Are you sure you want to delete this entry?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
JugadorRepository.getInstance(context).deleteJugadorById(id);
Equipo e = EquipoRepository.getInstance(context).findEquipoById(JugadorEquipoInfoActivity.idEquipo);
lastmAdapter = new com.followup.arielverdugo.followup.SeccionAdapterJugadorEquipoInfo(e,new ArrayList<Jugador>(e.jugadores),context);
FragmentJugadorEquipoInfo.mRecyclerViewStatic.setAdapter(lastmAdapter);
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
dialog.cancel();
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
break;
default:
}
return false;
}
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case INTENT_ELEGIR_IMAGEN:
Uri selectedImageUri = data.getData();
if(selectedImageUri !=null) {
try {
fotoJugador.setImageBitmap(decodeUri(selectedImageUri));
imageSelected = true;
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
break;
}
}
}
private Bitmap decodeUri(Uri selectedImage) throws FileNotFoundException {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(context.getContentResolver().openInputStream(selectedImage), null, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 150;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE) {
break;
}
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(context.getContentResolver().openInputStream(selectedImage), null, o2);
}
public String[] getArrayWithSteps(Integer iMinValue,Integer iMaxValue, Integer iStep)
{
double iStepsArray = iMaxValue-iMinValue; //obtengo el largo del array
String[] arrayValues= new String[(int)iStepsArray]; //creo un array de ese largo
arrayValues[0] = String.valueOf(iMinValue);
for(int i = 1; i < iStepsArray; i++)
{
arrayValues[i] = String.valueOf(Integer.parseInt(arrayValues[i-1])+iStep);
}
return arrayValues;
}
In my activty i have a recyclerview and my cardview. In my cardview i have a overflowmenu, it has a 2 items: *Delete and *edit
When you click on edit, i create an dialog with the attributes to edit and one of this is an image. I have an imageview and when you click on it launch pick intent to pick an image in gallery. All at this poinr are OK, but i cant set imageview because i cant get the image that i pick.
First of all please ask for permission to access External/Internal Storage.
For picking a picture from gallery use below code.
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, 0);
Your onActivityResult will be like:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0 && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri uri = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
fotoJugador.setImageBitmap(bitmap);
imageSelected = true;
} catch (IOException e) {
e.printStackTrace();
}
}
}
Remove onActivityResult(chooserIntent);from your code.
Run this and let me know if this works.

How to add picture from gallery or taken with camera into a ListView dinamically using 2 activities and a custom adapter

I have two activity:
First activity: MyCollectionActivity
In this activity I have a TextView for title, a ListView - to show my list of stamps and a FloatingButtonAction.
When I click on the FloatingButtonAction I want to start my second activity that I'm talking about: InsertStampActivity.
Second activity: InsertStampActivity
InsertStampActivity where I have 3 EditText (inserting country, value, year), an ImageButton and an empty ImageView(for the inserted image). When I click on the ImageButton it will pop up an AlertDialogBox with 3 buttons: Button - FROM GALLERY, Button - TAKE PHOTO or Button - EXIT.
When I click on FROM GALLERY I want to select a picture from my phone's gallery, when I click on TAKE PHOTO to open phone's camera to take photo and when I click on EXIT, to return to MyCollectionActivity.
For this to happend I want to use an CustomAdapter.
---My problem is how to manage the inserted image.---
My CLASS Timbru (meaning stamp):
public class Timbru implements Parcelable {
private Integer year;
private String country;
private Float value;
private String imagePath;
public Timbru(int year, String country, float value, String imagePath) {
this.year = year;
this.country = country;
this.value = value;
this.imagePath = imagePath;
}
public Timbru() {
}
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
public Integer getYear() {
return year;
}
public void setYear(Integer year) {
this.year = year;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public Float getValue() {
return value;
}
public void setValue(Float value) {
this.value = value;
}
#Override
public String toString() {
return "Timbru{" +
"year=" + year +
", country='" + country + '\'' +
", value=" + value +
", imagePath='" + imagePath + '\'' +
'}';
}
public Timbru(Parcel in) {
this.year = in.readInt();
this.country = in.readString();
this.value = in.readFloat();
}
public static Parcelable.Creator<Timbru> CREATOR = new Creator<Timbru>() {
#Override
public Timbru createFromParcel(Parcel parcel) {
return new Timbru(parcel);
}
#Override
public Timbru[] newArray(int i) {
return new Timbru[i];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeInt(year);
parcel.writeString(country);
parcel.writeFloat(value);
}
}
This is a class for keeping the List:
public class ListaTimbru {
private static ArrayList<Timbru> timbre = new ArrayList<>();
public static ArrayList<Timbru> getTimbre() {
return timbre;
}
public ListaTimbru() {
}
}
This is TimbruAdapter class:
public class TimbruAdapter extends ArrayAdapter {
private int resource;
private List<Timbru> objects;
private LayoutInflater inflater;
public TimbruAdapter(#NonNull Context context, #LayoutRes int resource, #NonNull List objects, LayoutInflater inflater) {
super(context, resource, objects);
this.inflater = inflater;
this.resource = resource;
this.objects = objects;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View row = inflater.inflate(this.resource, parent, false);
TextView tvYear = (TextView) row.findViewById(R.id.tv_year_rowLayout2);
TextView tvCountry = (TextView) row.findViewById(R.id.tv_country_rowLayout2);
TextView tvValue = (TextView) row.findViewById(R.id.tv_value_rowLayout2);
Timbru timbru = objects.get(position);
tvCountry.setText(timbru != null && timbru.getCountry() != null ? timbru.getCountry() : "");
tvYear.setText(timbru != null && timbru.getYear() != null ? timbru.getYear().toString() : "");
tvValue.setText(timbru != null && timbru.getValue() != null ? timbru.getValue().toString() : "");
return row;
}
}
This is MyCollectionActivity:
public class MyColectionActivity extends AppCompatActivity {
FloatingActionButton fltBtn_insert;
ListView listViewStamps;
List<String> listStamps = new ArrayList<>();
List<Timbru> listStamps2 = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_colection);
fltBtn_insert = (FloatingActionButton)
findViewById(R.id.flBtn_insertNewStamp_myCollection);
listViewStamps = (ListView)
findViewById(R.id.lv_stampList_myCollection);
TimbruAdapter adapter = new TimbruAdapter(getApplicationContext(), R.layout.row_layout2, ListaTimbru.getTimbre(), getLayoutInflater());
listViewStamps.setAdapter(adapter);
fltBtn_insert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), InsertStampActivity.class);
startActivityForResult(intent, Constants.ADD_STAMP_REQUEST_CODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Constants.ADD_STAMP_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
Timbru result = data.getParcelableExtra(Constants.ADD_STAMP_KEY);
if (result != null) {
ListaTimbru.getTimbre().add(result);
TimbruAdapter currentAdapter = (TimbruAdapter) listViewStamps.getAdapter();
currentAdapter.notifyDataSetChanged();
}
}
}
This is InsertStampActivity:
public class InsertStampActivity extends AppCompatActivity {
EditText et_year;
EditText et_country;
EditText et_value;
Intent intent;
Button insertStamp;
ImageView poza_timbru;
Uri imageUri;
static final int PICK_IMAGE_REQUEST=1;
static final int REQUEST_IMAGE_TAKEN=2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert_stamp);
initializareComponente();
intent = getIntent();
}
private void initializareComponente() {
et_year = (EditText) findViewById(R.id.et_year_insertStamp);
et_country = (EditText) findViewById(R.id.et_country_insertStamp);
et_value = (EditText) findViewById(R.id.et_value_insertStamp);
poza_timbru = (ImageView) findViewById(R.id.imgView_stampAdded_insertStamp);
insertStamp = (Button) findViewById(R.id.btn_insertStamp);
insertStamp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (validation()) {
Timbru timbru = createTimbruFromComponents();
if (timbru != null) {
intent.putExtra(ADD_STAMP_KEY, timbru);
setResult(RESULT_OK, intent);
finish();
}
}
}
});
}
private Timbru createTimbruFromComponents() {
Integer year = Integer.parseInt(et_year.getText().toString());
String country = et_country.getText().toString();
Float value = Float.parseFloat(et_value.getText().toString());
Uri selectedImage=intent.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
int columnIndex = 0;
String picturePath = null;
if (cursor != null) {
cursor.moveToFirst();
columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
}
return new Timbru(year, country, value,picturePath);
}
private boolean validation() {
//only for EditTexts
if (et_year.getText() == null || et_year.getText().toString().trim().isEmpty() || et_year.getText().toString().length() < 4) {
Toast.makeText(getApplicationContext(), "Year is not valid", Toast.LENGTH_SHORT).show();
}
if (et_country.getText() == null || et_country.getText().toString().trim().isEmpty()) {
Toast.makeText(getApplicationContext(), "Country is not valid", Toast.LENGTH_SHORT).show();
}
if (et_value.getText() == null || et_value.getText().toString().trim().isEmpty()) {
Toast.makeText(getApplicationContext(), "Value is not valid", Toast.LENGTH_SHORT).show();
}
return true;
}
public void imgBtn_insertImagine(View view) {
//DIALOG BOX
final Dialog dialog = new Dialog(getApplicationContext());
dialog.setContentView(R.layout.custom_dialog_box);
dialog.setTitle("PICK ONE");
Button exit = (Button) findViewById(R.id.btnExit_dialogBox);
exit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
dialog.findViewById(R.id.btnForGallery_dialogBox).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openGallery();
}
});
dialog.findViewById(R.id.btnTakePhoto_dialogBox).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openCamera();
}
});
dialog.show();
}
public void openCamera() {
Intent intentCamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intentCamera.resolveActivity(getPackageManager()) != null) {
String fileName = "temp.jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, REQUEST_IMAGE_TAKEN);
}
}
public void openGallery() {
Intent intentGallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*"); //arata doar imagini, nu si video sau altceva
startActivityForResult(intentGallery, PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case PICK_IMAGE_REQUEST:
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
int columnIndex = 0;
String picturePath = null;
if (cursor != null) {
cursor.moveToFirst();
columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
}
Timbru timbru = new Timbru();
timbru.setCountry("Madagascar");
timbru.setValue(20.4f);
timbru.setImagePath(picturePath);
timbru.setYear(1200);
ListaTimbru.getTimbre().add(timbru);
}
break;
case REQUEST_IMAGE_TAKEN:
if (requestCode == REQUEST_IMAGE_TAKEN && resultCode == RESULT_OK) {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(imageUri, projection, null, null, null);
int column_index_data = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String picturePath = cursor.getString(column_index_data);
Timbru timbru = new Timbru();
timbru.setCountry("Australia");
timbru.setValue(55.5f);
timbru.setImagePath(picturePath);
timbru.setYear(1800);
ListaTimbru.getTimbre().add(timbru);
}
break;
}
}
}
In the same Activity(InsertStampActivity) you can use this code to display image from camera & gallery to imageview
case REQUEST_IMAGE_TAKEN:
if (requestCode == REQUEST_IMAGE_TAKEN && resultCode == RESULT_OK)
{
Bitmap photo = (Bitmap) data.getExtras().get("data");
poza_timbru.setImageBitmap(photo); //poza_timbru is your imageview.
}
case PICK_IMAGE_REQUEST:
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null)
{
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
poza_timbru.setImageBitmap(thumbnail); //poza_timbru is your imageview.
}
Then in adapter class view add one imageview in R.Layout.row_layout2 pass your data to adapter class then display it in listview.
Hope it helps..!

My Fragment doesn't get destroyed after it is recreated

I am developing a gallery application, I display all the icons from the external storage into my application. I followed the tutorial from the below link and it is working.
https://deepshikhapuri.wordpress.com/2017/03/20/get-all-images-from-gallery-in-android-programmatically/
Now in addition to this, I provide an option for the user to take a picture from the application and save it to the gallery. When the picture is taken using the Camera intent, the image gets actually saved in the gallery. But I have to intent to another fragment and come back to the Gallery to see the picture I have taken.
To see the changes immediately, onActivityResult() of the Camera intent, I am recreating the fragment. But the problem occurs when we click the back button. The recreated fragment stays in the backstack forever. I am brain faded searching for answers. Any help is appreciated.
Please find below what I have tried so far.
public class GalleryFragment extends Fragment {
Toolbar toolbar;
MenuItem search;
public static ArrayList<Model_images> al_images = new ArrayList<>();
boolean boolean_folder;
Adapter_PhotosFolder obj_adapter;
GridView gv_folder;
FloatingActionButton cameraButton;
private static final int REQUEST_PERMISSIONS = 100;
static final int REQUEST_TAKE_PHOTO = 1;
static final int REQUEST_IMAGE_CAPTURE = 1;
String projectName = "ProjectGA";
File directory;
String mCurrentPhotoPath;
List<GridViewItem> gridItems;
GridView gridView;
public static GalleryFragment newInstance(){
GalleryFragment galleryFragment = new GalleryFragment();
return galleryFragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
directory = new File(Environment.getExternalStorageDirectory() + projectName);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_gallery, container, false);
toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
ImageView icon = (ImageView) getActivity().findViewById(R.id.toolbarIcon);
icon.setImageResource(R.drawable.ic_perm_media_black_24dp);
icon.setColorFilter(getResources().getColor(R.color.Gallery));
TextView title = (TextView) getActivity().findViewById(R.id.toolbarTitle);
title.setText(getString(R.string.galleryLabel));
title.setTextColor(getResources().getColor(R.color.textInputEditTextColor));
toolbar.setBackground(getResources().getDrawable(R.drawable.tile_green));
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_menu_green_24dp));
cameraButton = (FloatingActionButton) getActivity().findViewById(R.id.rightActionButton);
cameraButton.setVisibility(View.VISIBLE);
cameraButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
//gridView = (GridView) view.findViewById(R.id.gridView);
gv_folder = (GridView)view.findViewById(R.id.gv_folder);
gv_folder.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getContext(), PhotosActivity.class);
intent.putExtra("value",i);
startActivity(intent);
}
});
if ((ContextCompat.checkSelfPermission(getContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) && (ContextCompat.checkSelfPermission(getContext(),
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
if ((ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.WRITE_EXTERNAL_STORAGE)) && (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.READ_EXTERNAL_STORAGE))) {
} else {
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSIONS);
}
}else {
Log.e("Else","Else");
fn_imagespath();
}
setHasOptionsMenu(true);
return view;
}
#Override
public void onDestroyView() {
cameraButton.setVisibility(View.INVISIBLE);
super.onDestroyView();
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {photoFile = createImageFile();
} catch (IOException ex) {
Context context = getContext();
CharSequence text = "Photo cannot be stored.";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
// Continue only if the File was successfully created
if (photoFile != null) {
Context context = getContext();
Uri photoURI = FileProvider.getUriForFile(context,
"com.example.projectga.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}else{
Context context = getContext();
CharSequence text = "Attention! Required to take picture!!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
}
public void createFolder(){
if (!directory.exists()){
directory.mkdirs();
}
}
private File createImageFile() throws IOException {
createFolder();
// Create an image file name
Context context = getContext();
String timeStamp = new SimpleDateFormat("dd-MMM-yyyy").format(new Date());
String imageFileName = projectName + "_" + timeStamp + "_";
File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
addImageToGallery(image, context);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getPath();
return image;
}
public static void addImageToGallery(File image, final Context context) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.MediaColumns.DATA, image.toString());
context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
getFragmentManager().beginTransaction()
.replace(R.id.container_gaFragments, GalleryFragment.newInstance()).commit();
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
search = menu.add("search").setIcon(R.drawable.ic_search_green_24dp).setShowAsActionFlags(1);
super.onCreateOptionsMenu(menu, inflater);
}
public ArrayList<Model_images> fn_imagespath() {
al_images.clear();
int int_position = 0;
Uri uri;
Cursor cursor;
int column_index_data, column_index_folder_name;
String absolutePathOfImage = null;
uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.MediaColumns.DATA, MediaStore.Images.Media.BUCKET_DISPLAY_NAME};
final String orderBy = MediaStore.Images.Media.DATE_TAKEN;
cursor = getContext().getContentResolver().query(uri, projection, null, null, orderBy + " DESC");
column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
column_index_folder_name = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
while (cursor.moveToNext()) {
absolutePathOfImage = cursor.getString(column_index_data);
Log.e("Column", absolutePathOfImage);
Log.e("Folder", cursor.getString(column_index_folder_name));
for (int i = 0; i < al_images.size(); i++) {
if (al_images.get(i).getStr_folder().equals(cursor.getString(column_index_folder_name))) {
boolean_folder = true;
int_position = i;
break;
} else {
boolean_folder = false;
}
}
if (boolean_folder) {
ArrayList<String> al_path = new ArrayList<>();
al_path.addAll(al_images.get(int_position).getAl_imagepath());
al_path.add(absolutePathOfImage);
al_images.get(int_position).setAl_imagepath(al_path);
} else {
ArrayList<String> al_path = new ArrayList<>();
al_path.add(absolutePathOfImage);
Model_images obj_model = new Model_images();
obj_model.setStr_folder(cursor.getString(column_index_folder_name));
obj_model.setAl_imagepath(al_path);
al_images.add(obj_model);
}
}
for (int i = 0; i < al_images.size(); i++) {
Log.e("FOLDER", al_images.get(i).getStr_folder());
for (int j = 0; j < al_images.get(i).getAl_imagepath().size(); j++) {
Log.e("FILE", al_images.get(i).getAl_imagepath().get(j));
}
}
obj_adapter = new Adapter_PhotosFolder(getContext(),al_images);
gv_folder.setAdapter(obj_adapter);
return al_images;
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_PERMISSIONS: {
for (int i = 0; i < grantResults.length; i++) {
if (grantResults.length > 0 && grantResults[i] == PackageManager.PERMISSION_GRANTED) {
fn_imagespath();
} else {
Toast.makeText(getContext(), "The app was not allowed to read or write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
}
}
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
I also override the onBackPressed() in the Activity. Please help. Also attaching some images to make it clear.
The exact problem of what is happening
Any help is appreciated.

Take Picture From Camera And Show it to the ImageView Android

before i'm so sorry if my post maybe duplicated, but i have another case in this problem, i wanna show an image that i capture from camera in ImageView and after that i save it or upload it into my json file, but after i take the picture, it's stopped in Log.i ("Error", "Maybe Here");
no error in my code but the image cant saved into thumbnail ImageView
Here is my code, i'm using Asyntask
public class StoreTodoDisplayActivity extends AppCompatActivity {
public Context ctx;
Uri imgUri;
ActionBar actionBar;
public static CategoryData category_data_ar[];
public static CategoryData category_data_ar2[];
String targetUrl;
String path = Environment.getExternalStorageDirectory()
+ "/DCIM/Camera/img11.jpg";
public static final String PREFS_NAME = "MyPrefsFile";
SharedPreferences settings;
RestData restData;
ImageData imgData;
public Uri mCapturedImageURI;
public String image_path = "";
Toolbar toolbar;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.camera_display);
targetUrl = Config.getEndPointUrl();
ctx = this.getApplicationContext();
System.gc();
set_Spinner();
set_Spinner2();
// Toolbar show
toolbar = (Toolbar) findViewById(R.id.actionbarCameraDisplay);
setSupportActionBar(toolbar);
final android.support.v7.app.ActionBar abar = getSupportActionBar();
abar.setDisplayShowCustomEnabled(true);
abar.setDisplayShowTitleEnabled(false);
abar.setDisplayHomeAsUpEnabled(true);
abar.setHomeButtonEnabled(true);
// Back button pressed
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onBackPressed();
}
});
settings = getSharedPreferences(PREFS_NAME, 0);
}
#Override
public void onResume() {
if (!UserInfo.loginstatus) {
finish();
}
super.onResume();
}
public void get_pic(View view) {
String fileName = "temp.jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
mCapturedImageURI = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
startActivityForResult(intent, 12345);
}
public void save_img(View view) {
EditText te = (EditText) findViewById(R.id.camera_display_txt);
String msg = te.getText().toString();
Spinner sp = (Spinner) findViewById(R.id.spinner1);
int catid = (int) sp.getSelectedItemId();
String cat = category_data_ar[catid].catid;
Spinner sp2 = (Spinner) findViewById(R.id.spinner2);
int catid2 = (int) sp2.getSelectedItemId();
String cat2 = category_data_ar2[catid2].catid;
ImageUploader uploader = new ImageUploader("display", msg, cat, cat2);
uploader.execute(Config.getEndPointUrl() + "/uploadimage.json");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 12345) {
if (resultCode == RESULT_OK) {
getimage getm = new getimage();
getm.execute();
}
}
}
public void set_Spinner2() {
Spinner sp = (Spinner) findViewById(R.id.spinner2);
sp.setVisibility(View.VISIBLE);
CatProductHelper helper = new CatProductHelper(ctx);
category_data_ar2 = helper.getCategories();
String[] isidesc = new String[category_data_ar2.length];
for (int k = 0; k < category_data_ar2.length; k++) {
isidesc[k] = category_data_ar2[k].catdesc;
Log.i("AndroidRuntime", "Desc -- " + category_data_ar2[k].catdesc);
}
ArrayAdapter spinnerArrayAdapter = new ArrayAdapter(
StoreTodoDisplayActivity.this,
android.R.layout.simple_spinner_item, isidesc);
spinnerArrayAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(spinnerArrayAdapter);
}
public void set_Spinner() {
// set list activity
Spinner sp = (Spinner) findViewById(R.id.spinner1);
category_data_ar = StoreInfo.storeDisplayCat;
try {
String[] isidesc = new String[category_data_ar.length];
Log.i("toTry", "Normal");
for (int k = 0; k < category_data_ar.length; k++) {
isidesc[k] = category_data_ar[k].catdesc;
Log.i("AndroidRuntime", "Desc -- "
+ category_data_ar[k].catdesc);
}
ArrayAdapter spinnerArrayAdapter = new ArrayAdapter(
StoreTodoDisplayActivity.this,
android.R.layout.simple_spinner_item, isidesc);
spinnerArrayAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(spinnerArrayAdapter);
} catch (Exception e) {
Log.i("toCatch", "NULL EXCEPTION");
DisplayCatHelper helperDisplayCat = new DisplayCatHelper(ctx);
CategoryData[] displayCat = helperDisplayCat.getCategories();
String[] isidesc = new String[displayCat.length];
for (int k = 0; k < displayCat.length; k++) {
isidesc[k] = displayCat[k].catdesc;
Log.i("AndroidRuntime", "Desc -- " + displayCat[k].catdesc);
}
ArrayAdapter spinnerArrayAdapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, isidesc);
spinnerArrayAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(spinnerArrayAdapter);
}
}
private class ImageUploader extends AsyncTask<String, String, String> {
ProgressDialog dialog;
private String url;
private String cameraType;
private String cameraMsg;
private String cameraCat;
private String catproduct;
public ImageUploader(String type, String msg, String cat, String cat2) {
cameraType = type;
cameraMsg = msg;
cameraCat = cat;
catproduct = cat2;
}
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(StoreTodoDisplayActivity.this, "",
"Uploading...", false);
// none
}
#Override
protected String doInBackground(String... params) {
url = params[0];
Log.i("ncdebug", "upload image to: " + url);
try {
if (image_path.equals("")) {
Log.i("ncdebug", "bmp kosong!!!!");
} else {
Log.i("ncdebug", "Ok bmp gak kosong, mari kirim");
restData = new RestData();
imgData = new ImageData();
restData.setTitle("Display : " + StoreInfo.storename);
restData.setRequestMethod(RequestMethod.POST);
restData.setUrl(url);
imgData.setImageData(url, image_path, cameraMsg, cameraCat
+ "-" + catproduct, UserInfo.username,
StoreInfo.storeid, cameraType, UserInfo.checkinid);
saveToDb();
return "Success";
}
} catch (Exception e) {
//saveToDb();
}
return "Penyimpanan gagal, ulangi tahap pengambilan gambar";
}
#Override
protected void onPostExecute(String Result) {
dialog.dismiss();
if (Result.equals("Success")) {
Toast.makeText(ctx, "Data tersimpan", Toast.LENGTH_SHORT)
.show();
// checked todo
String vVar = StoreInfo.storeid + "-" + UserInfo.username
+ "-displaycam";
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(vVar, true);
editor.commit();
Intent intent = new Intent(ctx, StoreTodoActivity.class);
startActivity(intent);
finish();
} else {
Toast.makeText(ctx, Result, Toast.LENGTH_LONG)
.show();
}
}
}
public void saveToDb() {
Log.i("eris", "connection failed so save to db");
RestHelper helper = new RestHelper(ctx);
helper.insertRest(restData);
imgData.setRestId(helper.getRestId());
Log.i("REST ID", helper.getRestId());
ImageHelper imgHelper = new ImageHelper(ctx);
imgHelper.insertRest(imgData);
}
public class getimage extends AsyncTask<String, String, String> {
String orientation = "";
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
// Log.i("INI BACKGROUND", "LIHAT");
try {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(mCapturedImageURI, projection,
null, null, null);
int column_index_data = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String capturedImageFilePath = cursor
.getString(column_index_data);
String parentPath = Environment.getExternalStorageDirectory()
+ "/Nestle Confect";
String filename = System.currentTimeMillis() + ".jpg";
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = 4;
Bitmap bmp = BitmapFactory.decodeFile(capturedImageFilePath,
opts);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File file = new File(parentPath);
file.mkdir();
try {
file.createNewFile();
Log.i("absoulute path", file.getAbsolutePath());
FileOutputStream fo = new FileOutputStream(file + "/"
+ filename, true);
// 5
fo.write(bytes.toByteArray());
fo.close();
image_path = parentPath + "/" + filename;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
image_path = capturedImageFilePath;
}
byte[] thumb = null;
try {
ExifInterface exif = new ExifInterface(
capturedImageFilePath);
orientation = exif
.getAttribute(ExifInterface.TAG_ORIENTATION);
thumb = exif.getThumbnail();
} catch (IOException e) {
}
if (thumb != null) {
Log.i("IMAGEVIEW", "THUMBNAIL");
bitmap = BitmapFactory.decodeByteArray(thumb, 0,
thumb.length);
} else {
Log.i("IMAGEVIEW", "REALFILE");
return "not fine";
}
return "fine";
} catch (Exception e) {
return "not fine";
}
}
#Override
public void onPostExecute(String result) {
// PROBLEM HERE
Log.i("ERROR", "HERE MAYBE");
if (result.equals("fine")) {
ImageView gambarHasil = (ImageView) findViewById(R.id.camera_display_img);
gambarHasil.setImageBitmap(bitmap);
if (!orientation.equals("1")) {
Log.i("ORIENTATION", orientation);
float angel = 0f;
if (orientation.equals("6")) {
angel = 90f;
} else if (orientation.equals("8")) {
angel = -90f;
}
Matrix matrix = new Matrix();
gambarHasil.setScaleType(ScaleType.MATRIX); // required
matrix.postRotate((float) angel, gambarHasil.getDrawable()
.getBounds().width() / 2, gambarHasil.getDrawable()
.getBounds().height() / 2);
gambarHasil.setImageMatrix(matrix);
}
} else {
Toast.makeText(
ctx,
"Error, Try To Take Picture Again",
Toast.LENGTH_LONG).show();
}
}
}
}
I think your activity just got restarted you need to put below code in manifest where you declare. and save your uri on saveInstanceState and restore it on onrestoreinstancestate. it will be resolve your issue
android:configChanges="orientation|keyboardHidden|screenSize"
Use this lib,Provides support above API 14
https://github.com/google/cameraview

adapter holder on listener cannot be final

I need to add a progress listener to each element of the horizontal list view, how can I do that?
For each item I upload a file.
I wanna to do something like that but holder is not final, so I have an error.
public class UploadsViewAdapter extends BaseAdapter {
private Context mContext;
private int mLayoutResourceId;
List<Upload> listFileToUpload;
public UploadsViewAdapter(Context context, int layoutResourceId, List<Upload> data) {
this.mLayoutResourceId = layoutResourceId;
this.mContext = context;
this.listFileToUpload = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
row = inflater.inflate(mLayoutResourceId, parent, false);
holder = new ViewHolder();
holder.image = (ImageView) row.findViewById(R.id.upload_item_image);
holder.progressUpdate = (ProgressBar) row.findViewById(R.id.progressUpdate);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
final Upload item = getItem(position);
holder.image.setImageBitmap(item.getThumbnail(160, 160));
item.setProgressListener(new ProgressListener() {
#Override
public void onProgress(int progress) {
holder.progressUpdate.setProgress(item.getProgress());
}
});
holder.progressUpdate.setProgress(item.getProgress());
return row;
}
static class ViewHolder {
ImageView image;
ProgressBar progressUpdate;
}
public void updateListFileToUpdate(List<Upload> listFileToUpload) {
this.listFileToUpload = listFileToUpload;
}
#Override
public int getCount() {
return listFileToUpload.size();
}
#Override
public Upload getItem(int location) {
return listFileToUpload.get(location);
}
#Override
public long getItemId(int position) {
return 0;
}
}
Class Update.java
public class Upload {
public String path;
public String type;
private int mProgress = 0;
private ProgressListener mListener;
public Upload(String path, String type) {
this.path = path;
this.type = type;
}
public void setProgressListener(ProgressListener listener) {
mListener = listener;
}
public void setProgress(int progress) {
mProgress = progress;
if (mListener != null) {
mListener.onProgress(progress);
}
}
public int getProgress() {
return mProgress;
}
public Bitmap getThumbnail(int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while (
(halfHeight / inSampleSize) > reqHeight &&
(halfWidth / inSampleSize) > reqWidth
) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
public interface ProgressListener {
public void onProgress(int progress);
}
}
Class which updates the file:
public class TheFormFragment extends Fragment {
private AmazonS3Client mS3Client = new AmazonS3Client(
new BasicAWSCredentials(Config.AWS_ACCESS_KEY, Config.AWS_SECRET_KEY));
public static final int RESULT_PHOTO_DISK = 10;
public static final int RESULT_PHOTO_APN = 100;
public static final int RESULT_VIDEO_APN = 1000;
public static final String INTENT_PHOTO_APN_PATH = "INTENT_PHOTO_APN_PATH";
public static final String INTENT_VIDEO_APN_PATH = "INTENT_VIDEO_APN_PATH";
private List<Medias> mTheFormPictures;
private static Activity mActivity;
private static ArrayList<Upload> mQueue;
private KeyboardEventLinearLayout mLinearLayoutBackground;
private LinearLayout mLinearLayoutPublish;
private TextView mTextViewPublish;
private ImageView mImageViewPublish; // todo image du bouton
private EditText mEditTextText;
private TextView mTextViewTitle;
private CircularImageView mCircularImageViewAvatar;
private ImageButton mImageButtonClose;
private ImageButton mImageButtonCamera;
private ImageButton mImageButtonLibrary;
private Tag[] mTags = null;
private Range mAutocompleting;
private LinearLayout mAutocompleteContainer;
private HorizontalListView mUploadsList;
private UploadsViewAdapter mUploading;
/**Contains list of images, vidoe to update*/
private List<Upload> listFileToUpload;
private KeyboardEventLinearLayout.KeyboardListener mKeyboardListener = new KeyboardEventLinearLayout.KeyboardListener() {
#Override
public void onShow() {
if (mUploadsList != null) {
mUploadsList.setVisibility(View.GONE);
}
}
#Override
public void onHide() {
if (mUploadsList != null) {
mUploadsList.setVisibility(View.VISIBLE);
}
}
};
private class Range {
public int start;
public int end;
public String value;
public Range(int start, int end, String value) {
this.start = start;
this.end = end;
this.value = value;
}
}
private TextWatcher textWatcher = new TextWatcher() {
#Override
public void onTextChanged(CharSequence text, int start, int oldCount, int newCount) {
String before = text.subSequence(0, start + newCount).toString();
Range range = findEditingTag(before);
autocompete(range);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void afterTextChanged(Editable s) {}
};
private OnClickListener mAutocompleteItemClickListener = new OnClickListener() {
#Override
public void onClick(View view) {
Editable text = mEditTextText.getText();
CharSequence tag = ((TextView) view).getText();
text.replace(mAutocompleting.start, mAutocompleting.end, tag);
}
};
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mActivity = activity;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_the_form, container, false);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
mTheFormPictures = new ArrayList<Medias>();
mQueue = new ArrayList<Upload>();
mS3Client.setRegion(Region.getRegion(Config.AWS_REGION));
mLinearLayoutBackground = (KeyboardEventLinearLayout) mActivity.findViewById(R.id.linearLayoutBackground);
mLinearLayoutPublish = (LinearLayout) mActivity.findViewById(R.id.linearLayoutPublish);
mTextViewPublish = (TextView) mActivity.findViewById(R.id.textViewPublish);
mTextViewTitle = (TextView) mActivity.findViewById(R.id.textViewTitle);
mImageViewPublish = (ImageView) mActivity.findViewById(R.id.imageViewPublish);
mCircularImageViewAvatar = (CircularImageView) mActivity.findViewById(R.id.circularImageViewAvatar);
mEditTextText = (EditText) mActivity.findViewById(R.id.editTextText);
mImageButtonClose = (ImageButton) mActivity.findViewById(R.id.imageButtonClose);
mImageButtonCamera = (ImageButton) mActivity.findViewById(R.id.imageButtonCamera);
mImageButtonLibrary = (ImageButton) mActivity.findViewById(R.id.imageButtonLibrary);
mAutocompleteContainer = (LinearLayout) mActivity.findViewById(R.id.autocompleteLayout);
mUploadsList = (HorizontalListView) mActivity.findViewById(R.id.uploadsList);
listFileToUpload =new ArrayList<Upload>();
mUploading = new UploadsViewAdapter(mActivity, R.layout.upload_item, listFileToUpload);
mUploadsList.setAdapter(mUploading);
mLinearLayoutBackground.setKeyboardListener(mKeyboardListener);
configure();
super.onActivityCreated(savedInstanceState);
}
#SuppressLint("NewApi")
#SuppressWarnings("deprecation")
private void configure() {
AQuery aq = new AQuery(mActivity);
ImageOptions options = new ImageOptions();
//options.round = 180;
options.fileCache = false;
options.memCache = true;
//options.animation = AQuery.FADE_IN;
User user = Preferences.getUser(mActivity);
if (user != null) {
mTextViewTitle.setText(user.getFirst_name() + " " + user.getLast_name());
if (user.getAvatar() != null && user.getAvatar().length() > 0) {
aq.id(mCircularImageViewAvatar).image(user.getAvatar(), options);
}
}
StatusConfigTheForm configTheForm = Preferences.getConfigTheForm(mActivity);
if (configTheForm != null) {
Log.i("theform config success");
Log.d("avatar: " + user.getAvatar() + " " + configTheForm.getBorderWidth());
if (configTheForm.getColors().getBackground().length == 3) {
mLinearLayoutBackground.setBackgroundColor(Color.parseColor(Utils.getHexaColor(configTheForm.getColors().getBackground())));
}
if (configTheForm.getColors().getBackgrounPublishButton().length == 3) {
// mButtonPublish.setBackgroundColor(Color.parseColor(Utils.getHexaColor(configTheForm.getColors().getBackgrounPublishButton())));
// prepare
int roundRadius = 6;
// normal state
GradientDrawable background_normal = new GradientDrawable();
background_normal.setColor(Color.parseColor(Utils.getHexaColor(configTheForm.getColors().getBackgrounPublishButton())));
background_normal.setCornerRadius(roundRadius);
// pressed state
GradientDrawable bacground_pressed = new GradientDrawable();
bacground_pressed.setColor(Color.parseColor(Utils.getHexaColor(configTheForm.getColors().getBackgrounPublishButton()).replace("#", "#CC"))); // opacity
bacground_pressed.setCornerRadius(roundRadius);
// states (normal and pressed)
StateListDrawable states = new StateListDrawable();
states.addState(new int[] {android.R.attr.state_pressed}, bacground_pressed);
states.addState(new int[] {-android.R.attr.state_pressed}, background_normal);
if (Build.VERSION.SDK_INT >= 16) {
mLinearLayoutPublish.setBackground(states);
} else {
mLinearLayoutPublish.setBackgroundDrawable(states);
}
}
if (configTheForm.getColors().getBackgroundTextView().length == 3) {
mEditTextText.setBackgroundColor(Color.parseColor(Utils.getHexaColor(configTheForm.getColors().getBackgroundTextView())));
}
if (configTheForm.getColors().getBorderColorPicture().length == 3) {
mCircularImageViewAvatar.setBorderColor(Utils.getHexaColor(configTheForm.getColors().getBorderColorPicture()));
}
// add color tag here
if (configTheForm.getColors().getColorTextPublish().length == 3) {
mTextViewPublish.setTextColor(Color.parseColor(Utils.getHexaColor(configTheForm.getColors().getColorTextPublish())));
}
if (configTheForm.getColors().getColorTextAttachment().length == 3) {
mCircularImageViewAvatar.setBorderColor(Utils.getHexaColor(configTheForm.getColors().getColorTextAttachment()));
}
if (configTheForm.getColors().getColorTextUser().length == 3) {
mTextViewTitle.setTextColor(Color.parseColor(Utils.getHexaColor(configTheForm.getColors().getColorTextUser())));
}
if (configTheForm.getBorderWidth() > 0) {
mCircularImageViewAvatar.setBorderWidth(configTheForm.getBorderWidth() * Integer.valueOf(Float.valueOf(getResources().getDisplayMetrics().density).intValue()));
}
// pictures
if (configTheForm.getPictures() != null) {
String baseUrl = configTheForm.getUrlPicto() + configTheForm.getFolder() + File.separator;
String ext = Utils.setExtension(mActivity, Config.PICTURE_EXTENSION);
Pictures pics = configTheForm.getPictures();
if (configTheForm.getPictures().getPictureBack() != null) {
aq.id(mImageButtonClose).image(baseUrl + pics.getPictureBack() + ext, options);
}
if (configTheForm.getPictures().getPictureCamera() != null) {
aq.id(mImageButtonCamera).image(baseUrl + pics.getPictureCamera() + ext, options);
}
if (configTheForm.getPictures().getPictureLibrary() != null) {
aq.id(mImageButtonLibrary).image(baseUrl + pics.getPictureLibrary() + ext, options);
}
if (configTheForm.getPictures().getPicturePublish() != null) {
mImageViewPublish.setVisibility(View.VISIBLE);
aq.id(mImageViewPublish).image(baseUrl + pics.getPicturePublish() + ext, options);
} else {
mImageViewPublish.setVisibility(View.GONE);
}
}
}
mEditTextText.addTextChangedListener(textWatcher);
}
private Range findEditingTag(String text) {
Pattern pattern = Pattern.compile("#[A-z0-9_]+$");
Matcher match = pattern.matcher(text);
if (match.find()) {
String value = text.substring(match.start());
return new Range(match.start(), match.end(), value);
}
return null;
}
private void autocompete(Range range) {
mAutocompleting = range;
mAutocompleteContainer.removeAllViews();
if (range != null && mTags != null) {
String tag;
for (int i = 0; i < mTags.length; i++) {
tag = "#" + mTags[i].getName();
if (tag.startsWith(range.value) && tag.equals(range.value) == false) {
addAutocompleteItem(tag);
}
}
}
}
#SuppressWarnings("deprecation")
#SuppressLint("NewApi")
private void addAutocompleteItem(String text) {
Drawable background = mActivity.getResources().getDrawable(R.drawable.autocomplete_item);
int textColor = mActivity.getResources().getColor(R.color.autocomplete_item_text);
TextView view = new TextView(mActivity);
view.setText(text);
view.setTextColor(textColor);
view.setPadding(20, 10, 20, 10);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
params.setMargins(10, 0, 10, 0);
view.setLayoutParams(params);
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
view.setBackgroundDrawable(background);
} else {
view.setBackground(background);
}
view.setClickable(true);
view.setOnClickListener(mAutocompleteItemClickListener);
mAutocompleteContainer.addView(view);
}
private void updateProgress() {
//int progress = 0;
//for (Upload file: mUploading) {
// progress += file.getProgress();
//}
//progress /= mUploading.size();
//mProgressBarFile.setProgress(progress);
//mTextViewFileProgress.setText(String.format(getString(R.string.theform_text_file_progress), Integer.valueOf(progress).toString()));
}
private class S3PutObjectTask extends AsyncTask<Upload, Integer, S3TaskResult> {
//private Dialog progressDialog;
ObjectMetadata mMetadata = new ObjectMetadata();
private String mS3Filename;
private Upload mFile;
#Override
protected void onPreExecute() {
updateProgress();
}
#Override
protected void onProgressUpdate(Integer... values) {
int progress = Integer.valueOf( (int) ((values[0] * 100) / mMetadata.getContentLength()) );
mFile.setProgress(progress);
updateProgress();
super.onProgressUpdate(values);
}
protected S3TaskResult doInBackground(Upload... files) {
if (files == null || files.length != 1 || files[0] == null) {
return null;
} else {
mFile = files[0];
}
ContentResolver resolver = mActivity.getContentResolver();
// The file location of the image selected.
Uri selectedSource = Uri.parse(mFile.path);
if (mFile.type.equals("image")) {
String size = null;
String fileSizeColumn[] = { OpenableColumns.SIZE };
Cursor cursor = resolver.query(selectedSource, fileSizeColumn, null, null, null);
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
int sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
// If the size is unknown, the value stored is null. But since an int can't be
// null in java, the behavior is implementation-specific, which is just a fancy
// term for "unpredictable". So as a rule, check if it's null before assigning
// to an int. This will happen often: The storage API allows for remote
// files, whose size might not be locally known.
if (!cursor.isNull(sizeIndex)) {
// Technically the column stores an int, but cursor.getString will do the
// conversion automatically.
size = cursor.getString(sizeIndex);
}
cursor.close();
}
mMetadata.setContentType(resolver.getType(selectedSource));
if (size != null) {
mMetadata.setContentLength(Long.parseLong(size));
}
}
if (mMetadata.getContentType() == null) {
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inJustDecodeBounds = true;
BitmapFactory.decodeFile(selectedSource.toString(), opt);
mMetadata.setContentType(opt.outMimeType);
}
if (mMetadata.getContentLength() <= 0) {
mMetadata.setContentLength(new File(selectedSource.toString()).length());
}
selectedSource = Uri.parse("file://" + selectedSource.toString().replace("content://", ""));
S3TaskResult result = new S3TaskResult();
// Put the image data into S3.
try {
Calendar cal = Calendar.getInstance();
if (mFile.type.equals("image")) {
mS3Filename = Long.valueOf(cal.getTime().getTime()).toString() + ".jpg";
} else {
mS3Filename = Long.valueOf(cal.getTime().getTime()).toString() + ".mp4";
}
PutObjectRequest por = new PutObjectRequest(
Config.getPictureBucket(cal.getTime().getTime()), mS3Filename,
resolver.openInputStream(selectedSource), mMetadata
).withGeneralProgressListener(new ProgressListener() {
int total = 0;
#Override
public void progressChanged(ProgressEvent pv) {
total += (int) pv.getBytesTransferred();
publishProgress(total);
}
});
mS3Client.putObject(por);
result.setName(mS3Filename);
} catch (Exception exception) {
exception.printStackTrace();
result.setName(null);
result.setErrorMessage(exception.getMessage());
}
return result;
}
protected void onPostExecute(S3TaskResult result) {
//mProgressBarFile.setProgress(0);
//mTextViewFileProgress.setText("");
// AWS Error
if (result != null && result.getErrorMessage() != null && result.getName() == null) {
FastDialog.showDialog(mActivity, FastDialog.SIMPLE_DIALOG, result.getErrorMessage());
} else {
// add picture name
mTheFormPictures.add(new Medias(result.getName()));
}
}
}
public static String getRealPathFromUri(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
/** close activity **/
public void close(View v) {
mActivity.finish();
}
/** select picture **/
public void selectPicture(View v) {
//Intent intent;
Intent intent = new Intent(
Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
/*if (Build.VERSION.SDK_INT < 19) {
intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
} else {
intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
}
if (Build.VERSION.SDK_INT >= 18) {
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
}*/
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setType("image/* video/*");
startActivityForResult(intent, RESULT_PHOTO_DISK);
}
/** take picture **/
public void tackePicture(View v) {
ApnActivity.show(mActivity, RESULT_PHOTO_APN);
}
/** record video **/
public void recordVideo(View v) {
RecordVideoActivity.show(mActivity, RESULT_VIDEO_APN);
}
/** publish button **/
public void publish(View v) {
// object
WebViewTheFormResult theFormResult = new WebViewTheFormResult(mEditTextText.getText().toString(), mTheFormPictures);
if (theFormResult.isEmpty()) {
FastDialog.showDialog(mActivity, FastDialog.SIMPLE_DIALOG, getString(R.string.theform_publish_error));
} else {
// intent
Intent dataIntent = new Intent();
Bundle bundle = new Bundle();
bundle.putSerializable(WebViewActivity.INTENT_OBJECT, (Serializable) theFormResult);
dataIntent.putExtras(bundle);
mActivity.setResult(Activity.RESULT_OK, dataIntent);
mActivity.finish();
}
}
#SuppressLint("NewApi")
public static void actionOnActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_CANCELED) {
return;
}
if (requestCode != RESULT_PHOTO_APN && requestCode != RESULT_VIDEO_APN) {
requestCode = RESULT_PHOTO_DISK;
}
switch (requestCode) {
case RESULT_PHOTO_DISK:
if (Build.VERSION.SDK_INT >= 18 && data.getData() == null) {
ClipData clipdata = data.getClipData();
for (int i = 0, l = clipdata.getItemCount(); i < l; i++) {
onDiskResult(clipdata.getItemAt(i).getUri());
}
} else {
onDiskResult(data.getData());
}
break;
case RESULT_PHOTO_APN:
onApnPhotoResult(data);
break;
case RESULT_VIDEO_APN:
onApnVideoResult(data);
break;
}
}
private static void onDiskResult(Uri selectedImage) {
InputStream imageStream;
try {
File file = new File(
Environment.getExternalStorageDirectory() + File.separator +
"Android" + File.separator +
"data" + File.separator +
mActivity.getPackageName()
);
if (new File(file.getAbsolutePath()).exists() == false) {
file.mkdirs();
}
imageStream = mActivity.getContentResolver().openInputStream(selectedImage);
Bitmap goodPicture = BitmapFactory.decodeStream(imageStream);
String filePath = file.getAbsoluteFile().toString() + "/" + String.valueOf(Utils.uid()) + Config.PHOTO_TMP_NAME;
try {
//goodPicture = ThumbnailUtils.createVideoThumbnail(filePath, MediaStore.Images.Thumbnails.MINI_KIND);
FileOutputStream out = new FileOutputStream(filePath);
goodPicture = Bitmap.createScaledBitmap(goodPicture, 800, 600, false);
goodPicture.compress(Bitmap.CompressFormat.JPEG, 80, out);
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
}
queueFile(filePath, "image");
} catch (FileNotFoundException e1) {
e1.printStackTrace();
return;
}
}
private static void onApnPhotoResult(Intent data) {
String filePath = data.getExtras().getString(TheFormFragment.INTENT_PHOTO_APN_PATH);
if (filePath.equals(Integer.valueOf(RESULT_VIDEO_APN).toString())) {
RecordVideoActivity.show(mActivity, RESULT_VIDEO_APN);
} else {
queueFile(filePath, "image");
}
}
private static void onApnVideoResult(Intent data) {
String filePath = data.getExtras().getString(TheFormFragment.INTENT_VIDEO_APN_PATH);
if (filePath.equals(Integer.valueOf(RESULT_PHOTO_APN).toString())) {
ApnActivity.show(mActivity, RESULT_PHOTO_APN);
} else {
queueFile(filePath, "video");
}
}
private static void queueFile(String filePath, String fileType) {
mQueue.add(new Upload(filePath, fileType));
}
#Override
public void onResume() {
fetchTags();
while (mQueue.size() > 0) {
uploadFile(mQueue.remove(mQueue.size() - 1));
}
super.onResume();
}
private void uploadFile(Upload file) {
new S3PutObjectTask().execute(file);
listFileToUpload.add(file);
mUploading.updateListFileToUpdate(listFileToUpload);
mUploading.notifyDataSetChanged();
}
private void fetchTags() {
Api.getTags(mActivity, new Api.Callback() {
#Override
public void onSuccess(String json) {
Gson gson = new Gson();
mTags = gson.fromJson(json, Tag[].class);
}
});
}
}
How can I resolve the problem?
Something like this should be enough:
...
holder.image.setImageBitmap(item.getThumbnail(160, 160));
final ViewHolder finalHolder = holder;
item.setProgressListener(new ProgressListener() {
#Override
public void onProgress(int progress) {
finalHolder.progressUpdate.setProgress(item.getProgress());
}
});
finalHolder.progressUpdate.setProgress(item.getProgress());
Think that you can remove setProgressListener() from Upload class.
Instead add a ProgressBar variable and a method setProgressBar() to Upload.
In getView():
Upload upload = getItem(position )
upload.setProgressBar(holder.progressUpdate);
In Upload: in setProgress() you can now directly address the ProgressBar variable
this is the setProgress() that in your AsyncTask is called with mFile.setProgress(progress);
Instead of removing better out comment the function and the call.
Untested. Please test. This will not be much work.
Don't make holder final. It will not help you. You also made item final in order to use it in onProgress. But that will not do either. You have to determine the right holder with getTag() and if you put position in the holder (as int variable) then you can use holder.position to get the right item again with a getItem(holder.position)
Thanks for your responses all.
I resolved the problem like this:
public class UploadsViewAdapter extends BaseAdapter {
private Context mContext;
List<Upload> listFileToUpload;
UploadsViewAdapter instanceUploadsViewAdapter;
public UploadsViewAdapter(Context context,
List<Upload> data) {
this.mContext = context;
this.listFileToUpload = data;
this.instanceUploadsViewAdapter = this;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
row = inflater.inflate(R.layout.upload_item, parent, false);
holder = new ViewHolder();
holder.image = (ImageView) row.findViewById(R.id.upload_item_image);
holder.play = (ImageView) row.findViewById(R.id.play);
holder.progressUpdate = (ProgressBar) row
.findViewById(R.id.progressUpdate);
holder.deleteFileUploaded = (ImageView) row.findViewById(R.id.delete_file_uploaded);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
final Upload item = getItem(position);
holder.image.setImageBitmap(item.getThumbnail(160, 160));
final ViewHolder finalHolder = holder;
item.setProgressListener(new ProgressListener() {
#Override
public void onProgress(int progress) {
//item.setProgress(progress);
finalHolder.progressUpdate.setProgress(progress);
if(progress==100){
finalHolder.image.setAlpha(1.0f);
finalHolder.progressUpdate.setVisibility(View.GONE);
}
else{
finalHolder.image.setAlpha(0.5f);
finalHolder.progressUpdate.setVisibility(View.VISIBLE);
}
}
});
if(item.getProgress()==100){
finalHolder.image.setAlpha(1.0f);
finalHolder.progressUpdate.setVisibility(View.GONE);
}
else{
finalHolder.image.setAlpha(0.5f);
finalHolder.progressUpdate.setVisibility(View.VISIBLE);
}
holder.deleteFileUploaded.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
listFileToUpload.remove(position);
instanceUploadsViewAdapter.notifyDataSetChanged();
}
});
if(item.getType().equals(EnumTypeFile.IMAGE.getTypeFile())){
holder.play.setVisibility(View.GONE);
}
else{
holder.play.setVisibility(View.VISIBLE);
}
finalHolder.progressUpdate.setProgress(item.getProgress());
return row;
}
static class ViewHolder {
ImageView image;
ProgressBar progressUpdate;
ImageView deleteFileUploaded;
ImageView play;
}
public void updateListFileToUpdate(List<Upload> listFileToUpload) {
this.listFileToUpload = listFileToUpload;
}
#Override
public int getCount() {
return listFileToUpload.size();
}
#Override
public Upload getItem(int location) {
return listFileToUpload.get(location);
}
#Override
public long getItemId(int position) {
return 0;
}
}

Categories

Resources