ListView is not populating - android

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.

Related

ListView very slow when scrolling

I really need help, Listview which I used in my app is very slow while scrolling how can I fix it ? I reduce the images, use viewholder but nothing change..
I am beginner in android : )
also get this message : I/Choreographer: Skipped 32 frames! The application may be doing too much work on its main thread.
Here is my code
public class asker extends Activity {
ListView list;
String[] askerbaslik;
int[] images =
{R.drawable.barbar_icon, R.drawable.okcu_icon,
R.drawable.dev_icon,
R.drawable.goblin_icon,
R.drawable.duvar_kirici_icon, R.drawable.balon_icon,
R.drawable.buyucu_icon, R.drawable.sifaci_icon,
R.drawable.ejderha_icon,
R.drawable.pekka_icon, R.drawable.yavruejder_icon, R.drawable.madenci_icon};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview);
Resources res = getResources();
askerbaslik = res.getStringArray(R.array.asker_adlari);
list = (ListView) findViewById(R.id.listview);
ilyasadapter adapter = new ilyasadapter(this, askerbaslik, images);
list.setAdapter(adapter);
}
class ilyasadapter extends ArrayAdapter<String> {
Context context;
int[] images;
String[] titlearray;
ilyasadapter(Context c, String[] titles, int imgs[]) {
super(c, R.layout.liste_tasarim, R.id.asker_baslik, titles);
this.context = c;
this.images = imgs;
this.titlearray = titles;
}
class MyViewHolder {
TextView mytitle;
ImageView myimage;
MyViewHolder(View v) {
mytitle = (TextView) v.findViewById(R.id.asker_baslik);
myimage = (ImageView) v.findViewById(R.id.asker_icon);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
MyViewHolder holder = null;
if (row == null) {
LayoutInflater inflater = (LayoutInflater)
context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.liste_tasarim, parent, false);
holder = new MyViewHolder(row);
row.setTag(holder);
Log.d("test", "creating a new row");
} else {
holder = (MyViewHolder) row.getTag();
Log.d("test", "Recycling stuff");
}
holder.myimage.setImageResource(images[position]);
holder.mytitle.setText(titlearray[position]);
return row;
}
}
}
Single row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_marginTop="5dp"
android:id="#+id/asker_icon"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="#drawable/barbar_icon"
android:background="#drawable/rounded_corner"
></ImageView>
<TextView
android:id="#+id/asker_baslik"
android:layout_marginTop="40dp"
android:layout_marginLeft="30dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Asker ismi"
android:textColor="#ffffff"
android:textSize="15dp"
android:fontFamily="sans-serif"
/>
</LinearLayout>
my listview
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#455A64" >
<ListView
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#263238"
android:dividerHeight="2px"
/>
</RelativeLayout>
Please try to remove the icons from the listview and see if that improves performance. You may be using images with too high of a resolution. I too have noticed performance anomalies when using high-resolution images.
Let me know if that helps. If not, there are a few other things that we can try.

Show Multiple Data in ListView

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>

How to resize activity listview in android?

Hi I want to resize my listview in android.
I have other source than previous topics.
.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="3dp" >
<TextView
android:id="#+id/currentDirectoryTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Current directory:" />
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginTop="5dp"
android:textSize="30sp"
android:layout_weight="1" />
</LinearLayout>
.class
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.activity_list_item, android.R.id.text1, values);
setListAdapter(adapter);
How to resize my list? It is always small. Same after changing textSize.
This is whole class ListFileActivity.
public class ListFileActivity extends ListActivity {
private String path;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Use the current directory
path = android.os.Environment.getExternalStorageDirectory()
+ File.separator + AppConstant.DIRECTORY;
if (getIntent().hasExtra("path")) {
path = getIntent().getStringExtra("path");
}
updateCurrentDirectoryTextView();
// Read all files sorted into the values-array
List values = new ArrayList();
File dir = new File(path);
if (!dir.canRead()) {
setTitle(getTitle() + " (inaccessible)");
}
String[] list = dir.list();
if (list != null) {
for (String file : list) {
if (!file.startsWith(".")) {
values.add(file);
}
}
}
Collections.sort(values);
// Put the data into the list
/* ListView lst = new ListView(this);
//String[] arr = {"Item 1","Item 2"};
ArrayAdapter<String> ad = new ArrayAdapter<String>(this,R.layout.mylist,values);
lst.setAdapter(ad);*/
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.activity_list_item, android.R.id.text1, values);
setListAdapter(adapter);
}
private void updateCurrentDirectoryTextView() {
((TextView) this.findViewById(R.id.currentDirectoryTextView))
.setText("Current directory: " + path);
}
}
Remove the weight, i.e. remove this line
android:layout_weight="1"
Also what you are trying to do by setting a text size to listView? you should do it with adapter or individual item layouts
The line
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.activity_list_item, android.R.id.text1, values);
Is responsible for setting the adapter for every list element.
What determines the size is the list element layout that is inflated by the adapter, not the ListView itself. In your case, that is android.R.id.text1, which is defined by the system. Therefore, if you want to change it, you need to create your own adapter. This is from an example:
public class MyDataAdapter extends ArrayAdapter<MyData>
{
MyDatadata[] = null;
public MyDataAdapter(Context context, int layoutResourceId, MyData[] data)
{
super(context, layoutResourceId, data);
this.data = data;
}
public MyDataAdapter(Context context, int layoutResourceId, List<MyData> data)
{
super(context, layoutResourceId, data);
this.data = data.toArray(new MyData[data.size()]);
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View row = convertView;
MyDataHolder holder = null;
if (row == null)
{
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new MyDataHolder();
holder.txtTitle = (TextView) row.findViewById(R.id.mydata_1);
holder.txtTitle2 = (TextView) row.findViewById(R.id.mydata_2);
holder.txtTitle3 = (TextView) row.findViewById(R.id.mydata_3);
holder.txtTitle4 = (TextView) row.findViewById(R.id.mydata_4);
row.setTag(holder);
}
else
{
holder = (MyDataHolder) row.getTag();
}
MyData mydata= data[position];
holder.txtTitle.setText(mydata.getName());
holder.txtTitle2.setText(mydata.getType());
holder.txtTitle3.setText(mydata.getDate());
holder.txtTitle4.setText(mydata.getStatus());
return row;
}
static class MyDataHolder
{
TextView txtTitle;
TextView txtTitle2;
TextView txtTitle3;
TextView txtTitle4;
}
#Override
public MyData getItem(int position)
{
return data[position];
}
The item xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/mydata_1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:gravity="center_vertical"
android:textAppearance="#android:attr/textAppearanceLarge"
android:textColor="#736F6E"
android:textSize="22sp"
android:textStyle="bold" />
<TextView
android:id="#+id/mydata_2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:layout_below="#id/mydata_1"
android:textStyle="bold"
android:textSize="12sp"
android:textColor="#736F6E"
android:layout_alignParentLeft="true"
android:textAppearance="#android:attr/textAppearanceLarge"
/>
<TextView
android:id="#+id/mydata_3"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:layout_below="#id/mydata_2"
android:textStyle="bold"
android:textSize="12sp"
android:textColor="#736F6E"
android:layout_alignParentLeft="true"
android:textAppearance="#android:attr/textAppearanceLarge"
/>
<TextView
android:id="#+id/mydata_4"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:layout_below="#id/mydata_3"
android:textStyle="bold"
android:textSize="12sp"
android:textColor="#736F6E"
android:layout_alignParentLeft="true"
android:textAppearance="#android:attr/textAppearanceLarge"
/>
</RelativeLayout>
And use it like this:
ArrayAdapter<MyData> adapter = new MyDataAdapter(inflater.getContext(), R.layout.listelement_mydata, mydatas);
setListAdapter(adapter);
Later I needed to change this to a SimpleCursorAdapter though because of changes in stuff, which looked like this:
Cursor c = getMyDataDataSource().getMyDatasCursor();
SimpleCursorAdapter adapter = new SimpleCursorAdapter(inflater.getContext(),
R.layout.listelement_mydata, c, new String[] { "name", "type", "date", "status" }, new int[] {
R.id.mydata_1, R.id.mydata_2, R.id.mydata_3, R.id.mydata_4 }, 0);
setListAdapter(adapter);
But you needed an ArrayAdapter so that's the one you will need.
EDIT:
....this might have been a stupidly bloated answer, considering you can probably use a single-textview List Element XML in place of android.R.id.text1, without your own adapter.
I won't remove it because if you need anything more complicated than a single textview then it might come in handy, but... yeah. Just define a single element XML for the list view with a single text view in it and it should work.

android: Custom SimpleCursorAdapter does not load all data

In need of assistance, I have a listview activity which I want to display couple of textfields per item plus 2 buttons (like contacts app having a call button and a text message button. Reading tutorials I found out how to get the buttons to be clickable, but now my textviews (all except 1) don't display any data other then the stock text I've left in the layout file. The 1 text view does display the data I require it to. No where in my custom SCA do I feed it specific data so I'm assuming it happens in the background.
My R.id.company_address_details_phone loads the needed data without any manipulation on my part, but non of the other TextViews in my ViewHolder display any data. My For loop attached to my call button does output data from my cursor so I know it's not that I'm missing data. Any and all help is appreciated.
As a side note, when first wrote the code and did not use a custom SimpleCursorAdapter all my text views populated as expected (i just couldnt click buttons). This leads me to assume that my CompanyActivity class has no errors but that I'm missing something in my CompanyDetailsCursroAdapter class.
*EDIT***
So I'm answering my own question after I looked back and tried something. non of my views where being populated, I just had one of my views set with default text that made it appear as if it was pulled from my DB. I'm now populating my views with data from the cursor adapter passed to my custom cursor adapter using the below code. I would like to know if this is the best way of doing it or is there a more streamlined or android approved method.
viewHolder.addressTextView.setText(companyDetailsCursor.getString(companyDetailsCursor.getColumnIndex("AddressStreet")));
viewHolder.cityTextView.setText(companyDetailsCursor.getString(companyDetailsCursor.getColumnIndex("AddressCity")));
viewHolder.stateTextView.setText(companyDetailsCursor.getString(companyDetailsCursor.getColumnIndex("AddressState")));
viewHolder.zipTextView.setText(companyDetailsCursor.getString(companyDetailsCursor.getColumnIndex("AddressZip")));
viewHolder.phoneTextView.setText(companyDetailsCursor.getString(companyDetailsCursor.getColumnIndex("AddressPhone")));
CompanyDetailsCursorAdapter.java
public class CompanyDetailsCursorAdapter extends SimpleCursorAdapter implements Filterable{
private final Context context;
private int layout;
Cursor companyDetailsCursor;
public CompanyDetailsCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to);
this.context = context;
this.layout = layout;
this.companyDetailsCursor = c;
}
static class ViewHolder {
protected TextView addressTextView;
protected TextView cityTextView;
protected TextView stateTextView;
protected TextView zipTextView;
protected TextView phoneTextView;
protected ImageButton callButton;
protected ImageButton mapButton;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
final LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.company_address_details, null);
convertView.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
viewHolder = new ViewHolder();
viewHolder.addressTextView = (TextView) convertView.findViewById(R.id.company_address_details_street);
viewHolder.cityTextView = (TextView) convertView.findViewById(R.id.company_address_details_city);
viewHolder.stateTextView = (TextView) convertView.findViewById(R.id.company_address_details_state);
viewHolder.zipTextView = (TextView) convertView.findViewById(R.id.company_address_details_zip);
viewHolder.phoneTextView = (TextView) convertView.findViewById(R.id.company_address_details_phone);
viewHolder.callButton = (ImageButton) convertView.findViewById(R.id.company_address_details_call_button);
viewHolder.callButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
companyDetailsCursor.moveToPosition(position);
if (RouteTrackerGlobal.APP_DEBUG) { Log.d(RouteTrackerGlobal.APP_TAG,"getview position set to " + String.valueOf(position));}
for (int i = 0; i < companyDetailsCursor.getColumnCount();i++){
Log.i(RouteTrackerGlobal.APP_TAG, companyDetailsCursor.getString(i));
}
}
});
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
return convertView;
}
CompanyActivity.java
public class CompanyActivity extends ListActivity {
DbAdapter dbAdapter;
int companyID;
Context context = this;
Cursor companyDetailsCursor;
#Override
public void onCreate(Bundle savedInstanceBundle) {
super.onCreate(savedInstanceBundle);
dbAdapter = new DbAdapter(this);
setContentView(R.layout.company_activity);
Bundle companyActivityBundle = getIntent().getExtras();
companyID = companyActivityBundle.getInt("CompanyID");
ListView list = getListView();
list.setOnItemLongClickListener(new OnItemLongClickListener(){
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
return false;
}
});
}
#Override
public void onPause() {
dbAdapter.close();
super.onPause();
}
#Override
public void onResume() {
dbAdapter.open();
super.onResume();
loadDetails();
}
#Override
protected void onListItemClick (ListView l, View v, int position, long id){
//TODO: When item in list clicked, call activity to display address and directions
}
public void loadDetails() {
TextView companyLabel = (TextView) findViewById(R.id.company_activity_company_label);
companyDetailsCursor = dbAdapter.getCompanyDetails(companyID);
startManagingCursor(companyDetailsCursor);
companyDetailsCursor.moveToFirst();
companyLabel.setText(companyDetailsCursor.getString(companyDetailsCursor.getColumnIndex("CompanyName")));
String[] columns = new String[] {"AddressPhone", "AddressStreet", "AddressCity", "AddressState", "AddressZip"};
int[] to = new int[] {R.id.company_address_details_phone, R.id.company_address_details_street, R.id.company_address_details_city, R.id.company_address_details_state, R.id.company_address_details_zip};
CompanyDetailsCursorAdapter companyDetailsAdapter = new CompanyDetailsCursorAdapter(context, R.layout.company_address_details, companyDetailsCursor, columns, to);
setListAdapter(companyDetailsAdapter);
}
}
Company_Address_Details.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" >
<RelativeLayout android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/company_address_details_phone"
style="#style/company_address_listview"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="#string/company_address_details_phone_default" />
<ImageButton android:id="#+id/company_address_details_call_button"
style="#style/company_address_listview"
android:layout_alignParentRight="true"
android:layout_centerInParent="true"
android:background="#android:color/transparent"
android:src="#android:drawable/sym_action_call"
android:contentDescription="#string/company_address_details_phone_hint"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toLeftOf="#+id/company_address_details_call_button1"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/company_address_details_street"
style="#style/company_address_listview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/company_address_details_street_default" />
</LinearLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/company_address_details_city"
style="#style/company_address_listview"
android:layout_width="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="#string/company_address_details_city_default" />
<TextView
android:id="#+id/company_address_details_state"
style="#style/company_address_listview"
android:layout_centerInParent="true"
android:layout_centerVertical="true"
android:text="#string/company_address_details_state_default" />
<TextView
android:id="#+id/company_address_details_zip"
style="#style/company_address_listview"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:text="#string/company_address_details_zip_default" />
</RelativeLayout>
</LinearLayout>
<ImageButton
android:id="#+id/company_address_details_call_button1"
style="#style/company_address_listview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerHorizontal="false"
android:layout_centerInParent="false"
android:layout_centerVertical="true"
android:background="#android:color/transparent"
android:contentDescription="#string/company_address_details_phone_hint"
android:paddingLeft="20dp"
android:src="#android:drawable/ic_dialog_map" />
</RelativeLayout>
</LinearLayout>

Nullpointer exception in Listview when using custom class in android

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);

Categories

Resources