How do I add activities to a favourites list? - android

I would like to have a favourites list in my app but I'm not sure how to do it. Basically when a star button is pressed in the menu bar of an activity I would like a custom link/button to bet added to a favourites menu in another activity.
Any help at all is great.
thanks in advance!
Edit here is where I'm at:
public class MainActivity extends Activity implements OnItemClickListener {
ListView lv;
List<ListViewItem> items;
CustomListViewAdapter adapter;
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
ListViewItem item = items.get(position);
items.remove(item);
adapter = new CustomListViewAdapter(this, items);
lv.setAdapter(adapter);
}
public static final String PREFS = "examplePrefs";
String LINK = "MainActivity";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.ListView);
items = new ArrayList<MainActivity.ListViewItem>();
items.add(new ListViewItem()
{{
ThumbnailResource = R.drawable.ic_launcher;
Title = "Item1";
SubTitle = "Item1 desciption";
}});
items.add(new ListViewItem()
{{
ThumbnailResource = R.drawable.ic_launcher;
Title = "Item2";
SubTitle = "Item2 desciption";
}});
adapter = new CustomListViewAdapter(this,items);
lv.setAdapter(adapter);
lv.setOnItemClickListener(this);
class ListViewItem
{
public int ThumbnailResource;
public String Title;
public String SubTitle;
}
Here is my listview adapter .java
public class CustomListViewAdapter extends BaseAdapter
LayoutInflater inflater;
List<ListViewItem> items;
public CustomListViewAdapter(Activity context, List<ListViewItem> items) {
super();
this.items = items;
this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return items.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ListViewItem item = items.get(position);
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.item_row, null);
ImageView imgThumbnail = (ImageView) vi.findViewById(R.id.imgThumbnail);
TextView txtTitle = (TextView) vi.findViewById(R.id.txtTitle);
TextView txtSubTitle = (TextView) vi.findViewById(R.id.txtSubTitle);
imgThumbnail.setImageResource(item.ThumbnailResource);
txtTitle.setText(item.Title);
txtSubTitle.setText(item.SubTitle);
return vi;
}
Here is my item row .xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="5dip">
<ImageView
android:layout_width="78dip"
android:layout_height="78dip"
android:id="#+id/imgThumbnail"
android:layout_alignParentLeft="true"
android:layout_centerInParent="true"
android:layout_marginLeft="-3dip"
android:scaleType="centerInside">
</ImageView>
<TextView
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_height="wrap_content"
android:text="TextView"
android:layout_width="wrap_content"
android:id="#+id/txtTitle"
android:layout_toRightOf="#+id/imgThumbnail"
android:layout_marginTop="6dip"
android:layout_marginLeft="6dip">
</TextView>
<TextView
android:layout_height="wrap_content"
android:text="TextView"
android:layout_width="wrap_content"
android:id="#+id/txtSubTitle"
android:layout_toRightOf="#+id/imgThumbnail"
android:layout_below="#+id/txtTitle"
android:layout_marginTop="3dip"
android:layout_marginLeft="6dip">
</TextView>
I'm stuck on trying to get all necessary information to populate a listview item from the Action Bar item that I've added in my activity that is to be faourited.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.favourite, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
//respond to menu item selection
switch (item.getItemId()) {
case R.id.favourite1:
//this is where shared prefrences is created?
return true;
default:
return super.onOptionsItemSelected(item);

My suggestion..
On clicking the fav icon:
get the name of the current activity and persist it.(db,sharedpref .. your choice).
Create a listView and an adapter for it, which fetches the activity name from the db or sharedPref.
Set click listener for the list view.
get the name of the clicked listview.
call an intent with the selected val.
My suggestion..
On clicking the fav icon:
get the name of the current activity and persist it.(db,sharedpref .. your choice).
Create a listView and an adapter for it, which fetches the activity name from the db or sharedPref.
Set click listener for the list view.
get the name of the clicked listview.
call an intent with the selected val.
EDIT:
Sharedpreference is one of the ways of persisting data in android.(others being database,file etc). The sharedPreference file stores in a key-value format.
Get an instance of the sharedpreference class and editor classs:
SharedPreferences wmbPreference = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = wmbPreference.edit();
Add values in the sharedPrefrence :
editor.putBoolean("key", value);
editor.putFloat("key1", value);
editor.putInt("key2", value);
editor.putLong("key3", value);
editor.putString("key4", value);
editor.putStringSet("key5", values);
Persist these inserted values:
editor.commit();
Now, these key-value pairs can be utilized from any activity:
Get an instance:
SharedPreferences wmbPreference = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Get the value by passing the right key:
boolean boolValue= wmbPreference.getBoolean("key", true);
Thats it, as of sharedprefrence is concerned.

Related

Maintaining checkbox states in listview with CursorAdapter

For my Android project, I have a listview which has a checkbox for every item. The data is loaded from an SQLite database by using a CursorAdapter class. However, whenever I scroll, the checkbox positions will get moved and get carried down to the next part of the listview. How can I fix this problem?
GIF of my CheckBox Problem
Here's my Cursor Adapter Class:
public class VocabCursorAdapter extends CursorAdapter {
private static final int DIFFICULT = 0;
private static final int FAMILIAR = 1;
private static final int EASY = 2;
private static final int PERFECT = 3;
public VocabCursorAdapter(Context context, Cursor c, int flags) {
super(context, c, 0);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.item_vocab, parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
// Find fields to populate in inflated template
TextView tvVocabName = (TextView) view.findViewById(R.id.vocabName);
TextView tvVocabDefinition = (TextView) view.findViewById(R.id.vocabDefinition);
ImageView tvVocabLevel = (ImageView) view.findViewById(R.id.vocabLevel);
// Extract properties from cursor
String vocab = cursor.getString(cursor.getColumnIndexOrThrow(VocabDbContract.COLUMN_NAME_VOCAB));
String definition = cursor.getString(cursor.getColumnIndexOrThrow(VocabDbContract.COLUMN_NAME_DEFINITION));
int level = cursor.getInt(cursor.getColumnIndexOrThrow(VocabDbContract.COLUMN_NAME_LEVEL));
// Populate fields with extracted properties
tvVocabName.setText(vocab);
tvVocabDefinition.setText(definition);
if (level == DIFFICULT) {
tvVocabLevel.setImageResource(R.drawable.level_bars_difficult);
tvVocabLevel.setTag(DIFFICULT);
}
else if (level == FAMILIAR) {
tvVocabLevel.setImageResource(R.drawable.level_bars_familiar);
tvVocabLevel.setTag(FAMILIAR);
}
else if (level == EASY) {
tvVocabLevel.setImageResource(R.drawable.level_bars_easy);
tvVocabLevel.setTag(EASY);
}
else if (level == PERFECT) {
tvVocabLevel.setImageResource(R.drawable.level_bars_perfect);
tvVocabLevel.setTag(PERFECT);
}
}
And here's my list item xml, item_vocab.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:longClickable="true">
<ImageView
android:layout_width="36sp"
android:layout_height="36sp"
android:id="#+id/vocabLevel"
android:layout_gravity="right"
android:src="#drawable/level_bars"
android:scaleType="fitXY"
android:contentDescription="#string/vocab_level"
android:layout_centerVertical="true"
android:layout_toLeftOf="#+id/editCheckbox"
android:layout_toStartOf="#+id/editCheckbox"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/vocabName"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_toLeftOf="#+id/vocabLevel"
android:layout_toStartOf="#+id/vocabLevel"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="#+id/vocabDefinition"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_toLeftOf="#+id/vocabLevel"
android:layout_toStartOf="#+id/vocabLevel"
android:layout_below="#id/vocabName"/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/editCheckbox"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
</RelativeLayout>
And here's my xml which contains a listview
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".controller.MyVocab"
android:paddingLeft="5dp">
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/mVocabList"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/empty_text_view"
android:id="#android:id/empty"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"/>
</RelativeLayout>
I have looked at a lot of different solutions on StackOverflow, but I wasn't able to successfully do it in my own app. For an example, this post has a similar problem, but its solution used getView and I had trouble understanding how to implement it with newView and bindView instead.
And some other solutions might be examples where a cursoradapter is not involved. Any help is much appreciated, thanks a lot!
Edit #1: After incorporating Phan's changes, the checkbox states get resets to false rather than keeping its states when I scroll the listview (See ).
Reason : ListView re-uses the views.
Solution :
class VocabCursorAdapter extends CursorAdapter {
List<Integer> selectedItemsPositions;//to store all selected items position
public VocabCursorAdapter(Context context, Cursor c,int flags) {
super(context, c,0);
selectedItemsPositions = new ArrayList<>();
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {
View view = LayoutInflater.from(context).inflate(R.layout.item_vocab, viewGroup, false);
CheckBox box = (CheckBox) view.findViewById(R.id.editCheckbox);
box.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
int position = (int) compoundButton.getTag();
if (b) {
//check whether its already selected or not
if (!selectedItemsPositions.contains(position))
selectedItemsPositions.add(position);
} else {
//remove position if unchecked checked item
selectedItemsPositions.remove((Object) position);
}
}
});
return view;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
//your other stuff
CheckBox box = (CheckBox) view.findViewById(R.id.editCheckbox);
box.setTag(cursor.getPosition());
if (selectedItemsPositions.contains(cursor.getPosition()))
box.setChecked(true);
else
box.setChecked(false);
}
}
Try this
public class VocabCursorAdapter extends CursorAdapter {
private ArrayList<Boolean> itemChecked = new ArrayList<Boolean>(); // array list for store state of each checkbox
public VocabCursorAdapter(Context context, Cursor c, int flags) {
for (int i = 0; i < c.getCount(); i++) { // c.getCount() return total number of your Cursor
itemChecked.add(i, false); // initializes all items value with false
}
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
...
final int position = cursor.getPosition(); // get position by cursor
CheckBox checkBox = (CheckBox) view.findViewById(R.id.editCheckbox);
checkBox.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (itemChecked.get(position) == true) { // if current checkbox is checked, when you click -> change it to false
itemChecked.set(position, false);
} else {
itemChecked.set(position, true);
}
}
});
checkBox.setChecked(itemChecked.get(position)); // set the checkbox state base on arraylist object state
Log.i("In VocabCursorAdapter","position: "+position+" - checkbox state: "+itemChecked.get(position));
}
}
public class ObservationselectattributeFragment extends Fragment {
DatabaseHandler mDBHandler;
ListView mListView;
SimpleCursorAdapter mSCA;
Cursor mCsr;
ArrayList<String> attributeItems = new ArrayList<>();
public ObservationselectattributeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Inflate the layout for this fragment
View view1=inflater.inflate(R.layout.fragment_observationselectattribute, container, false);
//Bundle bundle2 = getArguments();
Bundle bundle1 = getArguments();
final int firsttext= bundle1.getInt("TotalCount");
final String selectedtreatment= bundle1.getString("SelectedTreatment");
Toast.makeText(getActivity(),"value \n"+firsttext+"\n"+"treatment \n"+selectedtreatment, Toast.LENGTH_SHORT).show();
// Toast.makeText(getActivity(),"SelectedTreatment \n"+selectedtreatment, Toast.LENGTH_SHORT).show();
mListView = (ListView)view1.findViewById(R.id.lv001);
mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
Button addattribute = (Button)view1.findViewById(R.id.addattribute);
addattribute.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String items1="";
Integer tcount1=0;
for(String item1:attributeItems){
items1+="-"+item1+"\n";
tcount1++;
}
Toast.makeText(getActivity(),"you have selected \n"+items1,Toast.LENGTH_LONG).show();
Toast.makeText(getActivity(),"you have selected \n"+tcount1,Toast.LENGTH_LONG).show();
/*FragmentTransaction fr= getFragmentManager().beginTransaction();
fr.replace(R.id.main_container, new ShowObservationDataRecordingFragment()).addToBackStack("ObservationselectattributeFragment");
fr.commit();*/
Bundle bundle = new Bundle();
bundle.putInt("TotalCount2",firsttext);
bundle.putInt("TotalCount1", tcount1);
bundle.putString("SelectedTreatment", selectedtreatment);
Fragment showobservationdatarecordingfragment = new ShowObservationDataRecordingFragment();
showobservationdatarecordingfragment.setArguments(bundle);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.main_container, showobservationdatarecordingfragment).addToBackStack("ObservationselectattributeFragment").commit();
}
});
mDBHandler = new DatabaseHandler(this.getActivity());
mCsr = mDBHandler.getAllRecords();
// Prepare a list of the columns to get the data from, for the ListViewt
String[] columns_to_get_data_from = new String[]{
DatabaseHandler.KEY_IDS,
DatabaseHandler.KEY_NAMES,
DatabaseHandler.KEY_FNAME,
DatabaseHandler.KEY_MONAME,
DatabaseHandler.KEY_SNAME
};
// Prepare a list of the Views into which to place the data
int[] itemviews_to_place_data_in = new int[]{
R.id.euserid,
R.id.eusername,
R.id.efname,
R.id.emoname,
R.id.esname
};
// get and instance of SimpleCursorAdapter
mSCA = new SimpleCursorAdapter(getActivity(),
R.layout.listviewitem_record,
mCsr,
columns_to_get_data_from,
itemviews_to_place_data_in,
0);
// Save the ListView state (= includes scroll position) as a Parceble
Parcelable state = mListView.onSaveInstanceState();
// get and instance of SimpleCursorAdapter the listviewitem_record layout
mListView.setAdapter(mSCA);
// Restore previous state (including selected item index and scroll position)
mListView.onRestoreInstanceState(state);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String attributeItem1 = ((TextView)view.findViewById(R.id.euserid)).getText().toString();
String attributeItem2 = ((TextView)view.findViewById(R.id.eusername)).getText().toString();
String attributeItem3 = ((TextView)view.findViewById(R.id.efname)).getText().toString();
String attributeItem4 = ((TextView)view.findViewById(R.id.emoname)).getText().toString();
String attributeItem5 = ((TextView)view.findViewById(R.id.esname)).getText().toString();
String attributeItem = attributeItem1 + attributeItem2 + attributeItem3 + attributeItem4 + attributeItem5;
// CheckedTextView box = (CheckedTextView) view.findViewById(R.id.record_checkbox);
// box.setChecked(true);
CheckedTextView checkedTextView = (CheckedTextView) view.findViewById(R.id.record_checkbox);
if(checkedTextView.isChecked()) {
checkedTextView.setChecked(false);
} else {
checkedTextView.setChecked(true);
}
if(attributeItems.contains(attributeItem)){
attributeItems.remove(attributeItem);//uncheck item
}
else
{
attributeItems.add(attributeItem);
}
Toast.makeText(getActivity(), "Item1 = " + attributeItem1 +"\n"+ "Item2 ="+attributeItem2 +"\n"+"Item3 ="+attributeItem3+"\n"+"Item4 ="+attributeItem4+"\n"+"Item5 ="+attributeItem5, Toast.LENGTH_SHORT).show();
}
});
((HomeActivity) getActivity())
.setActionBarTitle("Select Attribute");
return view1;
}
}

How to create Popup Menu as submenu of another Popup Menu's menu item

I want to create popup menu submenu of another popup menu's menu item.Like below:
Advance Thanks
It is better to use navigation drawer rather then menu list. In your case you have sub menus & you are working on it. So you can refer below link:
http://www.karthikk.co.vu/2015/03/android-navigation-drawer-with-submenu.html
And If you want exact above then you can refer below link for sub menus:
https://www.packtpub.com/books/content/android-30-application-development-managing-menus
Step 1 : Main.xml
You can use either list view or any other Composite listviews:
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="right"
android:orientation="vertical"
>
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
Step 2 : listviewchild.xml
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginLeft="15dp"
android:layout_toRightOf="#+id/textview_name"
android:src="#drawable/ic_launcher" />
Step 3 :
String popUpContents[];
PopupWindow popupWindowDogs;
ListView listView1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView1=(ListView)findViewById(R.id.listView1);
listView1.setAdapter(new MyAddapter(MainActivity.this)); // binding the list view.
/*
* initialize pop up window items list
*/
// add items on the array dynamically
// format is Company Name:: ID
List<String> dogsList = new ArrayList<String>();
dogsList.add("Samsung");
dogsList.add("Google");
dogsList.add("Yahoo");
dogsList.add("Microsoft");
// convert to simple array
popUpContents = new String[dogsList.size()];
dogsList.toArray(popUpContents);
/*
* initialize pop up window
*/
popupWindowDogs = popupWindowDogs();
}
/*
*
*/
public PopupWindow popupWindowDogs() {
// initialize a pop up window type
PopupWindow popupWindow = new PopupWindow(this);
// the drop down list is a list view
ListView listViewDogs = new ListView(this);
// set our adapter and pass our pop up window contents
listViewDogs.setAdapter(dogsAdapter(popUpContents));
// set the item click listener
listViewDogs.setOnItemClickListener(new DogsDropdownOnItemClickListener());
// some other visual settings
popupWindow.setFocusable(true);
popupWindow.setWidth(250);
popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
// set the list view as pop up window content
popupWindow.setContentView(listViewDogs);
return popupWindow;
}
/*
* adapter where the list values will be set
*/
private ArrayAdapter<String> dogsAdapter(String dogsArray[]) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, dogsArray) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// setting the ID and text for every items in the list
String text = getItem(position);
// visual settings for the list item
TextView listItem = new TextView(MainActivity.this);
listItem.setText(text);
listItem.setTag(position);
listItem.setTextSize(22);
listItem.setPadding(10, 10, 10, 10);
listItem.setTextColor(Color.WHITE);
return listItem;
}
};
return adapter;
}
}
Step 4:
Context rContext;
private LayoutInflater rInflater;
private Activity activity;
public MyAddapter(Context c) {
rInflater = LayoutInflater.from(c);
rContext = c;
}
public MyAddapter(Activity imagebinding) {
// TODO Auto-generated constructor stub
activity = imagebinding;
rContext = imagebinding;
rInflater = LayoutInflater.from(imagebinding);
rContext = imagebinding;
rInflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 10;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub
convertView = rInflater.inflate(R.layout.child, null);
final MyDat mydat = new MyDat();
mydat.imageView1=(ImageView)convertView.findViewById(R.id.imageView1);
mydat.imageView1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
popupWindowDogs.showAsDropDown(v, -5, 0);
}
});
return convertView;
}
class MyDat {
ImageView imageView1;
}
Step 5 :
#Override
public void onItemClick(AdapterView<?> arg0, View v, int arg2, long arg3) {
// get the context and main activity to access variables
Context mContext = v.getContext();
MainActivity mainActivity = ((MainActivity) mContext);
// add some animation when a list item was clicked
Animation fadeInAnimation = AnimationUtils.loadAnimation(v.getContext(), android.R.anim.fade_in);
fadeInAnimation.setDuration(10);
v.startAnimation(fadeInAnimation);
// dismiss the pop up
mainActivity.popupWindowDogs.dismiss();
// get the text and set it as the button text
Toast.makeText(mContext, "Selected Positon is: " + arg2, 100).show();
}
you can use sub menu for that.for this purpose you just have to make your custom menu
link
you can use Dialog or DialogFragment.

How to implement checkbx with custom listview

   I want to make product list with their price,name,image and checkbox,
User checks the product as the user wants and then pass it to second activity,
       
 In second activity it display the item checked with their price,So what method i have to use specially for checkbox input,I am newbie to android so please help me,
I suppose you have a class Product with price, name ...
You have to create a layout (list_row.xml) with the format that you want, for example:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:background="?android:attr/activatedBackgroundIndicator"
android:layout_height="match_parent">
<TextView
android:id="#+id/tv_subtitle_list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/tv_title_list"
android:layout_below="#+id/tv_title_list"
android:longClickable="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tv_title_list"
android:longClickable="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignRight="#+id/tv_title_list"
android:layout_alignBottom="#+id/tv_title_list"
android:id="#+id/img_sync"
android:longClickable="true" />
</RelativeLayout>
After that, you need a List Adapter, the best way is create a Custom List adapter
public class ProductListAdapter extends ArrayAdapter<Product>
{
private List<Product> objects;
private Context context;
public ProductListAdapter(Context context, int textViewResourceId, List<Product> objects)
{
super(context, textViewResourceId, objects);
this.context = context;
this.objects = objects;
}
#Override
public int getCount() {
return objects.size();
}
#Override
public Incidence getItem(int position) {
return objects.get(position);
}
#Override
public long getItemId(int position) {
if(objects.get(position)==null) return -1;
return objects.get(position).getId(); // your database id
}
#Override
public void addAll(Collection<? extends Product> objects) {
this.objects= new ArrayList<>(objects);
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
Incidence rowItem = getItem(position); // get selected item
if (convertView == null)
{
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.list_row, null);
}
/* Access to row components */
TextView title = (TextView) convertView.findViewById(R.id.tv_title_list); // name
TextView subtitle = (TextView) convertView.findViewById(R.id.tv_subtitle_list); // price
ImageView img = (ImageView) convertView.findViewById(R.id.img_sync); // image
title.setText(rowItem.getName());
subtitle.setText(rowItem.getPrice());
img.setImageResource(android.R.drawable.ic_menu_share);
return convertView;
}
}
In your fragment or activity you create the adapter:
public class FragListIncidences extends ListFragment
{
public void initUI() // include this in your onCreate
{
mAdapter = new ProductListAdapter(getActivity(),
android.R.layout.simple_list_item_1, new ArrayList<Product>());
setListAdapter(mAdapter); // because of ListFragment
}
}
The checkbox functionality that you want can be implemented in two ways:
Add Cechbox component in your list_row.xml
You can use a contextual action mode menu. Here you have an example http://developer.android.com/intl/es/guide/topics/ui/menus.html#CAB
public void initUI() // include this in your onCreate
{
mAdapter = new ProductListAdapter(getActivity(),
android.R.layout.simple_list_item_1, new ArrayList<Product>());
setListAdapter(mAdapter); // because of ListFragment
mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
mListView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener()
{
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position,
long id, boolean checked) {
// Here you can do something when items are selected/de-selected,
// such as update the title in the CAB
final int checkedCount = mListView.getCheckedItemCount();
mode.setTitle(checkedCount + " Selected");
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
// Respond to clicks on the actions in the CAB
switch (item.getItemId()) {
case R.id.action_get:
getSelectedItems();
mode.finish(); // Action picked, so close the CAB
return true;
default:
return false;
}
return false;
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// Inflate the menu for the CAB
MenuInflater inflater = mode.getMenuInflater();
contextual_menu =menu;
inflater.inflate(R.menu.subactions, menu);
}
#Override
public void onDestroyActionMode(ActionMode mode) {
// Here you can make any necessary updates to the activity when
// the CAB is removed. By default, selected items are deselected/unchecked.
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// Here you can perform updates to the CAB due to
// an invalidate() request
return false;
}
});
}
private void getSelectedItems() {
final SparseBooleanArray selected = mListView.getCheckedItemPositions();
for (int i = (selected.size() - 1); i >= 0; i--)
if (selected.valueAt(i))
doWhateverYouWant (selected.keyAt(i));
}
In java you have to instantiate each checkBox that you put into your layouts (i.e. CheckBox checkbox1 = new (Checkbox) findViewById(R.id.checkbox1);
Then all you have to do is put a few if() statements into your onCreate like this:
if(checkbox1.isChecked == true){
//send the info to your next activity
}else{
//nothing
}

Generate background colour in listView from database

I have a listView generated from a database, is there a way to make a background colour or a picture to each "section" in the list:
if the first symbol in "Tip" is "W" the background should be Green, and if its "L" it should be red
Im thinking something like this, but i have no idea where to put it since it have to be done in every section:
tipvalue = BetsDbAdapter.KEY_TIP;
//Here to split the value to gain only "W" or "L"
String arrtip[] = tipvalue.split(" ", 2);
temptip = arrtip[0];
//then set background
if (temptip.equals("W")) {
getWindow().getDecorView().setBackgroundColor(Color.GREEN);
To the left is my listView and right is the xml file to make each "section" in the listview
Here is my database:
This is code generating the listView
public class StoredBets extends Activity {
private BetsDbAdapter dbHelper;
private SimpleCursorAdapter dataAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.results);
dbHelper = new BetsDbAdapter(this);
dbHelper.open();
}
#Override
public void onStart(){
super.onStart();
displayListView();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.results, menu);
return true;
}
public void testknap1(View v) {
Intent myIntent = new Intent(StoredBets.this, Overview.class);
startActivity(myIntent);
}
private void displayListView() {
Cursor cursor = dbHelper.fetchAllStats();
String[] columns = new String[] {
BetsDbAdapter.KEY_SMATCH,
BetsDbAdapter.KEY_TIP,
BetsDbAdapter.KEY_BETAMOUNT,
BetsDbAdapter.KEY_BODDS
};
// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.smatch,
R.id.tip,
R.id.bodds,
R.id.betamount,
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
this, R.layout.storedbets,
cursor,
columns,
to,
0);
ListView listView = (ListView) findViewById(R.id.listView2);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
// Get the cursor, positioned to the corresponding row in the result set
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
// Get the state's capital from this row in the database.
String betMatch =
cursor.getString(cursor.getColumnIndexOrThrow("smatch"));
Toast.makeText(getApplicationContext(),
betMatch, Toast.LENGTH_SHORT).show();
Intent myIntent = new Intent(StoredBets.this, SetWinVoidLoss.class);
myIntent.putExtra("id", id);
startActivity(myIntent);
}
});
}
}
EDIT 2:
#amal
This is the layout(results.xml) with the listview
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".StoredBets" >
<ListView
android:id="#+id/listView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_alignTop="#+id/button1" >
</ListView>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginLeft="180dp"
android:onClick="testknap1"
android:text="Button" />
</RelativeLayout>
you can get a fair idea from my code,
code snippet for displaying ListViews where the "curSelected" item has a different background:
final ListView lv = (ListView)findViewById(R.id.lv);
lv.setAdapter(new BaseAdapter()
{
public View getView(int position, View convertView, ViewGroup parent)
{
if (convertView == null)
{
convertView = new TextView(ListHighlightTestActivity.this);
convertView.setPadding(10, 10, 10, 10);
((TextView)convertView).setTextColor(Color.WHITE);
}
convertView.setBackgroundColor((position == curSelected) ?
Color.argb(0x80, 0x20, 0xa0, 0x40) : Color.argb(0, 0, 0, 0));
((TextView)convertView).setText((String)getItem(position));
return convertView;
}
public long getItemId(int position)
{
return position;
}
public Object getItem(int position)
{
return "item " + position;
}
public int getCount()
{
return 20;
}
});
This is a tutorial of how to write an adapter for a list view. amal is right, you can change the separate items in the list view in the getView() method.

Get row position in ListView with Checkbox in Android

I am writing an android app, and I am having trouble getting a row's position in ListView with CheckBox.
Here is a screenshot on the emulator:
I already made the ListView with CheckBoxes. But I can't figure out how find the row's position for each checked entry. And once I get the checked positions, I want to implement a Remove Selected action.
Please help!
Here is my code:
public class ListTest extends ListActivity implements OnCheckedChangeListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
//--- Importing StringsArray---
Bundle gotBasketScanner = getIntent().getExtras();
String[] StringArrayHistory = gotBasketScanner.getStringArray("fromHistory");
// ---Make Adapter---
setListAdapter( new ArrayAdapter<String>(ListTest.this,
android.R.layout.simple_list_item_multiple_choice,
StringArrayHistory));
// ---Put Array into a ListView and add Checkboxes to Listview
ListView list = getListView();
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
}
hey check this it will help you...
http://windrealm.org/tutorials/android/listview-with-checkboxes-without-listactivity.php
Android ListView with Checkbox and all clickable
http://appfulcrum.com/2010/09/12/listview-example-3-simple-multiple-selection-checkboxes/
Use onItemClick() in instead of onCheckedChangeListener...
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast.makeText(getApplicationContext(), "Item "+position+" is clicked",
Toast.LENGTH_SHORT).show();
}
}
This is the better way to get the clicked position and id.
I hope this will solve your problem.
EDIT
I have updated the following line:-
getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
now try ur code.
You can use PrefrenceScreen with CheckBoxPreference for easier and scalellable implementation
You can use CheckedTextView to implement the same:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:focusable="true"
android:checkMark="?android:attr/listChoiceIndicatorMultiple">
</CheckedTextView>
addlist.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/mainListView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
</ListView>
<Button android:id="#+id/click"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Click"/>
</LinearLayout>
And here is the activity GetCheckedTextPositionActivity. On click of the button you will get the positions of the listitem checked :
public class GetCheckedTextPositionActivity extends Activity {
private ListView myList;
private EfficientAdapter myAdapter;
private ArrayList<String> data;
private LayoutInflater mInflater;
private Button click;
private ArrayList<Integer> positions;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addlist);
positions = new ArrayList<Integer>();
data = new ArrayList<String>();
data.add("Bangalore");
data.add("Delhi");
data.add("Patna");
data.add("Mumbai");
click = (Button)findViewById(R.id.click);
mInflater = LayoutInflater.from(getApplicationContext());
myList = (ListView) findViewById(R.id.mainListView);
myAdapter = new EfficientAdapter(data, getApplicationContext());
myList.setAdapter(myAdapter);
click.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(positions.size() != 0){
for(Integer pos : positions){
Log.e("Positions checked :"," Positions :"+pos);
}
}
}
});
}
public class EfficientAdapter extends BaseAdapter {
private ArrayList<String> myData;
public EfficientAdapter(ArrayList<String> mData, Context ctx) {
// TODO Auto-generated constructor stub
this.myData = mData;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return myData.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return myData.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final int currentPos = position;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.main, null);
}
((CheckedTextView) convertView).setText(myData.get(position));
((CheckedTextView) convertView).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
((CheckedTextView) v).toggle();
if(((CheckedTextView) v).isChecked()){
positions.add(currentPos);
}
}
});
return convertView;
}
}
}
Hope this helps.

Categories

Resources