How to get selected item from custom ListView? - android

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

Related

Button listener and SimpleCursor adapter

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

ListView adapter does not show all requested data

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

CursorAdapter and OnItemClickListener

I have read other topics and I still have problem. setOnItemClickListener should be in Adapter class like below or in "MainActivity" class?
If is in Adapter class It can't do right reference to layout.
Error logcat:
Attempt to invoke virtual method 'void
android.widget.ListView.setOnItemClickListener(android.widget.AdapterView$OnItemClickListener)' on a null object reference
ListAdapter.java
public class ListAdapter extends CursorAdapter {
public ListAdapter(Context context, Cursor cursor, int flags) {
super(context, cursor, 0);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
final LayoutInflater inflater = LayoutInflater.from(context);
return LayoutInflater.from(context).inflate(R.layout.items, parent, false);
}
#Override
public void bindView(View view, Context context, final Cursor cursor) {
// Find fields to populate in inflated template
TextView txt1 = (TextView) view.findViewById(R.id.TitleLabel);
TextView txt2 = (TextView) view.findViewById(R.id.SecondLabel);
TextView txt3 = (TextView) view.findViewById(R.id.ThirdLabel);
// Extract properties from cursor
String name = cursor.getString(1);
txt1.setText(name);
ListView listview = (ListView) v.findViewById(R.id.listView);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view,
final int position, final long id) {
final String itemId = cursor.getString(cursor.getColumnIndex("_id"));
Log.i("Activity", "Cursor: " + cursor + " + " + position + " + id " + id + " ITEMID: " + itemId);
// final String item = (String) parent.getItemAtPosition(position);
view.animate().setDuration(500).alpha(0)
.withEndAction(new Runnable() {
#Override
public void run() {
// it was for SimpleCursorAdapter
listview.remove(item);
helper.deleteitem(id+1);
helper.deleteItemByName(item);
adapter.notifyDataSetChanged();
view.setAlpha(1);
}
});*/
}
});
}
}
items.xml layout
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="5dp"
android:paddingBottom="5dp"
>
<ImageView
android:id="#+id/postThumb"
android:layout_width="60dp"
android:layout_height="60dp"
android:src="#drawable/ic_launcher"
android:scaleType="centerCrop"
android:layout_marginRight="5dp"/>
<TextView
android:id="#+id/TitleLabel"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#id/postThumb"
android:layout_toRightOf="#id/postThumb"
android:maxLines="1"
android:text="Lorem Ipsum 1 line"
android:textIsSelectable="false"
android:textSize="16sp"
android:ellipsize="end"/>
<TextView
android:id="#+id/SecondLabel"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:maxLines="1"
android:textSize="12dp"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/postThumb"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<TextView
android:id="#+id/ThirdLabel"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignBottom="#id/postThumb"
android:layout_toRightOf="#id/postThumb"
android:maxLines="1"
android:textSize="11dp"
/>
</RelativeLayout>
Try to have setOnItemClickListener in oyur MainActivity but if you wish to use in your Adapter class then use setOnclickListener method of parent lauout of R.layout.items
Because in bindView each items are treated as single item.
Edited
Add id in Relative layout
android:id="#+id/myRelativelayout"
In Adatpter class
RelativeLayout rl =(RelativeLayout) view.findViewById(R.id.myRelativelayout);
implement r1.setOnClickListener and add your code.

android video playback

I'm new to android.
Can anyone help me how to display images from the Sd Card or play videos from Sd Card..
I tried it many ways but none of it is working..
<?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" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello" />
<VideoView
android:id="#+id/videoView1"
android:layout_width="243dp"
android:layout_height="234dp" />
</LinearLayout>
here is complete reference example about VideoView.
You just need to set path of your video file here.
This is binding all songs from sdcard into listview....
public class VideoListActivity extends ListActivity {
private MediaCursorAdapter mediaAdapter = null;
private String currentFile = "";
VideoView video;
MediaController mediaController;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main1);
video = (VideoView) findViewById(R.id.videoView1);
mediaController = new MediaController(this);
mediaController.setAnchorView(video);
video.setMediaController(mediaController);
video.setKeepScreenOn(true);
Cursor cursor = getContentResolver().query(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI, null, null, null,
null);
if (null != cursor) {
cursor.moveToFirst();
mediaAdapter = new MediaCursorAdapter(this, R.layout.listitem,
cursor);
setListAdapter(mediaAdapter);
}
}
#Override
protected void onListItemClick(ListView list, View view, int position,
long id) {
super.onListItemClick(list, view, position, id);
currentFile = (String) view.getTag();
video.setVideoPath(currentFile);
video.start();
video.requestFocus();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
private class MediaCursorAdapter extends SimpleCursorAdapter {
public MediaCursorAdapter(Context context, int layout, Cursor c) {
super(context, layout, c, new String[] {
MediaStore.Video.VideoColumns.DISPLAY_NAME,
MediaStore.Video.VideoColumns.ARTIST,
MediaStore.Video.VideoColumns.DURATION }, new int[] {
R.id.displayname, R.id.title, R.id.duration });
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView title = (TextView) view.findViewById(R.id.title);
TextView name = (TextView) view.findViewById(R.id.displayname);
TextView duration = (TextView) view.findViewById(R.id.duration);
name.setText(cursor.getString(cursor
.getColumnIndex(MediaStore.Video.VideoColumns.DISPLAY_NAME)));
String str=cursor.getString(cursor.getColumnIndex(MediaStore.Video.VideoColumns.ARTIST));
if(str.equals("<unknown>"))
title.setText(" ");
else
title.setText(""
+ cursor.getString(cursor
.getColumnIndex(MediaStore.Video.VideoColumns.ARTIST)));
long durationInMs = Long.parseLong(cursor.getString(cursor
.getColumnIndex(MediaStore.Video.VideoColumns.DURATION)));
double durationInMin = ((double) durationInMs / 1000.0) / 60.0;
durationInMin = new BigDecimal(Double.toString(durationInMin))
.setScale(2, BigDecimal.ROUND_UP).doubleValue();
duration.setText("" + durationInMin);
view.setTag(cursor.getString(cursor
.getColumnIndex(MediaStore.Video.VideoColumns.DATA)));
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.listitem, parent, false);
bindView(v, context, cursor);
return v;
}
}
}
listitem.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/displayname"
android:textSize="18dip"
android:textStyle="bold"
android:singleLine="true"
android:ellipsize="end"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/title"
android:textSize="15dip"
android:singleLine="true"
android:ellipsize="end"
android:layout_weight="1.0"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/duration"
android:gravity="right"
android:textSize="15dip"
android:singleLine="true"
android:ellipsize="end"/>
</LinearLayout>
</LinearLayout>

Android: archiving items in listview

I'm having a listview in which I'm displaying the text items. I want to display a checkbox along with the text for two type of actions to be performed. one is when the user click on the list item it should take to another activity and another is the user can select the checkbox of the list item and can move the items to some groups. As similar to that we do in the gmail inbox. how can i do it ? Any help ?
Here I attach my code.
keywords.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/keywordlayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/background_gradient"
android:orientation="vertical"
>
<LinearLayout
android:id="#+id/category_title_layout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:background="#fff"
>
<TextView
android:id="#+id/category_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=""
android:textColor="#000"
android:textStyle="italic"
android:typeface="sans"
android:gravity="center"
/>
</LinearLayout>
<ListView
android:id="#+id/keywordslist"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/background_gradient"
>
</ListView>
</LinearLayout>
The xml file used for displaying list items layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/list_display"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<CheckBox
android:id="#+id/chk_box"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:visibility="invisible"
>
</CheckBox>
<TextView
android:id="#+id/key_id"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
>
</TextView>
<TextView
android:id="#+id/key_name"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="16sp"
android:textColor="#FFF">
</TextView>
</LinearLayout>
and my java code for the activity
package com.sample.epiphron;
public class KeywordsList extends Activity {
TextView category_title;
ListView keywords_list ;
String categoryid, categoryname;
private ArrayList<KeywordDetails> listItems = new ArrayList<KeywordDetails>();
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.keywords);
Bundle extras = getIntent().getExtras();
categoryid = extras.getString("category_id");
categoryname = extras.getString("category_name");
category_title = (TextView) findViewById(R.id.category_title);
category_title.setText(""+categoryname+"- Keywords");
keywords_list = (ListView) findViewById(R.id.keywordslist);
drawList(LoginScreen.user_credential, categoryid);
//Toast.makeText(this, chkbx.toString(), Toast.LENGTH_SHORT).show();
keywords_list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
TextView txtv1 = (TextView) arg1.findViewById(R.id.key_id);
Toast.makeText(KeywordsList.this, txtv1.getText(), Toast.LENGTH_LONG).show();
}
});
}
public void drawList(String userid, String cat_id){
WebServiceCall res = new WebServiceCall();
SoapObject result = res.fetchKeyword(userid, cat_id);
ArrayList<String> al = new ArrayList<String>();
for (int i = 0; i<result.getPropertyCount(); i++){
SoapObject obj = (SoapObject) result.getProperty(i);
al.add((String) obj.getProperty("keywordname"));
KeywordDetails object = new KeywordDetails(Integer.parseInt(obj.getProperty("keywordid").toString()), obj.getProperty("keywordname").toString());
listItems.add(object);
}
for ( int j = 0; j < result.getPropertyCount(); j++ ) {
}
keywords_list.setAdapter(new ListItemsAdapter(listItems));
}
public class KeywordDetails{
private int keyword_id;
private String keyword_name;
public KeywordDetails(int key_id, String key_name){
this.keyword_id = key_id;
this.keyword_name = key_name;
}
public int getId(){
return this.keyword_id;
}
public String getName(){
return this.keyword_name;
}
//...
}
private class ListItemsAdapter extends ArrayAdapter<KeywordDetails> {
ArrayList<KeywordDetails> obj = null;
KeywordDetails keyworddtls = null;
public ListItemsAdapter(ArrayList<KeywordDetails> items) {
super(KeywordsList.this, android.R.layout.simple_list_item_1, items);
this.obj = items;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
convertView = inflater.inflate(R.layout.keyword_list_item, null);
final TextView text1 = (TextView) convertView.findViewById(R.id.key_id);
TextView text2 = (TextView) convertView.findViewById(R.id.key_name);
CheckBox chkbx = (CheckBox) convertView.findViewById(R.id.chk_box);
keyworddtls = obj.get(position);
text1.setText(Integer.toString(keyworddtls.getId()));
text2.setText(keyworddtls.getName());
chkbx.setVisibility(View.VISIBLE);
return convertView;
}
}
}
Add the CheckBox in the xml where is your <ListView > or in the xml which you use as item layout. Then in the getView() instantiate the CheckBox along the TextView. Implement listview.setOnItemClickListener() and based on which item was clicked (position) you start the activity [matter of logic] For the grouped of check items you can use getCheckedItemPositions(). I hope this will give you fire up idea.

Categories

Resources