Android custom listview - android

Hi i've got a custom listview with a text view and a button in each row.
Im having trouble trying to use the buttons . Each button will fire a different intent. This is the xml file for the list view rows.
<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout
android:id="#+id/widget28"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<Button
android:id="#+id/widget29"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Remind me"
android:layout_alignParentRight="true"
/>
<TextView android:id="#+id/text12"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#ff99ccff"
android:text="Text view" />
</RelativeLayout>
Then i have another xml file which simply contains the list view in a linear layout.
This is my custom array class.
public class customArray extends ArrayAdapter<String> {
int resource;
public customArray(Context cont, int _resource, List<String> items) {
super (cont, _resource,items);
resource = _resource;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
RelativeLayout rl;
String prod = getItem(position);
if (convertView == null) {
rl = new RelativeLayout(getContext());
LayoutInflater vi = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vi.inflate(resource, rl, true);
} else {
rl = (RelativeLayout)convertView;
}
TextView t1 = (TextView)rl.findViewById(R.id.text12);
t1.setText(prod);
Button b1 = (Button)rl.findViewById(R.id.widget29);
return rl;
}
}
Then the final class which gets the data from a database and uses the custom adapter to display the information. Does anyone know how i would call each button?
`public class SatMain extends Activity {
/** Called when the activity is first created.
* #param cont */
#Override
public void onCreate(Bundle savedInstanceState)
{
List<String> results = new ArrayList<String>();
super.onCreate(savedInstanceState);
setContentView(R.layout.satmain);
dbAdapter db = new dbAdapter(this);
// button.setOnClickListener(m);
//---get all titles---
db.open();
db.InsertData();
Cursor c = db.getSat1();
if (c.moveToFirst())
{
do {
String pub = c.getString(c.getColumnIndex(db.KEY_Artist));
String pub1 = c.getString(c.getColumnIndex(db.KEY_Time));
results.add(pub + pub1 );
} while (c.moveToNext());
}
db.close();
ListView listProducts;
customArray ca = new customArray(this, R.layout.button, results);
listProducts = (ListView)findViewById(R.id.list1);
listProducts.setAdapter(ca);
ca.notifyDataSetChanged();
}
}`

In the "getView" method of your adapter, you should set an onClick listener for the button. You can do an anonymous class so that you can refer to the contents of the row in the button. I.e, add the following where you get b1 in your example.
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//create activity based on prod
}
});

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

ListView not displaying on inflate

I have a TableLayout that has it's rows populated dinamically via database. On each row, I'm trying to make a OnLongClickListener() to show a ListView from a different .xml than my activity_product.xml. Here is relevant part of code from my activity_product.xml:
<TableLayout
android:id="#+id/productsTable"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="3dip"
android:paddingRight="3dip"
android:shrinkColumns="1"
android:weightSum="1"
android:stretchColumns="*">
</TableLayout>
And here is my edit_or_delete_menu.xml with the ListView
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/edirOrDeleteMenu"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</ListView>
</LinearLayout>
And here is the relevant part of the code I use to populate the rows and attempt to show the ListView:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product);
new LoadProductsTableContent().execute();
}
private class LoadProductsTableContent extends AsyncTask<Void, Void, Integer> {
private TableLayout productsTable = (TableLayout) findViewById(R.id.productsTable);
private TableRow labelRow = (TableRow) findViewById(R.id.productLabelsRow);
#Override
protected Integer doInBackground(Void... params)
{
int result=1;
// Usado para acessarmos as views da thread pai
// http://stackoverflow.com/questions/5161951/android-only-the-original-thread-that-created-a-view-hierarchy-can-touch-its-vi
runOnUiThread(new Runnable() {
#Override
public void run() {
// Create a new row to be added
TableRow tr = new TableRow(ProductActivity.this);
/* CODE TO SET ROW PROPERTIES AND CONTENT */
// Row click listener
tr.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
onClickRow(v);
return false;
}
});
// Add row to TableLayout
productsTable.addView(tr);
}
});
return result;
}
private void onClickRow(View v) {
String editText = getResources().getString(R.string.menuEditOption);
String deleteText = getResources().getString(R.string.menuDeleteOption);
// Inflating to display ListView
LayoutInflater inflater = (LayoutInflater) ProductActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.edir_or_delete_menu, null);
edirOrDeleteMenu = (ListView) v.findViewById(R.id.edirOrDeleteMenu);
String[] options = new String[]{editText, deleteText};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(ProductActivity.this, android.R.layout.simple_list_item_1, android.R.id.text1, options);
edirOrDeleteMenu.setAdapter(adapter);
}
The code compiles and no error happens when executing this code, but my ListView doesn't show up. What am I missing here?
Thanks in advance.
I guess the problem is here:
LayoutInflater inflater = (LayoutInflater) ProductActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.edir_or_delete_menu, null);
You inflated a view, but didn't add it anywhere. Add it as a child view to the view which is supposed to be its parent.
Also you need to declare and assign the inflater.inflate(...) result to another variable instead of v. The v is the view, which is clicked. Create a new variable and then add it as a child, as I wrote above.
Something like this:
LayoutInflater inflater = (LayoutInflater) ProductActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.edir_or_delete_menu, null);
v.addView(view);

Showing graphical instead of strings in an imagelist with title

At the moment I am getting items out of my database and add them to a string called result which I return and set to my TextView:
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.level);
loadDataBase();
int level = Integer.parseInt(getIntent().getExtras().getString("level"));
questions = new ArrayList<Question>();
questions = myDbHelper.getQuestionsLevel(level);
tvQuestion = (TextView) findViewById(R.id.tvQuestion);
i = 0;
String data = getAllItems();
tvQuestion.setText(data);
}
private String getAllItems() {
result = "";
for (i = 0; i<9; i++){
result = result + questions.get(i).getQuestion() + "\n";
}
return result;
// TODO Auto-generated method stub
}
The thing is, all these items also have a title(string) and graphical thumb (string) in the database. I would like to show them as illustrated in the picture below, each with an onclicklistener on it, instead of a boring list of items below eachother. Each item has a picture and title.
Since my beginning programming skills, I am wondering how to do this best, and if you know any good tutorials on it which explain it well?
Thanks!
if i understood your question you need to create a customize an adapter.
Create a new simple class like this which holds an string and a picture
Class ObjectHolder {
int Image;
String Title;
}
and create a getter and setter for this two
then create custom ArrayAdapter
Class CustomArrayAdapter extends ArrayAdapter<ObjectHolder> {
public CustomArrayAdapter(Context C, ObjectHolder[] Arr) {
super(C, R.layout.caa_xml, Arr);
}
#Override
public View getView(int position, View v, ViewGroup parent)
{
View mView = v ;
if(mView == null){
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mView = vi.inflate(R.layout.cpa_xml, null);
}
TextView text = (TextView) mView.findViewById(R.id.tv_caarow);
ImageView image = (ImageView) mView.findViewById(R.id.iv_caarow);
if(mView != null )
{ text.setText(getItem(position).getText());
image.setImageResource(getItem(position).getImage());
return mView;
}
}
and create caa_xml.xml in res\layout\
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/iv_caarow"
android:src="#drawable/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/tv_caarow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="15dip"
android:layout_BottomOf="#+id/iv_caarow" />
</RelativeLayout>
and use it like this.
GridView GV= (GridView) findViewById(R.Id.gv); // reference to xml or create in java
ObjectHolder[] OHA;
// assign your array, any ways!
mAdapter CustomArrayAdapter= CustomArrayAdapter(this, OHA);
GridView.setAdapter(mAdapter);

How to print data in a ListView using ListAdapter

Updated
I'm trying to print the data retrieved from the database on a list view. For a while my application print for each data in the database, a row on the list view. So if there are 10 data in the database, the app prints 10 rows, corresponding to each row of the database. Here is a view of how it is being printed.
The new image of how it looks now:
But, it is not printing the data as I want. I want to print a column of the row in a specific text view, but it doesnt show anything.
So the activity RatedCalss calls the method selectTopCalls() and makes a List receive the list that this method returns. And then I pass this list to the listAdapter.
Well I have this activity named RatedCalls.java:
public class RatedCalls extends Activity {
private static final String LOG_TAG = "RatedCalls";
private CallDataHelper cdh;
private ListView listview;
private ArrayList<String> ratedCallsList;
private MyListAdapter listAdapter;
private View view;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.i(LOG_TAG, "calling from onCreate()");
cdh = new CallDataHelper(this);
startService(new Intent(this, RatedCallsService.class));
setBasicContent();
}
public void setBasicContent() {
listview = (ListView) findViewById(R.id.list_view);
ratedCallsList = this.cdh.selectTopCalls();
Log.i(LOG_TAG, "ratedCallsList size: " + ratedCallsList.size());
listAdapter = new MyListAdapter(this, this, R.id.list_view, ratedCallsList);
listview.setAdapter(listAdapter);
}
}
I have this class, a ListAdapter class named MyListAdapter.java:
public class MyListAdapter extends ArrayAdapter { //--CloneChangeRequired
private ArrayList mList;
private Context mContext;
private Activity mActivity;
private int selectedPos = -1; // init value for not-selected
private ArrayList<String> ratedCallsList;
private CallDataHelper cdh;
public void setSelectedPosition(int pos){
selectedPos = pos;
notifyDataSetChanged();
}
public int getSelectedPosition(){
return selectedPos;
}
public MyListAdapter(Context context, Activity activity, int textViewResourceId, ArrayList list) {
super(context, textViewResourceId, list);
this.mList = list;
this.mContext = context;
this.mActivity = activity;
}
public View getView(int position, View convertView, ViewGroup parent){
View view = convertView;
try{
if (view == null) {
LayoutInflater vi = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.list_item, null); // --CloneChangeRequired(list_item)
}
// setting STRIP BG
if(position == selectedPos){
view.findViewById(R.id.rlt_main).setBackgroundColor( Color.rgb(062, 076, 120) );
}else if(position%2==0){
view.findViewById(R.id.rlt_main).setBackgroundColor( Color.rgb(226, 231, 239) );
}else{
view.findViewById(R.id.rlt_main).setBackgroundColor( Color.rgb(200, 210, 223) );
}
setViews(position, view);
}catch(Exception e){
//Log.i(MyListAdapter.class.toString(), e.getMessage());
}
return view;
}
public void setViews(int position, View view) {
cdh = new CallDataHelper(mContext);
if(mContext.getClass().equals((RatedCalls.class))){
ratedCallsList = this.cdh.selectTopCalls();
Log.i("MYLISTADAPTER", "size " + ratedCallsList.size());
if (ratedCallsList != null) {
((TextView) view.findViewById(R.id.contact_name)).setText(ratedCallsList.get(0));
((TextView) view.findViewById(R.id.phone_number)).setText(ratedCallsList.get(1));
((TextView) view.findViewById(R.id.duration)).setText(ratedCallsList.get(2));
((TextView) view.findViewById(R.id.date)).setText(ratedCallsList.get(3));
}
}else if(mContext.getClass().equals(RatedContacts.class)){
final PublishersBO listPublisher = (PublishersBO) mList.get(position);
if (listPublisher != null) {
//--setting list_item views
((TextView) view.findViewById(R.id.contact_name)).setText(listPublisher.getName());
((TextView) view.findViewById(R.id.phone_number)).setText(listPublisher.getEmail());
//--onClickListener
view.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent myIntent = new Intent(mContext,RatedContacts.class);
myIntent.putExtra("NAME", listPublisher.getName());
myIntent.putExtra("ACTIVITY_NAME", mContext.getClass().toString());
mContext.startActivity(myIntent);
mActivity.finish();
}
});
}
}
}
}
The method that retrieve the data from the database is in a separated class that deals with SQLite function. This is the method:
public ArrayList<String> selectTopCalls() {
ArrayList<String> list1 = new ArrayList<String>();
Cursor cursor = this.db.query(TABLE_NAME, null, null, null, null, null,
"duration desc");
if (cursor.moveToFirst()) {
do {
//if (cursor.getString(2) != "") {
cdObj = new CallData();
list1.add(cursor.getString(2));
list1.add(cursor.getString(4));
list1.add(cursor.getString(5));
list1.add(cursor.getString(6));
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return list1;
}
And here is the xml file for the view named list_item.xml:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="67px"
android:id="#+id/rlt_main"
android:layout_toRightOf="#+id/iv_forward">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:id="#+id/iv_forward"
android:src="#drawable/icon"
android:layout_alignParentLeft="true">
</ImageView>
<TextView
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:id="#+id/phone_number"
android:layout_alignParentBottom="true"
android:layout_toRightOf="#+id/iv_forward"
android:layout_alignBottom="#+id/iv_forward">
</TextView>
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/duration"
android:layout_alignBottom="#+id/phone_number"
android:layout_alignRight="#+id/phone_number"
>
</TextView>
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/date"
android:layout_alignBottom="#+id/contact_name"
android:layout_alignRight="#+id/contact_name"
>
</TextView>
<TextView
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:id="#+id/contact_name"
android:textSize="20px"
android:layout_toRightOf="#+id/iv_forward"
android:layout_alignParentTop="true">
</TextView>
So I'd like to print the data in the text views in the activity, but I dont know where to set the text, in what class, if in the MyListAdapter class or if in the activity.
Thanks.
I have made few changes to your code, check here,
https://gist.github.com/683b84af9d01bf18fe3d
Thanks.........

Problem registering clicks on Button on CustomCursorAdapter in a ListView

What i am trying to do is catch a Button click that is inside a ListView managed by a CustomCursorAdapter. when clicked i need to make the button invisible and update a value in the database. here is the code i am using for the ListActivity and the CursorAdapter.
public class MainTabView extends ListActivity{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
fillListData();
}
private void fillListData(){
DataBaseNamesHelper myDbNamesHelper = new DataBaseNamesHelper(this);
myDbNamesHelper.openDataBase();
Cursor cursor = myDbNamesHelper.getCursorQueryWithAllTheTaxiStations();
startManagingCursor(cursor);
// the desired columns to be bound
String[] columns = new String[] { DataBaseNamesHelper.COLUMN_NAME, DataBaseNamesHelper.COLUMN_PEOPLE};
// the XML defined views which the data will be bound to
int[] to = new int[] { R.id.name_entry, R.id.number_entry };
// create the adapter using the cursor pointing to the desired data as well as the layout information
CustomCursorAdapter mAdapter = new CustomCursorAdapter(this, R.layout.list_entry, cursor, columns, to);
// set this adapter as your ListActivity's adapter
this.setListAdapter(mAdapter);
this.getListView().setOnItemClickListener(mAdapter);
myDbNamesHelper.close();
}
and the Adapter:
public class CustomCursorAdapter extends SimpleCursorAdapter implements SectionIndexer,Filterable,
android.widget.AdapterView.OnItemClickListener{
private Context context;
private int layout;
private AlphabetIndexer alphaIndexer;
public CustomCursorAdapter (Context context, int layout, Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to);
this.context = context;
this.layout = layout;
alphaIndexer=new AlphabetIndexer(c, c.getColumnIndex(DataBaseNamesHelper.COLUMN_NAME), " ABCDEFGHIJKLMNOPQRSTUVWXYZ");
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
Cursor c = getCursor();
final LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(layout, parent, false);
int nameCol = c.getColumnIndex(DataBaseNamesHelper.COLUMN_NAME);
String name = c.getString(nameCol);
/**
* Next set the name of the entry.
*/
TextView name_text = (TextView) v.findViewById(R.id.name_entry);
if (name_text != null) {
name_text.setText(name);
}
int favCol = c.getColumnIndex(DataBaseNamesHelper.COLUMN_FAVOURITED);
int fav = c.getInt(favCol);
Button button = (Button) v.findViewById(R.id.Button01);
if(fav==1){
button.setVisibility(View.INVISIBLE);
}
return v;
}
#Override
public void bindView(View v, Context context, Cursor c) {
int nameCol = c.getColumnIndex(DataBaseNamesHelper.COLUMN_NAME);
String name = c.getString(nameCol);
/**
* Next set the name of the entry.
*/
TextView name_text = (TextView) v.findViewById(R.id.name_entry);
if (name_text != null) {
name_text.setText(name);
}
int favCol = c.getColumnIndex(DataBaseNamesHelper.COLUMN_FAVOURITED);
int fav = c.getInt(favCol);
Button button = (Button) v.findViewById(R.id.Button01);
Log.e("fav",String.valueOf(fav));
if(fav==1){
button.setVisibility(View.INVISIBLE);
}
}
#Override
public int getPositionForSection(int section) {
return alphaIndexer.getPositionForSection(section);
}
#Override
public int getSectionForPosition(int position) {
return alphaIndexer.getSectionForPosition(position);
}
#Override
public Object[] getSections() {
return alphaIndexer.getSections();
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Log.e("item Click", arg1.toString()+ " position> " +arg2);
}
i have already set the button to be clickable(true) and focusable(false).
with this code i can achieve what i want but by clicking the listView row (logs only item clicks on the LinearLayout that is holding the button. how do i make the button receive click exactly the same as LinearLayout does?
here is the row layout:
<?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="wrap_content" android:orientation="horizontal" android:focusable="false">
<TextView
android:id="#+id/name_entry"
android:layout_height="wrap_content"
android:textSize="28dip" android:layout_width="wrap_content" android:layout_weight="1" android:layout_gravity="center_vertical"/>
<Button android:id="#+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Fav" android:layout_gravity="center_vertical" android:layout_marginRight="10dp" android:focusable="false" android:clickable="true"></Button><TextView
android:id="#+id/number_entry"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="28dip" />
</LinearLayout>
you need a new aproach as is this described in the button documentation.
However, instead of applying an OnClickListener to the button in your activity, you can assign a method to your button in the XML layout, using the android:onClick attribute. For example:
<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="#string/self_destruct"
android:onClick="selfDestruct" />
Now, when a user clicks the button, the Android system calls the activity's selfDestruct(View) method. In order for this to work, the method must be public and accept a View as its only parameter. For example:
public void selfDestruct(View view) {
// Kabloey
}
The View passed into the method is a reference to the widget that was clicked. You can setTag() on the View in the adapter to recognize which button was clicked.
Try adding the following line in your item layout xml file. This should be added to the root layout.
<LinearLayout .....
android:descendantFocusability="beforeDescendants"
..... />
From there you can set your onClickListener of the button in the getView method of your adapter.

Categories

Resources