ListView and Adapter with a large number of items - java

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.

Related

How to use buttons from different xml files in one class

I have a listview with multiple items and one button to start a new activity. I'm getting Null Pointer Exception when I run my app. How and where shoud I set the OnClickListener to run properly?
Also, how can I pass with Intent the arraylist named listaIngrediente?
Here is my code
main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.example.radu.fridgecheck.MainActivity"
android:orientation="vertical">
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1">
</ListView>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/find_recipies"
android:id="#+id/find"
android:layout_weight="0"/>
</LinearLayout>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="6dip" >
<CheckBox
android:id="#+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:focusable="false"
android:focusableInTouchMode="false"/>
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/checkBox"
android:layout_alignBottom="#+id/checkBox"
android:layout_toRightOf="#+id/checkBox"
android:text="TextView" />
</RelativeLayout>
Adapter
public class Adapter extends ArrayAdapter<Ingredient> {
public LayoutInflater inflater;
public ArrayList<Ingredient> listaIngrediente;
ArrayList<String> ingredienteDisponibile;
private Activity activity;
public Adapter(Activity activity, int textResourceId, ArrayList<Ingredient> ingrediente) {
super(activity, textResourceId, ingrediente);
this.activity=activity;
this.listaIngrediente=ingrediente;
try {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
} catch (Exception e) {
e.printStackTrace();
}
}
public int getCount() {
return listaIngrediente.size();
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (convertView == null) {
v = inflater.inflate(R.layout.list_item, null);
}
final Ingredient ingredients = getItem(position);
final TextView display_ingredients = (TextView) v.findViewById(R.id.name);
display_ingredients.setText(ingredients.getNameI());
final CheckBox checkBox = (CheckBox) v.findViewById(R.id.checkBox);
ListView listView = (ListView) v.findViewById(R.id.listView1);
Button button = (Button) v.findViewById(R.id.button);
listView.addFooterView(button);
Button find = (Button) v.findViewById(R.id.find);
find.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getContext(), ShowRecipes.class);
Bundle args = new Bundle(); /// nu reusesc sa transfer obiectele
args.putSerializable("ARRAYLIST",listaIngrediente);
i.putExtra("BUNDLE",args);
activity.startActivity(i);
}
});
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(!ingredients.isSelected()) {
checkBox.setChecked(true);
ingredients.setSelected(true);
}
else{
checkBox.setChecked(false);
ingredients.setSelected(false);
}
}
});
return v;
}
}
You have to write that in MainActivity class, because your button is in main_activity.xml
In MainActivity, write this method
public void showRecipes(View view) {
Intent i = new Intent(getContext(), ShowRecipes.class);
Bundle args = new Bundle(); /// nu reusesc sa transfer obiectele
args.putSerializable("ARRAYLIST",listaIngrediente);
i.putExtra("BUNDLE",args);
startActivity(i);
}
In Xml add onClick
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/find_recipies"
android:id="#+id/find"
android:onClick="showRecipes"
/>`
More Information on click Events
http://developer.android.com/guide/topics/ui/controls/button.html#HandlingEvents

Fragment and Adapter in Android App Not Displaying Data

I'm really new in Android. I have this problem, I have an Activity (MainActivity) and there is a NavigationDrawer, this switches two fragments - ActivitiesFragment and ReportFragments.
The problem is with ActivitiesFragments, data is not displayed.
I have my adapter ready and my layouts ready and the fragment. When I debugg my app, it actually brings data, but is not shown. This is my code:
ActivitiesAdapter
public class ActivitiesAdapter extends ArrayAdapter<Activities>
{
Context mContext;
int mLayoutResourceId;
public ActivitiesAdapter(Context context, int layoutResourceId)
{
super(context, layoutResourceId);
mContext = context;
mLayoutResourceId = layoutResourceId;
}
public View getView(int position, View convertView, ViewGroup parent)
{
View row = convertView;
final Activities currentItem = getItem(position);
if (row == null)
{
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
row = inflater.inflate(mLayoutResourceId, parent, false);
}
row.setTag(currentItem);
final TextView tituloview = (TextView) row.findViewById(R.id.tituloAct);
tituloview.setText(currentItem.getTitle());
final TextView descrpview = (TextView) row.findViewById(R.id.descrAct);
descrpview.setText(currentItem.getDescription());
return row;
}
}
This is my fragment ActivitiesFragment
public class ActivitiesFragment extends Fragment
{
protected static final String TAG = "ActivitiesFragmment";
private MobileServiceClient mClient;
private MobileServiceTable<Activities> mActivitiesTable;
private ActivitiesAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.act_listfragment, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
try
{
mClient = new MobileServiceClient("https://site.azure-mobile.net/",
"APPLICATIONKEYAPPLICATIONKEY",
getActivity().getApplicationContext()).withFilter(new ProgressFilter());
mActivitiesTable = mClient.getTable(Activities.class);
}
catch (MalformedURLException e)
{
createAndShowDialog(new Exception("There was an error creating the Mobile Service. Verify the URL"), "Error");
}
mAdapter = new ActivitiesAdapter(getActivity(), R.layout.act_itemlist);
ListView listViewToDo = (ListView) getView().findViewById(R.id.activities_fragment_list);
listViewToDo.setAdapter(mAdapter);
refreshItemsFromTable();
}
private void createAndShowDialog(Exception exception, String title)
{
createAndShowDialog(exception.toString(), title);
}
private void createAndShowDialog(String message, String title)
{
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity().getApplicationContext());
builder.setMessage(message);
builder.setTitle(title);
builder.create().show();
}
private void refreshItemsFromTable()
{
mActivitiesTable.execute(new TableQueryCallback<Activities>()
{
public void onCompleted(List<Activities> result, int count, Exception exception, ServiceFilterResponse response) {
if (exception == null) {
mAdapter.clear();
for (Activities item : result) {
mAdapter.add(item);
Log.i(TAG, "Titulo: " + item.getTitle());
}
} else {
createAndShowDialog(exception, "Error");
}
}
});
}
}
I don't know whats wrong, but I guess this block is not working on the OnActivityCreated method:
mAdapter = new ActivitiesAdapter(getActivity(), R.layout.act_itemlist);
ListView listViewToDo = (ListView) getView().findViewById(R.id.activities_fragment_list);
listViewToDo.setAdapter(mAdapter);
refreshItemsFromTable();
And here are my Layouts:
This is my frgament's layout:
<LinearLayout 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:background="#e1e1e1"
android:orientation="vertical" >
<TextView
android:id="#+id/tvTituloActs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/all_activities"
android:layout_marginLeft="16dp"
android:layout_marginTop="8dp"
android:textColor="#009ad2"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ListView android:id="#+id/activities_fragment_list"
android:layout_marginTop="8dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
android:layout_weight="1"
tools:listitem="#layout/act_itemlist"
android:drawSelectorOnTop="false"/>
<TextView android:id="#id/android:empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="No hay datos"/>
</LinearLayout>
This is the layout act_itemlist. The row layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="64dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/icon"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_marginLeft="8dp"
android:gravity="center_vertical"
android:src="#drawable/done"
android:layout_gravity="center_vertical"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/tvTituloAct"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginTop="16dp"
android:textSize="16sp"/>
<TextView
android:id="#+id/tvDescrAct"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:text="Description de la actividad" />
</LinearLayout>
</LinearLayout>
I really need help with this! Please if someone can see something that I'm missing please tell me!
Thanks!!!!
Try to swap these lines:
mAdapter = new ActivitiesAdapter(getActivity(), R.layout.act_itemlist);
ListView listViewToDo = (ListView) getView().findViewById(R.id.activities_fragment_list);
refreshItemsFromTable(); // populate first before attaching your adapter
listViewToDo.setAdapter(mAdapter);
I finally solved my problem. Everything was Ok, the only detail was the layout. It was on the fragments layout.
<TextView android:id="#id/android:empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="No hay datos"/>
This textview did not let to show the data so I deleted it and worked.
Thankk you for your help #LazyNinja

NullPointer Exception in custom ListView Adapter

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

Adding Custom Header to List Fragment in Android

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>

Edit listView , margin top

I have a list view that looks like this
and that's its code ..
package com.a.c;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
public class calender extends ListActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, calendr));
getListView().setTextFilterEnabled(true);
}
static final String[] calendr = new String[]{
"MONT Blanc",
"Gucci",
"Parker",
"Sailor",
"Porsche Design",
"Rotring",
"Sheaffer",
"Waterman"
};}
i want to modify it to add this layout ,, and shift the listview downward little bit
the image looks like a picture frame that's why i want to move the list view ..
Layout code at .XML file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:id="#+id/relativeLayout1"
android:layout_width="600px"
android:layout_height="1024px"
xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView android:id="#+id/layout"
android:src="#drawable/layout"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"></ImageView>
</RelativeLayout>
Hi You can use this code and achieve your target:
main.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:id="#+id/layout"
android:src="#drawable/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></ImageView>
<ListView
android:layout_width="match_parent"
android:id="#+id/listViewScore"
android:cacheColorHint="#00000000"
android:layout_height="match_parent"
android:layout_weight="1.00"
android:divider="#C0C0C0"
android:layout_below="#+id/layout"
android:dividerHeight="2dip" />
</RelativeLayout>
listviewtext.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="Name"
android:id="#+id/textViewName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false"
android:focusableInTouchMode="false"></TextView>
</LinearLayout>
public class TestProjeectActivity extends Activity {
private ListView listViewScore = null;
private ListViewAdapter listViewAdapter = null;
private String[] usernameArr = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listViewScore=(ListView)findViewById(R.id.listViewScore);
usernameArr = new String[]{"Alan","Bob","Carl","Doaniel","Evan","Fred","Gram","Ian","Jordan"};
listViewAdapter = new ListViewAdapter();
listViewScore.setAdapter(listViewAdapter);
}
class ListViewAdapter extends BaseAdapter{
#Override
public int getCount() {
// TODO Auto-generated method stub
if(usernameArr==null){
return 0;
}
return usernameArr.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return usernameArr[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
// TODO Auto-generated method stub
View rowView=view;
if(rowView==null){
LayoutInflater layoutinflate =LayoutInflater.from(TestProjeectActivity.this);
rowView=layoutinflate.inflate(R.layout.listviewtext, parent, false);
}
TextView textViewName=(TextView)rowView.findViewById(R.id.textViewName);
textViewName.setText(usernameArr[position]);
return rowView;
}
}
}

Categories

Resources