Android custom listview layout - android

im new to android and java programming. Im having trouble getting my custom layout (currently with only one textview in it to work with my code. I have followed many tutorials and look and many examples but still Im getting confused as to how I would integrate it with my existing code.
Any help would be appreciated.
Here is my code:
public class checkListActivity extends MainActivity {
static String filename = "checkList";
String currentList;
SharedPreferences checkListData;
SharedPreferences.Editor checkListEditor;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.checklist);
Button bAddItem = (Button) findViewById(R.id.bAddItem);
final EditText etItemName = (EditText) findViewById(R.id.etItemName);
final TextView tvTitle = (TextView) findViewById(R.id.tvTitle);
final ListView lvCheckList = (ListView) findViewById(R.id.lvCheckLists);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String selectedItem = extras.getString("selectedItem");
// get the value based on the key
currentList = selectedItem;
}
tvTitle.setText(currentList);
checkListData = getSharedPreferences(filename, 0);
updateListView();
// Button Click Listener
bAddItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String checkListStringData = etItemName.getText().toString();
checkListData = getSharedPreferences(filename, 0);
SharedPreferences.Editor checkListEditor = checkListData.edit();
checkListEditor.putString(currentList + "ItemName",
checkListStringData);
checkListEditor.commit();
String checkListDataReturned = checkListData.getString(
currentList + "ItemName", currentList);
tvTitle.setText(checkListDataReturned);
updateListView();
etItemName.setText("");
};
});
}
private void updateListView() {
final ListView lvCheckList = (ListView) findViewById(R.id.lvCheckList);
Map<String, ?> keys = checkListData.getAll();
ArrayList<String> checkListStrings = new ArrayList<String>();
for (Map.Entry<String, ?> entry : keys.entrySet()) {
if (entry.getValue() instanceof String) {
if (entry.getKey().equals(currentList + "ItemName")) {
checkListStrings.add((String) entry.getValue());
}
}
ArrayAdapter<String> checkListArrayAdapter = new ArrayAdapter<String>(
this, R.layout.single_listview_item);
lvCheckList.setAdapter(checkListArrayAdapter);
}
}
}

first create this custom adapter class...
private static class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public Context con;
public String[] sms;
public EfficientAdapter(Context context,String[] rssFeed) {
mInflater = LayoutInflater.from(context);
this.con=context;
this.sms=rssFeed;
}
public int getCount() {
return sms.length;
}
public Object getItem(int position) {
return sms[position];
}
public long getItemId(int position) {
return position;
}
#SuppressLint({ "SdCardPath", "InflateParams", "ResourceAsColor" })
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list, null);
holder = new ViewHolder();
holder.text2 = (TextView) convertView.findViewById(R.id.text_list_f);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text2.setText(sms[position]);
}
return convertView;
}
}
static class ViewHolder {
TextView text2;
}
then use it in your activity ...
list.setAdapter(new EfficientAdapter(this, your array));

Related

ListView disappears after reloading it again

I have 3 arraylist that i have combined to show in listview. Wehen i click on to generate listview, it works fine the first time but when i hit back and then click the button again, the listview shows nothing. Not sure what is cause it. I checked other post but couldnt find an answer. I am not too good with Arraylist so any details would be greatly appreciated.
I have also noticed this message in Log cat. not sure what it means.
onVisibilityChanged() is called, visibility : 0
public class Edit extends Activity implements OnItemClickListener {
private int pic;
public String filename ="User Info";
//Declaring SHareddPreference as userprofile
static SharedPreferences userprofile;
ListView listView;
List<RowItem> rowItems;
// String[] titles, descriptions;
File imgpath=null;
Context context=this;
CustomListAdapter adapter;
private List<String> Titles = new ArrayList<String>();
private List<String> Actions = new ArrayList<String>();
private List<Bitmap> Images = new ArrayList<Bitmap>();
int x;
int y=1;
int z=1;
static int a=1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.aname);
listView = (ListView)findViewById(R.id.listing);
userprofile = getSharedPreferences(filename,0);
Intent pdf=getIntent();
pic= userprofile.getInt("lastpic",pic);
x=pic;
Log.d("editpic",new Integer(pic).toString());
while(y!=x){
String comment = commentresult();
Titles.add(comment);
y++;
Log.d("y",new Integer(y).toString());
}
while(z!=x){
String act = actionresult();
Actions.add(act);
z++;
Log.d("z",new Integer(z).toString());}
while(a!=x){
Bitmap photo = getbitmap();
Images.add(photo);
a++;
Log.d("a",new Integer(a).toString());}
Titles.toArray();
Actions.toArray();
Images.toArray();
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < Images.size(); i++) {
RowItem item = new RowItem(Images.get(i), Titles.get(i),Actions.get(i));
rowItems.add(item);
}
Log.d("TAG", "listview null? " + (listView == null));
CustomListAdapter adapter = new CustomListAdapter(this,
R.layout.aname_list_item, rowItems);
Log.d("TAG", "adapter=null? " + (adapter == null));
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
listView.setOnItemClickListener(this);
}
public static Bitmap getbitmap() {
String photo1 =userprofile.getString("picpath"+a, "");
File imgpath=new File(photo1);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap bmp=DecodeImage.decodeFile(imgpath, 800, 1000, true);
bmp.compress(Bitmap.CompressFormat.JPEG, 100 , stream);
Bitmap photo2=bmp;
return photo2;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast toast = Toast.makeText(getApplicationContext(),
"Item " + (position + 1) + ": " + rowItems.get(position),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
public String commentresult()
{
// String com2 = null;
// while(y!=x){
String comment=userprofile.getString("comment"+y, "");
String com1=comment;
String com2=com1;
// }
return com2;
}
public String actionresult()
{
// String act2 = null;
// while(y!=x){
String action=userprofile.getString("action"+z, "");
String act1=action;
String act2=act1;
// }
return act2;
}
private static final long delay = 2000L;
private boolean mRecentlyBackPressed = false;
private Handler mExitHandler = new Handler();
private Runnable mExitRunnable = new Runnable() {
#Override
public void run() {
mRecentlyBackPressed=false;
}
};
#Override
public void onBackPressed() {
//You may also add condition if (doubleBackToExitPressedOnce || fragmentManager.getBackStackEntryCount() != 0) // in case of Fragment-based add
if (mRecentlyBackPressed) {
mExitHandler.removeCallbacks(mExitRunnable);
mExitHandler = null;
super.onBackPressed();
}
else
{
mRecentlyBackPressed = true;
Toast.makeText(this, "press again to exit", Toast.LENGTH_SHORT).show();
mExitHandler.postDelayed(mExitRunnable, delay);
}
}
#Override
public void onDestroy() {
// Destroy the AdView.
super.onDestroy();
}
Custom List Adapter:
public class CustomListAdapter extends ArrayAdapter<RowItem> {
Context context;
List<RowItem> items;
public CustomListAdapter(Context context, int resourceId,
List<RowItem> items) {
super(context, resourceId, items);
this.context = context;
this.items = items;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return items.size();
}
#Override
public RowItem getItem(int position) {
// TODO Auto-generated method stub
return items.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
/*private view holder class*/
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
TextView txtDesc;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
RowItem rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.aname_list_item, null);
holder = new ViewHolder();
holder.txtDesc = (TextView) convertView.findViewById(R.id.desc);
holder.txtTitle = (TextView) convertView.findViewById(R.id.rab);
holder.imageView = (ImageView) convertView.findViewById(R.id.icon);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
// String name=items.get(position).getDesc();
holder.txtDesc.setText(rowItem.getDesc());
holder.txtTitle.setText(rowItem.getTitle());
holder.imageView.setImageBitmap(rowItem.getImageId());
// holder.imageView.setImageResource(Images.get(position) .getPlaceholderleft());
return convertView;
}
}
It looks like this is because you've made your variables x, y, z and a all static, which means there is a single instance of the variables shared by all instances of the class. Therefore, when you call onCreate the second time, all your while loop termination conditions are already met, so the while loops never execute. It's unclear to me why you've made these static, so unless you need them to be, you should remove the static keyword for these variables.
Why are you creating another object of ListView in onCreate() and onResume()
Remove code from onResume()
Also replace this line in onCreate()
old line ListView listView = (ListView)findViewById(R.id.listing);
New line listView = (ListView)findViewById(R.id.listing);

How to get sum from textview in list layout?

I'm having problem with coding how to count all numbers that user inserted in TextView in ListView...
Here is my app... All I need to now is how to get the sum from rows in list view and show them in another text view:
This is my Main Activity:
public class MainActivity extends Activity {
private Adapter adapter;
private ArrayList<Ruka> fetch = new ArrayList<Ruka>();
Button bt;
EditText et;
TextView tv;
TextView mi;
TextView vi;
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Inflate the menu; this adds items to the action bar if it is present.
bt = (Button) findViewById(R.id.button1);
et = (EditText) findViewById(R.id.editText1);
tv = (TextView) findViewById(R.id.textView1);
mi = (TextView) findViewById(R.id.textViewMi);
vi = (TextView) findViewById(R.id.textViewVi);
lv = (ListView) findViewById(R.id.lista);
// final String input = et.getText().toString();
bt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (et.getText().length() == 0) {
Toast.makeText(this, "test",
Toast.LENGTH_SHORT).show();
return;
}
if (Float.valueOf(et.getText().toString()) >= 12) {
Toast.makeText(this,
"test2", Toast.LENGTH_SHORT)
.show();
return;
}
String input = et.getText().toString();
if (null != input && input.length() > 0) {
String maxpunti = "11";
int a = Integer.parseInt(maxpunti);
int b = Integer.parseInt(input);
int c = a - b;
String input2 = String.valueOf(c);
Ruka one = new Ruka(input, input2);
fetch.add(one);
et.setText("");
adapter = new Adapter(MainActivity.this, R.id.lista, fetch);
lv.setAdapter(adapter);
}
}
});
}
}
This is my Adapter:
public class Adapter extends ArrayAdapter<Ruka>{
private ArrayList<Ruka> entries;
private Activity activity;
public Adapter(Activity a, int textViewResourceId, ArrayList<Ruka> entries) {
super(a, textViewResourceId, entries);
this.entries = entries;
this.activity = a;
}
public static class ViewHolder{
public TextView item1;
public TextView item2;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder holder;
if (v == null) {
LayoutInflater vi =
(LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.row, null);
holder = new ViewHolder();
holder.item1 = (TextView) v.findViewById(R.id.textView1);
holder.item2 = (TextView) v.findViewById(R.id.textView2);
v.setTag(holder);
}
else
holder=(ViewHolder)v.getTag();
final Ruka custom = entries.get(position);
if (custom != null) {
holder.item1.setText(custom.getFirst());
holder.item2.setText(custom.getSecond());
}
return v;
}
}
UPDATE
Here is Ruka.java:
public class Ruka {
private String customBig;
private String customSmall;
public Ruka(String string, String string2) {
this.customBig = string;
this.customSmall = string2;
}
public String getFirst() { return customBig; }
public void setcustomBig(String getFirst) { this.customBig = getFirst; }
public String getSecond() { return customSmall; }
public void setcustomSmall(String getSecond) { this.customSmall = getSecond; }
}
If someone can find solution... Please... Anyone :)
I would say add a method to your adapter that does this:
public int getSum(){
int sum;
for(Ruka ruka: entries){
sum += ruka.getFirst();
}
}
Assuming ruka.getFirst() is a numeric value.

Android Color Rows

does anyone know how to color the background of each row in a listview as they are created?
I have an arraylist which is pulled from my database and populates a layout with a listview in it.
I suspect there might be a way to do it with a simpleadaptor but cant figure it out.
Any help would be much appreciated :)
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.item_list);
// Read var from Intent
Intent intent= getIntent();
final String ListID = intent.getStringExtra("ListID");
golbalItemID = ListID;
ivAdd = (ImageView) findViewById(R.id.ivAdd);
ivCancel = (ImageView) findViewById(R.id.ivCancel);
tvTotItems = (TextView) findViewById(R.id.tvTotItems);
final myDBClass myDb = new myDBClass(this);
final ArrayList<HashMap<String, String>> MebmerList = myDb.SelectAllItemData(ListID);
myData = myDb.SelectItemData(Integer.parseInt(ListID.toString()));
// listView1
final ListView lisView1 = (ListView)findViewById(R.id.listView1);
registerForContextMenu(lisView1);
MyAdapter sAdap;
sAdap = new MyAdapter(ListItems.this, MebmerList, R.layout.activity_column, new String[] {"Name", "Price", "Quan"}, new int[] {R.id.ColName, R.id.ColTel, R.id.ColQuan});
lisView1.setAdapter(sAdap);
lisView1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter, View myView, int position, long mylng) {
int iChk = 0;
// Show Data
String arrData[] = myDb.SelectItemData((MebmerList.get(position).get("ItemID").toString()));
if(arrData != null)
{
iChk = Integer.parseInt(arrData[4]);
}
if(iChk == 1)
{
ischkCheck(Integer.parseInt(MebmerList.get(position).get("ItemID").toString()), 0);
change_color(lisView1, position, 255, 255, 255);
System.out.println("POSITION!ichk=1" + myAdapter.getItemAtPosition(position).toString());
setTitle(myAdapter.getItemAtPosition(position).toString());
}
else if(iChk == 0)
{
ischkCheck(Integer.parseInt(MebmerList.get(position).get("ItemID").toString()), 1);
change_color(lisView1, position, 155, 155, 138);
System.out.println("POSITION!ichk=0" + myAdapter.getItemAtPosition(position).toString());
}
}});
ivAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent newActivity = new Intent(ListItems.this,AddItem.class);
newActivity.putExtra("ListID", ListID);
startActivity(newActivity);
finish();
}
});
ivCancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent newActivity = new Intent(ListItems.this,MenuScreen.class);
startActivity(newActivity);
finish();
}
});
Create an Adapter Class, and control each Row's color in it, then set it as adapter of ListView
Here is a sample code from one of my projects, check getView function:
public class ListAdapter extends BaseAdapter {
private LayoutInflater myInflater;
private List<Poet> list;
public ListAdapter(Context context) {
super();
myInflater = LayoutInflater.from(context);
Log.d("Ganjoor", "Data passed to the adapter.");
}
static class ViewHolder {
TextView tvName;
}
public void setData(List<Poet> list) {
this.list = list;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Poet getItem(int position) {
return (null == list) ? null : list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = myInflater.inflate(R.layout.list_adapter, parent,
false);
holder = new ViewHolder();
holder.tvName = (TextView) convertView.findViewById(R.id.tvName);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tvName.setTag(list.get(position).getId());
holder.tvName.setText(list.get(position).getName());
// Log.d("Ganjoor", "Adapter: " + list.get(position).getName());
if (position % 2 == 0) {
convertView.setBackgroundResource(R.drawable.grad_blue);
} else {
convertView.setBackgroundResource(R.drawable.row_style);
}
return convertView;
}
}
As #Nikita Beloglazov states, you can do this by implementing a custom ArrayAdapter, putting your coloring scheme in the getView Override method. See ArrayAdapter doc.

How to get Values from the ArrayAdapter to the MainActivity for Custom ListView?

I would like to get a value ArrayAdapter to the MainActivity for Custom ListView with CheckBoxes.But Whenever I tried to get any value from the main activity the app crashes.Please give me a snippet on this,I am struck here for little while Thanks.Here is my code
public class ModelListViewActivity extends ListActivity {
public static final String KK_TAG="KK AHH!!!";
MyCustomArrayAdapter mas;
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.main);
ArrayAdapter<Model> adapter = new MyCustomArrayAdapter(this,getModel());
setListAdapter(adapter);
}
private List<Model> getModel()
{
List<Model> list = new ArrayList<Model>();
list.add(get("Android +200","Google"));
list.add(get("Windows +500","Microsoft"));
list.add(get("iPhone +600","Apple"));
list.add(get("Ubuntu +700","Linux"));
list.add(get("Bada -800","Samsung"));
list.add(get("Android +1000","Google"));
list.add(get("Symbian -1000","Nokia"));
list.add(get("Windows XP +400","Microsoft"));
// select one item by default
return list;
}
private Model get(String s,String place)
{
return new Model(s,place);
}
}
Here is the adapter & in this I want to get the selcted String in the Main activity
public class MyCustomArrayAdapter extends ArrayAdapter<Model>
{
public static final String KK_TAG="KK AHH!!!";
String selected = "Karthik";
private final List<Model> list;
private final Activity context;
public MyCustomArrayAdapter(Activity context, List<Model> list) {
super(context, R.layout.list_layout, list);
this.context = context;
this.list = list;
}
static class ViewHolder
{
protected TextView text, sub;
protected CheckBox checkbox;
}
public void manipulation()
{
int valued=0;
selected = selected.replaceAll("\\s+", " ");
Log.v(KK_TAG,"selected:" +selected);
Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher(selected);
while (m.find())
{
Log.v(KK_TAG,m.group());
String test=m.group();
int aInt = Integer.parseInt(test);
valued=valued+aInt;
}
String conv=Integer.toString(valued);
Log.v(KK_TAG, "Conv: "+conv);
}
public void tester()
{
Log.v(KK_TAG, "Conv: ");
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View view = null;
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
view = inflator.inflate(R.layout.list_layout, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.text = (TextView) view.findViewById(R.id.label);
viewHolder.text.setTextColor(Color.BLACK);
viewHolder.sub = (TextView) view.findViewById(R.id.sub);
viewHolder.sub.setTextColor(Color.GRAY);
viewHolder.checkbox = (CheckBox) view.findViewById(R.id.check);
viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked)
{
Model element = (Model) viewHolder.checkbox.getTag();
element.setSelected(buttonView.isChecked());
Log.v(KK_TAG, "Checked : " + element.getName());
if(isChecked)
{
selected +=element.getName()+" ";
Log.v(KK_TAG, "Checked : " + selected);
}
else
{
String source = selected;
String find = element.getName();
String replace = "";
Pattern pattern = Pattern.compile(find);
Matcher matcher = pattern.matcher(source);
selected = matcher.replaceAll(replace);
Log.v(KK_TAG,"Source = " + source);
Log.v(KK_TAG,"UnChecked = " + selected);
}
} });
view.setTag(viewHolder);
viewHolder.checkbox.setTag(list.get(position));
} else
{
view = convertView;
((ViewHolder) view.getTag()).checkbox.setTag(list.get(position));
}
ViewHolder holder = (ViewHolder) view.getTag();
holder.text.setText(list.get(position).getName());
holder.sub.setText(list.get(position).getPlace());
holder.checkbox.setChecked(list.get(position).isSelected());
return view;
}
}

How to Display two dimensional Array in ListView?

I Have 2D Array and this 2D Array has Strings. I would like to know How to Display the Strings in ListView?how to scroll both vertically and horizontally?
String[][] board = new String[][] {{"1","10","100"},{"hi0","1hello","test"},{"test31","test32","test43"}};
It seem to be you are asking basic things, How to use ListView. please check it you will get all about ListView.
Android ListView and ListActivity
It is to display two-d array in list view.Here's my source code in which i have implemented 2-d array in list view
My Adapter class:-
public class MyArrayAdapter extends ArrayAdapter<List>{
QuickActionDemo quickActionDemo;
public Activity context;
public List<List> list;
int CAMERA_PIC_REQUEST=10;
private int selectedPos = -1;
int clickPosition,rowPosition;
Camera camera;
private static final String TAG = "CameraDemo";
public MyArrayAdapter(Activity context,List<List> list) {
super(context,R.layout.attach_pic,list);
this.context = context;
this.list = list;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position+1;
}
static class ViewHolder {
public TextView tv1,tv2,tv3;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View rowView = null;
final ViewHolder holder = new ViewHolder();
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
rowView = inflator.inflate(R.layout.attach_pic, null);
holder.tv1 = (TextView) rowView.findViewById(R.id.defectpic);
holder.tv2 = (TextView) rowView.findViewById(R.id.no_of_uploded_pics);
holder.tv3 = (TextView) rowView.findViewById(R.id.camera);
holder.tv3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Intent in = new Intent(getContext(),QuickActionDemo.class);
// context.startActivityForResult(in,0);
}
});
rowView.setTag(holder);
List itemVal1 = (List)getItem(position);
String st1 = (String)itemVal1.get(0);
holder.tv1.setText(st1);
List itemVal2 = (List)getItem(position);
String st2 = (String)itemVal2.get(1);
holder.tv2.setText(st2);
} else {
rowView = convertView;
((ViewHolder) rowView.getTag()).tv1.setTag(list.get(position));
((ViewHolder) rowView.getTag()).tv2.setTag(list.get(position));
((ViewHolder) rowView.getTag()).tv3.setTag(list.get(position));
}
return rowView;
}
#Override
public int getItemViewType(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public int getViewTypeCount() {
// TODO Auto-generated method stub
return list.size();
}
}
Here's my activity class:-
public class MyActivity extends ListActivity {
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); // to hide the virtual keyboard
setContentView(R.layout.defect_pic_listview);
try{
ArrayAdapter<List> adapter = new MyArrayAdapter(this,makeList());
setListAdapter(adapter);
}
}
private List<List> makeList(){
List<List> all = new ArrayList();
String[] newArray1 = {"Defect Picture1", "2"};
List<String> newListObject1 = Arrays.asList(newArray1);
String[] newArray2 = {"Defect Picture2","1"};
List<String> newListObject2 = Arrays.asList(newArray2);
String[] newArray3 = {"Defect Picture3","4"};
List<String> newListObject3 = Arrays.asList(newArray3);
String[] newArray4 = {"Defect Picture4","1"};
List<String> newListObject4 = Arrays.asList(newArray4);
String[] newArray5 = {"Defect Picture5","3"};
List<String> newListObject5 = Arrays.asList(newArray5);
all.add(newListObject1);
all.add(newListObject2);
all.add(newListObject3);
all.add(newListObject4);
all.add(newListObject5);
return all;
}
}
Creating a model as an inner class always works well.
Good way to store any number of items.
public class ActivityClass extends Activity {
...
ArrayList<ValuesModel> listViewValues = new ArrayList<ValuesModel>();
listViewValues.add(new ValuesModel("row title", "row details"));
ListViewAdapter listAdapter = new ListViewAdapter(this, listViewValues);
((ListView) findViewById(android.R.id.list)).setAdapter(listAdapter);
...
public class ValuesModel {
private String rowTitle;
private String rowDetails;
public ValuesModel(String rowTitle, String rowDetails) {
this.rowTitle = rowTitle;
this.rowDetails = rowDetails;
}
public String getRowTitle() {
return rowTitle;
}
public String getRowDetails() {
return rowDetails();
}
}
Then inside of your list adapter,
public class ListViewAdapter extends ArrayAdapter<ActivityClass.ValuesModel> {
private ArrayList<ActivityClass.ValuesModel> mValues;
...
#Override
public View getView(int position, View convertView, ViewGroup parent) {
...
//here whenever you need to retrieve your values, just say:
// mValues.get(position).getRowTitle();
// mValues.get(position).getRowDetails();
//if you use a viewholder pattern, you can do this:
viewHolder.rowTitle = (TextView) convertView.findViewById(R.id.row_title_textview);
viewHolder.rowTitle.setText(mValues.get(position).getRowTitle());
...
}
}

Categories

Resources