Button listener and SimpleCursor adapter - android

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

Related

OnItemClick never being called for button in ListView

I'm trying to implement Onclicklistener for button inside Listview item but unable to get OnitemClick method called in listview.
I got the following code snippet from stack overflow
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> list, View v, int pos, long id) {
// Your code for item clicks
( break point)
click++;
}
});
The break point never goes off when i click the button.
Activity Code
public class MainActivity extends AppCompatActivity {
long click=0;
String[] aOrderID = {"1-AA-355433", "2-AA-456474", "3-AA-43546464", "4-A-446464E6","5-A-43555" };
String[] aOrderType = {
"LIMIT-BUY",
"LIMIT-SELL",
"LIMIT-BUY",
"LIMIT-SELL",
"LIMIT-BUY"
};
double[] aPrice={3353.33, 4567.77, 335.66, 535.77, 678.67};
double[] aVOL={93353.33, 94567.77, 9335.66, 9535.77, 9678.67};
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CustomListAdapter whatever = new CustomListAdapter(this,
aOrderID, aOrderType,aPrice, aVOL );
listView = (ListView) findViewById(R.id.list_view);
listView.setAdapter(whatever);
////////////////////////
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> list, View v, int pos, long id) {
// Your code for item clicks
// CODE NEVER GETS HER AFTER BUTTON IS CLICKED ON
click++;
}
});
}
}
CUSTOM ADAPTER
public class CustomListAdapter extends ArrayAdapter {
int ted;
//to reference the Activity
private final Activity context;
//to store the animal images
private Integer[] imageIDarray = null;
//List of order ids
private String[] aOrderID = null;
// Type of order id limit buy
private String[] aOrderType = null;
// Price, price to sell of buy at
private double[] aPrice = null;
// Amount of bitcoins to buy or sell
private double[] aVol = null;
public CustomListAdapter(Activity context,
String[] aOrderID, String[] aOrderType,
double[] aPrice, double[] aVol) {
super(context, R.layout.row2, aOrderID);
this.context = context;
this.aOrderID = aOrderID;
this.aOrderType = aOrderType;
this.aPrice = aPrice;
this.aVol = aVol;
}
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.row2, null, true);
TextView temp;
temp = (TextView) rowView.findViewById(R.id.idOrderID);
temp.setText(aOrderType[position]);
temp = (TextView) rowView.findViewById(R.id.idOrderID);
temp.setText(aOrderID[position]);
temp = (TextView) rowView.findViewById(R.id.idVol);
temp.setText(Double.toString(aVol[position]));
temp = (TextView) rowView.findViewById(R.id.idPrice);
temp.setText(Double.toString(aPrice[position]));
return rowView;
}
}
XML FOR LISTVIEW
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteY="81dp">
<TextView
android:id="#+id/textView33"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ROW!"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/textView34"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ROW2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView33" />
<TextView
android:id="#+id/textView35"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Oder Type "
app:layout_constraintStart_toEndOf="#+id/textView33"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/IDtYPE"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Buy Limit Order"
app:layout_constraintStart_toEndOf="#+id/textView35"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/textView37"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Volume "
app:layout_constraintStart_toEndOf="#+id/textView34"
app:layout_constraintTop_toBottomOf="#+id/textView35" />
<TextView
android:id="#+id/textView40"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Type::"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/idOrderID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Buy Limmit"
app:layout_constraintStart_toEndOf="#+id/textView40"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/textView43"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Price "
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView40" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="34dp"
android:layout_marginTop="4dp"
android:text="Delete Order"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.501"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView34" />
<TextView
android:id="#+id/textView45"
android:layout_width="wrap_content"
android:layout_height="17dp"
android:text="-------------------------------------------------"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/button" />
<TextView
android:id="#+id/idPrice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="000.00"
app:layout_constraintStart_toEndOf="#+id/textView43"
app:layout_constraintTop_toBottomOf="#+id/idOrderID" />
<TextView
android:id="#+id/idVol"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2.9999"
app:layout_constraintStart_toEndOf="#+id/textView37"
app:layout_constraintTop_toBottomOf="#+id/textView35" />
You should use button click event from this method. Try this.
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.row2, null, true);
TextView temp;
temp = (TextView) rowView.findViewById(R.id.idOrderID);
temp.setText(aOrderType[position]);
temp = (TextView) rowView.findViewById(R.id.idOrderID);
temp.setText(aOrderID[position]);
temp = (TextView) rowView.findViewById(R.id.idVol);
temp.setText(Double.toString(aVol[position]));
temp = (TextView) rowView.findViewById(R.id.idPrice);
temp.setText(Double.toString(aPrice[position]));
Button btn = (Button) rowView.findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do your stuff.
}
});
return rowView;
}

How to add SwipeListener to list Item using cursor Adapter

I'm trying to add left and right swipe to listview for creating calling intent and messaging intent like contacts app :
swipe right -> call
swipe left -> message
OnSwipe, it should call an intent
I'm trying lot of ways to do i'm unable get the solution
Here is my code below for spanning list View items(excluding swipe related code because i use libraries till now):
This is my adpater class
class ContactCursorAdapter extends CursorAdapter{
public ContactCursorAdapter(Context context, Cursor c) {
super(context, c, 0);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.contacts_list_item, parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView nameTextView = (TextView) view.findViewById(R.id.text_view_name);
ImageView profilePictureView = (ImageView) view.findViewById(R.id.image_person);
int columnNameIndex = cursor.getColumnIndex(ContactEntry.COLUMN_PERSON_NAME);
int columnNumberIndex = cursor.getColumnIndex(ContactEntry.COLUMN_CONTACT_NUMBER);
int profilePictureIndex = cursor.getColumnIndex(ContactEntry.COLUMN_PROFILE_PICTURE);
String contactName = cursor.getString(columnNameIndex);
final String contactNumber = cursor.getString(columnNumberIndex);
byte[] profilePicture = cursor.getBlob(profilePictureIndex);
if (contactName.length() == 0) {
nameTextView.setText(contactNumber);
} else {
nameTextView.setText(contactName);
}
if (profilePicture != null) {
if (profilePicture.length > 3) {
profilePictureView.setImageBitmap(BitmapFactory.decodeByteArray(profilePicture, 0, profilePicture.length));
} else {
profilePictureView.setImageResource(R.drawable.ic_person);
}
}
}
This is my contact list item file
<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="?android:listPreferredItemHeight"
android:background="#drawable/selector_color">
<ImageView
android:id="#+id/image_person"
android:layout_width="?android:attr/listPreferredItemHeight"
android:layout_height="?android:attr/listPreferredItemHeight"
android:contentDescription="#string/profile_picture"
android:scaleType="centerCrop"
android:src="#drawable/ic_person" />
<TextView
android:id="#+id/text_view_name"
android:layout_width="match_parent"
android:layout_height="?android:listPreferredItemHeight"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_toEndOf="#id/image_person"
android:layout_toRightOf="#id/image_person"
android:ellipsize="marquee"
android:fontFamily="sans-serif-light"
android:gravity="center_vertical"
android:maxLines="1"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/white"
tools:targetApi="jelly_bean" />
</RelativeLayout>
I want to use CursorAdapter only

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.

Custom CursorAdaptor is showing nothing

I'm trying to do a list getting the data from y sqlite db using a custom CursorAdaptor to show an image an some data to the right, but so far all I got was a blank screen or a spinning loading circle without a result.
Here is my fragment activity:
public class FragMvp extends SherlockListFragment {
private DataBaseManager dataBase;
private MyCursorAdapter mAdapter;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// creates and open the database so we can use it
dataBase = DataBaseManager.instance();
String query = "SELECT mo._id,mo.sprite,mo.iName FROM Mobs AS mo WHERE mo.MobType = 2 ORDER BY mo.iName ASC;";
Cursor cursor = dataBase.select(query);
if (cursor != null) {
mAdapter = new MyCursorAdapter(ApplicationContextProvider.getContext(), cursor, false);
setListAdapter(mAdapter);
cursor.close();
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Do something with the data
}
}
The query is working perfectly on my database manager and if I use an ArrayAdapter, it works and shows data. So I guess that the problem is not database related.
Then, here is the CursorAdapter:
public class MyCursorAdapter extends CursorAdapter {
private final LayoutInflater mInflater;
public MyCursorAdapter(Context context, Cursor c, boolean autoRequery) {
super(context, c, autoRequery);
mInflater = LayoutInflater.from(context);
mContext = context;
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return mInflater.inflate(R.layout.my_adapter, parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
String mobSprite = cursor.getString(cursor.getColumnIndex("sprite"));
String mobName = cursor.getString(cursor.getColumnIndex("iName"));
int lvl = cursor.getInt(cursor.getColumnIndex("LVL"));
String hp = cursor.getString(cursor.getColumnIndex("HP"));
ImageView imageView = (ImageView) view.findViewById(R.id.mobSprite);
TextView mobNameView = (TextView) view.findViewById(R.id.mobName);
TextView levelView = (TextView) view.findViewById(R.id.lvl);
TextView hpView = (TextView) view.findViewById(R.id.hp);
int resID = context.getResources().getIdentifier(mobSprite, "drawble", context.getPackageName());
imageView.setImageResource(resID);
mobNameView.setText(mobName);
levelView.setText(lvl);
hpView.setText(hp);
}
}
And the XML just in case. It's not finished yet, but first I want to see some results and see how they look.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/mobSprite"
android:layout_width="55dp"
android:layout_height="55dp"
android:layout_marginBottom="4dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="4dp" >
</ImageView>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/mobName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:layout_marginTop="4dp"
android:text="#+id/mobName"
android:textSize="20sp" />
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/lvlString"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:text="#string/lvl"
android:textSize="12sp" />
<TextView
android:id="#+id/lvl"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/lvlString"
android:text="#+id/lvl"
android:textSize="12sp" />
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/hpString"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="15dp"
android:text="#string/hp"
android:textSize="12sp" />
<TextView
android:id="#+id/hp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/hpString"
android:text="#+id/hp"
android:textSize="12sp" />
</RelativeLayout>
</LinearLayout>
</LinearLayout>
I don't know where is the problem, I've look for countless of tutorials and it's always the same. Do the CursorAdapter, pass it the cursor and context and set the listAdapter... but it's not working.
The problem is here.
Cursor cursor = dataBase.select(query);
if (cursor != null) {
mAdapter = new MyCursorAdapter(ApplicationContextProvider.getContext(), cursor, false);
setListAdapter(mAdapter);
cursor.close(); <========
}
You are closing the cursor prematurely. If you close it here, the Adapter will have zero results. The CursorAdapter will take care of closing the cursor when it is done or when you change the cursor to a new one.
Hope this helps.

Categories

Resources