NullPointerException in onLoaderFinished using SimpleCursorAdapter - android

I have switched from a ResourceCursorAdapter where I used newView and bindView to a SimpleCursorAdapter where I am using only the getView method.
Now I have an error in onLoaderFinished. Although it gives me NullPointerException on adapter.swapCursor(cursor) both my adapter and cursor object are NOT null. I will post all of my code below. Any help is greatly appreciated (not got much hair left to pull out).
import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.ResourceCursorAdapter;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
public class ContactSelect extends FragmentActivity implements LoaderManager.LoaderCallbacks<Cursor> {
private static final int LOADER_ID = 1;
private MyAdapter adapter;
private ListView list;
private View row;
private SparseBooleanArray checkedState = new SparseBooleanArray();
#SuppressLint({ "NewApi", "NewApi" })
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_contact_select);
adapter = new MyAdapter(this, R.layout.contacts_select_row, null, null, null, 0);
getSupportLoaderManager().initLoader(LOADER_ID, null, this);
list = (ListView)findViewById(R.id.list);
list.setAdapter(adapter);
list.setEmptyView(findViewById(R.id.empty));
}
#SuppressLint("NewApi")
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
final String projection[] = new String[]{ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME};
final Uri uri = ContactsContract.Contacts.CONTENT_URI;
final String selection = ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1" +
" AND " + ContactsContract.Contacts.IN_VISIBLE_GROUP + " =1";
final String order = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
final CursorLoader loader = new CursorLoader(this, uri, projection, selection, null, order);
return loader;
}
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
for(int i=0;i<cursor.getCount();i++){
checkedState.put(i, false);
}
adapter.swapCursor(cursor);
}
public void onLoaderReset(Loader<Cursor> loader) {
adapter.swapCursor(null);
}
private class MyAdapter extends SimpleCursorAdapter implements OnClickListener{
private CheckBox markedBox;
private TextView familyText;
private Context context;
private Cursor cursor;
public MyAdapter(Context context, int layout, Cursor c, String[] from,
int[] to, int flags) {
super(context, layout, c, from, to, flags);
this.context = context;
this.cursor = getCursor();
}
#Override
public View getView(int position, View view, ViewGroup group) {
final LayoutInflater li = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = li.inflate(R.layout.contacts_select_row, group, false);
view.setTag(cursor.getPosition());
view.setOnClickListener(this);
familyText = (TextView)view.findViewById(R.id.contacts_row_family_name);
markedBox = (CheckBox)view.findViewById(R.id.contacts_row_check);
familyText.setText(cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME)));
boolean currentlyChecked = checkedState.get(cursor.getPosition());
markedBox.setChecked(currentlyChecked);
setProgressBarIndeterminateVisibility(false);
return super.getView(position, view, group);
}
public void onClick(View view) {
int rowId = (Integer)view.getTag();
Log.d("OnClick", String.valueOf(rowId));
boolean currentlyChecked = checkedState.get(rowId);
markedBox.setChecked(!currentlyChecked);
checkedState.put(rowId, !currentlyChecked);
Log.d("checkedState", "checkedState(" + rowId + ") = " + checkedState.get(rowId));
}
}
}

A call of the swapCursor method of the SimpleCursorAdapter class will trigger a function which maps the column names from the String array provided to the constructor(the 4th parameter) to an array of integers representing the columns indexes. As you pass null in the constructor of MyAdapter for the String array representing the columns names from the cursor, this will throw a NullPointerException later when the swapCursor will try to make the mapping(the NullPointerException should appear in a method findColumns, which is the actual method that uses the column names String array).
The solution is to pass a valid String array, you may also want to do this for the int array representing the ids for the views in which to place the data:
String[] from = {ContactsContract.Contacts.DISPLAY_NAME};
int[] to = {R.id.contacts_row_family_name, R.id.contacts_row_check};
adapter = new MyAdapter(this, R.layout.contacts_select_row, null, from, to, 0);
I don't know what you are trying to do but your implementation of the getView method is not quite right:
You do the normal stuff for the getView method(creating layouts, searching views, binding data) and then you simply return the view from the superclass(?!?), you'll probably just see the default layout with nothing in it.
The way you wrote the getView method is not very efficient, you may want to look into view recycling and the view holder pattern.
cursor.getPosition() will not do what you want as you don't move the cursor to the correct position. By default cursors based adapters will do this for you in the getView method, but, as you overrode the method it's your job to move the cursor's position.
You should leave the getView method and use the two methods newView and bindView as they offer a better separation of the logic.

adapter = new MyAdapter(this, R.layout.contacts_select_row, null, null, null, 0);
and your MyAdapter class you are passing null cursor
public MyAdapter(Context context, int layout, Cursor c, String[] from,
int[] to, int flags) {
super(context, layout, c, from, to, flags);
this.context = context;
this.cursor = getCursor();
}

Related

How to add a header row to a list of child views of an expandablelistview that uses simplecursortreeadapter

I'm using a simplecursortreeadapter to populate an expandablelistview and want to have a row at the top of all the children views that has titles for the data.
Group 1 Name [Expanded]
Header (Date, Name, $)
Child 1 (07/12/2017, Chad, 50.00)
Child 2 (08/11/2017, Mike, 63.21)
Group 2 Name [Expanded]
Header (Date, Name, $)
Child 1 (03/25/2017, Ken, 23.97)
Child 2 (01/25/2017, Will, 101.11)
Group 3 [Collapsed]
Is it possible to have the textviews that contain the 3 sets of header text (Date, Name, $) to only appear when the group is expanded? Since the SimpleCursorTreeAdapter handles adding the cursor data into the views, I'm not sure how to add a row to that or how to achieve this. Is this possible?
Edit: Here is my adapter class:
package com.example.myproject.michaelc.billme;
import android.content.Context;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.database.MergeCursor;
import android.support.v4.content.Loader;
import android.util.Log;
import android.widget.SimpleCursorTreeAdapter;
import com.example.myproject.michaelc.billme.data.BillMeContract;
import java.util.HashMap;
public class PayeeCursorAdapter extends SimpleCursorTreeAdapter {
private final String LOG_TAG = getClass().getSimpleName();
private PayeeActivity mActivity;
protected final HashMap<Integer, Integer> mGroupMap;
// No cursor is added to the adapter so that it only runs when the CursorLoader runs, instead of every time the activity does
public PayeeCursorAdapter(
Context context, // The activity where the adapter will be running
int groupLayout, // The .xml layout file for the group layout
int childLayout, // The .xml layout file for the child layout
String[] groupFrom, // String of column names in the cursor that is the data for each group item
int[] groupTo, // The ID of the views in the group layout that display the column from the groupFrom String[]
String[] childrenFrom, // String of column names in the cursor that is the data for each child item
int[] childrenTo) { // The ID of the views in the child layout that display the column from the childFrom String[]
super(context, null, groupLayout, groupFrom, groupTo, childLayout, childrenFrom, childrenTo);
mActivity = (PayeeActivity) context;
mGroupMap = new HashMap<Integer, Integer>();
}
#Override
protected Cursor getChildrenCursor(Cursor groupCursor) {
int groupPos = groupCursor.getPosition();
int groupId = groupCursor.getInt(groupCursor.getColumnIndex(BillMeContract.PayeeEntry._ID));
Log.d(LOG_TAG, "getChildrenCursor() for groupPos " + groupPos);
Log.d(LOG_TAG, "getChildrenCursor() for groupId " + groupId);
mGroupMap.put(groupId, groupPos);
Loader<Cursor> loader = mActivity.getSupportLoaderManager().getLoader(groupId);
if(loader != null && !loader.isReset()) {
mActivity.getSupportLoaderManager().restartLoader(groupId, null, mActivity);
} else {
mActivity.getSupportLoaderManager().initLoader(groupId, null, mActivity);
}
return null;
}
public HashMap<Integer, Integer> getGroupMap(){
return mGroupMap;
}
}
Yes it can possible .
you can also see this link , hope you will get your solution.
http://www.worldbestlearningcenter.com/tips/Android-expandable-listview-header.htm
package android.widget.expandablelistview;
import android.os.Bundle;
import android.util.ExpandableListScenario;
import android.widget.Button;
import android.widget.ExpandableListView;
public class ExpandableListWithHeaders extends ExpandableListScenario {
private static final int[] sNumChildren = {1, 4, 3, 2, 6};
private static final int sNumOfHeadersAndFooters = 12;
#Override
protected void init(ExpandableParams params) {
params.setStackFromBottom(false)
.setStartingSelectionPosition(-1)
.setNumChildren(sNumChildren)
.setItemScreenSizeFactor(0.14)
.setConnectAdapter(false);
}
#Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
final ExpandableListView expandableListView = getExpandableListView();
expandableListView.setItemsCanFocus(true);
for (int i = 0; i < sNumOfHeadersAndFooters; i++) {
Button header = new Button(this);
header.setText("Header View " + i);
expandableListView.addHeaderView(header);
}
for (int i = 0; i < sNumOfHeadersAndFooters; i++) {
Button footer = new Button(this);
footer.setText("Footer View " + i);
expandableListView.addFooterView(footer);
}
// Set adapter here AFTER we set header and footer views
setAdapter(expandableListView);
}
/**
* #return The number of headers (and the same number of footers)
*/
public int getNumOfHeadersAndFooters() {
return sNumOfHeadersAndFooters;
}
}

SQLite: get id from ListView

This is my first app and i'm having some problem whit ListView
How can I get the ID in the database after clicking on a Item?
I can't use position because the Id may not be continuous and even if it is in order sometimes does not return the correct Id any.
this is my code, Thank you for your help:
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class livello1 extends AppCompatActivity {
DatabaseHelper myDb;
Button next;
#Override
protected void onCreate(Bundle savedInstanceState) {
myDb = new DatabaseHelper(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.livello1);
populateListView();
registerClick();
}
private void registerClick(){
ListView list =(ListView)findViewById(R.id.listViewMain);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked, int position, long id) {
Intent i = new Intent(livello1.this, bossi.note.Edit.class);
i.putExtra("id", position);
//i.putExtra("id", id);
startActivity(i);
}
});
}
private void populateListView(){
Cursor res = myDb.getAllData();
String[] myItems = new String[myDb.numRow()];
int cont = 0;
if(res.getCount() == 0){
// show message
return;
}
while( res. moveToNext()){
myItems[cont] = res.getString(1);
cont ++;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.da_item, myItems);
ListView list =(ListView)findViewById(R.id.listViewMain);}
There are a lot of solution approaches.
For example, you can store of Id's if ArrayList before ListView initialization.
That is, execute "SELECT id FROM mytable"
Then store in arraylist and use while click method.
Example:
//in class declaration
private ArrayList<Long> ar_ids = new ArrayList<Long>;
//
String sql = "SELECT id FROM table";
Cursor cur = db.rawQuery(sql, null);
String out = "";
ArrayList<Long> ar_ids = new ArrayList<Long>;
if (cur.moveToFirst()) {
do {
ar.add(cur.getString(0));
} while (cur.moveToNext());
}else{
}
}
cur.close();
for click event:
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked, int position, long id) {
Intent i = new Intent(livello1.this, bossi.note.Edit.class);
i.putExtra("id", ar_id.get(position));
//this is awsome!
startActivity(i);
}
and initialize this something like:
private void myfunc() {
String sql = "SELECT id FROM table";
Cursor cur = myDb.rawQuery(sql, null);
String out = "";
ArrayList<Long> ar_ids = new ArrayList<Long>;
if (cur.moveToFirst()) {
do {
ar.add(cur.getString(0));
} while (cur.moveToNext());
}else{
throw new NullPointerException();
}
}
cur.close();
}
private void populateListView(){
myfunc();
Cursor res = myDb.getAllData();
String[] myItems = new String[myDb.numRow()];
int cont = 0;
if(res.getCount() == 0){
// show message
return;
}
while( res. moveToNext()){
myItems[cont] = res.getString(1);
cont ++;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.da_item, myItems);
ListView list =(ListView)findViewById(R.id.listViewMain);}
well instead of using the ArrayAdapter you can extend a BaseAdapter or ListAdapter or even the ArrayAdapter to make your custom adapter. First of all make a plain java class to map your database data including id to an object. Then make a custom BaseAdapter instead of using the ArrayAdapter. In your BaseAdapter class you have to override various methods including getItem and getItemId methods. Now you can return the whole mapped object from the getItem method and simply obtain the object of selected item of the ListView by using listView.getSelectedItem() method in the Activity or Fragment class. Once you get the object you can access the id easily.
You can find a good example and explanation of a custom adapter here
About mapping the database result to an object, you can get some concept here
Here, you can replace you code class with this one, I have added a cursorAdapter and attached it with your ListView, in adapter I have added a method for getting Id that I call from click listener to retrieve id from cursor, you will have to set column number for _ID in public void getId(int position) from MyCursorAdapter class below.
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class livello1 extends AppCompatActivity {
DatabaseHelper myDb;
Button next;
private MyCursorAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
myDb = new DatabaseHelper(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.livello1);
populateListView();
registerClick();
}
private void registerClick(){
ListView list =(ListView)findViewById(R.id.listViewMain);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked, int position, long id) {
Intent i = new Intent(livello1.this, bossi.note.Edit.class);
//retrieve id from cursor
int _id = adapter.getId(position)
i.putExtra("id", _id);
//i.putExtra("id", id);
startActivity(i);
}
});
}
private void populateListView(){
Cursor res = myDb.getAllData();
adapter = new MyCursorAdapter(this, res, 0);
ListView list =(ListView)findViewById(R.id.listViewMain);
list.setAdapter(adapter);
}
//adapter for list view
class MyCursorAdapter extends CursorAdapter {
Cursor cursor;
// Default constructor
public MyCursorAdapter(Context context, Cursor cursor, int flags) {
super(context, cursor, flags);
this.cursor = cursor;
}
public void bindView(View view, Context context, Cursor cursor) {
String text = cursor.getString(1);
//make sure the TextView id is "#+id/text1" in da_item.xml
TextView tvText = (TextView) view.findViewById(R.id.text1);
tvText.setText(text);
}
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflator inflater = (LayoutInflater) context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
return Inflater.inflate(R.layout.da_item, parent, false);
}
public int getId(int position){
cursor.moveToPosition(position);
int colId = //set id column number here
int id = cursor.getLong(colId);
return id;
}
}
Since the code is untested, you might face a build issue in start, but it should give an idea of what's going on in code. feel free to ask any question if you face any problem in compilation

Alphabetize and sort a String[] Array (from Contacts) in a Fragment

I have read for hours and hours to figure out how to sort and alphabetize a String[], but since I am pulling from my phone's Contacts and this whole ListView is a Fragment, there is nothing that really addresses my situation. I must use a CursorAdapter in my String[] and some alphabetize tutorials use other adapters, so I couldn't figure it out.
If you know of a very simple way to sort/alphabetize my String[] using the code I already have (considering all the particulars that come with using a ListView, Fragment, and pulling from Contacts), I would be very grateful. Currently this code works, but it pulls contacts that are not sorted.
Thanks for your suggestions.
ContactsFragment.java
package com.example.practiceapp.addressbook;
import java.util.ArrayList;
import java.util.Arrays;
import android.app.ListFragment;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import com.example.practiceapp.R;
/*
* Taken from http://stackoverflow.com/questions/18199359/how-to-display-contacts-in-a-listview-in-android-for-android-api-11
*/
public class ContactsFragment extends ListFragment implements
LoaderCallbacks<Cursor>{
private CursorAdapter mAdapter;
public ListView listView;
// Name should be displayed in the text1 TextView in item layout
public static String[] from = { ContactsContract.Contacts.DISPLAY_NAME_PRIMARY };
private static final int[] TO = { android.R.id.text1 };
private android.content.Context context;
ArrayList<String> elements;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// create adapter once
context = getActivity();
int layout = android.R.layout.simple_list_item_1;
Cursor c = null; // there is no cursor yet
int flags = 0; // no auto-requery! Loader requeries.
Arrays.sort(from);
// put List in adapter
mAdapter = new SimpleCursorAdapter(context, layout, c, from, TO, flags);
}
// columns requested from the database
private static final String[] PROJECTION = {
Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME_PRIMARY
};
// Empty public constructor, required by the system
public ContactsFragment() {}
// A UI Fragment must inflate its View (all fragments must override onCreateView)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the fragment layout
View view = inflater.inflate(R.layout.contact_list_view,
container, false);
listView = (ListView) view.findViewById(R.id.list);
return view;
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// and tell loader manager to start loading
getLoaderManager().initLoader(0, null, this);
listView.setAdapter(mAdapter);
listView.setFastScrollEnabled(true);
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// load from the "Contacts table"
Uri contentUri = Contacts.CONTENT_URI;
// no sub-selection, no sort order, simply every row
// projection says we want just the _id and the name column
return new CursorLoader(getActivity(),
contentUri,
PROJECTION,
null,
null,
null
);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
// Once cursor is loaded, give it to adapter
mAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
// Delete the reference to the existing Cursor,
// so it can recycle it
mAdapter.swapCursor(null);
}
}
The last parameter to the CursorLoader constructor is the sort order. It uses the same syntax as a normal SQL ORDER BY clause.

Duplicate contacts in resultant List View using cursor adapter

I am creating simple contact application where i want to display only name and number in the list view.
I used cursor adapter to load the contact name and number alone in the list of columns(FROM string array) in Simple Cursor Adapter. However my output lists out contact email id and duplicate names. Here is my code. Please help me to figure out where i went wrong to extract name and number alone.
import android.app.ListActivity;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
public class ListViewLoader extends ListActivity implements
LoaderCallbacks<Cursor> {
SimpleCursorAdapter mAdapter;
static final String[] PROJECTION = new String[] {
ContactsContract.Data._ID, ContactsContract.Data.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER };
static final String SELECTION = "((" + ContactsContract.Data.DISPLAY_NAME
+ " NOTNULL) AND (" + ContactsContract.Data.DISPLAY_NAME
+ " != '' ) AND ("
+ ContactsContract.CommonDataKinds.Phone.HAS_PHONE_NUMBER
+ " != 0 ))";;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ProgressBar progressBar = new ProgressBar(this);
progressBar.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
progressBar.setIndeterminate(true);
getListView().setEmptyView(progressBar);
ViewGroup root = (ViewGroup) findViewById(android.R.id.content);
root.addView(progressBar);
String[] fromColumns = { ContactsContract.Data.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER };
int[] toViews = { android.R.id.text1, android.R.id.text2 };
mAdapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_2, null, fromColumns,
toViews, 0);
setListAdapter(mAdapter);
getLoaderManager().initLoader(0, null, this);
}
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CursorLoader(this, ContactsContract.Data.CONTENT_URI,
PROJECTION, SELECTION, null, null);
}
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
mAdapter.swapCursor(data);
}
public void onLoaderReset(Loader<Cursor> loader) {
mAdapter.swapCursor(null);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
}
}
My Output that lists out email ids which i do not want to get populated:
A
a#gmail.com
B
b#gmail.com
C
c#gmail.com
D
d#gmail.com
A
(000)000-000
B
(111)111-111
(Since I do not have enough reputation, I am unable to upload my output image. Sorry for that)

Adapter doesn´t show the corrects Strings

I´m developing an android app and I want to display some data from a database in a ListView with a Title and Subtitle. I did an adapter extending SimpleCursorAdapter and it´s working but it shows the 2 first fields and no what I choose in the method BindView. I´m trying to find the error but I can´t, probably it´s something really stupid but that errors is really hard to find by yourself :-)
So that's the code of the adapter:
package com.apeirons.apeironsdatabasemanager;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
public class MyListAdapter extends SimpleCursorAdapter {
//private Context context;
LayoutInflater inflater;
#SuppressWarnings("deprecation")
public MyListAdapter(Context context, int layout, Cursor c, String[] from,
int[] to) {
super(context, R.layout.consult, c, from, to);
inflater = LayoutInflater.from(context);
}
public void bindview (View view, Context context, Cursor cursor){
TextView titulo = (TextView)view.findViewById(R.id.Titulo);
titulo.setText(cursor.getString(cursor.getColumnIndex("name")));
TextView subtitulo = (TextView)view.findViewById(R.id.SubTitulo);
subtitulo.setText(cursor.getString(cursor.getColumnIndex("kind_place")));
subtitulo.append(cursor.getString(cursor.getColumnIndex("score")));
}
#Override
public View newView (Context context, Cursor cursor, ViewGroup parent){
View v = inflater.inflate(R.layout.entrys, parent, false);
return v;
}
}
And here is where I use the adapter:
package com.apeirons.apeironsdatabasemanager;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
public class Consult extends Activity {
private ListView list;
private SQLiteDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.consult);
list = (ListView)findViewById(R.id.list);
this.getIntent();
ApeironsSQLiteHelper apeironsdb = new ApeironsSQLiteHelper(this, "DBApeirons.DB", null, 1);
db = apeironsdb.getReadableDatabase();
String[] campos = new String[]{"_id", "name", "kind_place", "score"};
Cursor c = db.query("Apeirons", campos, null, null, null, null, null);
int cuenta = c.getCount();
c.moveToFirst();
Log.d("CONSULTA", Integer.toString(cuenta));
Log.d("CURSOR", c.getString(c.getColumnIndex("score")));
String[] from = new String[]{"name", "kind_place", "score"};
int [] to = new int[] {R.id.Titulo, R.id.SubTitulo};
//#SuppressWarnings("deprecation")
MyListAdapter myadapter = new MyListAdapter (this,
R.layout.entrys, c, from, to);
list.setAdapter(myadapter);
}
}
Really thank you for your help.
You are not overriding the bindView method of SimpleCursorAdapter, but defining a new method bindview (not the capitalisation!) which is called nowhere.
Because your new method is public in a public class, you won't be warned by the compiler that it is unused.
If you had used the #Override annotation, your compiler would have warned you that you don't actually override a method...

Categories

Resources