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.
Related
I am new to Android development.
I am trying to complete my application, this app is saving data into a SQLite database, showing, updating, deleting, etc. But when I try to show all rows from database, this takes too much time. I want to add a ProgressBar to show users that it's taking its time.
Where in this code can I add a ProgressBar?
This is MainActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Instantiate database handler
db=new DatabaseHandler(this);
lv = (ListView) findViewById(R.id.list1);
pic = (ImageView) findViewById(R.id.pic);
nazev =(EditText) findViewById(R.id.nazev);
objem =(EditText) findViewById(R.id.objem);
obsah_alkoholu =(EditText) findViewById(R.id.obsah_alkoholu);
aroma =(EditText) findViewById(R.id.aroma);
chut =(EditText) findViewById(R.id.chut);
dokonceni =(EditText) findViewById(R.id.dokonceni);
poznamka =(EditText) findViewById(R.id.poznamka);
vsechnyradky =(TextView) findViewById(R.id.textView);
ShowRecords();
}
public void buttonClicked(View v){
int id=v.getId();
switch(id){
case R.id.save:
if(nazev.getText().toString().trim().equals("")){
Toast.makeText(getApplicationContext(),"Není název.", Toast.LENGTH_LONG).show();
} else{
addRumy();
}
ShowRecords();
break;
case R.id.display:
ShowRecords();
break;
case R.id.pic:
selectImage();
break;
}
}
public void selectImage(){
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 2);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode) {
case 2:
if(resultCode == RESULT_OK){
Uri choosenImage = data.getData();
if(choosenImage !=null){
bp=decodeUri(choosenImage, 400);
pic.setImageBitmap(bp);
}
}
}
}
//COnvert and resize our image to 400dp for faster uploading our images to DB
protected Bitmap decodeUri(Uri selectedImage, int REQUIRED_SIZE) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, o);
// The new size we want to scale to
// final int REQUIRED_SIZE = size;
// 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(getContentResolver().openInputStream(selectedImage), null, o2);
}
catch (Exception e){
e.printStackTrace();
}
return null;
}
//Convert bitmap to bytes
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
private byte[] profileImage(Bitmap b){
ByteArrayOutputStream bos = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.PNG, 0, bos);
return bos.toByteArray();
}
// function to get values from the Edittext and image
private void getValues(){
f_nazev = nazev.getText().toString();
f_objem = objem.getText().toString();
f_obsah_alkoholu = obsah_alkoholu.getText().toString();
f_aroma = aroma.getText().toString();
f_chut = chut.getText().toString();
f_dokonceni = dokonceni.getText().toString();
f_poznamka = poznamka.getText().toString();
photo = profileImage(bp);
}
//Insert data to the database
private void addRumy(){
getValues();
db.addRumy(new Rumy(f_nazev, f_objem, f_obsah_alkoholu, f_aroma, f_chut, f_dokonceni, f_poznamka, photo));
showProgressDialogHorizontal();
db.close();
}
//Retrieve data from the database and set to the list view
private void ShowRecords(){
final ArrayList<Rumy> rumy = new ArrayList<>(db.getAllRumy());
data=new DataAdapter(this, rumy);
lv.setAdapter(data);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
dataModel = rumy.get(position);
final Dialog openDialog = new Dialog(context2);
openDialog.setContentView(R.layout.dialogove_okno_mazani);
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Souhrn záznamu k odeslání:");
alertDialog.setMessage("Opravdu si přejete smazat tento záznam???");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "Zpět",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Zrušit mazání",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
startActivity(getIntent());
}
});
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Smazat trvale!",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// db.deleteRumy(String.valueOf(dataModel.getID()));
showProgressDialogHorizontal();
db.clearDatabase();
db.close();
// ShowRecords();
finish();
// Toast.makeText(getApplicationContext(),String.valueOf(dataModel.getID()), Toast.LENGTH_SHORT).show();
// startActivity(getIntent());
}
});
alertDialog.show();
}
});
}}
db.getAllRumy
public List<Rumy> getAllRumy() {
List<Rumy> rumytList = new ArrayList<Rumy>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Rumy rumy = new Rumy();
rumy.setID(Integer.parseInt(cursor.getString(0)));
rumy.setNazev(cursor.getString(1));
rumy.setObjem(cursor.getString(2));
rumy.setObsahAlkoholu(cursor.getString(3));
rumy.setAroma(cursor.getString(4));
rumy.setChut(cursor.getString(5));
rumy.setDokonceni(cursor.getString(6));
rumy.setPoznamka(cursor.getString(7));
rumy.setFoto(cursor.getBlob(8));
// Adding contact to list
rumytList.add(rumy);
} while (cursor.moveToNext());
}
// return contact list
return rumytList;
}
Error
use this
ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("please wait...");
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setCancelable(false);
pDialog.show();
and after data load dismiss the progress dialog
pDialog.dismiss();
Use an asyncTask for ShowRecords() and override the OnProgressUpdate method
#Override
protected void onProgressUpdate(Integer... values) {
// use the values to update your progress bar
}
your ShowRecords should look like this
private void ShowRecords() {
final ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setCancelable(false);
new AsyncTask<Object,Integer,ArrayList<Rumy>>() {
#Override
protected ArrayList<Rumy> doInBackground(Object[] params) {
ArrayList<Rumy> rumy = db.getAllRumy();
return rumy;
}
#Override
protected void onProgressUpdate(Integer... values) {
pDialog.setMessage("please wait..."+ values[0]);
pDialog.show();
}
#Override
protected void onPostExecute(ArrayList<Rumy> list) {
data=new DataAdapter(this,list);
lv.setAdapter(list);
//lv.setOnItemClickListener can be put here
}
}.execute();
}
When your function showRecords() is calling in the next line set progress bar visible and when the function is fully executed make progress bar gone.
I guess u know how to add progress bar because u didn't mention how to use it so.
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
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;
}
}
In my code when i take image from camera it shows correctly in imageview. But when i take second image, both listview items shows same picture..Old picture replaces with new one..when i take third picture then all of three items show same result.and so on..Please can anyone solve my problem.
public class CustomerRegistrationL0 extends Activity {
int take_image;
int UploadFile;
static SimpleAdapter Adapter;
static Bitmap thumbnail;
static String encodedImageString;
Bitmap image2;
LayoutInflater mInflater;
Uri selectedImage ;
static ListView listviewattachment;
public ArrayList<ListItem> myItems = new ArrayList<ListItem>();
private MyAdapter myAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cr_l0);
//declare fields
final EditText textcnic=(EditText)findViewById(R.id.EditTextCNIC);
final String cnic=textcnic.getText().toString();
final EditText textmobile=(EditText)findViewById(R.id.editTextMob);
final String mobileNo=textmobile.getText().toString();
final EditText textname=(EditText)findViewById(R.id.editTextName);
final String name=textname.getText().toString();
final EditText textaddress=(EditText)findViewById(R.id.EditTextAdd);
final String address=textaddress.getText().toString();
final EditText textkin=(EditText)findViewById(R.id.EditTextKin);
final String nextkin=textkin.getText().toString();
listviewattachment=(ListView)findViewById(R.id.listView1);
//////////////////////////////////////////////////////////
//make listview scrollable manuallly(shit)
listviewattachment.setOnTouchListener(new ListView.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent arg1) {
// TODO Auto-generated method stub
int action = arg1.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
// Disallow ScrollView to intercept touch events.
v.getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_UP:
// Allow ScrollView to intercept touch events.
v.getParent().requestDisallowInterceptTouchEvent(false);
break;
}
// Handle ListView touch events.
v.onTouchEvent(arg1);
return true;
}
});
//////////////// // //////////////////////////////////////////////////////////////
Button buttonCamera=(Button)findViewById(R.id.buttonCamera);
Button buttonFromGallery=(Button)findViewById(R.id.buttonAttach);
Button formSubmit=(Button)findViewById(R.id.buttonSubmit);
buttonCamera.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View view) {
Intent i = new Intent( android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, take_image);
}
});
buttonFromGallery.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(
Intent.createChooser(intent, "Select a File to Upload"),
UploadFile);
}
});
formSubmit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
validate(textcnic,textmobile,textname,textaddress,textkin);
//decoding bytes
String attachedImage=encodedImageString;
JSONObject jsonObj = new JSONObject();
try {
jsonObj.put("CNIC Number", cnic);
jsonObj.put("Mobile Number", mobileNo);
jsonObj.put("Name", name);
jsonObj.put("Address", address);
jsonObj.put("Next Kin", nextkin);
jsonObj.put("Image",attachedImage);
String jsonString=jsonObj.toString();
File sdcard = Environment.getExternalStorageDirectory();
try {
File myfile = new File(sdcard,"JSONCache.json");
myfile.createNewFile();
Writer myOutWriter = new BufferedWriter(new FileWriter(myfile));
myOutWriter.write(jsonString);
myOutWriter.close();
Toast.makeText(v.getContext(), "File Created", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.getStackTrace();
Toast.makeText(v.getContext(), "COuld not create file", Toast.LENGTH_LONG).show();
}
//end of write json object
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//write json object
}
});
}
private void validate(EditText cnic, EditText mobile,
EditText name, EditText address, EditText kin) {
// TODO Auto-generated method stub
if(name.getText().toString().trim().equals("")){
name.setError("Please Enter Name");
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == Activity.RESULT_OK )
{
if (requestCode==UploadFile){
// Uri selectedImage = data.getData();
// if ("content".equalsIgnoreCase(selectedImage.getScheme())) {
// String[] filePathColumn = { "_data" };
//Cursor cursor = getContentResolver().query(selectedImage,
// filePathColumn, null, null, null);
//cursor.moveToFirst();
//int columnIndex = cursor.getColumnIndex("_data");}
// String picturePath = cursor.getString(columnIndex);
// cursor.close();
// }
// else if ("file".equalsIgnoreCase(selectedImage.getScheme())) {
// String path= selectedImage.getPath();}
/* Uri selectedImage = data.getData();
String[] filePathColumn = { "data"};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();*/
}
if (requestCode == take_image) {
//get image
thumbnail = (Bitmap) data.getExtras().get("data");
BitmapFactory.Options factoryOptions = new BitmapFactory.Options();
factoryOptions.inJustDecodeBounds = true;
int imageWidth = factoryOptions.inDensity=50;
int imageHeight = factoryOptions.inDensity=50;
image2 = Bitmap.createScaledBitmap(thumbnail, imageWidth , imageHeight, true);
//////listview work
listviewattachment.setItemsCanFocus(true);
myAdapter = new MyAdapter();
ListItem listItem = new ListItem();
myItems.add(listItem);
listviewattachment.setAdapter(myAdapter);
myAdapter.notifyDataSetChanged();
////////////////////end of listview work
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
//encode image
byte[] b = bytes.toByteArray();
encodedImageString = Base64.encodeToString(b, Base64.DEFAULT);
}
}
}
public class MyAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public MyAdapter() {
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return myItems.size();
}
public ListItem getItem(int position) {
return myItems.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.imageview2, null);
holder.image = (ImageView) convertView
.findViewById(R.id.imageView2);
holder.Delete=(Button)convertView.findViewById(R.id.buttonClose);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.image.setImageBitmap(image2);
holder.image.setTag(position);
holder.Delete.setTag(position);
holder.image.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
final Dialog imgDialog = new Dialog(view.getContext(),android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);
imgDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
imgDialog.setCancelable(false);
// layout imageview2 is used because when i use simple imageview layout dialogue with imageview and closebutton,
// every taken image at instancewill not be shown in dialogue.
imgDialog.setContentView(R.layout.imageview);
Button btnClose = (Button)imgDialog.findViewById(R.id.btnIvClose);
ImageView ivPreview = (ImageView)imgDialog.findViewById(R.id.image1);
BitmapFactory.Options factoryOptions = new BitmapFactory.Options();
int imageWidth = factoryOptions.inDensity=400;
int imageHeight = factoryOptions.inDensity=500;
//thumbnail is selected coz if we select bm to enlarge it will give poor quality(bm is small sized image)
Bitmap Scaled = Bitmap.createScaledBitmap(CustomerRegistrationL0.thumbnail, imageWidth, imageHeight, true);
ivPreview.setImageBitmap(Scaled);
btnClose.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
imgDialog.dismiss();
}
});
imgDialog.show();
// ListItem listItem = new ListItem();
//myItems.add(listItem);
myAdapter.notifyDataSetChanged();
//listviewattachment.setSelection(myAdapter.getCount()+1 );
}
});
holder.Delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
int tag = (Integer) view.getTag();
if (tag != (myItems.size() )) {
myItems.remove(tag);
Log.d("GCM", "Item removed from " + tag);
myAdapter.notifyDataSetChanged();
}
}
});
return convertView;
}
}
class ViewHolder {
ImageView image;
Button Delete;
}
}
This is because in your getView() you do not consider the position. You always set the bitmap to image2 which is the most recent bitmap: holder.image.setImageBitmap(image2);
I think you misunderstood how get view works. The getView() method is called for each item in the list when you notifyDataSetChanged().
The solution is to keep reference to the different bitmaps in a list (or elsewhere.. i am just giving a possible solution),
List<Bitmap> images = new ArrayList<>();
When you get the image from the result, add it to the images list.
image2 = Bitmap.createScaledBitmap(thumbnail, imageWidth , imageHeight, true);
images.add(image2)
Finally, setImageBitmap based on the position of the item during getView()
holder.image.setImageBitmap(images.get(position));
my code is save images from gallery in default location /data/data/applicationname/files
if i change path in AppPhotos class to "/data/data/com.isummation.customgallery/files/";
this is not show any image in list what do ido?? plz help me
public class AndroidCustomGalleryActivity extends Activity {
private int count;
private Bitmap[] thumbnails;
private boolean[] thumbnailsselection;
private String[] arrPath;
private ImageAdapter imageAdapter;
Cursor imagecursor;
int image_column_index;
Button selectBtn;
ProgressDialog myProgressDialog = null;
DataBase db;
Handler handle = new Handler(){
public void handleMessage(Android.os.Message message) {
if (message.what == 1)
{
hideProgress();
GridView imagegrid = (GridView)
findViewById(R.id.PhoneImageGrid);
imageAdapter = new ImageAdapter();
imagegrid.setAdapter(imageAdapter);
}
else if (message.what == 3)
{
hideProgress();
AndroidCustomGalleryActivity.this.finish();
}
else if (message.what == 2)
{
hideProgress();
}
super.handleMessage(msg);
};
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gallery);
showProgress();
new Thread() {
public void run() {
try
{
loadFeed();
android.os.Message alertMessage = new android.os.Message();
alertMessage.what = 1;
handle.sendMessage(alertMessage);
}
catch(Exception e)
{
android.os.Message alertMessage = new android.os.Message();
alertMessage.what = 2;
handle.sendMessage(alertMessage);
}
}
}.start();
selectBtn = (Button) findViewById(R.id.selectBtn);
selectBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
showProgress();
new Thread() {
public void run() {
try
{
SelecedtPhotos();
android.os.Message alertMessage = new
android.os.Message();
alertMessage.what = 3;
handle.sendMessage(alertMessage);
}
catch(Exception e)
{
android.os.Message alertMessage = new
android.os.Message();
alertMessage.what = 2;
handle.sendMessage(alertMessage);
}
}
}.start();
}
});
}
public static byte[] getBitmapAsByteArray(Bitmap bitmap) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0, outputStream);
return outputStream.toByteArray();
}
public class ImageAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public ImageAdapter() {
mInflater = (LayoutInflater)
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return count;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.galleryitem,
null);
holder.imageview = (ImageView)
convertView.findViewById(R.id.thumbImage);
holder.checkbox = (CheckBox)
convertView.findViewById(R.id.itemCheckBox);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.checkbox.setId(position);
holder.imageview.setId(position);
holder.checkbox.setOnClickListener(new OnClickListener()
{
public void onClick(View v) {
// TODO Auto-generated method stub
CheckBox cb = (CheckBox) v;
int id = cb.getId();
if (thumbnailsselection[id])
{
cb.setChecked(false);
thumbnailsselection[id] = false;
}
else
{
cb.setChecked(true);
thumbnailsselection[id] = true;
}
}
});
/*holder.imageview.setOnClickListener(new OnClickListener()
{
public void onClick(View v) {
// TODO Auto-generated method stub
int id = v.getId();
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" +
arrPath[id]), "image/*");
startActivity(intent);
}
});*/
holder.imageview.setImageBitmap(thumbnails[position]);
holder.checkbox.setChecked(thumbnailsselection[position]);
holder.id = position;
return convertView;
}
}
class ViewHolder {
ImageView imageview;
CheckBox checkbox;
int id;
}
public void loadFeed()
{
final String[] columns = { MediaStore.Images.Media.DATA,
MediaStore.Images.Media._ID };
final String orderBy = MediaStore.Images.Media._ID;
imagecursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
columns, null,null, orderBy);
image_column_index =
imagecursor.getColumnIndex(MediaStore.Images.Media._ID);
this.count = imagecursor.getCount();
this.thumbnails = new Bitmap[this.count];
this.arrPath = new String[this.count];
this.thumbnailsselection = new boolean[this.count];
for (int i = 0; i < this.count; i++)
{
imagecursor.moveToPosition(i);
int id = imagecursor.getInt(image_column_index);
int dataColumnIndex =
imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
thumbnails[i] =
MediaStore.Images.Thumbnails.getThumbnail(getApplicationContext()
.getContentResolver(), id,MediaStore.Images.Thumbnails.MICRO_KI ND, null);
arrPath[i]= imagecursor.getString(dataColumnIndex);
}
imagecursor.close();
}
private void showProgress()
{
myProgressDialog =
ProgressDialog.show(AndroidCustomGalleryActivity.this,null, "Loading
Data...", true);
}
private void hideProgress()
{
if (myProgressDialog != null)
myProgressDialog.dismiss();
}
///////////////////// Get File Name from path ////////////////////////////
public String FileName(String path)
{
String f = " /";
boolean c = false;
for(int i=path.length()-1;i>0;i--)
{
if(c == false)
if(path.charAt(i) == f.charAt(1))
{
c = true;
return
path.substring(i+1,path.length());
}
}
return "";
}
///////////////////// Get Extension from path ////////////////////////////
public String fileExt(String audio)
{
String fileName = "";
String f = " .";
boolean c = false;
for(int I=audio.length()-1;I>0;I--)
{
if(c == false)
if(audio.charAt(I) == f.charAt(1))
{
fileName = audio.substring(I+1, audio.length());
c = true;
}
}
return fileName;
}
public void SelecedtPhotos()
{
final int len = thumbnailsselection.length;
// int cnt = 0;
for (int i =0; i<len; i++)
{
if (thumbnailsselection[i])
{
//cnt++;
BitmapFactory.Options options = new
BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(arrPath[i],
options);
try {
FileOutputStream outputStream =
openFileOutput(FileName(arrPath[i]), Context.MODE_PRIVATE);
outputStream.write(getBitmapAsByteArray(bitmap));
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
db = new DataBase(getBaseContext());
try {
db.createDataBase();
} catch (IOException e1) {
e1.printStackTrace();
}
db.insert_update("INSERT INTO Photos(name,ext,path)
VALUES ('"+FileName(arrPath[i])+"','"+fileExt(arrPath[i])+"','"+arrPath[i]+"')");
db.close();
File file = new File(arrPath[i]);
boolean t = file.delete();
}
}
}
}
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.database.DataBase;
import com.isummation.customgallery.R;
public class AppPhotos extends Activity{
ProgressDialog myProgressDialog = null;
ListView list;
Activity activity = AppPhotos.this;
List<AppPhotosData> picList;
DataBase db;
int position;
Handler handle = new Handler(){
public void handleMessage(Android.os.Message message) {
if (message.what == 1)
{
hideProgress();
list.setAdapter(new
AppPhotosAdapter(getApplicationContext(),activity,0,picList));
}
else if (message.what == 2)
{
hideProgress();
}
super.handleMessage(msg);
};
};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.photolist);
list = (ListView) findViewById(R.id.listView1);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
position = arg2;
AlertDialog.Builder builder = new
AlertDialog.Builder(AppPhotos.this);
builder.setTitle("Hidden Photos");
builder.setMessage("Are you sure you want to revert the
photo?");
builder.setPositiveButton("Yes", new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
DialogBtn();
}
});
builder.setNegativeButton("No", new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
showProgress();
new Thread() {
public void run() {
try
{
loadFeed();
android.os.Message alertMessage = new android.os.Message();
alertMessage.what = 1;
handle.sendMessage(alertMessage);
}
catch(Exception e)
{
android.os.Message alertMessage = new android.os.Message();
alertMessage.what = 2;
handle.sendMessage(alertMessage);
}
}
}.start();
}
private void showProgress()
{
myProgressDialog = ProgressDialog.show(AppPhotos.this,null, "Loading...",
true);
}
private void hideProgress()
{
if (myProgressDialog != null)
myProgressDialog.dismiss();
}
public void loadFeed()
{
String filePaths = "/data/data/com.isummation.customgallery/files/";
File outputFile1 = new File(filePaths);
File[] files1 = outputFile1.listFiles();
picList = new ArrayList<AppPhotosData>();
for(File f:files1)
{
AppPhotosData picObj = new AppPhotosData();
Bitmap bmDulicated4 = BitmapFactory.decodeFile(f.getAbsolutePath());;
picObj.setImage(bmDulicated4);
picObj.setName(f.getName());
picList.add(picObj);
}
}
public void DialogBtn()
{
db = new DataBase(getBaseContext());
try {
db.createDataBase();
} catch (IOException e1) {
e1.printStackTrace();
}
Cursor DataC = db.selectQuery("SELECT path FROM Photos where name
='"+picList.get(position).getName()+"'");
if(DataC.getCount() > 0)
{
Bitmap bitmap = picList.get(position).getImage();
if(picList.get(position).getImage() != null)
{
try {
FileOutputStream outputStream = new
FileOutputStream(DataC.getString(DataC.getColumnIndex("path")));
outputStream.write(getBitmapAsByteArray(bitmap));
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
File file = new File("/data/data/com.isummation.customgallery
/files/"+picList.get(position).getName());
file.delete();
showProgress();
new Thread() {
public void run() {
try
{
loadFeed();
android.os.Message alertMessage = new
android.os.Message();
alertMessage.what = 1;
handle.sendMessage(alertMessage);
}
catch(Exception e)
{
android.os.Message alertMessage = new
android.os.Message();
alertMessage.what = 2;
handle.sendMessage(alertMessage);
}
}
}.start();
}
}
db.close();
}
public static byte[] getBitmapAsByteArray(Bitmap bitmap) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0, outputStream);
return outputStream.toByteArray();
}
}
Manually create your app directory in sd card and then save image in that directory.
You can try following snippet.
String root=Environment.getExternalStorageDirectory().toString();
File myDir = new File(root+"/demo_image");
if(!myDir.exists())
{
myDir.mkdir();
}
String fname = "Image"+String.valueOf(System.currentTimeMillis())+".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
photo.compress(Bitmap.CompressFormat.JPEG,100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}