I'm trying to use a SimpleCursorAdapter with a ViewBinder to get an image from the database and put it into my ListView item view. Here is my code:
private void setUpViews() {
mNewsView = (ListView) findViewById(R.id.news_list);
Cursor cursor = getNews();
SimpleCursorAdapter curAdapter = new SimpleCursorAdapter(
getApplicationContext(), R.layout.cursor_item, cursor,
new String[] { "title", "content", "image" },
new int[] { R.id.cursor_title, R.id.cursor_content,
R.id.news_image });
ViewBinder viewBinder = new ViewBinder() {
public boolean setViewValue(View view, Cursor cursor,
int columnIndex) {
ImageView image = (ImageView) view;
byte[] byteArr = cursor.getBlob(columnIndex);
image.setImageBitmap(BitmapFactory.decodeByteArray(byteArr, 0, byteArr.length));
return true;
}
};
ImageView image = (ImageView) findViewById(R.id.news_image);
viewBinder.setViewValue(image, cursor, cursor.getColumnIndex("image"));
curAdapter.setViewBinder(viewBinder);
mNewsView.setAdapter(curAdapter);
}
I am getting:
android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 60
while executing byte[] byteArr = cursor.getBlob(columnIndex);. Does anyone have an idea what am I doing wrong?
I extended SimpleCursorAdapter, and while I did not use a ViewBinder here is my code for using an image stored as a blob in an sqlite database in a listview. This was adapted from an article I read here.
My layout file for a row is:
row_layout_two_line.xml
<?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:background="#drawable/select_item">
<ImageView
android:id="#+id/pic"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginLeft="10dp"
android:contentDescription="#string/imagedesc"
android:src="#drawable/icon"
android:layout_gravity="center_vertical">
</ImageView>
<LinearLayout
android:id="#+id/linearLayout0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="#+id/label"
android:textStyle="bold"
android:textColor="#000"
android:textSize="20sp" >
</TextView>
<TextView
android:id="#+id/label1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="#+id/label1"
android:textStyle="bold"
android:textColor="#000"
android:textSize="20sp" >
</TextView>
</LinearLayout>
<TextView
android:id="#+id/label2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="35dp"
android:text="#+id/label2"
android:textColor="#000"
android:textSize="15sp" >
</TextView>
</LinearLayout>
The calling code
...
adapter = null;
mCursor = search();
startManagingCursor(mCursor);
// Now create a new list adapter bound to the cursor.
BaseAdapter adapter = new ImageCursorAdapter(this, // Context.
R.layout.row_layout_two_line, // Specify the row template
// to use (here, two
// columns bound to the
// two retrieved cursor
// rows).
mCursor, // Pass in the cursor to bind to.
// Array of cursor columns to bind to.
new String [] {"personImage", "firstName", "lastName", "title"},
// Parallel array of which template objects to bind to those
// columns.
new int[] { R.id.pic, R.id.label, R.id.label1, R.id.label2 });
// Bind to our new adapter.
setListAdapter(adapter);
...
ImageCursorAdapter.java
import android.content.Context;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
public class ImageCursorAdapter extends SimpleCursorAdapter {
private Cursor c;
private Context context;
public ImageCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to);
this.c = c;
this.context = context;
}
public View getView(int pos, View inView, ViewGroup parent) {
View v = inView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.row_layout_two_line, null);
}
this.c.moveToPosition(pos);
String firstName = this.c.getString(this.c.getColumnIndex("firstName"));
String lastName = this.c.getString(this.c.getColumnIndex("lastName"));
String titleStr = this.c.getString(this.c.getColumnIndex("title"));
byte[] image = this.c.getBlob(this.c.getColumnIndex("personImage"));
ImageView iv = (ImageView) v.findViewById(R.id.pic);
if (image != null) {
// If there is no image in the database "NA" is stored instead of a blob
// test if there more than 3 chars "NA" + a terminating char if more than
// there is an image otherwise load the default
if(image.length > 3)
{
iv.setImageBitmap(BitmapFactory.decodeByteArray(image, 0, image.length));
}
else
{
iv.setImageResource(R.drawable.icon);
}
}
TextView fname = (TextView) v.findViewById(R.id.label);
fname.setText(firstName);
TextView lname = (TextView) v.findViewById(R.id.label1);
lname.setText(lastName);
TextView title = (TextView) v.findViewById(R.id.label2);
title.setText(titleStr);
return(v);
}
}
Here is what it looks like in the end
I think the cursor.moveToFirst() has not been called so the cursor is throwing android.database.CursorIndexOutOfBoundsException.
Before using a cursor you should always check is the cursor is empty or not by calling cursor.moveToFirst(). This will also position the cursor at the first position.
Contact List using ListView and SimpleCusrorAdapter with Contact Photos and Filter/Search
I had been looking for a simpler solution and my final solution is quite closer to the one Daniel mentioned here so I thought I should share mine here. I am using Fragment to show Device Contacts as a list of names with their pictures. Result is pretty similar to that of Daniel's but is showing only names. More information can be shown very easily once you understand the code.
In my case I was fetching names and pictures from ContactsContract using PHOTO_URI so I didn't have to extend SimpleCursorAdapter as Daniel had to.
My example also includes filtering the list of contacts as user types in SearchView to find a contact
I have a Fragment called FragmentContacts and two Layout files, first the main Layout frag_contacts.xml and second for each contact row list_row_contact.
frag_contacts.xml
<LinearLayout 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:orientation="vertical">
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#android:color/holo_blue_light"
android:padding="8dip">
<android.support.v7.widget.SearchView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
android:id="#+id/searchView"/>
</FrameLayout>
<LinearLayout
android:id="#+id/ll_contactList"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="9"
android:orientation="vertical" >
<ListView
android:id="#+id/lv_ContactList"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:divider="#aaaaaa"
android:dividerHeight="1dp" >
</ListView>
</LinearLayout>
</LinearLayout>
list_row_contact.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:descendantFocusability="blocksDescendants">
<FrameLayout
android:layout_height="match_parent"
android:layout_width="0dp"
android:layout_weight="1"
android:gravity="center">
<ImageView
android:id="#+id/imgContact"
android:layout_width="35dip"
android:layout_height="35dip"
android:layout_gravity="center"
android:layout_margin="5dip" />
</FrameLayout>
<TextView
android:id="#+id/contact_name"
android:layout_height="match_parent"
android:layout_width="0dp"
android:layout_weight="6"
android:gravity="center_vertical"
android:textSize="18sp"
android:paddingLeft="10dip">
</TextView>
</LinearLayout>
FragmentContacts.java
public class FragmentContacts extends Fragment
implements LoaderManager.LoaderCallbacks<Cursor>{
private ListView lv_ContactList;
private SearchView searchView;
private SimpleCursorAdapter mCursorAdapter;
private static final String DISPLAY_NAME = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ? Contacts.DISPLAY_NAME_PRIMARY : Contacts.DISPLAY_NAME;
private static final String[] contactsColumns = { Contacts._ID, Contacts.LOOKUP_KEY, DISPLAY_NAME, Contacts.PHOTO_URI };
private final String contactsFilter = "(" +Contacts.HAS_PHONE_NUMBER+ "='1') AND (" + Contacts.IN_VISIBLE_GROUP + "='1')";
private final String contactsSortOrder = DISPLAY_NAME + " COLLATE LOCALIZED ASC";
private final static String[] listDisplayColumns = { DISPLAY_NAME, Contacts.PHOTO_URI };
private final static int[] listDataViewIDs = { R.id.contact_name, R.id.imgContact };
String[] mSelectionArgs;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frag_contacts, null);
lv_ContactList = (ListView)view.findViewById(R.id.lv_ContactList);
searchView = (SearchView)view.findViewById( R.id.searchView);
return view;
}
#Override
public void onResume(){
super.onResume();
mCursorAdapter= new SimpleCursorAdapter( getActivity(), R.layout.list_row_contact, null, listDisplayColumns, listDataViewIDs, 0);
lv_ContactList.setAdapter(mCursorAdapter);
getLoaderManager().initLoader(0, null, this);
searchView.setOnQueryTextListener( new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit( String query ) {return false;}
#Override
public boolean onQueryTextChange( String newText ) {
if( newText.isEmpty() ) mSelectionArgs = null;
else mSelectionArgs = new String[]{ "%"+newText.trim()+"%"};
getLoaderManager().restartLoader( 0, null, FragmentContacts.this );
return false;
}
} );
}
#Override
public Loader<Cursor> onCreateLoader( int id, Bundle args ) {
if(mSelectionArgs == null)
return new CursorLoader( getActivity(), Contacts.CONTENT_URI, contactsColumns, contactsFilter, null, contactsSortOrder );
else
return new CursorLoader( getActivity(), Contacts.CONTENT_URI, contactsColumns, contactsFilter + " AND (" + DISPLAY_NAME+" LIKE ?)", mSelectionArgs, contactsSortOrder );
}
#Override
public void onLoadFinished( Loader<Cursor> loader, Cursor data ) {
mCursorAdapter.swapCursor(data);
}
#Override
public void onLoaderReset( Loader<Cursor> loader ) {
mCursorAdapter.swapCursor(null);
}
}
Related
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());
...
}
I am new to android . I have an application working with listview and i want to number each list view item.
Like,
1 list item
2 list item
3 list item
MainActivity.java
public class MainActivity extends AppCompatActivity {
private OrderDbManager orderDbManager;
private ListView listView;
private SimpleCursorAdapter adapter;
final String[] from = new String[] { OrderDbHelper.FOOD_NAME,
OrderDbHelper.QUANTITY, OrderDbHelper.PRICE };
final int[] to = new int[] {R.id.tvFoodName, R.id.tvItemQuantity, R.id.tvItemPrice };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
orderDbManager = new OrderDbManager(this);
orderDbManager.open();
final Cursor cursor = orderDbManager.fetch();
listView = (ListView) findViewById(R.id.listView);
listView.setEmptyView(findViewById(R.id.empty));
adapter = new SimpleCursorAdapter(this, R.layout.list_item, cursor, from, to, 0);
adapter.notifyDataSetChanged();
LayoutInflater layoutInflater = getLayoutInflater();
listView.addHeaderView(layoutInflater.inflate(R.layout.cart_header,listView, false));
listView.setAdapter(adapter);
}
public class MyAdapter extends SimpleCursorAdapter {
public MyAdapter(Context context, int layout, Cursor c,
String[] from,int[] to) {
super(context, layout, c, from, to);
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.list_item, null, true);
TextView txt= (TextView) convertView.findViewById(R.id.tvSlNo);
txt.setText(position + 1);
return convertView;
}
}
}
activity_main.xml
<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="#+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ListView>
list_item.xml
<?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:layout_margin="5dp"
android:minHeight="50dp"
android:orientation="horizontal"
android:weightSum="1">
<TextView
android:id="#+id/tvSlNo"
android:layout_width="0dip"
android:layout_height="match_parent"
android:gravity="center"
android:textStyle="normal"
android:textColor="#android:color/black"
android:layout_weight="0.1" />
<TextView
android:id="#+id/tvFoodName"
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_weight="0.5"
android:gravity="center"
android:textStyle="normal"
android:textColor="#android:color/black"
android:text=""/>
<TextView
android:id="#+id/tvItemQuantity"
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_weight="0.15"
android:textStyle="normal"
android:textColor="#android:color/black"
android:gravity="center"/>
<TextView
android:id="#+id/tvItemPrice"
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_weight="0.25"
android:gravity="center"
android:textStyle="normal"
android:textColor="#android:color/black"
android:text=""/>
</LinearLayout>
i want to set numbering in tvSlNo.
please help
In your getView() method of your listViewAdapter simply use the position variable and set it on your TextView. You may need to add 1 to the position since it starts with 0. So use (position+1) and then set it to your TextView
Though this question may be too late but for other reference purposes.
Check where you have this code: txt.setText(position + 1);
you are close to your solution. You just have to typecast position + 1 to String since setText() only take String alone.
I would like to display a two textView in my ListView depending on the database value.
But in result nothing is displayed (error)
This is my code:
public class ListbookActivity extends ListActivity implements OnQueryTextListener{
private DBHelper database;
private Intent intent;
private ListView listav;
private SimpleCursorAdapter adapter;
private String strclickmenu;
private Cursor cursor;
private Toast t;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] from = new String[] { "titolo", "autore" };
int[] to = new int[] { R.id.name, R.id.surname};
database = new DBHelper(getApplicationContext());
SQLiteDatabase db = database.getReadableDatabase();
//query
cursor = db.query("libreria", null, null, null, null, null, "titolo", null);
cursor.moveToFirst();
listav = (ListView) findViewById(R.id.list);
adapter = new SimpleCursorAdapter(this,R.layout.list_row, cursor,from,to,0);
adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
if (view.getId() == R.id.name) {
String userFullName = cursor.getString(cursor.getColumnIndex("titolo"));
TextView tit = (TextView)view;
tit.setText(userFullName);
return true;
} else if (view.getId() == R.id.surname) {
String userEmail = cursor.getString(cursor.getColumnIndex("titolo"));
TextView aut = (TextView)view;
aut.setText(userEmail);
return true;
} else {
return false;
}
}
});
listav.setAdapter(adapter);
list_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<TextView
android:id="#+id/name"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1.51"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/surname"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1.51"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
activity_listbook.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:smoothScrollbar="false"
android:fadingEdge="none"/>
</LinearLayout>
This is the error:
Unable to start activity componentInfo{com.example.mybooks.ListBookActivity} : Java.lang.nullPointerException
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.
I have my ListView setup but it only shows 3 rows with numbers 1-3 and it's not showing the entries from my database.I've tried to find the answer for this but this ListView subject is very vague and I can't find a clear answer on how to show the text from my DB entries.
Here is the codes from my xml layout,ListView class and Cursor entry in database.
Layout:
<?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:background="#drawable/nfbackground"
android:orientation="vertical" >
<ImageView
android:id="#id/titlebar"
android:layout_width="wrap_content"
android:layout_height="66dp"
android:src="#drawable/nftitlebar" />
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/searchimageview"
android:textColor="#color/black"
android:textSize="25dp"
android:textStyle="bold"
android:text=""
android:orientation="vertical" >
</ListView>
</LinearLayout>
Code:
package com.fullfrontalgames.numberfighter;
import com.fullfrontalgames.numberfighter.DBAdapter;
import com.fullfrontalgames.numberfighter.R;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
public class PlayAFriend extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.playafriend);
ListView FriendLV = (ListView) findViewById(android.R.id.list);
DBAdapter db = new DBAdapter(this);
db = db.open();
Cursor friendslist = db.GetAllFriends();
String[] from = new String[] {"ID","USERNAME","FRIENDS"}; // your column/columns here
int[] to = new int[] {android.R.id.text1};
#SuppressWarnings("deprecation")
ListAdapter cursorAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, friendslist, from, to);
FriendLV.setAdapter(cursorAdapter);
db.close();
}
}
Code:
public Cursor GetAllFriends()
{
Cursor cursor = db.rawQuery("select rowid _id,* from NFDB", null);
int iRow = cursor.getColumnIndex("ID");
int iName = cursor.getColumnIndex("USERNAME");
int iFriends = cursor.getColumnIndex("FRIENDS");
if (cursor.moveToFirst()) {
do {
TextView friendslist = new TextView(context);
friendslist.setId(Integer.parseInt(cursor.getString(iRow)));
friendslist.setText(cursor.getString(iName));
friendslist.setText(cursor.getString(iFriends));
} while (cursor.moveToNext());
}
return cursor;
}
You need to create a layout with 2 TextView for your listview columns
list_items.xml
<?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:padding="5dp"
android:orientation="vertical" >
<TextView
android:id="#+id/textview_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/textview_friends"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
change
String[] from = new String[] {"USERNAME","FRIENDS"}; // your column/columns here
int[] to = new int[] {textview_name, textview_friends};
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this, R.layout.list_items, friendslist, from, to, 0);
FriendLV.setAdapter(cursorAdapter);
//db.close(); Close the db in onDestroy
change
public Cursor GetAllFriends()
{
return db.rawQuery("select * from NFDB", null);
}