i fill listview with data from local sqlite database. from my current query I want to get the foodname and protein, have set it in the Textview , adapter and query to get this data, but it only return only the name not the protein.
Here is the adapter class:
public class Db_listView_Adapter extends CursorAdapter {
public Db_listView_Adapter(Context context, Cursor cursor) {
super(context, cursor, 0);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {
return LayoutInflater.from(context).inflate(R.layout.db_list, viewGroup, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView foodName = (TextView) view.findViewById(R.id.foodNameInListView);
TextView foodProtein = (TextView) view.findViewById(R.id.foodProteinInListView);
TextView foodCarbs = (TextView) view.findViewById(R.id.foodCarbsInListView);
TextView foodFat = (TextView) view.findViewById(R.id.foodFatsInListView);
TextView foodCalories = (TextView) view.findViewById(R.id.foodCaloriesInListView);
TextView foodFibers = (TextView) view.findViewById(R.id.foodFibersInListView);
TextView foodVitA = (TextView) view.findViewById(R.id.foodVitAInListView);
TextView foodVitB = (TextView) view.findViewById(R.id.foodVitBInListView);
TextView foodCalcium = (TextView) view.findViewById(R.id.foodCalciumInListView);
TextView foodMagnesium = (TextView) view.findViewById(R.id.foodMagnesiumInListView);
String foodNameString = cursor.getString(cursor.getColumnIndexOrThrow("_FoodName"));
String foodProteinString = cursor.getString(cursor.getColumnIndexOrThrow("_FoodProtein"));
foodName.setText(foodNameString);
foodProtein.setText(foodProteinString);
}
}
Here is the xml for the layout of 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">
<TextView
android:id="#+id/foodNameInListView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/foodProteinInListView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/foodCarbsInListView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/foodFatsInListView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/foodCaloriesInListView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/foodFibersInListView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/foodVitAInListView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/foodVitBInListView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/foodCalciumInListView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/foodMagnesiumInListView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
Here I try to get the data from the database and fill the listview:
public class Db_fragment extends Fragment {
View view;
ListView listView;
Db_listView_Adapter db_listView_adapter;
public Db_fragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.db_fragment, container, false);
listView = (ListView) view.findViewById(R.id.dbView);
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
final MyDatabaseOpenHelper mDbHelper = new MyDatabaseOpenHelper(view.getContext());
final EditText foodName = (EditText) view.findViewById(R.id.nameForDb);
Button enterData = (Button) view.findViewById(R.id.enterData);
Button showData = (Button) view.findViewById(R.id.showData);
final TextView errorTextNameMissing = (TextView) view.findViewById(R.id.errorTextNameMissing);
showData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (foodName.getText().toString().trim().length() != 0) {
errorTextNameMissing.setText("");
SQLiteDatabase myDb = mDbHelper.getReadableDatabase();
String[] projection = {TableFoodMacros.FoodMacros._ID, TableFoodMacros.FoodMacros.FOOD_NAME, TableFoodMacros.FoodMacros.FOOD_PROTEIN};
String rawQuery = "SELECT _ID, _Foodname , _FoodProtein FROM FoodMacros where _FoodName = " + "'" + foodName.getText().toString() + "'";
Cursor c = myDb.rawQuery(rawQuery, null);
if(c.getCount() == 0){
Intent goToSaveFood = new Intent(getActivity(),Save_Food.class);
goToSaveFood.putExtra("FoodName", foodName.getText().toString());
myDb.close();
startActivity(goToSaveFood);
}else {
db_listView_adapter = new Db_listView_Adapter(view.getContext(), c);
listView.setAdapter(db_listView_adapter);
myDb.close();
}
} else {
errorTextNameMissing.setText(getResources().getString(R.string.errorTextNameMissing));
}
}
});
}
}
So i found that the problem was in the activity that add data in the DB, i was doing in onCreate instead of onClick... ;x
Related
I am working on a sqlite database project on android. And it's my first sqlite project. I read lots of article and created my app but there's a problem that I can't find a way to solve it.i want to get NAME_FILTER table to autoCompleteTextView
here is my layout code
<?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="wrap_content"
android:paddingTop="10dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="90dp"
android:layout_height="wrap_content"
android:text="#string/customers_name"
android:textSize="16sp" />
<AutoCompleteTextView
android:id="#+id/autoCompleteTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="5"/>
<EditText
android:id="#+id/edt_filter_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:imeOptions="actionNext"
style="#style/EditText.Input"
android:theme="#style/EditText.Input"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingTop="20dp"
android:paddingBottom="20dp">
<Button
android:id="#+id/btn_submit"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/btn_submit"
android:textColor="#333333"
android:background="#drawable/buttonshape"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:textSize="18sp"
android:drawableStart="#drawable/ic_check_black_24dp"/>
<Button
android:id="#+id/btn_cancel"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/btn_cancel"
android:textColor="#333333"
android:background="#drawable/red_button_background"
android:textSize="18sp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:drawableStart="#drawable/ic_cancel_black_24dp"/>
</LinearLayout>
</LinearLayout>
and here is my Activity
public class FiltersActivity extends AppCompatActivity implements ActionMode.Callback{
#Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
private static int Filter_list_position = -1;
private Button btnSubmit;
private Button btnCancel;
private ListView listView;
private FilterListAdapter adapter;
private EditText edtName;
private int seletcedFilterId;
ActionMode mActionMode;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(R.string.filters_title);
setContentView(R.layout.activity_filters);
btnCancel = (Button) findViewById(R.id.btn_cancel);
btnSubmit = (Button) findViewById(R.id.btn_submit);
edtName = (EditText) findViewById(R.id.edt_filter_name);
btnCancel.setOnClickListener(onCancelbuttonClicked);
listView = (ListView) findViewById(R.id.listView);
//Creating the instance of ArrayAdapter containing list of fruit names
ArrayAdapter<String> adapterr = new ArrayAdapter<String>
(this, android.R.layout.select_dialog_item, NAME_FILTER);
//Getting the instance of AutoCompleteTextView
AutoCompleteTextView actv = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
actv.setThreshold(1);//will start working from first character
actv.setAdapter(adapterr);//setting the adapter data into the AutoCompleteTextView
refreshList();
if(getSupportActionBar() != null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
DataBaseHelper Cllas
public class DatabaseHelper {
private SQLiteDatabase mydb;
public DatabaseHelper(Context context){
mydb = new MyDatabase(context).getWritableDatabase();
}
public void addNewFilter(filter filter){
ContentValues values = new ContentValues();
values.put("name", filter.getName());
mydb.insert(MyDatabase.tableFilters, null, values);
mydb.close();
}
public List<filter> getListOfFilters(){
Cursor c = mydb.rawQuery("select * from " + MyDatabase.tableFilters, null);
List<filter> filters = new ArrayList<>();
while (c.moveToNext()){
filter em = new filter();
em.setId(c.getInt(c.getColumnIndex(MyDatabase.ID_FILTER)));
em.setName(c.getString(c.getColumnIndex(MyDatabase.NAME_FILTER)));
filters.add(em);
}
c.close();
mydb.close();
return filters;
}
public void editFilter(filter filter){
ContentValues values = new ContentValues();
values.put("name", filter.getName());
mydb.update(MyDatabase.tableFilters, values, "id = " + filter.getId(), null);
mydb.close();
}
public void deleteFilter(filter filter){
mydb.delete(MyDatabase.tableFilters, "id = " + filter.getId(), null);
mydb.close();
}
public List<filter> searchFilterByName(String name){
Cursor c = mydb.rawQuery("select * from " + MyDatabase.tableFilters + " where name like '%" + name + "%'", null);
List<filter> filters = new ArrayList<>();
while (c.moveToNext()){
filter em = new filter();
em.setId(c.getInt(c.getColumnIndex(MyDatabase.ID_FILTER)));
em.setName(c.getString(c.getColumnIndex(MyDatabase.NAME_FILTER)));
filters.add(em);
}
c.close();
mydb.close();
return filters;
}
}
and this is my ListAdapter Class
class FilterListAdapter extends BaseAdapter {
private Context context;
private List<filter> filters;
FilterListAdapter(Context context, List<filter> filters){
this.context = context;
this.filters = filters;
}
#Override
public int getCount() {
return filters.size();
}
#Override
public Object getItem(int i) {
return filters.get(i);
}
#Override
public long getItemId(int i) {
return filters.get(i).getId();
}
#Override
public View getView(final int position, View view, ViewGroup viewGroup) {
View rowView = LayoutInflater.from(context).inflate(R.layout.filter_list_item, viewGroup, false);
TextView txtName = (TextView) rowView.findViewById(R.id.txt_filter_name);
txtName.setText(filters.get(position).getName());
return rowView;
}
}
I have a Fragment class that can display everything in my database in a ListView, and I have an inner class that extends SimpleCursorAdapter to use buttons within my ListView.
So in each element of my list view, I have several TextView's and 2 button. With my following code, I can use a button listener for a button inside my ListView. But inside my listener, I want to get the content of the TextView inside the same element that the button I click on. But When I click on a button to display my TextView, it display the last element of my ListView and I don't know why !
For example if I have 3 elements in my ListView like this :
_id = 1, name = "bob"
_id = 2, name = "john"
_id = 3, name = "bobby"
Each of these element are displayed with a button to display there ID, but if I click on the button inside bob, I get "id = 3". Same for john and bobby. And if I had a new element, I get his ID
My listener is in the bind function in my inner class MySimpleCursorAdapter.
Here is my Fragment Class :
public class ViewCardEditor extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
public static final String authority = "com.example.jean.cartememoire.CardContentProvider";
public String[] from;
public final int[] to = {R.id.idList, R.id.themeList, R.id.questionList, R.id.reponseList, R.id.difficultList};
StockCard stock;
ViewGroup container;
ListView listView;
MySimpleCursorAdapter adapter;
private ArrayList<String> data = new ArrayList<String>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup c,
Bundle savedInstanceState) {
container = c;
View view = inflater.inflate(R.layout.fragment_view_card_editor, container, false);
stock = new StockCard(c.getContext());
from = new String[]{stock._ID,
stock.THEME,
stock.QUESTION,
stock.REPONSE,
stock.DIFFICULTE};
// Inflate the layout for this fragment
if (container != null) {
container.removeAllViews();
}
//listView.setAdapter(new MyListAdapter(container.getContext(), R.layout.card_stock, data));
//View view_cs = LayoutInflater.from(container.getContext()).inflate(R.layout.card_stock, null);
//Supprimer = (Button) view_cs.findViewById(R.id.buttonDelete);
//Modifier = (Button) view_cs.findViewById(R.id.buttonModifier);
databaseView(view);
return view;
}
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
Uri.Builder builder = new Uri.Builder();
Uri uri = builder.scheme("content").authority(authority)
.appendPath(stock.STOCK_TABLE).build();
return new CursorLoader(container.getContext(), uri, from,
null, null, null);
}
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
adapter.swapCursor(data);
}
public void onLoaderReset(Loader<Cursor> loader) {
adapter.swapCursor(null);
}
public void databaseView(View view)
{
ArrayList<String> list;
Cursor cursor = stock.getData();
listView = (ListView) view.findViewById(R.id.listView);
adapter = new MySimpleCursorAdapter(container.getContext(), R.layout.card_stock, null, from, to,0);
listView.setAdapter(adapter);
LoaderManager manager = getLoaderManager();
manager.initLoader(0, null, this);
}
public void deleteOneCard(int id)
{
Uri.Builder builder = new Uri.Builder();
builder.scheme("content").authority(authority).appendPath(stock.STOCK_TABLE);
ContentUris.appendId(builder, id);
Uri uri = builder.build();
ContentResolver resolver = container.getContext().getContentResolver();
resolver.delete(uri, null, null);
}
private class MySimpleCursorAdapter extends SimpleCursorAdapter
{
ViewHolder vh;
public MySimpleCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) {
super(context, layout, c, from, to, flags);
}
public View newView(Context _context, Cursor _cursor, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) _context.getSystemService(_context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.card_stock, parent, false);
vh = new ViewHolder();
vh.idList = (TextView) view.findViewById(R.id.idList);
vh.themeList = (TextView) view.findViewById(R.id.themeList);
vh.questionList = (TextView) view.findViewById(R.id.questionList);
vh.reponseList = (TextView) view.findViewById(R.id.reponseList);
vh.difficulteList = (TextView) view.findViewById(R.id.difficultList);
vh.Supprimer = (Button) view.findViewById(R.id.buttonDelete);
vh.Modifier = (Button) view.findViewById(R.id.buttonModifier);
view.setTag(vh);
return view;
}
public void bindView(View view, Context Context, Cursor cursor) {
vh.idList.setText(cursor.getString(cursor.getColumnIndex(stock._ID)));
vh.themeList.setText(cursor.getString(cursor.getColumnIndex(stock.THEME)));
vh.questionList.setText(cursor.getString(cursor.getColumnIndex(stock.QUESTION)));
vh.reponseList.setText(cursor.getString(cursor.getColumnIndex(stock.REPONSE)));
vh.difficulteList.setText(cursor.getString(cursor.getColumnIndex(stock.DIFFICULTE)));
vh.Supprimer.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
int id = Integer.parseInt(vh.idList.getText().toString());
Toast.makeText(container.getContext(), "bouton delete : "+id, Toast.LENGTH_LONG).show();
//Here everytime I hit the button, the last ID i put on the listView is displayed, no matter what Supprimer button I click
}
});
}
}
public class ViewHolder
{
Button Supprimer, Modifier;
TextView idList, themeList, questionList, reponseList, difficulteList;
}
}
And here is my layout for my TextView :
<?xml version="1.0" encoding="utf-8"?>
<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:id="#+id/relativeList"
android:descendantFocusability="blocksDescendants">
<TextView
android:text="#string/difficult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView8"
android:layout_below="#+id/textView7"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="29dp" />
<TextView
android:text="#string/r_ponse"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView7"
android:layout_marginTop="20dp"
android:layout_below="#+id/textView6"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/idList"
android:layout_alignParentTop="true"
android:layout_alignLeft="#+id/themeList"
android:layout_alignStart="#+id/themeList"
tools:ignore="HardcodedText" />
<TextView
android:text="Question :"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView6"
android:layout_marginTop="14dp"
android:layout_below="#+id/textView4"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
tools:ignore="HardcodedText" />
<TextView
android:text="#string/id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView3"
android:layout_alignParentTop="true"
android:layout_alignRight="#+id/textView4"
android:layout_alignEnd="#+id/textView4" />
<TextView
android:text="Thème :"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView4"
android:layout_below="#+id/textView3"
android:layout_alignRight="#+id/textView6"
android:layout_alignEnd="#+id/textView6"
tools:ignore="HardcodedText" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/textView6"
android:id="#+id/questionList"
android:layout_toRightOf="#+id/themeList"
android:layout_toEndOf="#+id/themeList" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/textView8"
android:layout_alignLeft="#+id/questionList"
android:layout_alignStart="#+id/questionList"
android:id="#+id/reponseList" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/textView8"
android:layout_alignRight="#+id/reponseList"
android:layout_alignEnd="#+id/reponseList"
android:id="#+id/difficultList"
android:layout_toEndOf="#+id/reponseList"
android:layout_toRightOf="#+id/reponseList" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/themeList"
android:layout_marginLeft="33dp"
android:layout_marginStart="33dp"
tools:ignore="HardcodedText"
android:layout_below="#+id/idList"
android:layout_toRightOf="#+id/textView8"
android:layout_toEndOf="#+id/textView8" />
<Button
android:text="#string/supprimerb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:id="#+id/buttonDelete"/>
<Button
android:text="#string/modifierB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/buttonModifier"
android:layout_alignTop="#+id/questionList"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignLeft="#+id/buttonDelete"
android:layout_alignStart="#+id/buttonDelete" />
</RelativeLayout>
Thank you for help !
Probably vh.idList is containing last item view which is provided by last call of newView .
Get clicked row item id using findViewById and v parameter of onClick method:
public void onClick(View v) {
View parentView = (View)v.getParent();
TextView idList = parentView.findViewById(R.id.idList);
int id = Integer.parseInt(idList.getText().toString());
...
}
This question already has answers here:
ListView and Buttons inside ListView
(5 answers)
Closed 8 years ago.
Currently, my listView is sitting inside a fragment. However, the buttons inside my view are not able to receive the on click event whenever I tap on them.
I am not sure what to do.
Here is my code:
public class ViewInvitationsCursorAdapter extends CursorAdapter {
private Activity activity;
private int layout;
private Cursor cr;
private final LayoutInflater inflater;
private Fragment f;
private boolean displayAcceptDeny;
public ViewInvitationsCursorAdapter(Activity activity, Fragment f,
int layout, Cursor c, boolean displayAcceptDeny) {
super(activity, c);
this.layout = layout;
this.activity = activity;
this.inflater = LayoutInflater.from(activity);
this.cr = c;
this.f = f;
this.displayAcceptDeny = displayAcceptDeny;
}
public static class ViewHolder {
public TextView sender;
public TextView sender_email;
public TextView author_role;
public Button deny;
public Button accept;
public Button cancel;
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
ViewHolder holder = new ViewHolder();
View view = inflater.inflate(layout, parent, false);
holder.sender = (TextView) view.findViewById(R.id.connection_sender);
holder.sender_email = (TextView) view
.findViewById(R.id.connection_sender_email);
holder.author_role = (TextView) view.findViewById(R.id.connection_role);
holder.accept = (Button) view.findViewById(R.id.connection_allow);
holder.deny = (Button) view.findViewById(R.id.connection_deny);
holder.cancel = (Button) view.findViewById(R.id.connection_cancel);
view.setTag(holder);
return view;
}
#Override
public void bindView(View view, Context context, final Cursor cursor) {
// .bindView(view, context, cursor);
final ViewHolder holder = (ViewHolder) view.getTag();
int sender_index = cursor
.getColumnIndexOrThrow(FamilyDBHelper.COLUMN_SENDER_BY_NAME);
int sender_email_index = cursor
.getColumnIndexOrThrow(FamilyDBHelper.COLUMN_SENDER_BY_EMAIL);
String senderString = cursor.getString(sender_email_index);
int author_role_name = cursor
.getColumnIndexOrThrow(FamilyDBHelper.COLUMN_RELATIONTYPE_NAME);
int message_index = cursor
.getColumnIndexOrThrow(FamilyDBHelper.COLUMN_MESSAGE);
holder.sender.setText(cursor.getString(sender_index));
holder.author_role.setText(cursor.getString(author_role_name));
holder.sender_email.setText(cursor.getString(sender_email_index));
holder.cancel.setVisibility(View.VISIBLE);
// setUpCancel(view, cursor);
holder.cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Log.i("cancel", "cancel clicked!");
}
});
}
protected void setUpAcceptDeny(View view, final Cursor cursor) {
final ViewHolder holder = (ViewHolder) view.getTag();
holder.accept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Log.i("accept", "accept clicked!");
}
});
holder.deny.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Log.i("deny", "deny clicked!");
}
});
}
}
Here is the xml for each of the items:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/connection_item_row_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingBottom="8dp"
android:paddingLeft="8dp"
android:paddingRight="8dp"
android:paddingTop="8dp" >
<LinearLayout
android:id="#+id/connection_item_info_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:layout_weight="1"
android:orientation="vertical" >
<TextView
android:id="#+id/connection_sender"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:textSize="16sp"
android:textStyle="bold"
tools:text="ANDROID: PREFERENCEFRAGMENTCOMPAT" >
</TextView>
<TextView
android:id="#+id/connection_sender_email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/connection_sender"
android:textColor="#000000"
android:textSize="14sp"
tools:text="ANDROID: PREFERENCEFRAGMENTCOMPAT" >
</TextView>
<TextView
android:id="#+id/connection_role"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/connection_sender_email"
android:textColor="#000000"
android:textSize="14sp"
>
</TextView>
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/connection_item_info_layout"
android:orientation="horizontal"
android:paddingBottom="1.0dip"
android:paddingLeft="4.0dip"
android:paddingRight="4.0dip"
android:paddingTop="5.0dip" >
<Button
android:id="#+id/connection_allow"
android:layout_width="0.0dip"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:text="Allow"
android:background="#color/green"
android:textColor="#color/white"
android:visibility="gone" />
<Button
android:id="#+id/connection_deny"
android:layout_width="0.0dip"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:background="#color/red"
android:textColor="#color/white"
android:text="Deny"
android:visibility="gone" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/connection_item_info_layout_request"
android:orientation="horizontal"
android:paddingBottom="1.0dip"
android:paddingLeft="4.0dip"
android:paddingRight="4.0dip"
android:paddingTop="5.0dip" >
<Button
android:id="#+id/connection_cancel"
android:layout_width="0.0dip"
android:background="#color/red"
android:textColor="#color/white"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:text="Cancel Request"
android:visibility="gone" />
</LinearLayout>
</LinearLayout>
Add this line to your list item xml file.
android:descendantFocusability="blocksDescendants"
if you set clicklistener inside newView method like this it should work. I generally user getView() for this method and there has never been a problem..
#Override
public View getView(Context context, View View, ViewGroup parent) {
ViewHolder holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View = inflater.inflate(R.layout.your_layout_file_id, parent,
false);
holder.sender = (TextView) view.findViewById(R.id.connection_sender);
holder.sender_email = (TextView) view
.findViewById(R.id.connection_sender_email);
holder.author_role = (TextView) view.findViewById(R.id.connection_role);
holder.accept = (Button) view.findViewById(R.id.connection_allow);
holder.deny = (Button) view.findViewById(R.id.connection_deny);
holder.cancel = (Button) view.findViewById(R.id.connection_cancel);
view.setTag(holder);
holder.cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Log.i("cancel", "cancel clicked!");
}
});
return view;
}
I have a custom ListView where each row consists of a number of TextViews inside it. When I click on the ListItem, the OnListItemClick() doesn't get called. So how do you get the selected of a custom list view?
Thanks for your help!
XML for Row:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/priorityView"
android:layout_width="20dip"
android:layout_height="match_parent"
android:background="#cccccc"
android:layout_marginTop="2dip"
android:layout_marginBottom="2dip" />
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:weightSum="1.0"
>
<TextView
android:id="#+id/dateText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:paddingBottom="2dip"
android:paddingLeft="5dip"
android:paddingRight="5dip"
android:paddingTop="2dip"
android:text="#string/empty"
android:textSize="20dip"
android:textStyle="bold" />
<TextView
android:id="#+id/monthText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:padding="5dip"
android:text="#string/empty"
android:textSize="10dip" >
</TextView>
</LinearLayout>
<TextView
android:id="#+id/timeText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:padding="5dip"
android:text="#string/empty" >
</TextView>
<TextView
android:id="#+id/titleText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:padding="5dip"
android:text="#string/empty"
android:textStyle="bold"
android:layout_weight="1.0" >
</TextView>
<CheckBox
android:id="#+id/selectedCheckbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="5dip" >
</CheckBox>
</LinearLayout>
XML for 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" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true" >
</ListView>
</RelativeLayout>
Java
public class MainActivity extends ListActivity {
private AppointmentsDB dbHelper;
private Cursor cursor;
private AppointmentsCursorAdapter cursorAdapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHelper = new AppointmentsDB(this);
StringBuilder selectQuery = new StringBuilder();
selectQuery.append("SELECT "+AppointmentsDB.KEY_ID+",");
selectQuery.append(AppointmentsDB.KEY_TITLE + ", ");
selectQuery.append(AppointmentsDB.KEY_DESCRIPTION + ", ");
selectQuery.append(AppointmentsDB.KEY_PRIORITY + ", ");
selectQuery.append(AppointmentsDB.KEY_DATE_TIME + ", ");
selectQuery.append(AppointmentsDB.KEY_DURATION + ", ");
selectQuery.append(AppointmentsDB.KEY_ALARM_TIME + " FROM "
+ AppointmentsDB.DATABASE_TABLE + " ");
selectQuery.append("ORDER BY " + AppointmentsDB.KEY_DATE_TIME + " ASC");
cursor = dbHelper.openReadableDatabase().rawQuery(
selectQuery.toString(), null);
String[] columnNames = new String[] { };
int[] ids = new int[] { };
cursorAdapter = new AppointmentsCursorAdapter(this,
R.layout.row, cursor, columnNames, ids);
this.setListAdapter(cursorAdapter);
}
// This class sets our customised layout for the ListView
class AppointmentsCursorAdapter extends SimpleCursorAdapter {
private int layout;
private int[] colours;
#SuppressWarnings("deprecation")
public AppointmentsCursorAdapter(Context context, int layout, Cursor c,
String[] from, int[] to) {
super(context, layout, c, from, to);
this.layout = layout;
colours = new int[] {
context.getResources().getColor(R.color.light_gray),
context.getResources().getColor(R.color.green),
context.getResources().getColor(R.color.orange),
context.getResources().getColor(R.color.brick_red) };
}
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(layout, parent, false);
TextView titleText = (TextView) view.findViewById(R.id.titleText);
TextView priorityView = (TextView) view
.findViewById(R.id.priorityView);
TextView dateText = (TextView) view.findViewById(R.id.dateText);
TextView monthText = (TextView) view.findViewById(R.id.monthText);
TextView timeText = (TextView) view.findViewById(R.id.timeText);
String title = cursor.getString(cursor
.getColumnIndex(AppointmentsDB.KEY_TITLE));
int priority = 0;
String _priority = cursor.getString(cursor.getColumnIndex(AppointmentsDB.KEY_PRIORITY));
if(_priority != null)
priority = Integer.parseInt(_priority);
long dateTime = Long.parseLong(cursor.getString(cursor
.getColumnIndex(AppointmentsDB.KEY_DATE_TIME)));
Calendar calendar = new GregorianCalendar();
calendar.setTimeInMillis(dateTime);
SimpleDateFormat timeFormat = new SimpleDateFormat(
"dd,MMM,HH:mm aaa");
String[] tokens = timeFormat.format(calendar.getTime()).split(",");
dateText.setText(tokens[0]);
monthText.setText(tokens[1]);
timeText.setText(tokens[2]);
titleText.setText(title);
priorityView.setBackgroundColor(colours[priority]);
return view;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
super.bindView(view, context, cursor);
TextView titleText = (TextView) view.findViewById(R.id.titleText);
TextView priorityView = (TextView) view
.findViewById(R.id.priorityView);
TextView dateText = (TextView) view.findViewById(R.id.dateText);
TextView monthText = (TextView) view.findViewById(R.id.monthText);
TextView timeText = (TextView) view.findViewById(R.id.timeText);
String title = cursor.getString(cursor
.getColumnIndex(AppointmentsDB.KEY_TITLE));
int priority =0;
String _priority = cursor.getString(cursor
.getColumnIndex(AppointmentsDB.KEY_PRIORITY));
if(_priority != null)
priority = Integer.parseInt(_priority);
long dateTime = Long.parseLong(cursor.getString(cursor
.getColumnIndex(AppointmentsDB.KEY_DATE_TIME)));
Calendar calendar = new GregorianCalendar();
calendar.setTimeInMillis(dateTime);
SimpleDateFormat timeFormat = new SimpleDateFormat(
"dd,MMM,HH:mm aaa");
String[] tokens = timeFormat.format(calendar.getTime()).split(",");
dateText.setText(tokens[0]);
monthText.setText(tokens[1]);
timeText.setText(tokens[2]);
titleText.setText(title);
priorityView.setBackgroundColor(colours[priority]);
}
}
}
I find the solution.
You have to set the android:focusable attribute to false for each widget inside the custom ListView, including the Layout widgets.
Try usingOnItemClick() instead of OnListItemClick(),
This is the Custom listview created by SimpleCursorAdapter by sending cursor
SimpleCursorAdapter yearadapter =
new SimpleCursorAdapter(this, R.layout.listview, yearcursor, yearfrom, yearto);
setListAdapter(yearadapter);
amount.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
//Your code when item get clicked
}
});
It should work.
Below code will give you the list view item:
private ListView listView = (ListView) findviewbyid(.........);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
View v = v.getChildAt(arg2);//This will give the listview item
}
});
Hello i am trying to implement a listview which will display the contents of a class by TextView. However the adapter doesn't seem to take in the values of the objects as it throws a nullpointer exception.
this is my custom class
public class SubjectClass {
String sName;
String sCode;
String teacher;
}
Given Belows is the code for my CUstomarrayadapter
public CustomAdap(Activity context, ArrayList<SubjectClass> names) {
super(context, R.layout.listtempl, names);
this.context = context;
this.names = names;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.listtempl, null, true);
TextView textView1 = (TextView) rowView.findViewById(R.id.label1);
TextView textView2 = (TextView) rowView.findViewById(R.id.label2);
TextView textView3 = (TextView) rowView.findViewById(R.id.label3);
SubjectClass sClass= (SubjectClass)getItem(position);
String s1 = sClass.sName;
String s2 = sClass.sCode;
String s3 = sClass.teacher;
Toast.makeText(getContext(), sClass.sCode,Toast.LENGTH_SHORT).show();
textView1.setText(s1);
textView2.setText(s2);
textView3.setText(s3);
return rowView;
}
this is the xml file used by the adapter
<?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" >
<TextView android:text="#+id/label1" android:textColor="#F1235AFA" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="#+id/label" android:layout_alignParentTop="true" android:textAppearance="?android:attr/textAppearanceMedium" android:layout_alignParentLeft="true"></TextView>
<TextView android:text="TextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="#+id/textView2" android:textAppearance="?android:attr/textAppearanceSmall" android:layout_alignBaseline="#+id/textView1" android:layout_alignBottom="#+id/label2" android:layout_alignParentLeft="true"></TextView>
<TextView android:text="TextView" android:textColor="#2CD7E0" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="#+id/textView1" android:textAppearance="?android:attr/textAppearanceSmall" android:layout_below="#+id/label" android:layout_toRightOf="#+id/label3" android:layout_marginLeft="15dp"></TextView>
</RelativeLayout>
This is my activity
public class SampleActivity extends Activity
{
ListView listview;
CustomAdap adapter;
ArrayList<SubjectClass> values = new ArrayList<SubjectClass>();
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.list1);
SubjectClass subjectClass = new SubjectClass();
subjectClass.sCode="cs9410";
subjectClass.sName="Principles of management";
subjectClass.teacher="xyz";
values.add(subjectClass);
SubjectClass subjectClass1 = new SubjectClass();
subjectClass1.sCode="cs9401";
subjectClass1.sName="Ethics";
subjectClass1.teacher="xxx";
values.add(subjectClass1);
listview =(ListView) findViewById(R.id.lv1);
adapter = new CustomAdap(this, values);
listview.setAdapter(adapter);
}
}//
In row layout file change android:text="#+id/label1" to android:id="#+id/label1".
For all 3 TextView:
SubjectClass sClass = (SubjectClass) names.get(position);
I believe you need to change your code to
SubjectClass sClass= names.get(position);