ORMLite and ListView - android

I'm using ORMLite and I want to display data in a listView, for example, I have a List of SMS (id, number, message) so when I do a query for all I have all of my data and now I want to do a view to display each data, so I found how to do a listView but I don't know how to display the number and the message on each row...
public class SMSActivity extends Activity {
ListView lview;
SMSAdapter lviewAdapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sms);
DatabaseHandler db = new DatabaseHandler(this);
Dao<SMS, Integer> SMSDao = null;
try {
SMSDao = db.getSMSDao();
final List<SMS> users = SMSDao.queryForAll();
Log.d("list", users.toString());
lview = (ListView) findViewById(R.id.mainListView);
lviewAdapter = new SMSAdapter(this, ?, ?);
System.out.println("adapter => "+lviewAdapter.getCount());
lview.setAdapter(lviewAdapter);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
SMSAdapter:
public class SMSAdapter extends BaseAdapter {
Activity context;
String title[];
String description[];
public SMSAdapter(Activity context, String[] title, String[] description) {
super();
this.context = context;
this.title = title;
this.description = description;
}
public int getCount() {
// TODO Auto-generated method stub
return title.length;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
private class ViewHolder {
TextView txtViewTitle;
TextView txtViewDescription;
}
public View getView(int position, View convertView, ViewGroup parent)
{
// TODO Auto-generated method stub
ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
if (convertView == null)
{
convertView = inflater.inflate(R.layout.row_sms, null);
holder = new ViewHolder();
holder.txtViewTitle = (TextView) convertView.findViewById(R.id.firstLine);
holder.txtViewDescription = (TextView) convertView.findViewById(R.id.secondLine);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.txtViewTitle.setText(title[position]);
holder.txtViewDescription.setText(description[position]);
return convertView;
}
}

First of all, i would suggest that you use RecyclerView instead of ListView. Second, also my suggestion is to pass whole list of users in the adapter.
I think you would like to do this:
//...
lview = (ListView) findViewById(R.id.mainListView);
List<String> messages = new ArrayList<String>();
List<String> numbers = new ArrayList<String>();
for(int i = 0; i < users.size(); i++){
SMS sms = users.get(i);
messages.add(sms.getMessage());
numbers.add(sms.getNumber());
}
lviewAdapter = new SMSAdapter(this, numbers, messages);
System.out.println("adapter => "+lviewAdapter.getCount());
lview.setAdapter(lviewAdapter);
//...
Your adapter requires two arrays of strings and you can get them from the users list.

Related

Dynamic creation of list view dosen't show multiple rows in android

Being a newbie to android I am trying to implement List view on my project. The list view works. However I am only able to see one row in my list. I wish to add as many rows as I want dynamically.
I have created a separate XML which defines the structure of a single row in the list view.
Here is what I have coded until now :
public class Offers extends Activity
{
ListView latesttrans;
ArrayList<String> listItems = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_offers);
latesttrans = (ListView) findViewById(R.id.listView1);
latesttrans.setAdapter(new mylist2(this));
}
}
class SingleRow2
{
String title;
String description;
SingleRow2(String title, String description)
{
this.title=title;
this.description=description;
}
}
class mylist2 extends BaseAdapter
{
int i=0;
Boolean flagValue = false;
ArrayList<SingleRow> list;
Context context;
mylist2(Context c)
{
context=c;
list=new ArrayList<SingleRow>();
Resources res = c.getResources();
String[] title = res.getStringArray(R.array.titles);
String[] description = res.getStringArray(R.array.description);
list.add(new SingleRow(title[i],description[i]));
i++;
}
#Override
public int getCount()
{
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int arg0)
{
// TODO Auto-generated method stub
return list.get(arg0);
}
#Override
public long getItemId(int arg0)
{
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup viewGroup)
{
// TODO Auto-generated method stub
LayoutInflater inflater= (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.single_row_offers,viewGroup,false);
Uri latesttransuri = Uri.parse("content://sms/inbox");
Cursor latesttranscursor = context.getContentResolver().query(latesttransuri, new String[]{"_id","address","date","body"}, null, null, null);
if(flagValue == false)
{
latesttranscursor.moveToFirst();
flagValue = true;
}
String address = null,body = null;
int i=0;
while(latesttranscursor.moveToNext())
{
address=latesttranscursor.getString(1);
long date = latesttranscursor.getLong(2);
String sdate = millisToDate(date);
body = latesttranscursor.getString(3);
if(body.contains("FREE"))
{
TextView title = (TextView) row.findViewById(R.id.textViewSingleOffer1);
TextView description = (TextView) row.findViewById(R.id.textViewSingleOffer2);
title.setText(address);
description.setText(body);
}
else if(body.contains("unlimited"))
{
TextView title = (TextView) row.findViewById(R.id.textViewSingleOffer1);
TextView description = (TextView) row.findViewById(R.id.textViewSingleOffer2);
title.setText(address);
description.setText(body);
}
}
return row;
}
public String millisToDate(long currentTime)
{
String finalDate;
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(currentTime);
Date date = calendar.getTime();
finalDate = date.toString();
return finalDate;
}
}
You don't iterate over your items. In the constructor of your adapter you just increment i once, and then stop. This results in having one row. Change it to a for loop like this:
for(int i = 0; i < var; i++) {
list.add(new SingleRow(title[i], description[i]));
}
Where var is the size of your array that you retrieve from the resources.
For more information about ListView and the use of Adapters: http://www.ezzylearning.com/tutorial/customizing-android-listview-items-with-custom-arrayadapter

Unable to Print data in listview in android after Json Parsing

public class Setting extends Activity implements OnClickListener {
ListView listView1;
ImageView backbutton;
String Url = "http://182.71.212.110:8083/api/values/userdetails";
String Id;
String Designation;
String EmployeeName;
JSONArray _jarray;
List<RowItem> rowItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.setting);
listView1 = (ListView) findViewById(R.id.listView1);
backbutton = (ImageView) findViewById(R.id.backbutton);
backbutton.setOnClickListener(this);
new GetUserdetail().execute();
CustomList adapter = new CustomList(this, rowItems);
listView1.setAdapter(adapter);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.backbutton) {
finish();
}
}
class GetUserdetail extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
String json = HttpHitter.ExecuteData(Url);
_jarray = new JSONArray(json);
System.out.println("_jarray" + _jarray);
for (int i = 0; i <= _jarray.length(); i++) {
JSONObject _obj = _jarray.getJSONObject(i);
Id = _obj.getString("Id");
Designation = _obj.getString("Designation");
EmployeeName = _obj.getString("EmployeeName");
System.out.println(Id + "" + Designation + ""
+ EmployeeName);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
rowItems = new ArrayList<RowItem>();
}
}
}
This my code i am able to display the value after Jason parsing in this line System.out.println(Id + "" + Designation + ""
+ EmployeeName);
But i am unable to print data in Listview there is Error coming while i have created
Datamodel
public class RowItem {
public RowItem(String title, String desc) {
this.title = title;
this.desc = desc;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
private String title;
private String desc;
}
I have create adapter which i s extending from Base adapter that work fine can u please tell me how to bind value and display in list view after Json Parsing please suggest me i m trying to Implement .
Use Custom Adapter for binding your JSON data to your Listview like below :
public class ListViewAdapterForLead extends BaseAdapter {
Context context;
LayoutInflater inflater;
ArrayList<SpinnerNavItem> data;
TextView txtText;
public ListViewAdapterForLead(Context context,ArrayList<SpinnerNavItem> arraylist) {
this.context = context;
data = arraylist;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int index) {
return data.get(index);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.row_lead, null);
}
txtText = (TextView) convertView.findViewById(R.id.textLeadMenu);
txtText.setText(data.get(position).getTitle());
return convertView;
}
public View getDropDownView(int position,View convertView,ViewGroup parent){
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.row_lead, null);
}
txtText = (TextView) convertView.findViewById(R.id.textLeadMenu);
txtText.setText(data.get(position).getTitle());
return convertView;
}
}
bind your values in the getView() method of your custom adapter.
You should set the data after the background task gets completed.
* First try to set list adapter in onPostExecute() method.
* Make sure all the details in your model gets filled.
* Make use of getView() method in your Adapter class to parse the data.
For sample code for ListView with BaseAdapter, refer the below link
http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/
You forgot one thing,this is why the List is empty
Add the parsed data to your List
//initialize your list here
rowItems = new List<RowItems>();
for (int i = 0; i <= _jarray.length(); i++) {
JSONObject _obj = _jarray.getJSONObject(i);
RowItemsr = new RowItems();
Id = _obj.getString("Id");
Designation = _obj.getString("Designation");
EmployeeName = _obj.getString("EmployeeName");
System.out.println(Id + "" + Designation + ""
+ EmployeeName);
// you must create an object and add it to your list
r.setTitle(EmployeeName);
r.setDesc(Designation);
rowItems.add(r);
}
This is what you need

Custom BaseAdapter wont add new Data - Android

I have a custom baseadapter that creates comment boxes. Everything works great on it until I want to add data. When I try to add the data it deletes the previous data and adds the new data. How do I make it so it keeps all the data? Is my Add method incorrect? Here is my baseadapter,
class CreateCommentLists extends BaseAdapter{
Context ctx_invitation;
String[] listComments;
String[] listNumbers;
String[] listUsernames;
public CreateCommentLists(String[] comments, String[] usernames, String[] numbers, DashboardActivity context)
{
super();
ctx_invitation = context;
listComments = comments;
listNumbers = usernames;
listUsernames = numbers;
}
#Override
public int getCount() {
if(null == listComments)
{
return 0;
}
// TODO Auto-generated method stub
return listComments.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return listComments[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = null;
try
{
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater li = (LayoutInflater)ctx_invitation.getSystemService(inflater);
v = li.inflate(R.layout.list_item, null);
TextView commentView = (TextView)v.findViewById(R.id.listComment);
TextView NumbersView = (TextView)v.findViewById(R.id.listNumber);
TextView usernamesView = (TextView)v.findViewById(R.id.listPostedBy);
Button usernameButton = (Button)v.findViewById(R.id.listUsernameButton);
Button numberButton = (Button)v.findViewById(R.id.listNumberButton);
commentView.setText(listComments[position]);
NumbersView.setText(listNumbers[position]);
usernamesView.setText(listUsernames[position]);
usernameButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
i.putExtra("usernameOfProfile",listUsernames[position]);
startActivity(i);
finish();
}
});
numberButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
i.putExtra("NumberProfile",listNumbers[position]);
startActivity(i);
finish();
}
});
}
catch(Exception e)
{
e.printStackTrace();
}
return v;
}
public void add(String[] comments, String[] usernames,
String[] numbers) {
listComments = comments;
listNumbers = usernames;
listUsernames = numbers;
}
public int getCount1() {
if(null == listComments)
{
return 0;
}
// TODO Auto-generated method stub
return listComments.length;
}
public Object getItem1(int position) {
// TODO Auto-generated method stub
return listComments[position];
}
public long getItemId1(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView1(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = null;
try
{
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater li = (LayoutInflater)ctx_invitation.getSystemService(inflater);
v = li.inflate(R.layout.list_item, null);
TextView commentView = (TextView)v.findViewById(R.id.listComment);
TextView NumbersView = (TextView)v.findViewById(R.id.listNumber);
TextView usernamesView = (TextView)v.findViewById(R.id.listPostedBy);
Button usernameButton = (Button)v.findViewById(R.id.listUsernameButton);
Button numberButton = (Button)v.findViewById(R.id.listNumberButton);
commentView.setText(listComments[position]);
NumbersView.setText(listNumbers[position]);
usernamesView.setText(listUsernames[position]);
usernameButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
i.putExtra("usernameOfProfile",listUsernames[position]);
startActivity(i);
finish();
}
});
numberButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
i.putExtra("NumberProfile",listNumbers[position]);
startActivity(i);
finish();
}
});
}
catch(Exception e)
{
e.printStackTrace();
}
return v;
}
}
Setting the adapter:
final CreateCommentLists mycmlist = new CreateCommentLists(comments, usernames, numbers, DashboardActivity.this);
lstComments = (ListView)findViewById(android.R.id.list);
lstComments.setAdapter(mycmlist);
This is what how I call the add method,
mycmlist.add(comments,usernames,numbers);
mycmlist.notifyDataSetChanged();
In your add method you're setting the arrays to new values listComments = comments; That's replacing your old data with the new data.
You could use System.arrayCopy() to resize your listArrays to the new size and append the new items. A much less tedious approach, however, would be to store your arrays as List<String>, allowing you to add more items without worrying about resizing lists.
The result would look something like this...
public class CommentsAdapter extends BaseAdapter
{
private LayoutInflater inflater;
private List<String> comments;
private List<String> numbers;
private List<String> usernames;
public CommentsAdapter(Context context)
{
inflater = LayoutInflater.from(context);
comments = new ArrayList<String>();
numbers = new ArrayList<String>();
usernames = new ArrayList<String>();
}
public void add(String[] comments, String[] numbers, String[] usernames)
{
this.comments.addAll(Arrays.asList(comments));
this.numbers.addAll(Arrays.asList(numbers));
this.usernames.addAll(Arrays.asList(usernames));
notifyDataSetChanged();
}
#Override
public int getCount()
{
if (comments == null)
return 0;
return comments.size();
}
#Override
public String getItem(int position)
{
return comments.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
if (convertView == null)
{
convertView = inflater.inflate(R.layout.list_item, parent, false);
convertView.setTag(new ViewHolder(convertView));
}
ViewHolder holder = (ViewHolder) convertView.getTag();
holder.commentView.setText(comments.get(position));
//Other view bind logic here...
return convertView;
}
private static class ViewHolder
{
public TextView commentView;
public TextView numbersView;
public TextView usernamesView;
public Button usernameButton;
public Button numberButton;
public ViewHolder(View v)
{
commentView = (TextView) v.findViewById(R.id.listComment);
numbersView = (TextView) v.findViewById(R.id.listNumber);
usernamesView = (TextView) v.findViewById(R.id.listPostedBy);
usernameButton = (Button) v.findViewById(R.id.listUsernameButton);
numberButton = (Button) v.findViewById(R.id.listNumberButton);
}
}
}
I also highly recommend reading this page on the Android Developer's site: http://developer.android.com/training/improving-layouts/smooth-scrolling.html
Your current adapter implementation is very inefficient, and that page should help you iron out some kinks.
You probably need to add the String[] array to the existing one, instead of replacing it.
Add this function which joins two arrays (Sadly there is no already-implemented method for Java):
String[] concat(String[] A, String[] B) {
String[] C= new String[A.length + B.length];
System.arraycopy(A, 0, C, 0, A.length);
System.arraycopy(B, 0, C, A.length, B.length);
return C;
}
Credits: Sun Forum
And then change the add method to this:
public void add(String[] comments, String[] usernames,
String[] numbers) {
listComments = concat(listComments, comments);
listUsernames = concat(listUsernames, usernames);
listNumbers = concat(listNumbers, numbers);
}
And you had a typo in your code. In the add method, the listUsernames and listNumbers should be swapped I think.. I fixed it for you.

Repeating values in listview after back press

I have an application it have two activities. When press a button in the main activity, it shows customized listview, then I press hard back button and go to the main page of my application.
Then I again press the same button and go to the listview it shows the repeated values in the listview.
Any one have any sloution please???
CookList = new ArrayList<HashMap<String, String>>();
try {
url = new URI(cookUri);
List<DataModels> list1 = new ArrayList<DataModels>();
CookListServer cookServer = new CookListServer();
StringBuilder responseString = cookServer.CookConnect(url, "hi");
System.out.println("responseString---------"+responseString);
for(int i=0; i< itemId.size(); i++){
HashMap<String, String> Cook = new HashMap<String, String>();
Cook.put("ItemId", itemId.get(i));
System.out.println("itemId--------"+itemId.get(i));
Cook.put("ItemName", itemName.get(i));
Cook.put("ItemQty", itemQty.get(i));
CookList.add(Cook);
list1.add(get(i));
}
adapter = new MySimpleArrayAdapter(context, CookList, R.layout.cooklist_item, list1);
setListAdapter(adapter);
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private DataModels get(int s) {
return new DataModels(s);
}
#Override
public void onResume() {
super.onResume();
adapter.notifyDataSetChanged();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
// Adapter to list the Albums
public class MySimpleArrayAdapter extends ArrayAdapter<HashMap<String, String>> implements SectionIndexer {
private final Context context;
private final ArrayList<HashMap<String, String>> values;
List<DataModels> modellist;
public MySimpleArrayAdapter(Context context, ArrayList<HashMap<String, String>> values, int layout, List<DataModels> modellist) {
super(context, R.layout.cooklist_item, values);
this.context = context;
this.values = values;
this.modellist = modellist;
}
private final class ViewHolder {
public TextView Nametext;
public TextView Qntytext;
public Button prepareButton;
}
private LayoutInflater mLayoutInflater = null;
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
if (convertView == null) {
if (mLayoutInflater == null) {
mLayoutInflater = LayoutInflater.from(context);
}
convertView = mLayoutInflater.inflate(R.layout.cooklist_item, null);
viewHolder = new ViewHolder();
viewHolder.Nametext = (TextView) convertView.findViewById(R.id.label);
viewHolder.Qntytext = (TextView) convertView.findViewById(R.id.textView1);
viewHolder.prepareButton = (Button) convertView.findViewById(R.id.prepareButton1);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
((ViewHolder) convertView.getTag()).prepareButton.setTag(modellist.get(position));
}
final HashMap<String, String> cooklist = values.get(position);
final ViewHolder holder = (ViewHolder) convertView.getTag();
final String ItemId = cooklist.get("ItemId");
final String ItemName = cooklist.get("ItemName");
final String ItemQty = cooklist.get("ItemQty");
System.out.println("ItemId---------"+ItemId);
System.out.println("ItemName---------"+ItemName);
System.out.println("ItemQty---------"+ItemQty);
holder.Nametext.setText(ItemName);
holder.Qntytext.setText(ItemQty);
registerForContextMenu(convertView);
holder.prepareButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
DataModels element = (DataModels) viewHolder.prepareButton.getTag();
holder.prepareButton.setEnabled(false);
}
});
return convertView;
}
#Override
public int getPositionForSection(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public int getSectionForPosition(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public Object[] getSections() {
// TODO Auto-generated method stub
return null;
}
}
Thanks...
I got a solution
#Override
protected void onDestroy() {
itemId.clear();
itemName.clear();
itemQty.clear();
super.onDestroy();
}
Thanks....

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