Hello i am trying to implement a listview which will display the contents of a class by TextView. However the adapter doesn't seem to take in the values of the objects as it throws a nullpointer exception.
this is my custom class
public class SubjectClass {
String sName;
String sCode;
String teacher;
}
Given Belows is the code for my CUstomarrayadapter
public CustomAdap(Activity context, ArrayList<SubjectClass> names) {
super(context, R.layout.listtempl, names);
this.context = context;
this.names = names;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.listtempl, null, true);
TextView textView1 = (TextView) rowView.findViewById(R.id.label1);
TextView textView2 = (TextView) rowView.findViewById(R.id.label2);
TextView textView3 = (TextView) rowView.findViewById(R.id.label3);
SubjectClass sClass= (SubjectClass)getItem(position);
String s1 = sClass.sName;
String s2 = sClass.sCode;
String s3 = sClass.teacher;
Toast.makeText(getContext(), sClass.sCode,Toast.LENGTH_SHORT).show();
textView1.setText(s1);
textView2.setText(s2);
textView3.setText(s3);
return rowView;
}
this is the xml file used by the adapter
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView android:text="#+id/label1" android:textColor="#F1235AFA" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="#+id/label" android:layout_alignParentTop="true" android:textAppearance="?android:attr/textAppearanceMedium" android:layout_alignParentLeft="true"></TextView>
<TextView android:text="TextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="#+id/textView2" android:textAppearance="?android:attr/textAppearanceSmall" android:layout_alignBaseline="#+id/textView1" android:layout_alignBottom="#+id/label2" android:layout_alignParentLeft="true"></TextView>
<TextView android:text="TextView" android:textColor="#2CD7E0" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="#+id/textView1" android:textAppearance="?android:attr/textAppearanceSmall" android:layout_below="#+id/label" android:layout_toRightOf="#+id/label3" android:layout_marginLeft="15dp"></TextView>
</RelativeLayout>
This is my activity
public class SampleActivity extends Activity
{
ListView listview;
CustomAdap adapter;
ArrayList<SubjectClass> values = new ArrayList<SubjectClass>();
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.list1);
SubjectClass subjectClass = new SubjectClass();
subjectClass.sCode="cs9410";
subjectClass.sName="Principles of management";
subjectClass.teacher="xyz";
values.add(subjectClass);
SubjectClass subjectClass1 = new SubjectClass();
subjectClass1.sCode="cs9401";
subjectClass1.sName="Ethics";
subjectClass1.teacher="xxx";
values.add(subjectClass1);
listview =(ListView) findViewById(R.id.lv1);
adapter = new CustomAdap(this, values);
listview.setAdapter(adapter);
}
}//
In row layout file change android:text="#+id/label1" to android:id="#+id/label1".
For all 3 TextView:
SubjectClass sClass = (SubjectClass) names.get(position);
I believe you need to change your code to
SubjectClass sClass= names.get(position);
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 have a custom list view that fill with an image and text view in each row, and it shown correct :[1
but my problem is that I want to show the text that in a Toast in setOnItemClickListener. here is my codes:
public class Showing {
public int icon;
public String title;
public Showing(){
super();
}
public Showing(int icon, String title) {
super();
this.icon = icon;
this.title = title;
}}
and my adapter is:
public class ShowingAdapter extends ArrayAdapter<Showing> {
Context context;
int layoutResourceId;
Showing data[] = null;
public ShowingAdapter(Context context, int layoutResourceId, Showing[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ShowingHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ShowingHolder();
holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon);
holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);
row.setTag(holder);
}
else
{
holder = (ShowingHolder)row.getTag();
}
Showing showing = data[position];
holder.txtTitle.setText(showing.title);
holder.imgIcon.setImageResource(showing.icon);
return row;
}
static class ShowingHolder
{
ImageView imgIcon;
TextView txtTitle;
}}
And here are my layouts for Header:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:id="#+id/txtHeader"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:textStyle="bold"
android:textSize="22dp"
android:textColor="#FFFFFF"
android:padding="10dp"
android:text="Action Photos"
android:background="#336699" />
</LinearLayout>
And each row
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp">
<ImageView android:id="#+id/imgIcon"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_marginRight="15dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:layout_gravity="left" />
<TextView android:id="#+id/txtTitle"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:textStyle="bold"
android:textSize="22dp"
android:textColor="#000000"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp" />
</LinearLayout>
So here is My Main code :
public class MainActivity extends Activity {
private ListView listView1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Showing action_data[] = new Showing[]
{
new Showing(R.drawable.cut, "Cut"),
new Showing(R.drawable.delete, "Delete"),
new Showing(R.drawable.favorites, "Favorites"),
new Showing(R.drawable.redo, "Redo"),
new Showing(R.drawable.up, "Up")
};
ShowingAdapter adapter = new ShowingAdapter(this,R.layout.listview_item_row, action_data);
listView1 = (ListView) findViewById(R.id.listView1);
View header = (View) getLayoutInflater().inflate(R.layout.listview_header_row, null);
listView1.addHeaderView(header);
listView1.setAdapter(adapter);
listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
***// I want to make a toast here...
// but the 'VIEW' is LinearLayout and
// I want to retrive the 'TEXT VIEW.getText'***
}
});
}}
You don't need to act on the layout. You can simply retrieve the object associated with your row. So inside the onItemClick() you can get it in this way:
Showing showing = (Showing)adapter.getitem(position)
now, showing contains all the information you need. So you can get the text:
showing.title
or if you make title private (as it supposed to be), you would use a getter:
showing.getTitle();
Hi guys, I tried to learn how to use custom ListView by this page
It works fine but I have problems with another options.
Cannot set margin to listItems
Cannot set backgro
Cannot set OnItemClickListener
1# Margin
First of all I'm trying to set margin between list items but nothing works. I try to set margin on RelativeLayout in rowlayout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="75dp"
android:background="#drawable/rounded"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
>
2# Background
I want to set background on whole screen under listView. I think I put black color on every View in every xml I found but nothing affect the background. I can change background of single list items, that's all.
android:background="#000000"
3#OnItemClickListener
My last problem is that I'm not able to set onItemClickListener. I have no idea how to set it if I don't have simply ListView but RelativeLayout with TextView etc.
I guess I have to use
setOnClickListener(new OnClickListener()
and after that
public void onClick(View arg0) {
but I have no idea on which View I have to use this method.
Files
MyAdapter.java
public class MyAdapter extends ArrayAdapter<Model> {
private final Context context;
private final ArrayList<Model> modelsArrayList;
public MyAdapter(Context context, ArrayList<Model> modelsArrayList) {
super(context, R.layout.rowlayout, modelsArrayList);
this.context = context;
this.modelsArrayList = modelsArrayList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// 1. Create inflater
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// 2. Get rowView from inflater
View rowView = null;
if(!modelsArrayList.get(position).isGroupHeader()){
rowView = inflater.inflate(R.layout.rowlayout, parent, false);
// 3. Get icon,title & counter views from the rowView
ImageView imgView = (ImageView) rowView.findViewById(R.id.item_icon);
TextView titleView = (TextView) rowView.findViewById(R.id.item_title);
TextView counterView = (TextView) rowView.findViewById(R.id.item_counter);
// 4. Set the text for textView
imgView.setImageResource(modelsArrayList.get(position).getIcon());
titleView.setText(modelsArrayList.get(position).getTitle());
counterView.setText(modelsArrayList.get(position).getCounter());
}
else{
//rowView = inflater.inflate(R.layout.group_header, parent, false);
// TextView titleView = (TextView) rowView.findViewById(R.id.header);
// titleView.setText(modelsArrayList.get(position).getTitle());
}
// 5. retrn rowView
return rowView;
}
}
Model.java
package com.example.sunny.katan;
/**
* Created by Sunny on 15.09.14.
*/
public class Model{
private int icon;
private String title;
private String counter;
private boolean isGroupHeader = false;
public Model(String title) {
this(-1,title,null);
isGroupHeader = true;
}
public Model(int icon, String title, String counter) {
super();
this.icon = icon;
this.title = title;
this.counter = counter;
}
public String getCounter() {
return counter;
}
public String getTitle() {
return title;
}
public int getIcon() {
return icon;
}
public boolean isGroupHeader() {
return false;
}
public void setGroupHeader(boolean isGroupHeader) {
this.isGroupHeader = isGroupHeader;
}
//gettters & setters...
}
main.java
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
// if extending Activity
//setContentView(R.layout.activity_main);
// 1. pass context and data to the custom adapter
MyAdapter adapter = new MyAdapter(this, generateData());
// if extending Activity 2. Get ListView from activity_main.xml
//ListView listView = (ListView) findViewById(R.id.listview);
// 3. setListAdapter
//listView.setAdapter(adapter); if extending Activity
setListAdapter(adapter);
}
private ArrayList<Model> generateData(){
ArrayList<Model> models = new ArrayList<Model>();
models.add(new Model(R.raw.barbell,"Cviky","37"));
models.add(new Model(R.raw.stretching,"Protahování","94"));
models.add(new Model(R.raw.work,"Generování workoutu","293"));
return models;
}
rowlayout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="75dp"
android:background="#drawable/rounded"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
>
<!-- icon -->
<ImageView
android:id="#+id/item_icon"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_alignParentLeft="true"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_centerVertical="true"
android:src="#raw/barbell"
/>
<!-- title -->
<TextView
android:id="#+id/item_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:layout_toRightOf="#+id/item_icon"
android:layout_marginTop="30dp"
android:layout_alignBaseline="#+id/item_counter"
android:textSize="20dp"
/>
<!-- counter -->
<TextView
android:id="#+id/item_counter"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_alignParentRight="true"
android:layout_marginRight="8dp"
android:layout_centerVertical="true"
android:background="#drawable/rectangle"
android:gravity="center"
android:textColor="#FFFFFF"
android:textSize="12sp"
android:textStyle="bold" />
</RelativeLayout>
main.xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="false"
>
<LinearLayout
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".katan_lobby"
android:orientation="vertical"
>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/menu"
android:layout_gravity="center_horizontal"
android:background="#238CD4"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/prvniItemSeznamu"
android:background="#238CD4"
style="#style/listView"
/>
</LinearLayout>
</ScrollView>
Looks like you are half way there in your activity.
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
MyAdapter adapter = new MyAdapter(this, generateData());
ListView listView = (ListView) findViewById(R.id.menu);
listView.setAdapter(adapter); if extending Activity
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
onItemClick(AdapterView<?> parent, View view, int position, long id)
{
//You now have the position but you will need to get your model list and use .get(position) and cast it to Model to get access to it.
}
});
}
//First define your list view item xml… something like this.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/white"
android:layout_marginTop="10dp"
android:padding="10dp" >
<TextView
android:id="#+id/item1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/custom_blue"
android:text="TextView" />
<TextView
android:id="#+id/item2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:textColor="#color/custom_grey"
android:text="TextView" />
</LinearLayout>
//Then you define your list list adapter.
public class MyListAdapter extends ArrayAdapter<MyModel> {
private Context context;
private ArrayList<MyModel> myModel;
public MyListAdapter(Context context, ArrayList<MyModel> myModelList) {
super(context, R.id.icon, myModelList);
this.context = context;
this.myModelList = myModelList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = null;
View rowView = convertView;
TextView myItemName = (TextView)rowView.findViewById(R.id.item1);
TextView myItemTitle = (TextView)rowView.findViewById(R.id.item2);
//use your models getters/setters
myItemName.setText(myModelList.get(position).getItemTitle());
myItemTitle.setText(myModelList.get(position).getItemName());
return rowView
}
}
//Now use both the list adapter and list item in your ListFragment or ListActivity.
ArrayList<MyModel> myModelList = new ArrayList<MyModel>();
MyListAdapter myApt = new MyListAdapter(this, myModelList);
setListAdapter(myApt);
//For clicking on the items:
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// ListView Clicked item value
String itemValue = l.getItemAtPosition(position).toString();
doSomethingWihtMyItemMethod(position);
}
/* You can customize your list item anyway you like, just be aware of screen real estate when doing so.Hope this helps. */
I am new in android. I want to show the data that I get from Database into ListView.
For now I can show only a single data.
How to show multiple data into custom ListView?
Here's my MainActivity.class
DatabaseHandler db = new DatabaseHandler(this);
/**
* CRUD Operations
* */
Log.d("Reading: ", "Reading all contacts..");
List <AllItem> allItems = new ArrayList<AllItem>();
allItems = db.getAllAccommodations();
ArrayList <String> allItems2 = new ArrayList<String>();
for (AllItem cn : allItems) {
allItems2.add(cn.getItem_name());
allItems2.add(cn.getAreaNAme());
}
ArrayAdapter <String> adapter = new ArrayAdapter <String> (this, android.R.layout.simple_list_item_1,allItems2);
listview.setAdapter(adapter);
I have my own custom ListView like this
Acco.xml
<ListView
android:id="#+id/listAccommodation"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="8"
android:layout_marginLeft="7dip"
android:layout_marginRight="7dip"
android:background="#color/white"
android:divider="#color/black90"
android:dividerHeight="5.0sp"
android:listSelector="#color/black30" >
</ListView>
AccoLayout.xml
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dip"
android:paddingTop="10dip"
android:paddingBottom="10dip" >
<TextView
android:id="#+id/item_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="#+id/area_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp"
android:layout_below="#+id/item_name" />
</RelativeLayout>
Is there anyone can help me with this?
You need to create CustomAdapter class for this.
Use your listview as it is.
<ListView
android:id="#+id/listAccommodation"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="8"
android:layout_marginLeft="7dip"
android:layout_marginRight="7dip"
android:background="#color/white"
android:divider="#color/black90"
android:dividerHeight="5.0sp"
android:listSelector="#color/black30" >
</ListView>
And your custom Listview also.
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dip"
android:paddingTop="10dip"
android:paddingBottom="10dip" >
<TextView
android:id="#+id/item_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="#+id/area_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp"
android:layout_below="#+id/item_name" />
</RelativeLayout>
Create your custom adapter class and pass data to this class.
adapter = new ListAdapter(this, allItems2);
adapter.notifyDataSetChanged();
listview.setAdapter(adapter);
Here is CustomAdapter class.
public class ListAdapter extends BaseAdapter {
public ListAdapter(Activity a, List <AllItem> allItems) {
activity = a;
data = d;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.AccoLayout, null);
TextView itemName = (TextView)vi.findviewById(R.id.item_name);
TextView areaName = (TextView)vi.findviewById(R.id.area_name);
// Set your data here
itenName.setText(data.get(position));//like this
return vi;
}
}
I assume that your allItems2 list has a pattern like itemName0, areaName0, itemName1, areaName1, itemName2.. etc. Then, you can write a custom adapter like this.
public class CustomAdapter extends ArrayAdapter<String> {
private final Activity context;
private final List<String> items;
public CustomAdapter (Activity context, List<String> items) {
super(context, R.layout.AccoLayout, items);
this.context = context;
this.items= items;
}
#Override
public View getView(final int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.AccoLayout, null, true);
TextView itemName = (TextView) rowView.findViewById(R.id.item_name);
TextView areaName= (TextView) rowView.findViewById(R.id.area_name);
itemName.setText(items.get(2*position));
areaName.setText(items.get(2*position + 1));
return rowView;
}
}
Then call it from your main activity;
CustopAdapter adapter = new CustomAdapter (MainActivity.this, allItems2);
listview.setAdapter(adapter);
Also, by Android's convention, try not to use uppercase letters in XML file names to prevent any complication. You may change to acco_layout.xml.
Consider this to be your Cursor: after you fetch from DB
Cursor mCur = db.getAllAccommodations();
in onCreate:
CurAdapter Cur = new CurAdapter(getActivity(), mCur,0);
final ListView lv = (ListView)findViewById(R.id.listAccommodation);
lv.setFastScrollEnabled(true);
lv.setAdapter(Cur);
Then Make a Subclass:
private class CurAdapter extends CursorAdapter{
public CurAdapter(Context context, Cursor c, int flags) {
super(context, c, flags);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView tv = (TextView) view.findViewById(R.id.item_name);
TextView tv1 = (TextView) view.findViewById(R.id.area_name);
String item = (cursor.getString(cursor.getColumnIndexOrThrow("ColumnName1")));
String area = dateConvert(cursor.getString(cursor.getColumnIndexOrThrow("ColumnName2")));
tv1.setText(item);
tv.setText(area);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = LayoutInflater.from(context).inflate(R.layout.AccoLayout, null);
return view;
}
}
Where R.layout.AccoLayout is your "listview row" layout, for example:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="10dip"
android:paddingLeft="10dip"
android:paddingTop="10dip" >
<TextView
android:id="#+id/item_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="#+id/area_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/item_name"
android:textSize="14sp" />
</RelativeLayout>
I created an Adapter to populate my custom listView and when ran on the emulator the activity is blank. Plz help. I am sure I'm missing something 'cause I am new to java & Android. Some code snippets to correct it and pointers will be appreciated. Thnx!
My Activity:
public class List_AC3 extends ListActivity {
/**
* -- Called when the activity is first created
* ===================================================================
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.list_view2);
displayResultList();
}
private void displayResultList() {
Cursor databaseCursor = null;
DomainAdapter databaseListAdapter = new DomainAdapter(this, R.layout.list_item, databaseCursor,
new String[] {"label", "title", "description"},
new int[] { R.id.label, R.id.listTitle, R.id.caption });
databaseListAdapter.notifyDataSetChanged();
setListAdapter(databaseListAdapter);
}
}
My Adapter:
public class DomainAdapter extends SimpleCursorAdapter{
private LayoutInflater mInflater;
String extStorageDirectory;
public DomainAdapter(Context context, int layout, Cursor c, String[] from,
int[] to) {
super(context, layout, c, from, to);
mInflater = LayoutInflater.from(context);
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.text1 = (TextView) convertView.findViewById(R.id.label);
holder.text2 = (TextView) convertView.findViewById(R.id.listTitle);
holder.text3 = (TextView) convertView.findViewById(R.id.caption);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File dbfile = new File(extStorageDirectory+ "/Aero-Technologies/flyDroid/dB/flyDroid.db");
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile, null);
Cursor data = db.rawQuery("SELECT * FROM AC_list", null);
data.moveToPosition(position);
int label_index = data.getColumnIndex("label");
String label = data.getString(label_index);
int title_index = data.getColumnIndex("title");
String title = data.getString(title_index);
int description_index = data.getColumnIndex("description");
String description = data.getString(description_index);
holder.text1.setText(label);
holder.text2.setText(title);
holder.text3.setText(description);
return convertView;
}
static class ViewHolder {
TextView text1;
TextView text2;
TextView text3;
}
}
The list_view2.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="30dip"
android:padding="4dip"
android:background="#drawable/gradient" >
<ImageButton
android:id="#+id/homeBtn"
android:src="#drawable/ic_menu_icon"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:background="#null" />
<TextView
android:id="#+id/titleBarTitle"
android:layout_centerInParent="true"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:textSize="18sp" />
<ImageButton
android:id="#+id/toolBtn"
android:src="#drawable/ic_menu_list"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:background="#null" />
</RelativeLayout>
<ListView
android:id="#id/android:list"
android:layout_height="wrap_content"
android:layout_width="fill_parent" />
</LinearLayout>
And my list_item.xml:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/acItem"
style="#style/listItem" >
<TextView
android:id="#+id/label"
style="#style/listAcronym" />
<TextView
android:id="#+id/listTitle"
style="#style/listTitle" />
<TextView
android:id="#+id/caption"
style="#style/listDiscription"/>
<ImageView
style="#style/listNextIcon" />
</RelativeLayout>
the google notepad tutorials should also help you IIRC they should be using cursors passed to a listview
SimpleCursorAdapter doesn't need to be extended to work. Take your db logic out of getView and use it to construct a cursor which actually points to a db result. Then pass that cursor to the SimpleCursorAdapter constructor. In fact, I don't think getView is actually being called anywhere.
Try getting this example working http://thinkandroid.wordpress.com/2010/01/09/simplecursoradapters-and-listviews/ first and then edit it to do what you need.
If you want to do something more complex (like setting the various textviews yourself like you're trying to do in getView) look into CursorAdapter.
The correct answer can be found HERE along with the code.