I want to store the image path from resource folder (drawable) to sqlite and then retrieve that. How can I achieve this?
UPDATE:
After retrieving the images, I have a button here to reorder/sort the listview. That's why I need to store the image path to sqlite.
This is what I've tried so far:
static final int[] imgs = {
R.drawable.dinaretreat, // 0
R.drawable.cobterrace, // 1
R.drawable.ventassostreet, // 2
R.drawable.summerhillblvddrouin, // 3
R.drawable.todmanstreetdrouin, // 4
R.drawable.aqueductroad, // 5
R.drawable.northroad, // 6
R.drawable.pottsroad, // 7
R.drawable.onemcclenaghanplace, // 8
R.drawable.twomcclenaghanplace, // 9
R.drawable.threemcclenaghanplace, // 10
R.drawable.fourmcclenaghanplace, // 11
R.drawable.fivemcclenaghanplace, // 12
R.drawable.sevenmcclenaghanplace, // 13
R.drawable.elevenplacemcclenaghanplace, // 14
R.drawable.twelvemcclenaghanplace, // 15
R.drawable.fivethreetwosummerhillblvddrouin, // 16
R.drawable.seventeenajaxstreetdrouin, // 17
R.drawable.onethirtythreemountainviewblvd, // 18
R.drawable.fivethreeonesummerhillblvddrouin // 19
};
String[] text, price;
ArrayList<String> priceList;
private DBHelper dbHelper;
Cursor cursor;
MyCustomAdapter adapter;
Button back, filter;
TextView highest, lowest, location;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewhouseandland);
initControls();
displayRecords();
}
// TODO displayRecords
private void displayRecords() {
checkDatabaseConnection();
text = dbHelper.getAll();
price = dbHelper.getAllPrices();
adapter = new MyCustomAdapter(imgs, text, price);
lv.setAdapter(adapter);
}
private void initControls() {
// TextViews
highest = (TextView) findViewById (R.id.tvHighest);
lowest = (TextView) findViewById (R.id.tvLowest);
location = (TextView) findViewById (R.id.tvLocation);
// Buttons
filter = (Button) findViewById (R.id.btFilter);
back = (Button) findViewById (R.id.btBack);
back.setOnClickListener(this);
filter.setOnClickListener(this);
// ListView
lv = (ListView) findViewById (R.id.lv);
lv.setFastScrollEnabled(true);
lv.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View v, int pos, long id) {
String strHouseName = "house_name";
String strHousePrice = "house_price";
textview1 = (TextView) v.findViewById(R.id.text1);
textview2 = (TextView) v.findViewById(R.id.text2);
String strName = textview1.getText().toString().trim();
String strPrice = textview2.getText().toString().trim();
Intent i;
i = new Intent(this, ViewHouse.class);
i.putExtra(strHouseName, strName);
i.putExtra(strHousePrice, strPrice);
startActivity(i);
}
#SuppressLint("InlinedApi")
private void displayDialog() {
// TODO displayDialog
final ArrayAdapter<String> adp = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, sortBy);
LayoutInflater li = LayoutInflater.from(this);
View promptsView = li.inflate(R.layout.dialog_layout, null);
promptsView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
final Spinner mSpinner= (Spinner) promptsView
.findViewById(R.id.spDialog);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Sort By...");
builder.setIcon(R.drawable.launcher);
mSpinner.setAdapter(adp);
mSpinner.setSelection(0);
mSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View v,
int pos, long id) {
strSpinner = mSpinner.getSelectedItem().toString();
if(strSpinner.equals("Highest Price")){
highest.setTypeface(Typeface.DEFAULT_BOLD);
lowest.setTypeface(Typeface.DEFAULT);
location.setTypeface(Typeface.DEFAULT);
price = dbHelper.sortHighestPrice();
adapter = new MyCustomAdapter(imgs, text, price);
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
} else if (strSpinner.equals("Lowest Price")){
highest.setTypeface(Typeface.DEFAULT);
lowest.setTypeface(Typeface.DEFAULT_BOLD);
location.setTypeface(Typeface.DEFAULT);
price = dbHelper.sortLowestPrice();
adapter = new MyCustomAdapter(imgs, text, price);
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
} else if (strSpinner.equals("Location")) {
highest.setTypeface(Typeface.DEFAULT);
lowest.setTypeface(Typeface.DEFAULT);
location.setTypeface(Typeface.DEFAULT_BOLD);
} else {
Log.d("Default", "Default");
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
builder.setPositiveButton("Okay",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
builder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
builder.setView(promptsView);
AlertDialog alert = builder.create();
alert.show();
}
class MyCustomAdapter extends BaseAdapter
{
String[] data_text1;
String[] data_text2;
int[] data_image;
MyCustomAdapter() {
data_text1 = null;
data_text2 = null;
data_image = null;
}
MyCustomAdapter(int[] image, String[] house, String[] price) {
data_text1 = house;
data_text2 = price;
data_image = image;
}
public int getCount() {
return data_text1.length;
}
public String getItem(int position) {
return null;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row;
row = inflater.inflate(R.layout.listrow, null);
textview1 = (TextView) row.findViewById(R.id.text1);
textview2 = (TextView) row.findViewById(R.id.text2);
ImageView imageview = (ImageView) row.findViewById(R.id.image);
imageview.setScaleType(ImageView.ScaleType.FIT_XY);
textview1.setText(data_text1[position]);
String strPrice = "$" + (new DecimalFormat("#,###.00")).format(Integer.parseInt(data_text2[position])) ;
textview2.setText(strPrice);
imageview.setImageResource(data_image[position]);
return (row);
}
}
In here I have declared those drawables. How can I save their path to sqlite and then display them on my custom listview? Any ideas? Help is pretty much appreciated. Thanks.
Since resources in res are constants, there is no need to store them in a database! Instead, just load the drawables from a resource array:
Define an array in a file such as res/values/images.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<array name="list_images">
<item>#drawable/dinaretreat</item>
<item>#drawable/cobterrace</item>
<item>#drawable/ventassostreet</item>
<item>#drawable/summerhillblvddrouin</item>
<item>#drawable/todmanstreetdrouin</item>
<item>#drawable/aqueductroad</item>
<item>#drawable/northroad</item>
<item>#drawable/pottsroad</item>
<item>#drawable/onemcclenaghanplace</item>
<item>#drawable/twomcclenaghanplace</item>
<item>#drawable/threemcclenaghanplace</item>
<item>#drawable/fourmcclenaghanplace</item>
<item>#drawable/fivemcclenaghanplace</item>
<item>#drawable/sevenmcclenaghanplace</item>
<item>#drawable/elevenplacemcclenaghanplace</item>
<item>#drawable/twelvemcclenaghanplace</item>
<item>#drawable/fivethreetwosummerhillblvddrouin</item>
<item>#drawable/seventeenajaxstreetdrouin</item>
<item>#drawable/onethirtythreemountainviewblvd</item>
<item>#drawable/fivethreeonesummerhillblvddrouin</item>
</array>
</resources>
In your Adapter, get the resource array, and index into it:
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.listrow, null);
textview1 = (TextView) row.findViewById(R.id.text1);
textview1.setText(data_text1[position]);
textview2 = (TextView) row.findViewById(R.id.text2);
String strPrice = "$" + (new DecimalFormat("#,###.00")).format(Integer.parseInt(data_text2[position])) ;
textview2.setText(strPrice);
ImageView imageview = (ImageView) row.findViewById(R.id.image);
imageview.setScaleType(ImageView.ScaleType.FIT_XY);
imageview.setImageResource((context.getResources().getIntArray())[position]);
return (row);
}
Related
this is my first post, and I have a doubt about a listview item management, I have seen some post about recycleView, but I donĀ“t understand yet how to implement it in my problem.
Well, I've got a listView that shows some elements like a shopping car where the user clicks the button autorizarDetalleSolicitud, which opens an alertDialog where an user choices a wished amount of that respective item, so if the amount is bigger than zero, the checkbox changes to state TRUE, but when I test this function, I could see that other checkBoxes are activated (or changes to state TRUE) randomly; i.e. When I input an amount to first item, the state of penultimate checkBox changes to TRUE. Thanks for your attention.
//Button of each listview item
public void autorizarDetalleSolicitud(View v) {
LinearLayout layoutboton = (LinearLayout) v.getParent();
checkBoxelemento = (CheckBox) layoutboton.getChildAt(0);
RelativeLayout relativeLayout = (RelativeLayout) layoutboton.getParent();
TableLayout tableLayout = (TableLayout) relativeLayout.getChildAt(1);
TextView tipoelementotextview = (TextView) tableLayout.findViewById(R.id.tipoelem);
TextView unidadelem = (TextView) tableLayout.findViewById(R.id.unidadelem);
TextView idelem = (TextView) tableLayout.findViewById(R.id.idelem);
TextView cantpedida = (TextView) tableLayout.findViewById(R.id.cantidadelem);
cantautorizadatextview = (TextView) tableLayout.findViewById(R.id.cantautorizado);
final String tipoelemento = tipoelementotextview.getText().toString();
cantidadpedida = Double.parseDouble(cantpedida.getText().toString());
cantidadautorizada = Double.parseDouble(cantautorizadatextview.getText().toString());
idelemento = idelem.getText().toString();
// configura el alert dialog
builder = new AlertDialog.Builder(this);
builder.setMessage(unidadelem.getText() + " a autorizar:");
builder.setNegativeButton(R.string.cancelar, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
if (tipoelemento.equals("Material")) {
numberPickerCantidad = new NumberPicker(getApplicationContext());
numberPickerCantidad.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary));
numberPickerCantidad.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
String[] nums = new String[100];
for (int i = 0; i < nums.length; i++) {
nums[i] = Integer.toString(i);
}
numberPickerCantidad.setMinValue(0);
numberPickerCantidad.setMaxValue(nums.length - 1);
numberPickerCantidad.setWrapSelectorWheel(false);
numberPickerCantidad.setDisplayedValues(nums);
if(cantidadautorizada==0){
numberPickerCantidad.setValue(cantidadpedida.intValue());
}else{
numberPickerCantidad.setValue(cantidadautorizada.intValue());
}
builder.setPositiveButton(R.string.agregar, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
int cantidadautorizada = numberPickerCantidad.getValue();
autorizarCantidad((double)cantidadautorizada,tipoelemento);
}
});
builder.setView(numberPickerCantidad);
} else {
cantreactivosoli = new EditText(getApplicationContext());
cantreactivosoli.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
cantreactivosoli.setFilters(new InputFilter[]{new InputFilter.LengthFilter(4)});
cantreactivosoli.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary));
if(cantidadautorizada==0){
cantreactivosoli.setText(cantidadpedida + "");
}else{
cantreactivosoli.setText(cantidadautorizada + "");
}
cantreactivosoli.setText(cantidadpedida + "");
builder.setView(cantreactivosoli);
builder.setPositiveButton(R.string.aceptar, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String cantidadedittext = cantreactivosoli.getText().toString();
if (!cantidadedittext.equals("")) {
Double cantidadingresada = Double.parseDouble(cantidadedittext);
autorizarCantidad(cantidadingresada,tipoelemento);
} else {
Toast toast = Toast.makeText(getApplicationContext(), R.string.error_sincantidad, Toast.LENGTH_SHORT);
toast.show();
}
}
});
builder.setView(cantreactivosoli);
}
builder.show();
}
// Method that saves the input value in an arraylist and implements a setCheck(true) of that itemstrong text
public void autorizarCantidad(Double cantidadingresada, String tipoelemento){
if (cantidadingresada <= cantidadpedida) {
int flag = 0;
for (int indice = 0; indice < elementosrevisados.size(); indice++) {
if (elementosrevisados.get(indice).getId().equals(idelemento)) {
elementosrevisados.get(indice).setCantidadAutorizada(cantidadingresada+"");
if (tipoelemento.equals("Material")) {
cantautorizadatextview.setText(cantidadingresada.intValue()+"");
}else{
cantautorizadatextview.setText(cantidadingresada+"");
}
cantidadpedida = cantidadingresada;
flag=1;
break;
}
}
if(flag==0) {
Elemento elem = new Elemento(idelemento, cantidadpedida + "", cantidadingresada + "");
elementosrevisados.add(elem);
checkBoxelemento.setChecked(true);
if (tipoelemento.equals("Material")) {
cantautorizadatextview.setText(cantidadingresada.intValue()+"");
}else{
cantautorizadatextview.setText(cantidadingresada+"");
}
}
for(int i=0;i<elementosrevisados.size();i++){
Log.e("Elemento revisado: ",elementosrevisados.get(i).toString());
}
} else {
Toast toast = Toast.makeText(getApplicationContext(), R.string.error_cantidadautorizada, Toast.LENGTH_SHORT);
toast.show();
}
}
SOLUTION!
To solve my problem, I based on this answer recording an array with positions of the checkboxes verifying if they were checked, I mean, this a boolean array, and each checkbox has a status TRUE or FALSE. Thanks to #AnshulTyagi
public class ElementoAdapter extends BaseAdapter {
private ArrayList<Boolean> status = new ArrayList<Boolean>();
private static LayoutInflater inflater = null;
private ArrayList<HashMap<String, String>> data;
Activity activity;
CompoundButton.OnCheckedChangeListener miCheckedListener = new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton checkBoxView,boolean isChecked){
int posicioncheck = (Integer)checkBoxView.getTag();
if (checkBoxView.isChecked()) {
status.set(posicioncheck,true);
} else {
status.set(posicioncheck,false);
}
}
};
public ElementoAdapter(Activity activity, ArrayList<HashMap<String, String>> data){
this.activity = activity;
this.data = data;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (int i = 0; i < data.size(); i++) {
status.add(false);
}
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView (int position, View convertView, ViewGroup parent) {
View vista = convertView;
ViewHolder holder;
if (vista == null) {
vista = inflater.inflate(R.layout.listitem_elemento,null);
holder = new ViewHolder();
holder.labelIdElemento = (TextView) vista.findViewById(R.id.labelIdElemento);
holder.idElemento = (TextView) vista.findViewById(R.id.idelem);
holder.labelTipo = (TextView) vista.findViewById(R.id.labelTipoElemento);
holder.tipoElemento = (TextView) vista.findViewById(R.id.tipoelem);
holder.labelCodigoElemento = (TextView) vista.findViewById(R.id.labelCodigo);
holder.codigoElemento = (TextView) vista.findViewById(R.id.codigoelem);
holder.labelDescripcionElemento= (TextView) vista.findViewById(R.id.labelDescripcion);
holder.descripcionElemento = (TextView) vista.findViewById(R.id.descripcionelem);
holder.labelMarcaElemento = (TextView) vista.findViewById(R.id.labelMarca);
holder.marcaElemento = (TextView) vista.findViewById(R.id.marcaelem);
holder.labelUnidadMedida = (TextView) vista.findViewById(R.id.labelUnidadMedida);
holder.unidadMedida = (TextView) vista.findViewById(R.id.unidadelem);
holder.checkBoxElemento = (CheckBox) vista.findViewById(R.id.checkBox);
holder.botonElemento = (Button) vista.findViewById(R.id.botonsolic);
vista.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
// remove the listener so that it does not get attached to other chechboxes.
holder.checkBoxElemento.setOnCheckedChangeListener(null);
holder.checkBoxElemento.setChecked(status.get(position));
Log.e("check "+position,status.get(position)+"");
}
holder.idElemento.setText(data.get(position).get("idelemento"));
holder.tipoElemento.setText(data.get(position).get("tipoelemento"));
holder.codigoElemento.setText(data.get(position).get("codigoelemento"));
holder.descripcionElemento.setText(data.get(position).get("descripcionelemento"));
holder.marcaElemento.setText(data.get(position).get("marcaelemento"));
holder.unidadMedida.setText(data.get(position).get("unidadmedida"));
Log.e("idelemento creado ",data.get(position).get("idelemento"));
holder.checkBoxElemento.setTag(position);
//add a custom listener
holder.checkBoxElemento.setOnCheckedChangeListener(miCheckedListener);
return vista;
}
static class ViewHolder {
TextView labelIdElemento;
TextView idElemento;
TextView labelTipo;
TextView tipoElemento;
TextView labelCodigoElemento;
TextView codigoElemento;
TextView labelDescripcionElemento;
TextView descripcionElemento;
TextView labelMarcaElemento;
TextView marcaElemento;
TextView labelUnidadMedida;
TextView unidadMedida;
CheckBox checkBoxElemento;
Button botonElemento;
}
}
I am deleting the title 2 list item item
But the last title gets deleted that is the title 8 gets deleted
When I then go back to the previous screen and reopen the list. The correct that is the 2nd item title 2 had been deleted.
Here is the DataAdapter
public class DataAdapter extends BaseAdapter {
String a[];
Context ctx;
View.OnClickListener onClickListener;
MyDBHandler dbHelper;
AlertDialog alertDialog;
ArrayList<Calendars> arrayList;
public DataAdapter(Context reminderList, ArrayList<Calendars> arrayList, MyDBHandler dbHelper) {
this.ctx = reminderList;
this.arrayList = arrayList;
this.dbHelper = dbHelper;
}
public void Swap(ArrayList<Calendars> arrayList) {
this.arrayList.clear();
this.arrayList.addAll(arrayList);
this.notifyDataSetChanged();
Log.e("arraylist", arrayList.toString());
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return arrayList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflate = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflate.inflate(R.layout.activity_view_record, parent, false);
final ViewHolder holder = new ViewHolder();
holder.dateTextView = (TextView) convertView.findViewById(R.id.datelist);
holder.timeTextView = (TextView) convertView.findViewById(R.id.timelist);
holder.titleTextView = (TextView) convertView.findViewById(R.id.titlelist);
holder.idTextview = (TextView) convertView.findViewById(R.id.idlist);
holder.deleteButton = (Button) convertView.findViewById(R.id.deletelist);
holder.dateTextView.setText(arrayList.get(position).get_reminderdate());
holder.timeTextView.setText(arrayList.get(position).get_remindertime());
holder.titleTextView.setText(arrayList.get(position).get_remindertitle());
holder.idTextview.setText(arrayList.get(position).get_id() + "");
holder.deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder adb = new AlertDialog.Builder(v.getRootView().getContext());
adb.setTitle("Delete");
adb.setMessage("Are you sure you want to delete this reminder?");
//final int positionToRemove = view.getId();
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dbHelper.remove(arrayList.get(position).get_id());
Log.e("position", position + "");
arrayList.remove(position);
arrayList = dbHelper.databaseToArrayList();
notifyDataSetInvalidated();
notifyDataSetChanged();
//Swap(dbHelper.databaseToArrayList());
}
});
adb.show();
}
});
}
return convertView;
}
class ViewHolder {
TextView titleTextView, dateTextView, timeTextView, idTextview;
Button deleteButton;
}
}
Here is the ListActivity
public class ReminderList extends ActionBarActivity {
Calendars calendars;
Button deleteButton;
private MyDBHandler dbHelper;
private ListView listView;
private ArrayList<Calendars> arrayList;
private SimpleCursorAdapter adapter;
int pos;
DataAdapter dataAdapter;
final String[] from = new String[]{MyDBHandler.COLUMN_REMINDER_TITLE,
MyDBHandler.COLUMN_REMINDER_DATE, MyDBHandler.COLUMN_REMINDER_TIME, MyDBHandler.COLUMN_ID,
MyDBHandler.COLUMN_REMINDER_DESCRIPTION, MyDBHandler.COLUMN_REMINDER_SNOOZE, MyDBHandler.COLUMN_REMINDER_REPEAT, MyDBHandler.COLUMN_ID};
final int[] to = new int[]{R.id.titlelist, R.id.datelist, R.id.timelist, R.id.idlist,
R.id.descriptionlist, R.id.snoozelist, R.id.repeatlist, R.id.deletelist};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reminder_list);
deleteButton = (Button) findViewById(R.id.deletelist);
// adapter=new DataAdapter(ReminderList.this,from);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onStart() {
arrayList = new ArrayList<Calendars>();
dbHelper = new MyDBHandler(this);
Cursor cursor = dbHelper.fetch();
arrayList = dbHelper.databaseToArrayList();
listView = (ListView) findViewById(R.id.list_view);
listView.setEmptyView(findViewById(R.id.empty));
dataAdapter = new DataAdapter(this, arrayList, dbHelper);
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long viewId) {
String title = arrayList.get(position).get_remindertitle();
Log.d("title", title);
String date = arrayList.get(position).get_reminderdate();
String time = arrayList.get(position).get_remindertime();
String id = arrayList.get(position).get_id() + "";
String description = arrayList.get(position).get_reminderdescription();
String snooze = arrayList.get(position).get_remindersnooze();
String repeat = arrayList.get(position).get_reminderrepeat();
Intent modify_intent = new Intent(getApplicationContext(), AlarmActivity.class);
modify_intent.putExtra("id", id);
modify_intent.putExtra("title", title);
modify_intent.putExtra("time", time);
modify_intent.putExtra("date", date);
modify_intent.putExtra("description", description);
modify_intent.putExtra("snooze", snooze);
modify_intent.putExtra("repeat", repeat);
startActivity(modify_intent);
dataAdapter.notifyDataSetChanged();
listView.invalidateViews();
}
});
super.onStart();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home: {
NavUtils.navigateUpFromSameTask(this);
return true;
}
case R.id.add_record: {
Intent add_mem = new Intent(this, AlarmActivity.class);
startActivity(add_mem);
}
default:
return super.onOptionsItemSelected(item);
}
}
}
DatabasetoArraylist function
public ArrayList<Calendars> databaseToArrayList() {
ArrayList<Calendars> arrayList = new ArrayList();
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_REMINDER;
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
while (!c.isAfterLast()) {
if (c.getString(c.getColumnIndex("_reminderdate")) != null) {
Calendars calendars = new Calendars();
calendars.set_id(c.getInt(c.getColumnIndex(COLUMN_ID)));
calendars.set_reminderdate(c.getString(c.getColumnIndex(COLUMN_REMINDER_DATE)));
calendars.set_remindertime(c.getString(c.getColumnIndex(COLUMN_REMINDER_TIME)));
calendars.set_remindertitle(c.getString(c.getColumnIndex(COLUMN_REMINDER_TITLE)));
calendars.set_reminderdescription(c.getString(c.getColumnIndex(COLUMN_REMINDER_DESCRIPTION)));
calendars.set_reminderrepeat(c.getString(c.getColumnIndex(COLUMN_REMINDER_REPEAT)));
calendars.set_remindersnooze(c.getString(c.getColumnIndex(COLUMN_REMINDER_SNOOZE)));
arrayList.add(calendars);
}
c.moveToNext();
}
c.close();
db.close();
return arrayList;
}
Change your getView() method of adapter by below code:
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
ViewHolder holder = null;
final Calendars calendars = arrayList.get(position);
if (convertView == null)
{
LayoutInflater inflate = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflate.inflate(R.layout.activity_view_record, parent, false);
holder = new ViewHolder();
holder.dateTextView = (TextView) convertView.findViewById(R.id.datelist);
holder.timeTextView = (TextView) convertView.findViewById(R.id.timelist);
holder.titleTextView = (TextView) convertView.findViewById(R.id.titlelist);
holder.idTextview = (TextView) convertView.findViewById(R.id.idlist);
holder.deleteButton = (Button) convertView.findViewById(R.id.deletelist);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.dateTextView.setText(calendars.get_reminderdate());
holder.timeTextView.setText(calendars.get_remindertime());
holder.titleTextView.setText(calendars.get_remindertitle());
holder.idTextview.setText(calendars.get_id() + "");
holder.deleteButton.setTag(calendars);
holder.deleteButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
AlertDialog.Builder adb = new AlertDialog.Builder(v.getRootView().getContext());
adb.setTitle("Delete");
adb.setMessage("Are you sure you want to delete this reminder?");
//final int positionToRemove = view.getId();
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Ok", new AlertDialog.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
final selectedCalendar = (Calendars) holder.deleteButton.getTag();
dbHelper.remove(selectedCalendar.get_id());
arrayList = dbHelper.databaseToArrayList();
notifyDataSetInvalidated();
notifyDataSetChanged();
//Swap(dbHelper.databaseToArrayList());
}
});
adb.show();
}
});
}
return convertView;
}
I have checklist with search functionality(used edittext). When I use it to search it shows filtered items so that I can make the selection that I want, it works properly. However, the checked items become unchecked when the search functionality reloads the list. I want the items selected before the search to remain selected. How can I fix this?
Here is my code:
public class Lab extends Fragment {
Button mViewBtn,msaveBtn;
EditText mReviewdateEdt,mInputSearch;
TextView mMostprecrdTxv,mViewmoreTxv;
View android;
// final Context context = getActivity();
MyCustomAdapter dataAdapter = null;
ListView listView;
DatabaseHandler db;
SQLiteDatabase db1;
Pharmacy mPharmacyFrag;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
android = inflater.inflate(R.layout.lab_frag, container, false);
db=new DatabaseHandler(getActivity());
getIds();
displayListView();
viewAlertDialog();
saveAlertdialog();
return android;
}
private void getIds() {
// TODO Auto-generated method stub
mViewBtn = (Button)android.findViewById(R.id.view);
msaveBtn = (Button)android.findViewById(R.id.save);
mInputSearch = (EditText)android.findViewById(R.id.inputSearch);
listView = (ListView)android.findViewById(R.id.list);
}
ArrayList<States> stateList = new ArrayList<States>();
ArrayList<States> text_sort = new ArrayList<States>();
private void displayListView()
{
stateList = new ArrayList<States>();
States _states = new States("17 KETOSTERIODS","",false);
stateList.add(_states);
_states = new States("17-ALPHA HYDROXY PROGESTERON","",false);
stateList.add(_states);
_states = new States("24 HRS URINE ALBUMIN","",false);
stateList.add(_states);
_states = new States("24HRS URINARYCORTISOL/CREATININE RATIO","",false);
stateList.add(_states);
_states = new States("24HRS URINE PROTEIN","",false);
stateList.add(_states);
_states = new States("2D ECHO","",false);
stateList.add(_states);
_states = new States("2D ECHO&DOPPLER STUDY","",false);
stateList.add(_states);
_states = new States("5-HYDROXY INDOLE ACETIC ACID","",false);
stateList.add(_states);
_states = new States("ABSOLUTE EOSINOPHIL COUNT","",false);
stateList.add(_states);
_states = new States("ABSOLUTE NEUTROPHILIC COUNT","",false);
stateList.add(_states);
dataAdapter = new MyCustomAdapter(getActivity().getBaseContext(),R.layout.state_info, stateList);
listView.setAdapter(dataAdapter);
mInputSearch.addTextChangedListener(new TextWatcher()
{
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3)
{
int textlength = mInputSearch.getText().length();
text_sort.clear();
for (int i = 0; i < stateList.size(); i++)
{
System.out.println("firstlooop"+mInputSearch.getText().toString());
System.out.println("names"+stateList.get(i).getCode());
if (stateList.get(i).getCode().toLowerCase().contains(mInputSearch.getText().toString())||stateList.get(i).getCode().toUpperCase().contains(mInputSearch.getText().toString()))
{
States _states = new States(stateList.get(i).getCode(),"",false);
text_sort.add(_states);
System.out.println("Gdafdhujgkgj");
}
}
System.out.println("text_sort"+text_sort.size());
dataAdapter = new MyCustomAdapter(getActivity(),R.layout.state_info, text_sort);
listView.setAdapter(dataAdapter);
dataAdapter.notifyDataSetChanged();
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
private class MyCustomAdapter extends ArrayAdapter<States>
{
private LayoutInflater vi;
private ArrayList<States> stateList;
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<States> stateList)
{
super(context, textViewResourceId, stateList);
this.stateList = new ArrayList<States>();
this.stateList.addAll(stateList);
vi = (LayoutInflater)context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
}
private class ViewHolder
{
TextView code;
CheckBox name;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null)
{
convertView = vi.inflate(R.layout.state_info, null);
holder = new ViewHolder();
holder.code = (TextView) convertView.findViewById(R.id.code);
holder.name =(CheckBox)convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
holder.name.setOnClickListener( new View.OnClickListener()
{
public void onClick(View v)
{
CheckBox cb = (CheckBox) v;
States _state = (States) cb.getTag();
_state.setSelected(cb.isChecked());
}
});
}
else
{
holder = (ViewHolder) convertView.getTag();
}
States state = stateList.get(position);
holder.code.setText( state.getCode());
holder.name.setText(state.getName());
holder.name.setChecked(state.isSelected());
holder.name.setTag(state);
return convertView;
}
}
private void viewAlertDialog()
{
mViewBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
StringBuffer responseText = new StringBuffer();
ArrayList<States> stateList = dataAdapter.stateList;
for(int i=0;i<stateList.size();i++)
{
States state = stateList.get(i);
if(state.isSelected())
{
responseText.append("\n\n" + state.getCode());
}
}
final TextView myView = new TextView(getActivity());
myView.setText("Selected Tests are : \n"+responseText);
myView.setTextSize(14);
alertDialogBuilder.setCustomTitle(myView);
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setNegativeButton("Close",new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface arg0, int arg1)
{
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
});
}
private void saveAlertdialog()
{
// TODO Auto-generated method stub
msaveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
alertDialogBuilder.setMessage("Lab Orders Saved");
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setNegativeButton("PHARMACY",newDialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface arg0, int arg1) {
int newFragmentNumber = 1;
((Tabswipe) getActivity()).setDisplayedFragment(newFragmentNumber);
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
StringBuffer responseText = new StringBuffer();
ArrayList<States> stateList = dataAdapter.stateList;
for(int i=0;i<stateList.size();i++)
{
States state = stateList.get(i);
if(state.isSelected())
{
responseText.append("\n" + state.getCode());
}
}
db1=db.getWritableDatabase();
ContentValues values=new ContentValues();
values.put("LabTests",String.valueOf(responseText));
db1.insert("Labtests", null, values);
Cursor cursor=db1.rawQuery("select * from Labtests", null);
if(cursor!=null)
{
if(cursor.moveToFirst())
{
do
{
String tests=cursor.getString(cursor.getColumnIndex("LabTests"));
}while(cursor.moveToNext());
}
}
}
});
}
}
public class States {
String code = null;
String name = null;
boolean selected = false;
public States(String code, String name, boolean selected)
{
super();
this.code = code;
this.name = name;
this.selected = selected;
}
public String getCode()
{
return code;
}
public void setCode(String code)
{
this.code = code;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public boolean isSelected()
{
return selected;
}
public void setSelected(boolean selected)
{
this.selected = selected;
}
}
ListView recycles the views every time its associated edit text's value is changed. That's why the Check-boxes does not retain their states.
To accomplish your task:
Store the checked items in an array.
When you click any checkbox in the listview, change the value of that particular item in the array.
Inside your getView method, check or uncheck the Check-boxes by reading the values from the array.
That way your checkboxes will retain their states. I hope this is clear.
I have a multicolumn List view like the one shown in the image, i used custom adapters to populate this custom list.so the question is how to get data on click of submit button means when i click submit button i should get data like name, price and quantity of only checked checkbox....Thanx in advance.
In my Main xml i have a listview and in mainlist xml i have txtname, txtprice, edittext and checkbox and use efficient adapter.
i'm able to view data in list view, bt the problem is i m unable to save data on click of submit button... so plz help me out, with a sample code, bcz m new to android..
the following is my code..
public class Menu extends Activity {
ListView list;
Cursor cursorMenu;
Button btnPlaceOrder;
Button btnShowOrders;
String Descstr="";
String strtotal="";
List<String[]> lstSelectedItems = null;
DBAdapter db = new DBAdapter(this);
private String[] strName;
private String[] strPrice;
private String[] strDescription;
private class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
try {
return strName.length;
} catch (Exception e) {
//Toast.makeText(Menu.this, "No Data !", Toast.LENGTH_LONG).show();
return 0;
}
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.menulist, null);
holder = new ViewHolder();
holder.text = (TextView) convertView
.findViewById(R.id.txtItemName);
holder.text2 = (TextView) convertView
.findViewById(R.id.txtPrice);
holder.text3 = (TextView) convertView
.findViewById(R.id.txtDescription);
holder.etext3 = (EditText) convertView
.findViewById(R.id.txtQty);
holder.chk = (CheckBox) convertView
.findViewById(R.id.chkBox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText(strName[position]);
holder.text2.setText(strPrice[position]);
holder.text3.setText(strDescription[position]);
return convertView;
}
class ViewHolder {
TextView text;
TextView text2;
TextView text3;
EditText etext3;
CheckBox chk;
}
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
btnPlaceOrder = (Button) findViewById(R.id.btnPlaceOrder);
btnPlaceOrder.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
/*db.open();
cursorMenu = db.menu_getAllTitles();
int rowcount = cursorMenu.getCount();
System.out.println("---- +++++ " + rowcount);
System.out.println("---- column +++++ " + cursorMenu.getColumnCount());
int index = 0;
if (rowcount > 0) {
strName = new String[rowcount];
strPrice = new String[rowcount];
strDescription = new String[rowcount];
if (cursorMenu.moveToFirst()) {
do {
strName[index] = cursorMenu.getString(1);
strDescription[index] = cursorMenu.getString(2);
strPrice[index] = cursorMenu.getString(3);
Log.v(TAG, "Name-- " + strName[index] + "Price-- "
+ strPrice[index]);
index++;
} while (cursorMenu.moveToNext());
}
cursorMenu.close();
} else {
Toast.makeText(this, "No Data found", Toast.LENGTH_LONG).show();
}*/
list = (ListView) findViewById(R.id.lstMenu);
list.setAdapter(new EfficientAdapter(this));
System.out.println("--List Child count-----"+list.getChildCount());
System.out.println("--List count-----"+list.getCount());
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Toast.makeText(getBaseContext(),
"You clciked " + strName[arg2] + "\t" + strPrice[arg2],
Toast.LENGTH_LONG).show();
}
});
}
}
http://www.vogella.de/articles/AndroidListView/article.html go through this example you can get every thing regards listview.
I have got a main extending adapter which adds rows when user clicks on a button. In the adapter, I got a remove item button and a checkbox. How do I remove the item from the list?
public class main extends Activity{
ArrayList<String> noteList = new ArrayList<String>();
FancyAdapter aa = null;
Button calculate;
EditText result;
String total;
String name;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Spinner spinner = (Spinner)findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.spinner_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
ListView myListView = (ListView)findViewById(R.id.noteList);
aa = new FancyAdapter();
final EditText price = (EditText)findViewById(R.id.price);
final EditText name1 = (EditText)findViewById(R.id.name);
myListView.setAdapter(aa);
myListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
}
});
Button btnSimple = (Button)findViewById(R.id.btnSimple);
btnSimple.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
try
{
double totalPrice = Double.parseDouble(price.getText().toString());
int position = spinner.getSelectedItemPosition();
name = name1.getText().toString();
if(position == 0)
{
totalPrice = totalPrice * 1.07;
total = String.valueOf(totalPrice);
System.out.println(total);
}
else
{
totalPrice = (totalPrice * 1.1)*1.07;
total = String.valueOf(totalPrice);
System.out.println(total);
}
String wholeString = name + ":$" +total;
noteList.add(0, wholeString);
System.out.println(total);
name1.setText("");
price.setText("");
aa.notifyDataSetChanged();
}
catch (Exception e)
{
}
}
});
}
class FancyAdapter extends ArrayAdapter<String>
{
Button calculate;
EditText price;
EditText result;
FancyAdapter()
{
super(main.this, android.R.layout.simple_list_item_1, noteList);
}
public View getView(int position, View convertView, ViewGroup parent)
{
View row = convertView;
if(row == null)
{
LayoutInflater inflater = getLayoutInflater();
row = inflater.inflate(R.layout.custom_list_item, null);
}
StringTokenizer tokens = new StringTokenizer(noteList.get(position), ":");
String first = tokens.nextToken();
String second = tokens.nextToken();
row.getTag();
((TextView)row.findViewById(R.id.nametv)).setText(first);
((EditText)row.findViewById(R.id.result)).setText(second);
Button deleteButton = (Button) row.findViewById(R.id.button);
deleteButton.setTag(position);
deleteButton.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
}
}
);
return (row);
}
}
}
remove list item, and invoke notifyDataSetChanged();
public View getView(int position, View convertView, ViewGroup parent)
{
View row = convertView;
if(row == null)
{
LayoutInflater inflater = getLayoutInflater();
row = inflater.inflate(R.layout.custom_list_item, null);
}
StringTokenizer tokens = new StringTokenizer(noteList.get(position), ":");
String first = tokens.nextToken();
String second = tokens.nextToken();
row.getTag();
((TextView)row.findViewById(R.id.nametv)).setText(first);
((EditText)row.findViewById(R.id.result)).setText(second);
Button deleteButton = (Button) row.findViewById(R.id.button);
deleteButton.setTag(position);
deleteButton.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
noteList.remove(position);
notifyDataSetChanged();
}
}
);
return (row);
}
Remove the item from the arraylist using
noteList.remove(itemIndex);
and then call
aa.notifyDataSetChanged();