Show a ProgressBar while saving/showing a SQLite database - android

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.

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.

Multiple Selection in Alert Dialog

Good Day,
I created a method showDialog which will show an Alert Dialog and will list multiple data that I can select of. My problem is when I click OK, the next method (myMethod()) i want to call is not being called. Can someone help me with this? Here is my code:
private void showDialog(List<String> list) {
final CharSequence[] dialogList= list.toArray(new CharSequence[list.size()]);
final AlertDialog.Builder builderDialog = new AlertDialog.Builder(SharingActivity.this);
builderDialog.setTitle("Select Item");
int count = dialogList.length;
boolean[] is_checked = new boolean[count];
String result = "";
builderDialog.setMultiChoiceItems(dialogList, is_checked,
new DialogInterface.OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog,
int whichButton, boolean isChecked) {
}
});
builderDialog.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ListView list = ((AlertDialog) dialog).getListView();
// make selected item in the comma seprated string
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < list.getCount(); i++) {
boolean checked = list.isItemChecked(i);
if (checked) {
if (stringBuilder.length() > 0) stringBuilder.append(",");
stringBuilder.append(list.getItemAtPosition(i));
}
}
myMethod(stringBuilder.toString()); //this is the method
}
});
builderDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((TextView) findViewById(R.id.text)).setText("Click here to open Dialog");
}
});
AlertDialog alert = builderDialog.create();
alert.show();
}
Here is myMethod:
private void myMethod(String stringFriend){
Bundle extras = getIntent().getExtras();
byte[] byteArray = extras.getByteArray("image");
Bitmap image = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
//Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
SharePhoto photo = new SharePhoto.Builder()
.setBitmap(image)
.setCaption("")
.build();
List<String> peopleIds = new ArrayList<String>();
peopleIds.add(stringFriend);
SharePhotoContent content = new SharePhotoContent.Builder()
.addPhoto(photo)
.setPeopleIds(peopleIds)
.build();
ShareApi.share(content, null);
}

Memory Leaks and GridView

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

ListView Shows Recent Image taken from camera

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

Facebook wall stream implementation using graph api in android

My ImageLoader class-------------------->
private Bitmap decodeFile(File f){
try {
//decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
//Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE=Wall.width;
final int REQUIRED_SIZE1=Wall.height;
// final int REQUIRED_SIZE=250;
//
int width_tmp=o.outWidth, height_tmp=o.outHeight;
int scale=1;
// while(o.outWidth/scale/2>=REQUIRED_SIZE && o.outHeight/scale/2>=REQUIRED_SIZE)
//// scale*=2;
while(true){
if((width_tmp/2<REQUIRED_SIZE)||(height_tmp/2<REQUIRED_SIZE1))
break;
width_tmp/=2;
height_tmp/=2;
scale*=2;
}
//decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
o2.inSampleSize=scale;
o2.inJustDecodeBounds = false;
// o2.inSampleSize=2;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {}
return null;
}
I want to display the facebook wall stream in my application using graph api.
The wall stream consists of following things 1)profile picture
2)name ,posted message,posted image
3)Like,Comment options
I got the data from facebook graph api
https://graph.facebook.com/me/home?access_token="+accesstoken;
In this I got data of page1 and I used "paging" to get the data of second page and same for getting third page.
But when I tried to display the first page,because of more images I am getting
Bitmap size exceeds VM Budget error:Out of Memory error
I want to know, how the other facebook applications managing this issue,I observed that they are loading only less number of records at a time.How to do such things,if I got the data in pagewise?
public class Wall extends Activity {
private Button btnSettings,btnLogout,btnUpdate,btnWall,btnCheckin,btnPubfinder,btnCamera;
public String accesstoken,wallres,str_likevariable="",webserv,currentweb;
protected static JSONArray jsonArray;
JSONObject jsonObject = null;
MyProgressDialog dialog;
private PullToRefreshListView listView;
ArrayList<String> msg=new ArrayList<String>();
ArrayList<String> name=new ArrayList<String>();
ArrayList<String> id=new ArrayList<String>();
ArrayList<String> objid=new ArrayList<String>();
ArrayList<String> profimg=new ArrayList<String>();
ArrayList<String> img=new ArrayList<String>();
ArrayList<String> pic=new ArrayList<String>();
ArrayList<String> comment=new ArrayList<String>();
ArrayList<String> likes=new ArrayList<String>();
ArrayList<String> weburl=new ArrayList<String>();
ArrayList<String> like_or_unlike=new ArrayList<String>();
ArrayList<String> date=new ArrayList<String>();
ImageLoader imageLoader;
Handler mHandler;
View footerView;
private int previousTotal = 0,j=0;
public static int width,height;
public boolean loading = true,isScrolling,scroll=true,boolisLoad=true,boolDialog=true,addFooter=false;
MySimpleArrayAdapter adapter;
static {
StrictMode.setThreadPolicy( new StrictMode.ThreadPolicy.Builder().permitAll().build());
}
//onCreate
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.wall);
//To get device dimensions
android.view.WindowManager w = getWindowManager();
Display d = w.getDefaultDisplay();
width = d.getWidth();
height = d.getHeight();
System.out.println(width);
System.out.println(height);
btnSettings=(Button)findViewById(R.id.settings);
btnLogout=(Button)findViewById(R.id.logout);
btnCamera=(Button)findViewById(R.id.camera);
btnUpdate=(Button)findViewById(R.id.update);
btnWall=(Button)findViewById(R.id.wall);
btnCheckin=(Button)findViewById(R.id.checkin);
btnPubfinder=(Button)findViewById(R.id.pubfinder);
ButtonListener listener=new ButtonListener();
btnSettings.setOnClickListener(listener);
btnLogout.setOnClickListener(listener);
btnUpdate.setOnClickListener(listener);
btnWall.setOnClickListener(listener);
btnCheckin.setOnClickListener(listener);
btnPubfinder.setOnClickListener(listener);
btnCamera.setOnClickListener(listener);
//access token
accesstoken=Login.mFacebook.getAccessToken();
Log.e("accesstoken",accesstoken);
//first page webservice
webserv="https://graph.facebook.com/me/home?access_token="+accesstoken;
Log.e("firstweb",webserv);
//pullToRefresh Listview
listView= (PullToRefreshListView ) findViewById(R.id.walldata);
listView.setDivider(null);
//footer view
footerView = ((LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.listfooter, null, false);
// this.mHandler = new Handler();
listView.addFooterView(footerView);
//
// this.mHandler.postDelayed(m_Runnable,5000);
SessionStore.restore(Login.mFacebook, Wall.this);
SessionEvents.removeAllAuthListener();
listView.setOnRefreshListener(new OnRefreshListener() {
// #Override
public void onRefresh() {
// Your code to refresh the list contents goes here
scroll=true; //to keep the scroll at position where it has hits the load more data
pic.clear();
id.clear();
name.clear();
msg.clear();
img.clear();
profimg.clear();
objid.clear();
comment.clear();
weburl.clear();
adapter.clear();
likes.clear();
like_or_unlike.clear();
date.clear();
addFooter=true; // to add the footer view again after removing in pullToRefresh
previousTotal = 0;
loading = true;
listView.removeFooterView(footerView);
listView.setAdapter(null);
j=0;
webserv="https://graph.facebook.com/me/home?access_token="+accesstoken;
Log.e("inpull",webserv);
System.out.println(listView.getCount());
doInBack dob=new doInBack();
dob.execute();
System.out.println(listView.getCount());
Log.e("hi","doback called");
}
});
//
listView.setOnScrollListener(new OnScrollListener() {
private int threshold = 0;
//
public void onScrollStateChanged(AbsListView view, int scrollState) {
////
if (scrollState != 0) {
isScrolling = true;
}
else {
isScrolling = false; //To load the data when the scroll is in offstate
adapter.notifyDataSetChanged();
}
}
public void onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount)
{
// TODO Auto-generated method stub
if (loading) {
if (totalItemCount > previousTotal) {
Log.e("in loading","in load");
loading = false;
previousTotal = totalItemCount;
}
}
if (!loading && (firstVisibleItem + visibleItemCount+2) == totalItemCount+1){
System.out.println(firstVisibleItem);
System.out.println(visibleItemCount);
System.out.println(totalItemCount);
scroll=false;
Log.v("in gridview loading more","grid load");
//
doInBack dob=new doInBack();
dob.execute();
adapter.notifyDataSetChanged();
// doback(webserv);
loading = true;
}
}
// }
});
doInBack dob=new doInBack();
dob.execute();
// doback(webserv);
Log.e("hi","doback called");
}
/
private class ButtonListener implements View.OnClickListener{
public void onClick(View v) {
if(v.equals( btnSettings)){
Intent myintent=new Intent(Wall.this,Settings.class);
startActivity(myintent);
finish();
}
else if(v.equals(btnLogout)){
try {
String res=Login.mFacebook.logout(Wall.this);
Log.e("response",res);
System.out.println(res);
System.out.println(Login.mFacebook.isSessionValid());
//if(res.equals("true"))
//{
Intent in=new Intent(Wall.this,Login.class);
startActivity(in);
finish();
//}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else if(v.equals(btnUpdate)){
Update.i=0;
Intent myintent=new Intent(Wall.this,Update.class);
startActivity(myintent);
finish();
}
else if(v.equals(btnCamera)){
Intent myintent=new Intent(Wall.this,CameraActivity.class);
startActivity(myintent);
finish();
}
else if(v.equals(btnWall)){
// Intent myintent=new Intent(Wall.this,Wall.class);
// startActivity(myintent);
// finish();
}
else if(v.equals(btnCheckin)){
Intent myintent=new Intent(Wall.this,Checkin.class);
startActivity(myintent);
finish();
}
else if(v.equals(btnPubfinder)){
Intent myintent=new Intent(Wall.this,PubFinder.class);
startActivity(myintent);
finish();
}
}
}
class doInBack extends AsyncTask<URL, Integer, Long>
{
protected void onPreExecute()
{ if(boolDialog){
dialog=MyProgressDialog.show(Wall.this, null,null);
}
}
// currentweb= webserv;
#Override
protected Long doInBackground(URL... arg0) {
currentweb=webserv;
//
Log.e("hi","doback parsing");
try
{
// if(urlval>0){
wallres=UrltoValue.getValuefromUrl(currentweb);
Log.e("wallrespages",wallres);
}
JSONObject jobj1=new JSONObject(wallres);
JSONObject jobj2=jobj1.getJSONObject("paging");
webserv= jobj2.getString( "next");
jsonArray = jobj1.getJSONArray("data");
for(int i=0;i<jsonArray.length();i++){
jsonObject = jsonArray.getJSONObject(i);
if(jsonObject.has("message")||jsonObject.has("picture")) {
try{
// msg[j]=jsonObject.getString("message");
if(jsonObject.has("message"))
{
msg.add(jsonObject.getString("message"));
}
else{
msg.add("");
}
}
catch(Exception e){
e.printStackTrace();
}
try{
// msg[j]=jsonObject.getString("message");
if(jsonObject.has("picture"))
{
String firstpicture=jsonObject.getString("picture");
String secondpicture=firstpicture.replaceAll("_s.jpg", "_n.jpg");
Log.e("picurl",secondpicture);
pic.add(secondpicture);
}
else{
pic.add("");
}
}
catch(Exception e){
e.printStackTrace();
}
objid.add(jsonObject.getString("id"));
JSONObject jobj=jsonObject.getJSONObject("from");
name.add(jobj.getString("name"));
id.add(jobj.getString("id"));
if(jsonObject.getString("type").equals("checkin")){
name.set(i,jobj.getString("name")+" "+"is at"+" "+jsonObject.getString("name"));
}
Log.e("id",id[j]);
profimg.add("http://graph.facebook.com/"+id.get(j)+"/picture?type=square");
JSONObject commentjobj=jsonObject.getJSONObject("comments");
comment.add(commentjobj.getString("count"));
if(jsonObject.has("likes")) {
Log.e("likeornot","likre");
JSONObject likesjobj=jsonObject.getJSONObject("likes");
likes.add(likesjobj.getString("count"));
String postid=jsonObject.getString("id");
// graph_or_fql = "fql";
String query = "SELECT likes.user_likes FROM stream WHERE post_id = \'" + postid + "'";
// Log.d("finalThreadID", finalThreadID);
Bundle params = new Bundle();
params.putString("method", "fql.query");
params.putString("query", query);
// Utility.mAsyncRunner.request(null, params, new LikesListener());
String fqlResponse = Login.mFacebook.request(params);
System.out.println(fqlResponse);
JSONArray JOLikeresponse=new JSONArray(fqlResponse);
if(JOLikeresponse.length()!=0){
JSONObject JOLikeObject = JOLikeresponse.getJSONObject(0);
if ( JOLikeObject.has("likes")) {
String optlike,optlikesarray;
JSONObject optLikes=JOLikeObject;
JSONArray optLikesArray;
try{
optLikes = JOLikeObject.getJSONObject("likes");
optlike="like";
}
catch(Exception e){
optlike="unlike";
}
//
if(optlike.equals("like")){
if (optLikes.has("user_likes")) {
String getUserLikes = optLikes.getString("user_likes");
if (getUserLikes.equals("true")) {
like_or_unlike.add("Unlike");
} else if (getUserLikes.equals("false")) {
like_or_unlike.add("Like");
}
}
else {
like_or_unlike.add("Like");
}
} else {
like_or_unlike.add("Like");
}
}
//if likes object is not there in like response
else {
like_or_unlike.add("Like");
}
}
//if the like response Array length is zero
else {
like_or_unlike.add("Like");
}//FQL query object
}
//If likes are not there
else{
likes.add("0");
like_or_unlike.add("Like");
}
weburl.add(currentweb);
Log.e("comment", comment.get(j));
String getCreatedTime = jsonObject.getString("created_time");
SimpleDateFormat formatter = getDateFormat();
ParsePosition pos = new ParsePosition(0);
long then = formatter.parse(getCreatedTime, pos).getTime();
long now = new Date().getTime();
long seconds = (now - then)/1000;
long minutes = seconds/60;
long hours = minutes/60;
long days = hours/24;
String friendly = null;
long num = 0;
if (days > 0) {
num = days;
friendly = days + " day";
} else if (hours > 0) {
num = hours;
friendly = hours + " hour";
} else if (minutes > 0) {
num = minutes;
friendly = minutes + " minute";
} else if(seconds>0) {
num = seconds;
friendly = seconds + " second";
}
else{
friendly = "few seconds";
}
if (num > 1) {
friendly += "s";
}
String postTimeStamp = friendly.toLowerCase() + " ago";
Log.e("date",postTimeStamp );
date.add(postTimeStamp);
j++;
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Long result) {
try
{ if(addFooter){
listView.addFooterView(footerView);
}
addFooter=false;
System.out.println(scroll);
if(scroll){
adapter=new MySimpleArrayAdapter(Wall.this,R.layout.wall,pic,name,msg,id,profimg,comment,objid,weburl,likes, like_or_unlike,date);
listView.setAdapter(adapter);
listView.postDelayed(new Runnable() {
// #Override
public void run() {
listView.onRefreshComplete();
}
}, 2000);
if(boolDialog){
dialog.dismiss();
}
}
else{
// adapter=new MySimpleArrayAdapter(Wall.this,R.layout.wall,pic,name,msg,id,profimg,bitmap,comment,objid,weburl);
adapter.notifyDataSetChanged();
listView.postDelayed(new Runnable() {
// #Override
public void run() {
listView.onRefreshComplete();
}
}, 2000);
}
if(boolDialog){
dialog.dismiss();
}
}
catch(Exception e)
{
e.printStackTrace();
if(boolDialog){
dialog.dismiss();
}
}
boolDialog=false;
}
}
private static SimpleDateFormat getDateFormat() {
return new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ");
}
public class MySimpleArrayAdapter extends ArrayAdapter<String> {
private Activity context;
ArrayList<String> namear,msgar,idar,profimage,postimage,commentsnum,objectid,urlString,likescount,like_or_ulike,datesofpost;
TextView name1, message1,comments,commentsnumber, likesnumber,likes,dateofpost;
ImageView profimg,postimg;
ImageLoader imageLoader;
Bitmap[] bitdata;
// ViewHolder holder ;
// View rowView;
public MySimpleArrayAdapter(Activity c,int i,ArrayList<String> postpic, ArrayList<String> names,ArrayList<String> msg,ArrayList<String> id,ArrayList<String> proimg,ArrayList<String> comment,ArrayList<String> objid,ArrayList<String> web,ArrayList<String> likecount,ArrayList<String> unlike_or_like,ArrayList<String> dates) {
super(c, i, names);
Log.e("adapter","adap");
this.context = c;
this.namear = names;
this.msgar = msg;
this.idar = id;
this.profimage=proimg;
this.postimage=postpic;
// this.bitdata=bit;
this.commentsnum=comment;
this.objectid=objid;
this.urlString=web;
this.likescount=likecount;
this.like_or_ulike=unlike_or_like;
this.datesofpost=dates;
this.imageLoader = new ImageLoader(context);
}
// public View getView(final int position, View convertView, ViewGroup parent) {
//// View view;
// TextView title1,id,name1,dispdate,loc;
// ImageView image,delete,arrow;
// View view = convertView;
//// view = inflater.inflate(R.layout.myfav_row, parent, false);
// LayoutInflater inflator = context.getLayoutInflater();
// view = inflator.inflate(R.layout.myfav_row, null);
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// code to load images
View rowView=convertView ;
LayoutInflater inflator = getLayoutInflater();
rowView = inflator.inflate(R.layout.walldata, null);
name1 = (TextView) rowView.findViewById(R.id.name);
message1 = (TextView) rowView.findViewById(R.id.msg);
profimg= (ImageView) rowView.findViewById(R.id.profile_pic);
postimg= (ImageView) rowView.findViewById(R.id.picpost);
comments = (TextView) rowView.findViewById(R.id.comment);
likes = (TextView) rowView.findViewById(R.id.like);
commentsnumber = (TextView) rowView.findViewById(R.id.commentnumber);
likesnumber = (TextView) rowView.findViewById(R.id.likesnumber);
dateofpost = (TextView) rowView.findViewById(R.id.datepost);
// rowView.setTag(holder);
Log.e("user",idar.get(position));
Log.e("adapter","adap");
name1.setText(namear.get(position));
if(msgar.get(position)!=""){
message1.setText(msgar.get(position));
}
else
{
message1.setVisibility(View.GONE);
}
if(!isScrolling){
if(!postimage.get(position).equals(""))
{try{
imageLoader.DisplayImage(postimage.get(position).replace(" ", "%20"), postimg) ;
// Bitmap b= imageLoader.getBitmap(postimage.get(position));
// postimg.setImageBitmap(b);
}
catch(Exception e){
e.printStackTrace();
}
}
else
{
postimg.setVisibility(View.GONE);
}
}
try{
imageLoader.DisplayImage(profimage.get(position).replace(" ", "%20"), profimg) ;
}
catch(Exception e){
e.printStackTrace();
}
dateofpost.setText(datesofpost.get(position));
commentsnumber.setText(commentsnum.get(position));
likesnumber.setText(likescount.get(position));
likes.setText(like_or_ulike.get(position));
likes.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// if(likes.getText().toString().equals("Like")){
TextView t=(TextView)v;
TextView likescountmodify = null;
View parent = (View) t.getParent();
if (parent != null) {
likescountmodify = (TextView)parent.findViewById(R.id.likesnumber);
}
int i= Integer.parseInt(likescount.get(position));
if(like_or_ulike.get(position).equals("Like")){
Log.e("inlike","like");
like_or_ulike.set(position, "Unlike");
t.setText(like_or_ulike.get(position));
UrltoValue.getValuefromUrl("https://graph.facebook.com/"+objectid.get(position)+"/likes?access_token="+accesstoken+"&method="+"post");
// listView.getAdapter().getItemAt(position);
j=i+1;
String s=Integer.toString(j);
likescount.set(position, s);
likescountmodify.setText(likescount.get(position));
}
else{
Log.e("unlike","unlike");
like_or_ulike.set(position, "Like");
t.setText(like_or_ulike.get(position));
UrltoValue.getValuefromUrl("https://graph.facebook.com/"+objectid.get(position)+"/likes?access_token="+accesstoken+"&method="+"DELETE");
j=i-1;
String s=Integer.toString(j);
likescount.set(position, s);
likescountmodify.setText(likescount.get(position));
}
}
});
comments.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myintent=new Intent(Wall.this,Comments.class);
myintent.putExtra("name", namear.get(position));
myintent.putExtra("profimg", profimage.get(position));
myintent.putExtra("message", msgar.get(position));
myintent.putExtra("postpic", postimage.get(position));
myintent.putExtra("objectid", objectid.get(position));
myintent.putExtra("commentsnum",commentsnum.get(position));
myintent.putExtra("webservice", urlString.get(position));
startActivity(myintent);
finish();
}
});
return rowView;
}
}
please help
Thanks in advance
They might be caching the records or posts and they display(load) records visible to the user at that instant. on how to do this, check out this sample application from developer.android.com ->
displaying-bitmaps Efficiently.
You should try to limit the size of the Bitmaps that you show close to the size of the image view so that you don't waste memory by having large images in memory when you actually want to show a lower resolution image. I usually use this function to resize an image file to a size closer to the one that I want.
// decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f) {
try {
// decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
// 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(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
// TODO: Do something
}
return null;
}
// Use Option class instead of BitmapFactory.Options
Options opts = new Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, opts);
Log.e("optwidth",opts.outWidth+"");
opts.inJustDecodeBounds = false;
if(opts.outWidth>500){
opts.inSampleSize = 4;
mBitmap = BitmapFactory.decodeFile(path, opts);
}
else mBitmap = BitmapFactory.decodeFile(path, opts);
Note: It can degrades the quality of Image but surely it can remove your Out of memory error for bitmap according to my knowledge. for more details check this link: Handling large Bitmaps

Categories

Resources