I am getting a NullPointer Exception in custom ListView Adapter android application.
This is my custom class with a few variables and getter.
public class ViewClass {
String ItemName, Category, Amount, TotalAmount;
//get,set methods here
}
This is my Main Activity class.
public class ViewList extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ArrayList<ViewClass> details = new ArrayList<ViewClass>();
ViewClass[] v = new ViewClass[5];
for (int i = 0; i < 5; i++) {
v[i] = new ViewClass();
v[i].setItemName("Item Name");
v[i].setAmount("Rs 1111");
v[i].setCategory("cateGory");
v[i].setTotalAmount("aaaa");
details.add(v[i]);
}
ListView msgList = (ListView) findViewById(R.id.MessageList);
msgList.setAdapter(new CustomListAdapter(details, this));
// msgList.setOnItemClickListener(new OnItemClickListener() {
// public void onItemClick(AdapterView<?> a, View v, int position,
// long id) {
//
// String s = (String) ((TextView) v.findViewById(R.id.From))
// .getText();
// Toast.makeText(ViewList.this, s, Toast.LENGTH_SHORT).show();
// }
// });
}
}
This is the XML file for ListItem Layout, the name is list_item_trans
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/tvBGColor1"
android:layout_width="10dp"
android:layout_height="fill_parent"
android:background="#android:color/background_dark" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/space" />
<TextView
android:id="#+id/tvItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/tvAmount"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="right"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/space" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/tvBGColor2"
android:layout_width="10dp"
android:layout_height="fill_parent"
android:background="#android:color/background_dark" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/space" />
<TextView
android:id="#+id/tvCat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12sp" />
<TextView
android:id="#+id/tvTotalAmount"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="right"
android:textSize="12sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/space" />
</LinearLayout>
This is as the name suggests, the CustomListAdapter
public class CustomListAdapter extends BaseAdapter{
private ArrayList<ViewClass> _data;
Context _c;
CustomListAdapter(ArrayList<ViewClass> data, Context c) {
_data = data;
_c = c;
}
public int getCount() {
// TODO Auto-generated method stub
return _data.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return _data.get(position);
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) _c
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list_item_message, null);
}
TextView tvItemName = (TextView) v.findViewById(R.id.tvItem);
TextView tvCategory = (TextView) v.findViewById(R.id.tvCat);
TextView tvAmount = (TextView) v.findViewById(R.id.tvAmount);
TextView tvTotalAmount = (TextView) v.findViewById(R.id.tvTotalAmount);
ViewClass msg = _data.get(position);
tvItemName.setText(msg.ItemName);
tvCategory.setText("Subject: " + msg.Category);
tvAmount.setText(msg.Amount);
tvTotalAmount.setText(msg.TotalAmount);
return v;
}
}
I am getting the error on in the getView method of the CustomListAdapter
tvItemName.setText(msg.ItemName);
This is the XML file for ListItem Layout, the name is list_item_trans
So The xml layout name is list_item_trans.xml
v = vi.inflate(R.layout.list_item_message, null);
You are inflating list_item_message.xml but your layout name is list_item_trans.xml
Maybee the error is here ?
List item layout is list_item_trans, but you are inflating list_item_message.
Change this line:
v = vi.inflate(R.layout.list_item_message, null);
Into this:
v = vi.inflate(R.layout.list_item_trans, null);
NullPointer Exception in custom ListView Adapter is caused
because you are inflating list_item_message.xml instead of list_item_trans.xml and initializing textviews from list_item_trans.xml
so just change
v = vi.inflate(R.layout.list_item_message, null);
To this
v = vi.inflate(R.layout.list_item_trans, null);
Related
Here is my code so far based on various answers to related questions on SO.
In my Activity
GridView gv = (GridView) findViewById(R.id.gridView1);
MyCustomAdapter mAdapter = new MyCustomAdapter();
mAdapter.addItem("Action1");
mAdapter.addItem("Action2");
mAdapter.addItem("Action3");
gv.setAdapter(mAdapter);
My Adapter
private class MyCustomAdapter extends BaseAdapter {
private ArrayList<String> mData = new ArrayList<String>();
private LayoutInflater mInflater;
public MyCustomAdapter() {
mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void addItem(final String item) {
mData.add(item);
notifyDataSetChanged();
}
#Override
public int getCount() {
return mData.size();
}
#Override
public String getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
NumericViewHolder holder = new NumericViewHolder();
if (convertView == null) {
convertView = mInflater.inflate(R.layout.horizontalnumberpicker, null);
holder.textView = (TextView)convertView.findViewById(R.id.txtNPTitle);
holder.minus = (Button)convertView.findViewById(R.id.btnMinus);
holder.plus = (Button)convertView.findViewById(R.id.btnPlus);
holder.value = (TextView)convertView.findViewById(R.id.txtNPValue);
holder.minus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
TextView tv = (TextView) v.findViewById(R.id.txtNPValue);
int value = Integer.parseInt(tv.getText().toString());
Toast.makeText(getApplicationContext(), Integer.toString(value), Toast.LENGTH_SHORT).show();
if (value > 0) {
value = value - 1;
tv.setText(Integer.toString(value));
}
}
});
holder.plus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
TextView tv = (TextView) v.findViewById(R.id.txtNPValue);
int value = Integer.parseInt(tv.getText().toString()); <--Error is here
Toast.makeText(getApplicationContext(), Integer.toString(value), Toast.LENGTH_SHORT).show();
value = value + 1;
tv.setText(Integer.toString(value));
}
});
convertView.setTag(holder);
} else {
holder = (NumericViewHolder)convertView.getTag();
}
holder.textView.setText(mData.get(position));
return convertView;
}
}
XML - Main_Activity
<?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:id="#+id/rlAddProduct"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/btnSaveProduct"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginEnd="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:text="#string/Save" />
<TextView
android:id="#+id/lblSelectCategory"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/btnSaveProduct"
android:layout_alignBottom="#+id/btnSaveProduct"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="20dp"
android:layout_marginStart="20dp"
android:text="#string/selectCategory" />
<Spinner
android:id="#+id/spCategory"
android:layout_width="250dp"
android:layout_height="40dp"
android:layout_alignBottom="#+id/lblSelectCategory"
android:layout_marginLeft="33dp"
android:layout_marginStart="33dp"
android:layout_toEndOf="#+id/lblSelectCategory"
android:layout_toRightOf="#+id/lblSelectCategory" />
<GridView
android:id="#+id/gridView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/lblSelectCategory"
android:layout_below="#+id/btnSaveProduct"
android:layout_marginTop="14dp"
android:numColumns="auto_fit" >
</GridView>
</RelativeLayout>
XML - Horizontalnumberpicker
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/txtNPTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="EnterTextHere"
android:layout_marginTop="5dp" />
<Button
android:id="#+id/btnPlus"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignBaseline="#+id/txtNPValue"
android:layout_alignBottom="#+id/txtNPValue"
android:layout_toRightOf="#+id/txtNPValue"
android:text="+" />
<TextView
android:id="#+id/txtNPValue"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignTop="#+id/btnMinus"
android:layout_toRightOf="#+id/btnMinus"
android:gravity="center"
android:text="0"
android:textAppearance="#style/AppBaseTheme"
android:textSize="20dp" />
<Button
android:id="#+id/btnMinus"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_below="#+id/txtNPTitle"
android:layout_marginTop="2dp"
android:text="-" />
</RelativeLayout>
The requirement is that when I press the plus button, I need to increment the value in the corresponding txtNPValue. Similarly with the minus button, I need to decrement the value in the txtNPValue.
The error is
01-31 22:40:10.854: E/AndroidRuntime(32198): java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.TextView.getText()' on a null object reference
Also I do not know if this is the right way to program such a requirement and would like some pointers.
TextView tv = (TextView) v.findViewById(R.id.txtNPValue);
this will return null pointer exception, as the view that u r getting is of the button or the clicked item..
Use this :-
RelativeLayout rlLayout = (RelativeLayout) v.getParent();
TextView tv = (TextView) rlLayout.findViewById(R.id.txtNPValue);
please remove:
TextView tv = (TextView) v.findViewById(R.id.txtNPValue);
from onClick to resolve nullpointerException
I am getting a string[] Array and storing it in an String array [variable mystrings],Now i want this array to display it in a list view with check box .
ec_checkbox_number.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="match_parent" >
<CheckBox
android:id="#+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="26dp"
android:text="number" />
<TextView
android:id="#+id/checkboxtextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/checkBox"
android:layout_alignBottom="#+id/checkBox"
android:layout_alignParentLeft="true"
android:layout_marginLeft="107dp"
android:text="TextView" />
</RelativeLayout>
ec_number_selection.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="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/meetingprofilename"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="20dp"
android:text="Profile Name:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/meetingprofilename"
android:layout_alignBottom="#+id/meetingprofilename"
android:layout_alignParentRight="true"
android:layout_toRightOf="#+id/meetingprofilename"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="#+id/cancelnumberbutton"
android:layout_width="158dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignRight="#+id/editText2"
android:text="Cancel" />
<Button
android:id="#+id/donenumberbutton"
android:layout_width="158dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_toRightOf="#+id/cancelnumberbutton"
android:text="Done" />
<ListView
android:id="#+id/numberselectionlistView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/cancelnumberbutton"
android:layout_alignParentLeft="true"
android:layout_below="#+id/editText1" >
</ListView>
</RelativeLayout>
CheckBoxData.java
public class CheckBoxData {
private String[] number;
public String[] getNumber() {
return number;
}
public void setNumber(String[] number) {
this.number = number;
}
}
MyConferenceNumber.java
public class EcConferenceNumber extends Activity{
ListView checkBoxNumberListView;
ConferenceAdapter adapter;
Button doneBtn,cancelBtn;
EditText profileName;
MyCustomAdapter dataAdapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ec_number_selection);
adapter = new ConferenceAdapter(this);
checkBoxNumberListView = (ListView) findViewById(R.id.numberselectionlistView);
doneBtn=(Button) findViewById(R.id.donenumberbutton);
cancelBtn=(Button) findViewById(R.id.cancelnumberbutton);
Intent intent = getIntent();
String[] myStrings = intent.getStringArrayExtra("strings");
List<String> strings =
new ArrayList<String>(Arrays.asList(myStrings));
System.out.println(""+strings);
dataAdapter = new MyCustomAdapter(this,
R.layout.ec_checkbox_number, strings);
checkBoxNumberListView.setAdapter(dataAdapter);
checkBoxNumberListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
CheckBoxData country = (CheckBoxData) parent.getItemAtPosition(position);
Toast.makeText(getApplicationContext(),
"Clicked on Row: " + country.getNumber(),
Toast.LENGTH_LONG).show();
}
});
}
class MyCustomAdapter extends ArrayAdapter<String>{
private List<String> strings;
public MyCustomAdapter(Context context, int textViewResourceId, List<String> strings) {
super(context, textViewResourceId,strings);
this.strings=new ArrayList<String>();
this.strings.addAll(this.strings);
// TODO Auto-generated constructor stub
}
private class ViewHolder {
TextView code;
CheckBox name;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.ec_checkbox_number, null);
holder = new ViewHolder();
holder.code = (TextView) convertView.findViewById(R.id.checkboxtextView);
holder.name = (CheckBox) convertView.findViewById(R.id.checkBox);
convertView.setTag(holder);
holder.name.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v ;
CheckBoxData country = (CheckBoxData) cb.getTag();
Toast.makeText(getApplicationContext(),
"Clicked on Checkbox: " + cb.getText() +
" is " + cb.isChecked(),
Toast.LENGTH_LONG).show();
}
});
}
else {
holder = (ViewHolder) convertView.getTag();
}
return convertView;
}
}
}
The output what i am getting is..
For example:If String[] a={002,111,122} i want to display it in a listview with checkbox and i have to get the selected CheckBox text.But my output is displying like this
number
number
number
number
But i want the output like this ,
123
112
123
Since ,I am new to android i did not know how to set the array to output view.Any answers will be helpfull.
Paste your full xml code. There is no button in xml and some properties are missing.
I am a newbie of android programming. After some study of ListView and ArrayAdapter, i decided to write a simple demo program just for practicing.
I want to display my custom view style ListView, so I override ArrayAdapter's getView() function. I know that for preventing memory leak, parameter convertView should be checked, and only inflate new object when convertView is null. I Also make a AsyncTask to keep adding data into ArrayAdapter in background(in doInBackground), and keep notifyDataChanged to ListView(in onProgressUpdate() ).
Here is the problem: when I set MAX_ITEM=50 (which means how many data i will add in AsyncTask), everything works fine. But when I set MAX_ITEM=500, logcat shows error message: "Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views." and application shut down. Can anyone tell me where the problem is? The following is my source code "MyTest.java" and my layout xml file "main.xml" and "layout_row.xml", thanks for your watching and helping.
MyTest.Java:
public class MyTest extends Activity {
private static final String TAG="Tany";
private static final int MAX_ITEM = 50;
private MyArrayAdapter adapter;
private ListView listview;
private int addCounter = 0;
public class MyData implements Comparable<MyData>{
public String str1;
public String str2;
public String str3;
public MyData(String str1, String str2, String str3){
this.str1 = str1;
this.str2 = str2;
this.str3 = str3;
}
#Override
public int compareTo(MyData data) {
// TODO Auto-generated method stub
int result = this.str1.compareTo(data.str1);
return result;
}
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listview = (ListView)findViewById(R.id.listview);
adapter = new MyArrayAdapter(this, R.layout.layout_row);
//set adapter
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
Log.d(TAG, "position "+position+" is clicked");
Toast.makeText(parent.getContext(), adapter.getItem(position).str1+", "+adapter.getItem(position).str2, Toast.LENGTH_SHORT).show();
}
});
listview.setTextFilterEnabled(true);
}
public void onStart(){
super.onStart();
MyTask newTask = new MyTask();
newTask.execute();
}
public class MyTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
for(int i = addCounter; i<MAX_ITEM; i++)
{
adapter.add(new MyData("str1="+i,"str2="+i,"str3="+i));
addCounter++;
publishProgress();
}
return null;
}
#Override
protected void onProgressUpdate(Void... progress ){
adapter.notifyDataSetChanged();
}
#Override
protected void onPostExecute(Void result){
Log.d(TAG, "AsyncTask MyTask finsish its work");
}
}
public class MyArrayAdapter extends ArrayAdapter<MyData>{
public MyArrayAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
// TODO Auto-generated constructor stub
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
if(convertView == null){
LayoutInflater inflater = getLayoutInflater();
row = inflater.inflate(R.layout.layout_row, parent, false);
}else{
Log.d(TAG,"recycle view, pos="+position);
row = convertView;
}
TextView tv1 = (TextView) row.findViewById(R.id.textView1);
tv1.setText( ((MyData)getItem(position)).str1 );
TextView tv2 = (TextView) row.findViewById(R.id.textView2);
tv2.setText( ((MyData)getItem(position)).str2 );
TextView tv3 = (TextView) row.findViewById(R.id.textView3);
tv3.setText( ((MyData)getItem(position)).str3 );
return row;
}
}
}
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/vertical_container"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:text="#string/list_title_start"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</TextView>
<ListView
android:id="#+id/listview"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</ListView>
<TextView
android:text="#string/list_title_end"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</TextView>
</LinearLayout>
layout_row.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/linearLayout1"
android:orientation="horizontal">
<ImageView
android:layout_height="wrap_content"
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:src="#drawable/ic_launcher">
</ImageView>
<TextView
android:text="TextView1"
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="6dip"
android:layout_marginTop="6dip"
android:textAppearance="?android:attr/textAppearanceLarge">
</TextView>
</LinearLayout>
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/linearLayout1"
android:orientation="horizontal">
<TextView
android:id="#+id/textView2"
android:text="TextView"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall">
</TextView>
<TextView
android:text="TextView"
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:layout_marginLeft="6dip">
</TextView>
</LinearLayout>
</LinearLayout>
as Selvin rightly says You're modifying your Views from the method doInBackground which runs on another thread. In android this is forbidden, instead you should modify the views from the onPostExecute method also.
I am trying to add a custom header that isnt clickable but will have a checkbox that will "check all" checkboxes under it.
This is my List Fragment
public class AssesmentListFragment extends ListFragment {
private static String BUNDLE_KEY_APPLICATION = "LIST_ITEM";
FastAssesmentListAdapter adapter;
View listHeader;
public AssesmentListFragment() {}
public AssesmentListFragment(Data[] data) {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Data[] assestments = {new Data("Assesment ID","Name", "Date"), new Data("123456", "Assestment 2", "9/12/12"),
new Data("345672", "Assesment 3", "9/13/12"), new Data("566893", "Assesment 4", "9/14/12")};
//This is the part that makes the app crash
View header = getActivity().getLayoutInflater().inflate(R.layout.list_adapter_assesments, null);
ListView listView = getListView();
listView.addHeaderView(header);
adapter = new FastAssesmentListAdapter(getActivity(), assestments);
setListAdapter(adapter);
updateList(assestments);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
private void updateList(Data[] assestments) {
// NOTE: addAll is not being used to support pre-honeycomb devices
synchronized(adapter) {
adapter.clear();
adapter.addAll(assestments);
adapter.notifyDataSetChanged();
}
}
#Override
public void onListItemClick(ListView parentView, View selectedItemView, int position, long id) {
String model = (String) parentView.getItemAtPosition(position);
((FacilityActivity) getActivity()).onItemSelected(model);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//outState.putInt("curChoice", mCurCheckPosition);
}
}
This is the layout I am trying to use for header
<?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="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="25dp"
android:paddingRight="10dp"
android:orientation="horizontal">
<TextView android:id="#+id/adapter_header_textview_column1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="4"
android:textColor="#color/defaultTextColor"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="28sp"
android:text="Assesment ID" />
<TextView android:id="#+id/adapter_header_textview_column2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="4"
android:textColor="#color/defaultTextColor"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="28sp"
android:text="Name" />
<TextView android:id="#+id/adapter_header_textview_column3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:textColor="#color/defaultTextColor"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="28sp"
android:text="Date"/>
<CheckBox
android:id="#+id/header_check_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:color="#color/defaultTextColor"
android:layout_weight=".5"
android:gravity="center" />
</LinearLayout>
<View
android:layout_width="fill_parent"
android:layout_height="5dp"
android:background="#color/BPGreenColor" />
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
Then this is the array adapter I am using:
public class FastAssesmentListAdapter extends ArrayAdapter<Data> {
private static int LAYOUT_ID = R.layout.list_adapter_with_checkbox_three_column;
private final Data[] assesments;
private final Context context;
LinearLayout listHeader;
static class ViewHolder {
protected TextView column1;
protected TextView column2;
protected TextView column3;
protected CheckBox checkbox;
}
public FastAssesmentListAdapter(Context context, Data[] assesments) {
super(context, LAYOUT_ID, assesments);
this.context = context;
this.assesments = assesments;
}
//ListFragment and array adapter will automatically call this over and over to auto populate the list
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final Data item = getItem(position);
// Formulate row view (create if it does not exist yet)
View view = convertView;
if(view == null) {
LayoutInflater inflater = ((Activity) getContext()).getLayoutInflater();
view = inflater.inflate(LAYOUT_ID, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.column1 = (TextView) view.findViewById(R.id.adapter_textview_column1);
viewHolder.column2 = (TextView) view.findViewById(R.id.adapter_textview_column2);
viewHolder.column3 = (TextView) view.findViewById(R.id.adapter_textview_column3);
viewHolder.checkbox = (CheckBox) view.findViewById(R.id.check_box);
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "Clicked",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getContext(), FacilityActivity.class);
getContext().startActivity(intent);
}
});
if(viewHolder.checkbox != null) {
viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if(isChecked) {
item.setSelected(isChecked);
Toast.makeText(getContext(), "Checked",
Toast.LENGTH_SHORT).show();
}
}
});
}
view.setTag(viewHolder);
viewHolder.checkbox.setTag(position);
}
ViewHolder viewHolder = (ViewHolder) view.getTag();
viewHolder.checkbox.setTag(position);
viewHolder.column1.setText(item.getColumn1());
viewHolder.column2.setText(item.getColumn2());
viewHolder.column3.setText(item.getColumn3());
viewHolder.checkbox.setChecked(item.isSelected());
return view;
}
}
on a side note, the onlistitemclicked in the fragment doesnt work, i have to set a listener in the adapter and then it works. any ideas on that? but mainly I need to figure out how to use a custom header and custom rows in the list view. Here is the layout for the rows
<?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:paddingLeft="25dp"
android:paddingRight="10dp"
android:orientation="horizontal">
<TextView android:id="#+id/adapter_textview_column1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="4"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="25sp" />
<TextView android:id="#+id/adapter_textview_column2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="4"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="25sp" />
<TextView android:id="#+id/adapter_textview_column3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="25sp" />
<CheckBox
android:id="#+id/check_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight=".5"
android:gravity="center" />
</LinearLayout>
Good afternoon everybody :)
I have a listview for adding goals (not important :p). the listview's child has some textviews and edittextboxes, where the user can fill in its information.
I have a Textwatcher which checks whether the text in one of the listview's childs has changed, so the data can be written to the class in the array off the listview + a global array (for passing data between activety's, but this is also not important).
Now my problem is, when I add an Item to the list, the text of all the previous existing items in edittext 'discription' changes to the text of newly added Item. For example when i have 1 Item in the listview that says 'test' and I add a new one to the list that says 'this is a new test' >> Both change to 'this is a new test'. I debugged the program a lot and noticed that in the end (after adding the new item), the program will go trough the textwatcher with 's' = 'this is a new test' and position = '0'. This probably causes the text of the first one to change.. But I don't understand why this is happening.
Can somebody help me?
this is my listview:
class listViewAdapter extends BaseAdapter {
private Context context;
private ArrayList<Goals> list;
public listViewAdapter(final Context context, ArrayList<Goals> list) {
this.context = context;
this.list = list;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public void synchronise(){
geldclass.setGoals_list(this.list);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
final LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.goal_item, parent,
false);
}
Goals goal = (Goals) getItem(position);
final EditText txtdiscription = (EditText) convertView.findViewById(R.id.editDiscription);
txtdiscription.setText(goal.getDiscription());
txtdiscription.addTextChangedListener(new textWatcher(txtdiscription, position));
final EditText txtgoal = (EditText) convertView
.findViewById(R.id.editGoal);
txtgoal.addTextChangedListener(new textWatcher(txtgoal, position));
final EditText txtfrom = (EditText) convertView
.findViewById(R.id.editFrom);
txtfrom.addTextChangedListener(new textWatcher(txtfrom, position));
final EditText txtto = (EditText) convertView
.findViewById(R.id.editto);
txtto.addTextChangedListener(new textWatcher(txtto, position));
final CheckBox check_date = (CheckBox) convertView
.findViewById(R.id.check_enable_date);
check_date
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
}
});
return convertView;
}
private class textWatcher implements TextWatcher {
private View view;
private int position;
private textWatcher(View view, int position) {
this.view = view;
this.position = position;
}
#Override
public void afterTextChanged(Editable s) {
switch (view.getId()) {
case R.id.editDiscription:
list.get(position).setDiscription(s.toString());
synchronise();
break;
case R.id.editGoal:
list.get(position).setGoalvalue(Integer.parseInt(s.toString()));
synchronise();
break;
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
}
}
this is my goal child item in xml:
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textDiscription"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="right"
android:text="#string/name"
android:textSize="15dp"
android:width="80dp" />
<EditText
android:id="#+id/editDiscription"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textNoSuggestions"
android:width="120dp" >
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textGoal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="right"
android:text="#string/goal"
android:textSize="15dp" />
<EditText
android:id="#+id/editGoal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textNoSuggestions"
android:width="200dp" >
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<CheckBox
android:id="#+id/check_enable_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/from"
android:textSize="15dp" />
<EditText
android:id="#+id/editFrom"
android:enabled="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="date"
android:ems="10" >
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow4"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textfrom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="right"
android:text="#string/to"
android:textSize="15dp" />
<EditText
android:id="#+id/editto"
android:enabled="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="date"
android:ems="10" >
</EditText>
</TableRow>
</TableLayout>
And here is where I add the Items (don't pay attention to 'geldclass'.. Its a global class where the global array is stored):
public void onClick(View v) {
Goals goal = new Goals("this is a new test");
geldclass.addGoals(goal);
goal_adapter = new listViewAdapter(GoalManager.this, geldclass.getGoals_list());
goal_list.setAdapter(goal_adapter);
}
public void onClick(View v) {
Goals goal = new Goals("this is a new test");
geldclass.addGoals(goal);
goal_adapter = new listViewAdapter(GoalManager.this, geldclass.getGoals_list());
goal_list.setAdapter(goal_adapter);
}
should be changed to
public void onClick(View v) {
Goals goal = new Goals("this is a new test");
geldclass.addGoals(goal);
goal_adapter.setNotifyDatasetChanges();
}
calling the setNotifyDatasetChanges() make the Adapter to refresh the listView with the new changed data in its list, i'm assuming that the geldclass.getGoals_list() is the same list that you initialized the Adapter before.