I want to make a list from some data that I have in my database.
The first two sets of data in my database are first name and last name.
I want my list to show both first and last name instead of now where it only shows the first name. How do I do that? My code looks like this:
private void fillData()
{
Cursor contactCursor = mDbHelper.fetchAllReminders();
startManagingCursor(contactCursor);
String[] from = new String[]{DbAdapter.KEY_FIRST};
int[] to = new int[]{R.id.contactlist};
SimpleCursorAdapter contacts = new SimpleCursorAdapter(this, R.layout.list, contactCursor, from, to);
setListAdapter(contacts);
}
Here is a full implementation. You will need to create a custom row and a custom Array adapter.
Here is a full tutorial http://commonsware.com/Android/excerpt.pdf
This will tell you everything you need to know to get this done.
Also refer here where ive posted another example.
How to add an EditText to a ListView
EDIT: How to build a custom listview and return data from a databse
You first create a listview activity.
public class meeting_list extends ListActivity {
Cursor model = null;
meetingAdapter adapter = null;
//This should be what ever your database helper is from your SQLite base.
meetingHelper helper = null;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.meeting_list);
helper = new meetingHelper(this);
model = helper.getAll();
startManagingCursor
(model);
adapter = new meetingAdapter(model);
setListAdapter(adapter);
registerForContextMenu(getListView());
//Ondestroy is used to close the database to free up resources
#Override
public void onDestroy(){
super.onDestroy();
helper.close();
}
#Override
public void onListItemClick(ListView list, View view, int position, long id){
Intent i = new Intent(meeting_list.this, meeting_create_edit.class);
//
i.putExtra(ID_EXTRA, String.valueOf(id));
startActivity(i);
}
//Here create a class to extend the Cursor Adapter
class meetingAdapter extends CursorAdapter{
meetingAdapter(Cursor c){
super(meeting_list.this, c);
}
#Override
public void bindView(View row, Context ctxt, Cursor c) {
meetingHolder holder = (meetingHolder)row.getTag();
holder.populateFrom(c, helper);
}
#Override
public View newView(Context ctxt, Cursor c, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.mrow, parent, false);
meetingHolder holder = new meetingHolder(row);
row.setTag(holder);
return row;
}
}
//Here create a class to actually hold the view for the row in the listview.
static class meetingHolder{
private TextView mtitle = null;
private TextView maddress = null;
private ImageView Icon = null;
meetingHolder(View row){
mtitle=(TextView)row.findViewById(R.id.mtitle);
maddress = (TextView)row.findViewById(R.id.address);
Icon = (ImageView)row.findViewById(R.id.Micon);
}
//Here populate the row with the data from your database
void populateFrom(Cursor c, meetingHelper helper){
mtitle.setText(helper.getMettingTitle(c));
maddress.setText(helper.getAddress(c));
This should do it. Just substitute your informations where it should be. This is a tutorial ive put together for you.
Now i have tried to edit the code according to your guide, what i have done for now looks like this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
mDbHelper = new DbAdapter(this);
mDbHelper.open();
fillData();
}
private void fillData()
{
Cursor contactCursor = mDbHelper.fetchAllReminders();
startManagingCursor(contactCursor);
String[] from = new String[]{DbAdapter.KEY_FIRST};
int[] to = new int[]{R.id.contactlist};
SimpleCursorAdapter contactsfirst = new SimpleCursorAdapter(this, R.layout.list, contactCursor, from, to);
String[] from2 = new String[]{DbAdapter.KEY_LAST};
int[] to2 = new int[]{R.id.contactlist};
SimpleCursorAdapter contactslast = new SimpleCursorAdapter(this, R.layout.list, contactCursor, from2, to2);
setListAdapter(contactsfirst,last);
}
And my xml file looks like this:
<?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"
>
<TextView
android:id="#+id/first"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="40sp"
/>
<TextView
android:id="#+id/last"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="40sp"
/>
</LinearLayout>
Related
I had populated a listview using simplecursoradapter. However, I want to add images, wherein if the answer is correct it should display check on the right and if null or incorrect it should display an x-mark. It does not display anything but there is no error. Here is my activity code:
public class Results extends ListActivity{
DBAdapter db = new DBAdapter(this);
private Cursor mCursor;
ImageView iv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.resultslist);
db.open();
fillData();
db.close();
}
private void fillData() {
mCursor = db.getAllInfo();
startManagingCursor(mCursor);
String[] from = new String[]{DBAdapter.KEY_QUESTIONS, DBAdapter.KEY_CORRECTANSWERS, DBAdapter.KEY_YOURANSWERS};
int[] to = new int[]{R.id.textViewquestionresults, R.id.textViewcorrectansresults, R.id.textViewyouranswerresults};
SimpleCursorAdapter c=
new SimpleCursorAdapter(this, R.layout.rowresults, mCursor, from, to);
setListAdapter(c);
}
private class c extends SimpleCursorAdapter{
Context lcontext;
public c(Context context, int layout, Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to);
lcontext = context;
}
#Override
public View getView(final int pos, View v, ViewGroup parent) {
v = super.getView(pos, v, parent);
final ImageView iv = (ImageView) v.findViewById(R.id.imageViewresults);
final TextView tvQuestion = (TextView) v.findViewById(R.id.textViewQuestion);
final TextView tvCorrectAns = (TextView) v.findViewById(R.id.textViewcorrectansresults);
final TextView tvYourAns = (TextView) v.findViewById(R.id.textViewyouranswerresults);
if(tvYourAns.equals(tvCorrectAns)){
iv.setImageResource(R.drawable.greencheckmark);
}else{
iv.setImageResource(R.drawable.redxmark);
}
return v;
}
}
}
When extending SimpleCursorAdapter, you shouldn't override getView().
You should override newView() and bindView() instead.
In newView() inflate your layout and initialize your views.
In bindView() set your views' values.
Fetching data from database into LisFragment. I need to use this ListFragment file content into MainActivity.java.
SecondActivity which extends ListFragment:
String DB = "TestDB";
String TABLE_NAME = "addcamera";
SQLiteDatabase sampleDB = null;
ArrayList<String> results = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sampleDB = SQLiteDatabase.openOrCreateDatabase(DB, null);
Cursor c = sampleDB.rawQuery("SELECT CameraName FROM " + TABLE_NAME , null);
if (c != null) {
if (c.moveToFirst()) {
do {
String CameraName = c.getString(c.getColumnIndex("CameraName"));
results.add(CameraName);
}while (c.moveToNext());
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, results);
}
main.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">
<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
android:name="com.exercise.FragmentTest.SecondActivity"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/image_list_fragment">
</fragment>
</LinearLayout>
Can anyone helpme?
Well, first thing's first - your Activity should not be extending ListFragment, your own Fragment class should be doing so. Hopefully I haven't misunderstood anything. :-)
However, you could easily see your ListFragment derivative as a ListActivity, ie you can use the getListView() method to get the ListView corresponding element (#android:id/list) from your XML.
Seeing that you already have a Cursor ready, you should consider using a SimpleCursorAdapter and let it manage the cursor for you and *all* you need to do is to specify what fields to populate elements with.
Example:
getListView().setAdapter(
new SimpleCursorAdapter(
getActivity(),
R.layout.your_list_item_layout,
cursor,
new String[] { "database_table_1", "database_table_2" },
new int[] { R.id.element_1, R.id.element_2 }
)
);
Update:
Here's what your custom ListFragment could look like:
public class CustomListFragment extends ListFragment {
// Attributes
private Context mContext;
private LayoutInflater mLayoutInflater;
private SQLiteDatabase mSampleDb;
private List<String> mResults;
private Cursor mCursor;
// Elements
private ListView mListView;
private SimpleCursorAdapter mListAdapter;
// Constants
private final String DB = "TestDB";
private final String TABLE_NAME = "addcamera";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Set our attributes
mContext = getActivity();
mLayoutInflater = inflater;
// Let's inflate & return the view
View view = mLayoutInflater.inflate(R.layout.your_fragment_layout, container, false);
// Get the database handler & the cursor
mSampleDb = SQLiteDatabase.openOrCreateDatabase(DB, null);
mCursor = mSampleDb.rawQuery("SELECT CameraName FROM " + TABLE_NAME , null);
// Init
init(view);
// Return
return view;
}
public void init(View v) {
// Setup the listAdapter
mListAdapter = new SimpleCursorAdapter(
mContext,
R.layout.your_list_item_layout,
cursor,
new String[] { "database_table_1", "database_table_2" },
new int[] { R.id.element_1, R.id.element_2 }
)
);
mListView.setAdapter(mListAdapter);
}
#Override
public void onListItemClick(ListView l, View v, int pos, long id) {
Toast.makeText(mContext, "CLICKED ON POS #" + pos + "!", Toast.LENGTH_SHORT).show();
}
}
What is the best way to implement a ListFragment using SQLite database. Currently I have created an DBAdapter to facilitate opening, closing, and fetching records into a SimpleCursorAdapter. I have my MainActivity which implements an ActionBar with Navigation Tabs which I would like to display a different ListView for each tab.
Here is my ListFragment:
public class MaterialsListFragment extends ListFragment {
public DBAdapter db;
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.portrait_material_view, container, false);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// create new DBAdapter
db = new DBAdapter(getActivity());
db.open();
Cursor c = db.getAllRecords();
String[] from = new String[] { DBAdapter.KEY_IDNO, DBAdapter.KEY_MATERIAL };
int[] to = new int[] { R.id.idno, R.id.materials };
// Now create an array adapter and set it to display using our row
MyListAdapter materials = new MyListAdapter(this, R.layout.list_cell, c, from, to);
setListAdapter(materials);
}
Here is MyListAdapter code which for now is in it's own class file:
public class MyListAdapter extends SimpleCursorAdapter {
public MyListAdapter(Context context, int layout, Cursor cursor, String[] from, int[] to) {
super(context, layout , cursor, from, to);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
// Create the idno textview with background image
TextView idno = (TextView) view.findViewById(R.id.idno);
idno.setText(cursor.getSring(3));
// create the material textview
TextView materials = (TextView) view.findViewById(R.id.materials);
materials.setText(cursor.getString(1));
}
}
Is this the way to go about this? I would appreciate any suggestion you may have or if you know of any good examples.
I was able to get this to work, so I think I'm on the right track. I had to make this modification to get it to run, but it seems to be working well.
MyListAdapter materials = new MyListAdapter(getActivity(), R.layout.list_cell, c, from, to);
I would still be interested in any suggestions or ways to improve this approach.
I want to be able to fetch a row from a list view and populate textViews in a different activity. I want to be able to do this onclick of an item with the list view..
public class CBFilter extends Activity {
ListView RecipeNames;
Cursor cursor;
SimpleCursorAdapter adapter;
CBDataBaseHelper data;
SQLiteDatabase data2;
TextView RecipeText;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
RecipeNames = (ListView) findViewById(R.id.List1);
RecipeNames.setTextFilterEnabled(true);
RecipeText = (TextView) findViewById(R.id.recipeText);
adapter = new SimpleCursorAdapter (this, 0, cursor, null, null);
data = new CBDataBaseHelper(this);
data.open();
cursor = data.query();
startManagingCursor(cursor);
String[] from = {CBDataBaseHelper.KEY_NAME};
int[] to = { R.id.recipeText};
adapter = new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
RecipeNames.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
public void CreateNew(View view){
Intent myIntent = new Intent(this, CBCreate.class);
startActivity(myIntent);
}
}
How can i convert this code in order to achieve the required functionality.. thanks Stefan
try like this
public void onListItemClick(ListView parent, View v, int position, long id) {
String string = from[position]); // this depends on your Adapter ...
Intent i = new Intent(CheckData.this,ShowData.class);
i.putExtra("SELECTED", string);
startActivity(i);
i got it from this link , it will be use full for you :
Use of SQLite
I'm trying to have another activity launch when a list item gets clicked. Below is my code:
public class AvoidForeclosure extends CustomListTitle {
/** Called when the activity is first created. */
private DbAdapter db;
private SimpleCursorAdapter clients;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListView list = getListView();
setContentView(R.layout.main);
this.title.setText("Avoid Foreclosure");
db = new DbAdapter(this);
db.open();
fillData();
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick( AdapterView<?> parent, View view, int position, long id ) {
int viewId = view.getId();
TextView theView = (TextView) findViewById(viewId);
String name = theView.getText().toString();
Cursor clientData = db.getClientByName(name);
Intent intent = new Intent();
intent.setClass(view.getContext(), CurrentMarketValue.class);
intent.putExtra("clientId", clientData.getInt(0));
startActivity(intent);
}
});
}
private void fillData() {
// Get all of the notes from the database and create the item list
Cursor c = db.fetchAllClients();
startManagingCursor(c);
String[] from = new String[] { DbAdapter.KEY_NAME };
int[] to = new int[] { R.id.text1 };
// Now create an array adapter and set it to display using our row
clients = new SimpleCursorAdapter(this, R.layout.clientsrow, c, from, to);
setListAdapter(clients);
}
}
Yet when I click it, nothing happens at all. Any ideas?
Try switching this line:
ListView list = getListView();
to be after this one:
setContentView(R.layout.main);
Otherwise you'll be getting a handle to the ListActivity's default layout's ListView, rather than R.layout.main's listview (which is the one you really want).