Multiple Selection in Alert Dialog - android

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

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.

Show a ProgressBar while saving/showing a SQLite database

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.

Inserting Data into database from input alert dialog box

Its a game in which at the end activity the score is displayed But before that the input alert box is displayed where user need to add their name,and that name and score should go to the database. score is getting stored but not the name. how to get name from input alert dialog box and set it on db.insertScore(Score,Name).how am i suppose to add input value of alert dialog box to extra.getString(""); there is getter & setter method.here is my code
Bundle extra = getIntent().getExtras();
if (extra != null)
{
showInputDialog();
final String Name=extra.getString("");
final int Score = extra.getInt("SCORE");
final int totalQuestion = extra.getInt("TOTAL");
int correctAnswer = extra.getInt("CORRECT");
txtTotalScore.setText(String.format("SCORE : %d", Score));
txtTotalQuestion.setText(String.format("PASSED : %d/%d", correctAnswer, totalQuestion));
progressBarResult.setMax(totalQuestion);
progressBarResult.setProgress(correctAnswer);
db.insertScore(Score, Name);
}
}
protected void showInputDialog() {
// get prompts.xml view
LayoutInflater layoutInflater = LayoutInflater.from(Done.this);
View promptView = layoutInflater.inflate(R.layout.dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Done.this);
alertDialogBuilder.setView(promptView);
final EditText editText = (EditText) promptView.findViewById(R.id.edittext);
// setup a dialog window
alertDialogBuilder.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String Name = editText.getText().toString();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
try this
protected void showInputDialog() {
// get prompts.xml view
LayoutInflater layoutInflater = LayoutInflater.from(Done.this);
View promptView = layoutInflater.inflate(R.layout.dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Done.this);
alertDialogBuilder.setView(promptView);
final EditText editText = (EditText) promptView.findViewById(R.id.edittext);
// setup a dialog window
alertDialogBuilder.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String Name = editText.getText().toString();
//call a function which do in background and have a connection with database
new setname(Name);
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
private void setname(final String name){
#Override
protected String doInBackground(String... params){
Data = new HashMap<String, String>();
Data.put("name", name);
try {
JSONObject json = Connection.UrlConnection("http://url", Data);
int succ = json.getInt("success");
if (succ == 0) {
s = "false";
} else {
s = "true";
}
} catch (Exception e) {
}
return s;
}
}
}
Also write a php file which code insert to db
Make the Name variable global and don't use the following line :
String Name;
Bundle extra = getIntent().getExtras();
if (extra != null)
{
showInputDialog();
final int Score = extra.getInt("SCORE");
final int totalQuestion = extra.getInt("TOTAL");
int correctAnswer = extra.getInt("CORRECT");
txtTotalScore.setText(String.format("SCORE : %d", Score));
txtTotalQuestion.setText(String.format("PASSED : %d/%d", correctAnswer, totalQuestion));
progressBarResult.setMax(totalQuestion);
progressBarResult.setProgress(correctAnswer);
db.insertScore(Score, Name);
}
}
protected void showInputDialog() {
// get prompts.xml view
LayoutInflater layoutInflater = LayoutInflater.from(Done.this);
View promptView = layoutInflater.inflate(R.layout.dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Done.this);
alertDialogBuilder.setView(promptView);
final EditText editText = (EditText) promptView.findViewById(R.id.edittext);
// setup a dialog window
alertDialogBuilder.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Name = editText.getText().toString();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}

How to get selected value from alert dialog?

I'm using alert dialog to show some records.those records are comming from db and display in Alertdialog.when user click on item i want to get item name to Log.this is my code.it show item as [test] but i want it showing as test
ArrayList arrayList and String [] categoryStrings initialized on top
List<Video> vd=Video.findWithQuery(Video.class, "select * from Video");
if (vd.size()>0) {
for (Video v : vd) {
arrayList.add(v.getTitle());
}
final List<String> list = Arrays.asList(arrayList.toString());
categoryStrings=new String[list.size()];
categoryStrings=list.toArray(categoryStrings);
AlertDialog.Builder alert = new AlertDialog.Builder(Editmedia.this);
alert.setTitle("Media List");
alert.setCancelable(false);
final int selected = 0; // or whatever you want
alert.setSingleChoiceItems(categoryStrings, selected, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
//onclick
String categoryString = categoryStrings[item];
Log.d("sel", " " + item+" "+categoryString);
edit();
}
});
alert.show();
log value showing
0 [test] i want it as test
Log
Try this, it should help
String categoryString = categoryStrings[item];
categoryString = categoryString.replaceAll("[\\p{Ps}\\p{Pe}]","");
Log.d("sel", " " +" "+categoryString);
[EDIT]
String categoryString = categoryStrings[item];
categoryString = categoryString.replace("[","");
categoryString = categoryString.replace("]","");
Log.d("sel", " " +" "+categoryString);
Try this:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Media List");
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1);
arrayAdapter.clear();
for (int i = 0; i < list.size(); i++) {
Log.i(LOG_TAG, list.get(i));
arrayAdapter.add(list.get(i));
}
builder.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), list.get(which),
Toast.LENGTH_LONG).show();
}
});
builder.setPositiveButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();

How to work out MultipleChoice filters on Listview using checkbox

I have different categories of filters like id, name, gender, area, caste, religion. Now i want to use multiple choice filters showing checkboxes, how can i work out with multiple choice filters because there are many kind of filters so permutation & combination is worst for it.
currently i am done with single selection of filter (1 checkbox true at a time).
String str[] = new String[('Z' - 'A') + 1];
boolean selectedItems[] = new boolean[str.length];
protected ArrayList<CharSequence> selectedChars = new ArrayList<CharSequence>();
private AlertDialog alertBox;
private void showSpinner() {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
int a = 0;
for (char c = 'A'; c < 'Z'; c++) {
str[a++] = String.valueOf(c);
}
boolean[] checkedChars = new boolean[str.length];
int count = str.length;
for (int i = 0; i < count; i++)
checkedChars[i] = selectedChars.contains(str[i]);
alertBuilder.setTitle("Select Country");
alertBuilder.setCancelable(true);
alertBuilder.setMultiChoiceItems(str, selectedItems,
new OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
if (isChecked)
selectedChars.add(str[which]);
else
selectedChars.remove(str[which]);
}
});
alertBox = alertBuilder.create();
alertBox.show();
}
it will jst display the spinner with mulitple selection options.

Categories

Resources