Android - How to remove list item? - android

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

Related

how to remove custom listview item in android

i want to remove listview item in my list.. But When I click On Button nothing happened. please tell ME Where I m Doing Wrong...this code can add item but only remove item cant...
//listview java
public class MemberActivity extends AppCompatActivity implements BaseColumns {
ListView mylist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_member);
final ListView listview;
final ListViewAdapter adapter;
//final ArrayList<String> items = new ArrayList<String>();
mylist = (ListView) findViewById(R.id.listview1);
final LinearLayout linewarLayout1 = (LinearLayout) findViewById(R.id.addmember);
final LinearLayout linewarLayout2 = (LinearLayout) findViewById(R.id.buttongroup);
adapter = new ListViewAdapter();
listview = (ListView) findViewById(R.id.listview1);
final View header = getLayoutInflater().inflate(R.layout.listview_header, null, false);
listview.setAdapter(adapter);
Button addButton = (Button) findViewById(R.id.add);
addButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
mylist.setVisibility(View.INVISIBLE);
linewarLayout2.setVisibility(View.INVISIBLE);
linewarLayout1.setVisibility(View.VISIBLE);
}
});
final EditText name = ((EditText) findViewById(R.id.etName));
final EditText ID = ((EditText) findViewById(R.id.etID));
final EditText Major = ((EditText) findViewById(R.id.etMajor));
Button btnDone = (Button) findViewById(R.id.btnDone);
btnDone.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
//TextView cnttxt = (TextView)findViewById(R.id.count);
//cnttxt.setText(adapter.getCount());
adapter.addItem(name.getText().toString(), ID.getText().toString(), Major.getText().toString());
name.setText("");
ID.setText("");
Major.setText("");
Toast.makeText(getApplicationContext(), "add.", Toast.LENGTH_LONG).show();
mylist.setVisibility(View.VISIBLE);
linewarLayout2.setVisibility(View.VISIBLE);
linewarLayout1.setVisibility(View.INVISIBLE);
}
});
Button btnCancel = (Button) findViewById(R.id.btnCancel);
btnCancel.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
name.setText("");
ID.setText("");
Major.setText("");
mylist.setVisibility(View.VISIBLE);
linewarLayout2.setVisibility(View.VISIBLE);
linewarLayout1.setVisibility(View.INVISIBLE);
}
});
// delete button
Button deleteButton = (Button) findViewById(R.id.delete);
deleteButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
int count, checked;
count = adapter.getCount();
if (count > 0) {
listview.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
checked = listview.getCheckedItemPosition();
if (checked > -1 && checked < count) {
adapter.removeitem(checked);
listview.clearChoices();
adapter.notifyDataSetChanged();
}
}
}
});
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView parent, View v, int position, long id) {
// get item
ListViewItem item = (ListViewItem) parent.getItemAtPosition(position);
String nameStr = item.getname();
String IDStr = item.getID();
String majorStr = item.getmajor();
}
});
}
}//adapter
public class ListViewAdapter extends BaseAdapter {
private ArrayList<ListViewItem> listViewItemList = new ArrayList<ListViewItem>();
public ListViewAdapter() {
}
#Override
public int getCount() {
return listViewItemList.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final int pos = position;
final Context context = parent.getContext();
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.listview_item, parent, false);
}
TextView nameTextView = (TextView) convertView.findViewById(R.id.list_name);
TextView IDTextView = (TextView) convertView.findViewById(R.id.list_ID);
TextView majorTextView = (TextView) convertView.findViewById(R.id.list_major);
ListViewItem listViewItem = listViewItemList.get(position);
nameTextView.setText(listViewItem.getname());
IDTextView.setText(listViewItem.getID());
majorTextView.setText(listViewItem.getmajor());
return convertView;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public Object getItem(int position) {
return listViewItemList.get(position);
}
public void removeitem(int position) {
listViewItemList.remove(position);
notifyDataSetChanged();
}
public void addItem(String name, String ID, String major) {
ListViewItem item = new ListViewItem();
item.setname(name);
item.setID(ID);
item.setmajor(major);
listViewItemList.add(item);
notifyDataSetChanged();
}
}
//ListViewItem java
public class ListViewItem {
private String nameStr;
private String IDStr;
private String majorStr;
public void setname(String name) {
nameStr = name;
}
public void setID(String ID) {
IDStr = ID;
}
public void setmajor(String major) {
majorStr = major;
}
public String getname() {
return this.nameStr;
}
public String getID() {
return this.IDStr;
}
public String getmajor() {
return this.majorStr;
}
}
Update your code as below. Set choice mode to CHOICE_MODE_SINGLE when you crate listview and before set adapter. Remove CHOICE_MODE_SINGLE from button click.
listview = (ListView) findViewById(R.id.listview1);
listview.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
listview.setAdapter(adapter);
Also, You need to setItemChecked in onItemClick of listview.
Check below example code.
public class MainActivity extends Activity {
private ListView mListView;
private String[] mData = new String[] { "xxx", "yyy", "zzz", "aaa" };
private BaseAdapter mAdapter;
private int mLastCorrectPosition = -1;
private int mButtonPosition = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = (ListView) findViewById(R.id.list_view);
mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
mAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_activated_1, mData);
mListView.setAdapter(mAdapter);
mListView.setSelector(new ColorDrawable(0));
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (position == mButtonPosition) {
if (mLastCorrectPosition != -1) {
mListView.setItemChecked(mLastCorrectPosition, true);
}
else {
mListView.setItemChecked(mButtonPosition, false);
}
// here show dialog
}
else {
mLastCorrectPosition = position;
// here refresh fragment
}
}
});
}
}

ListView click show/hide all check box

I am having a listview and it has one checkbox and two textfields , i would like to change check box visibility properties from listview on click funtion, i am able to change the properties from inside the getView funtion but i want it from listview click. Help me find a solution
public class HelpList extends Fragment {
amfFunctions amf;
MyCustomAdapter dataAdapter = null;
Database_Contact contact = new Database_Contact();
DBHelper mydb = new DBHelper(getActivity());
public static final int PICK_CONTACT = 1;
public String user_phone_number;
public String buddyName;
public String buddyNum;
LayoutInflater vi;
View v ;
Fragment fragment = null;
Button myAddButton,myDelButton;
int selected = 0;
Boolean isInternetPresent = false;
ConnectionDetector cd;
ArrayList<Database_Contact> selectedList = new ArrayList<>();
Database_Contact addcontacts = new Database_Contact();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.activity_helplist, container, false);
// Inflate the layout for this fragment
displayListView();
cd = new ConnectionDetector(getActivity());
myDelButton = (Button)v. findViewById(R.id.deleteContact);
myDelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
DeleteContact();
}
else{
Toast.makeText(getActivity(),
getString(R.string.nointernet), Toast.LENGTH_SHORT).show();
}
}
});
Constants.i = 0;
myAddButton = (Button)v. findViewById(R.id.Addanother);
myAddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isInternetPresent = cd.isConnectingToInternet();
Log.e("Myaddbutton text ", (String) myAddButton.getText());
if (isInternetPresent) {
if (myAddButton.getText().equals("Close")){
Toast.makeText(getActivity(),
getString(R.string.click_to_close), Toast.LENGTH_SHORT).show();
}
else{
AddContact();
}
}
else{
Toast.makeText(getActivity(),
getString(R.string.nointernet), Toast.LENGTH_LONG).show();
}
}
});
return v;
}
private void displayListView() {
mydb = new DBHelper(getActivity());
ArrayList<Database_Contact> contactlist = (ArrayList<Database_Contact>)
mydb.getAllDatabase_Contacts();
Collections.sort(contactlist, new Comparator<Database_Contact>() {
#Override
public int compare(Database_Contact lhs, Database_Contact rhs) {
return lhs.getName().compareTo(rhs.getName());
}
});
//create an ArrayAdaptar from the String Array
dataAdapter = new MyCustomAdapter(getActivity(),
R.layout.activity_allcontactlist, contactlist);
ListView listView = (ListView)v.findViewById(R.id.helplistview);
// Assign adapter to ListView
listView.setTextFilterEnabled(true);
listView.setAdapter(dataAdapter);
dataAdapter.notifyDataSetChanged();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Database_Contact contact = (Database_Contact)
parent.getItemAtPosition(position);
contact.isSelected();
}
});
}
private class MyCustomAdapter extends ArrayAdapter<Database_Contact> {
private ArrayList<Database_Contact> contactlist;
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<Database_Contact> contactlist) {
super(context, textViewResourceId, contactlist);
this.contactlist = new ArrayList<Database_Contact>();
this.contactlist.addAll(contactlist);
}
private class ViewHolder {
TextView code;
TextView Number;
CheckBox name;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
vi = (LayoutInflater) getActivity().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.activity_allcontactlist,
null);
holder = new ViewHolder();
holder.code = (TextView)
convertView.findViewById(R.id.helplist_name);
holder.Number = (TextView)
convertView.findViewById(R.id.helplist_num);
holder.name = (CheckBox)
convertView.findViewById(R.id.checkbox_all);
convertView.setTag(holder);
final ViewHolder finalHolder = holder;
final ViewHolder finalHolder1 = holder;
holder.code.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (finalHolder1.name.isShown() == false){
Constants.i = Constants.i+1;
myDelButton.setEnabled(true);
finalHolder.name.setVisibility(View.VISIBLE);
}
else if(finalHolder1.name.isShown() == true) {
finalHolder.name.setVisibility(View.GONE);
Constants.i = Constants.i-1;
if (Constants.i == 0){
myDelButton.setEnabled(false);
}
}
}
});
holder.Number.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (finalHolder1.name.isShown() == false){
Constants.i = Constants.i+1;
myDelButton.setEnabled(true);
finalHolder.name.setVisibility(View.VISIBLE);
}
else if(finalHolder1.name.isShown() == true) {
finalHolder.name.setVisibility(View.GONE);
Constants.i = Constants.i-1;
if (Constants.i == 0){
myDelButton.setEnabled(false);
}
}
}
});
holder.name.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
Database_Contact contact = (Database_Contact)
cb.getTag();
contact.setSelected(cb.isChecked());
}
});
} else {
holder = (ViewHolder) convertView.getTag();
}
Database_Contact contact = contactlist.get(position);
holder.code.setText(contact.getName());
holder.Number.setText(contact.getPhoneNumber());
holder.name.setText("");
holder.name.setChecked(contact.isSelected());
holder.name.setTag(contact);
return convertView;
}
}
}
As I could not find any perfect solution i tried it in a different manner alough its a bit diffenrt from what i wanted i.e on click i used my displayListView() funtion and got the work done
ischeckboxVisible = true;
Runnable run = new Runnable() {
#Override
public void run() {
displayListView();
}
};
getActivity().runOnUiThread(run);
and coming to getView i have used:
if (!ischeckboxVisible)
{
holder.name.setVisibility(View.GONE);
}
if (ischeckboxVisible)
{
holder.name.setVisibility(View.VISIBLE);
}
so every time i do the click it changes the ischeckboxVisible to either true or false and initializes the displatListview() and it works.
I have had help from here Android hide and show checkboxes in custome listview on button click
Hope this might come in handy for some one out there.
Please check below code if it helps you,
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Database_Contact contact = (Database_Contact) contactlist.get(position);
contact.setSelected(!contact.isSelected());
if(contact.isSelected())
{
((CheckBox) view.findViewById(R.id.checkbox_all)).setVisibility(View.VISIBLE);
}
else
{
((CheckBox) view.findViewById(R.id.checkbox_all)).setVisibility(View.GONE);
}
}
});

Footer button in listview, how to get value from custom list adapter

I have a listview with switch button in each row. I store sum of checked switches in variable. In MainActivity where I start custom adapter I want to get a sum of checked switches. So how to pass value from custom adapter to parent activity? In the footer of listview I have a button "Dalej" I've create it in MainActivity, and want to get value (this sum) from adapter when user click on it?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cardio);
String[] cardio_1 = getResources().getStringArray(R.array.cardio_1);
ListView listView = (ListView) findViewById(R.id.listView);
View footer = getLayoutInflater().inflate(R.layout.cardio_footer, null);
listView.addFooterView(footer);
ListAdapter listAdapter = new Adapter_cardio(this, cardio_1);
cardio.addAll(Arrays.asList(cardio_1))
listView.setAdapter(listAdapter);
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
});
Adapter
public Adapter_cardio(Context context, String[] cardios ) {
super(context, R.layout.cardio_row, cardios);
this.context = context;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Log.d("TAG", "tessst1");
zaznaczone = new ArrayList();
}
public String suma(String sum) {
return sum;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
String pytanie = getItem(position);
if (convertView==null){
convertView = inflater.inflate(R.layout.cardio_row, null);
holder = new ViewHolder();
holder.question = (TextView) convertView.findViewById(R.id.question);
holder.s = (Switch)convertView.findViewById(R.id.switch1);
convertView.setTag(holder);
}
else{
holder = (ViewHolder) convertView.getTag();
}
holder.question.setText(pytanie);
//Model_cardio question = getItem(position);
//final boolean doCheck = (position == 4) || (position == 5);
holder.s.setTag(position);
holder.s.setOnCheckedChangeListener(null);
if (zaznaczone.contains(position) )
{
holder.s.setChecked(true);
}
else
{
holder.s.setChecked(false);
}
holder.s.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
zaznaczone.add((Integer) buttonView.getTag());
} else {
zaznaczone.remove((Integer) buttonView.getTag());
}
}
});
sum = zaznaczone.size();
String x = "2";
Log.d("TAG_Switch_all", "suma = " + sum);
return convertView;
}
want to get value (this sum) from adapter when user click on it?
Create a method as public which return sum from Adapter_cardio class as:
public int getSum(){
return zaznaczone.size();
}
and call getSum method on Button click using listAdapter object as:
public void onClick(View v) {
Log.d("TAG_Switch_all", "suma = " + ((Adapter_cardio)listAdapter).getSum());
}
if listAdapter not accessible inside onClick method then declare it as final

Android store image path to sqlite from res folder

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

How to get the position of Item on Click in Android

Hello Everyone!!
I am making a sample shopping cart in which i need to get the position of item clicked and get the image displayed on the page on selecting the image from the shopping cart..But here i am getting image of first item only no matter i have clicked another..it is always showing first image of the list...
Here is my code for ProductAdapter.java
public class ProductAdapter extends BaseAdapter {
private List<Product> mProductList;
private LayoutInflater mInflater;
private boolean mShowQuantity;
public ProductAdapter(List<Product> list, LayoutInflater inflater, boolean showQuantity) {
mProductList = list;
mInflater = inflater;
mShowQuantity = showQuantity;
}
#Override
public int getCount() {
return mProductList.size();
}
#Override
public Object getItem(int position) {
return mProductList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewItem item;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.item, null);
item = new ViewItem();
item.productImageView = (ImageView) convertView
.findViewById(R.id.ImageViewItem);
item.productTitle = (TextView) convertView
.findViewById(R.id.TextViewItem);
item.productQuantity = (TextView) convertView
.findViewById(R.id.textViewQuantity);
convertView.setTag(item);
} else {
item = (ViewItem) convertView.getTag();
}
Product curProduct = mProductList.get(position);
item.productImageView.setImageDrawable(curProduct.productImage);
item.productTitle.setText(curProduct.title);
// Show the quantity in the cart or not
if (mShowQuantity) {
item.productQuantity.setText("Quantity: "
+ ShoppingCartHelper.getProductQuantity(curProduct));
} else {
// Hid the view
item.productQuantity.setVisibility(View.GONE);
}
return convertView;
}
private class ViewItem {
ImageView productImageView;
TextView productTitle;
TextView productQuantity;
}}
And Here is my shoppingcart file
public class ShoppingCartActivity extends Activity {
private List<Product> mCartList;
private ProductAdapter mProductAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shoppingcart);
mCartList = ShoppingCartHelper.getCartList();
// Make sure to clear the selections
for (int i = 0; i < mCartList.size(); i++) {
mCartList.get(i).selected = false;
}
// Create the list
final ListView listViewCatalog = (ListView) findViewById(R.id.ListViewCatalog);
mProductAdapter = new ProductAdapter(mCartList, getLayoutInflater(),
true);
listViewCatalog.setAdapter(mProductAdapter);
listViewCatalog.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent productDetailsIntent = new Intent(getBaseContext(),
ProductDetailsActivity.class);
productDetailsIntent.putExtra(ShoppingCartHelper.PRODUCT_INDEX,
position);
startActivity(productDetailsIntent);
}
});
}
#Override
protected void onResume() {
super.onResume();
// Refresh the data
if (mProductAdapter != null) {
mProductAdapter.notifyDataSetChanged();
}
double subTotal = 0;
for (Product p : mCartList) {
int quantity = ShoppingCartHelper.getProductQuantity(p);
subTotal += p.price * quantity;
}
TextView productPriceTextView = (TextView) findViewById(R.id.TextViewSubtotal);
productPriceTextView.setText("Subtotal: $" + subTotal);
}
}
ProductActivity.java
public class CatalogActivity extends Activity {
private List<Product> mProductList;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.catalog);
// Obtain a reference to the product catalog
mProductList = ShoppingCartHelper.getCatalog(getResources());
// Create the list
ListView listViewCatalog = (ListView) findViewById(R.id.ListViewCatalog);
listViewCatalog.setAdapter(new ProductAdapter(mProductList, getLayoutInflater(), false));
listViewCatalog.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent productDetailsIntent = new Intent(getBaseContext(),ProductDetailsActivity.class);
productDetailsIntent.putExtra(ShoppingCartHelper.PRODUCT_INDEX, position);
startActivity(productDetailsIntent);
}
});
Button viewShoppingCart = (Button) findViewById(R.id.ButtonViewCart);
viewShoppingCart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent viewShoppingCartIntent = new Intent(getBaseContext(), ShoppingCartActivity.class);
startActivity(viewShoppingCartIntent);
}
});
}
}
Code for ProductDetailsActivity.java
public class ProductDetailsActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.productdetails);
List<Product> catalog = ShoppingCartHelper.getCatalog(getResources());
int productIndex = getIntent().getExtras().getInt(
ShoppingCartHelper.PRODUCT_INDEX);
final Product selectedProduct = catalog.get(productIndex);
// Set the proper image and text
ImageView productImageView = (ImageView) findViewById(R.id.ImageViewProduct);
productImageView.setImageDrawable(selectedProduct.productImage);
TextView productTitleTextView = (TextView) findViewById(R.id.TextViewProductTitle);
productTitleTextView.setText(selectedProduct.title);
TextView productDetailsTextView = (TextView) findViewById(R.id.TextViewProductDetails);
productDetailsTextView.setText(selectedProduct.description);
TextView productPriceTextView = (TextView) findViewById(R.id.TextViewProductPrice);
productPriceTextView.setText("$" + selectedProduct.price);
// Update the current quantity in the cart
TextView textViewCurrentQuantity = (TextView) findViewById(R.id.textViewCurrentlyInCart);
textViewCurrentQuantity.setText("Currently in Cart: "
+ ShoppingCartHelper.getProductQuantity(selectedProduct));
// Save a reference to the quantity edit text
final EditText editTextQuantity = (EditText) findViewById(R.id.editTextQuantity);
Button addToCartButton = (Button) findViewById(R.id.ButtonAddToCart);
addToCartButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Check to see that a valid quantity was entered
int quantity = 0;
try {
quantity = Integer.parseInt(editTextQuantity.getText()
.toString());
if (quantity < 0) {
Toast.makeText(getBaseContext(),
"Please enter a quantity of 0 or higher",
Toast.LENGTH_SHORT).show();
return;
}
} catch (Exception e) {
Toast.makeText(getBaseContext(),
"Please enter a numeric quantity",
Toast.LENGTH_SHORT).show();
return;
}
// If we make it here, a valid quantity was entered
ShoppingCartHelper.setQuantity(selectedProduct, quantity);
// Close the activity
finish();
}
});
}
Plz guys Any help will be highly appreciated.
Thanx in advance..
The int position in onItemClick gives the position of the clicked item in the array/list you gave to the adapter.
You can also do getItemAtPosition(); on your listview, if you don't have an easy handle on your original list.
add this code to your Project :
mProductList.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent,
View v, int position, long id)
{
int h = parent.getPositionForView(v);
Toast.makeText(getBaseContext(),
"pic" + (position + 1) + " selected" + h,
Toast.LENGTH_SHORT).show();
}
});
Just geussig that you have a problematic code where you are reading the index value. Following is the sample code for writing and reading int extra:
To put int value:
productDetailsIntent.putExtra(ShoppingCartHelper.PRODUCT_INDEX,
position);
Following code should be used to read this value in another Activity
int index = getIntent().getExtras().getInt(ShoppingCartHelper.PRODUCT_INDEX);
Hope it helps...

Categories

Resources