At the moment I am getting items out of my database and add them to a string called result which I return and set to my TextView:
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.level);
loadDataBase();
int level = Integer.parseInt(getIntent().getExtras().getString("level"));
questions = new ArrayList<Question>();
questions = myDbHelper.getQuestionsLevel(level);
tvQuestion = (TextView) findViewById(R.id.tvQuestion);
i = 0;
String data = getAllItems();
tvQuestion.setText(data);
}
private String getAllItems() {
result = "";
for (i = 0; i<9; i++){
result = result + questions.get(i).getQuestion() + "\n";
}
return result;
// TODO Auto-generated method stub
}
The thing is, all these items also have a title(string) and graphical thumb (string) in the database. I would like to show them as illustrated in the picture below, each with an onclicklistener on it, instead of a boring list of items below eachother. Each item has a picture and title.
Since my beginning programming skills, I am wondering how to do this best, and if you know any good tutorials on it which explain it well?
Thanks!
if i understood your question you need to create a customize an adapter.
Create a new simple class like this which holds an string and a picture
Class ObjectHolder {
int Image;
String Title;
}
and create a getter and setter for this two
then create custom ArrayAdapter
Class CustomArrayAdapter extends ArrayAdapter<ObjectHolder> {
public CustomArrayAdapter(Context C, ObjectHolder[] Arr) {
super(C, R.layout.caa_xml, Arr);
}
#Override
public View getView(int position, View v, ViewGroup parent)
{
View mView = v ;
if(mView == null){
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mView = vi.inflate(R.layout.cpa_xml, null);
}
TextView text = (TextView) mView.findViewById(R.id.tv_caarow);
ImageView image = (ImageView) mView.findViewById(R.id.iv_caarow);
if(mView != null )
{ text.setText(getItem(position).getText());
image.setImageResource(getItem(position).getImage());
return mView;
}
}
and create caa_xml.xml in res\layout\
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/iv_caarow"
android:src="#drawable/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/tv_caarow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="15dip"
android:layout_BottomOf="#+id/iv_caarow" />
</RelativeLayout>
and use it like this.
GridView GV= (GridView) findViewById(R.Id.gv); // reference to xml or create in java
ObjectHolder[] OHA;
// assign your array, any ways!
mAdapter CustomArrayAdapter= CustomArrayAdapter(this, OHA);
GridView.setAdapter(mAdapter);
Related
I have a process in which a user selects a city, then sees medical practitioners in that state.
I have results that show the name of the medical practice:
#Override
protected void onResume() {
super.onResume();
setProgressBarIndeterminateVisibility(true);
Bundle b = getIntent().getExtras();
final String[] resultArr = b.getStringArray("selectedItems");
String location = b.getString("selectedItems");
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.orderByAscending(ParseConstants.KEY_PRACTICE_NAME);
query.findInBackground(new FindCallback<ParseUser>() {
#Override
public void done(List<ParseUser> users, ParseException e) {
setProgressBarIndeterminateVisibility(false);
if (e == null) {
// Success
//store users variable in Parse to mMidwifeLocations
mMidwives = users;
mCurrentUser = ParseUser.getCurrentUser();
//mMidwifeType = ParseUser.getString("usertype");
//store users in string array, locations
String[] midwives = new String[mMidwives.size()];
String[] locations = new String[mMidwives.size()];
String check;
String location;
int i = 0;
for(ParseUser user : mMidwives) {
//get city value from user, assign it to check variable
location = user.getString("city");
check = user.getString("userType");
if (!Arrays.asList(midwives).contains(check) && type != "patient" && Arrays.asList(resultArr).contains(location) ) {
//in locations array, assign practiename values
midwives[i] = user.getString("practicename");
}
}
i++;
I also want to return in the list the primary contact, address, and practice philosophy..what is the best strategy to do this? I am using a simple_list_item_1 list type...there are other list types...wondering if using one of those might be the answer..thanks in advance..
First of all you probably want to do all of this inside the onCreate() method.
Im not to sure if this is what you want but from what i understand i am writing this.
I would personally write down all the data you want in a string-array in your strings.XML
<string-array name="string_array">
<item name ="item1"> item1 </item>
.......
</string-array>
Then I would just grab that data and sort it in order of what order your states are in. So they would match. But by looking at what you have done you have done that with ease
Then creating a custom layout assign each string to it.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content" android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
Change this layout how you would like to see your data, also add more textviews to how many you would need.
Now you would need to create a adapter for this listview.
class adapter extends BaseAdapter {
ArrayList<SingleRow> arrayList;
Context context;
adapter(Context contxt) {
context = contxt;
arrayList = new ArrayList<SingleRow>();
Resources res = contxt.getResources();
String[] items= res.getStringArray(R.array.string_array);
for (int i = 0; i < 1; i++) {//Change the 1 in i < 1 to how big your list is.
arrayList.add(new SingleRow(items[i]));
}
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return arrayList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.items_layout, parent, false);
TextView item1 = (TextView) row.findViewById(R.id.txtItem1);
SingleRow temp = arrayList.get(position);
items.setText(temp.items);
return row;
}
}
class SingleRow {
String items;
SingleRow(String items) {
this.items = items;
}
}
After reading the code and analyzing it you would figure out how to add data to the textviews for each row item, and do so by how many you will need.
Now you will have to set the adapter to the listview by...
ListView listView = (ListView) findViewById(R.id.itemListView);
listView.setAdapter(new adapter(getActivity()));
Now you should be able to make a custom listview layout. If any problems occur please just comment on this answer and ill try to fix it.
Good luck.
So I'm trying to make a custom SimpleCursorAdapter, because I want to make list rows that look something like this:
ToggleButton | TextView | ImageButton,
and I know of no way to do this without making a custom adapter.
The problem being that my code doesn't work and I'm not really sure why. Even if there's no data to be displayed, I get a row with the default format:
ToggleButton | "default" | ImageButton.
Furthermore, all rows displayed look exactly the same as the default row, and the OnClickListener I set up doesn't do anything.
Can someone tell me what I'm doing wrong, or at least point me in the direction of a decent tutorial for how to deal with custom CursorAdapters and OnClickListeners? Because I've been totally unable to find anything remotely helpful.
Here is my code for the adapter:
public class AlarmCursorAdapter extends SimpleCursorAdapter {
private Cursor mCursor;
private Context mContext;
private Activity mActivity;
public AlarmCursorAdapter(Context context, int layout, Cursor c,
String[] from, int[] to, int flags) {
super(context, layout, c, from, to, flags);
// TODO Auto-generated constructor stub
mCursor = c;
mContext = context;
mActivity = (Activity) context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if(view == null) {
view = LayoutInflater.from(mContext).inflate(R.layout.alarm_list_row, parent, false);
}
if(mCursor == null || mCursor.getCount() == 0) {
return view;
}
mCursor.moveToPosition(position);
// Set the alarm time view
TextView alarmView = (TextView) view.findViewById(R.id.alarmView);
int timeStringIndex = mCursor.getColumnIndexOrThrow(DailyAlarmTable.ALARM_TIME);
String alarmTime = mCursor.getString(timeStringIndex);
alarmView.setText(alarmTime);
// Set up the toggle button
int isActiveIndex = mCursor.getColumnIndexOrThrow(DailyAlarmTable.ALARM_ISACTIVE);
int isActive = mCursor.getInt(isActiveIndex);
ToggleButton alarmToggle = (ToggleButton)view.findViewById(R.id.alarmToggle);
if(isActive == 1) {
alarmToggle.setChecked(true);
} else {
alarmToggle.setChecked(false);
}
final int currentPosition = mCursor.getPosition();
int idIndex = mCursor.getColumnIndexOrThrow(DailyAlarmTable.ALARM_ID);
final long alarmId = mCursor.getLong(idIndex);
alarmToggle.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String toastStr = "clicked alarm " + alarmId + " at position " + currentPosition;
Toast.makeText(mContext, toastStr, Toast.LENGTH_SHORT).show();
}
});
return view;
}
}
Here's the implementation, which occurs inside a fragment:
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
/*
mAdapter = new SimpleCursorAdapter(getActivity(),
R.layout.alarm_list_row, null,
new String[] { DailyAlarmTable.ALARM_TIME, DailyAlarmTable.ALARM_ISACTIVE },
new int[] { R.id.alarmView, R.id.alarmToggle }, 0);
*/
mAdapter = new AlarmCursorAdapter(getActivity(),
R.layout.alarm_list_row, null,
new String[] { DailyAlarmTable.ALARM_TIME, DailyAlarmTable.ALARM_ISACTIVE },
new int[] { R.id.alarmView, R.id.alarmToggle }, 0);
//mAdapter.setViewBinder(new AlarmViewBinder());
ListView alarmList = (ListView) this.getActivity().findViewById(R.id.alarmListView);
TextView emptyView = (TextView) this.getActivity().findViewById(R.id.empty);
alarmList.setEmptyView(emptyView);
alarmList.setAdapter(mAdapter);
// Initialize the loader
getLoaderManager().initLoader(1, savedInstanceState, this);
}
Here's the XML file for the row:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ToggleButton
android:id="#+id/alarmToggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="#string/details_default" />
<TextView
android:id="#+id/alarmView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/details_default"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ImageButton
android:id="#+id/alarmDiscard"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_discard"
android:contentDescription="#string/alarm_discard_description" />
</LinearLayout>
If there's any other code you need, I can gladly add that. Thank you very much in advance.
As suggested by pskink's comment, the solution was not to use a custom SCA at all, but to just implement a View Binder.
I'm new #andorid development. Pls help me for this.
Here is my question:
I create listview.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:gravity="left|center"
android:layout_width="wrap_content"
android:paddingBottom="5dp"
android:paddingTop="5dp"
android:paddingLeft="5dp">
<TextView android:id="#+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="#FFFF00"
android:textIsSelectable="true">
</TextView>
<TextView android:id="#+id/TextView02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:textColor="#0099CC"
android:textIsSelectable="true">
</TextView>
And local class declaration:
public class listview_row{
TextView Text1;
TextView Text2;
public listview_row(){
Text1 = (TextView) findViewById(R.id.TextView01);
Text2 = (TextView) findViewById(R.id.TextView02);
}
}
when I create object from this class:
listview_row obListview = new listview_row();
obListview.Text1.setText(bundle.getString("first_name"));
obListview.Text2.setText(bundle.getString("last_name"));
obListview.Text1 allways equal null and nullobjectexecption is raising. How can I fix this.
I thought I can create textview on constructor, but I was wrong I think.
PS : I want to create Listview with two textview, I used android.R.layout.simple_list_item_1 and I can manage to pass data between two acticity with no problem. Now I try to display first_name|last_name #first screen listview.
For more information here is my onActivityResult:
public void onActivityResult(int requestCode, int resultCode, Intent intent){
if ( resultCode == RESULT_OK ){
Bundle extras = intent.getExtras();
if (extras != null){
switch (requestCode){
case Activity_New:
add_new_row( extras );
break;
case Activity_Edit:
edit_row( extras );
break;
}}
}
}
and this is add_new_row:
public void add_new_row( Bundle bundle){
// Başlık bilgilerini kayıt ediyoruz
int sayi = HeaderArray.size();
listview_row obListview = new listview_row();
obListview.Text1.setText(bundle.getString("first_name"));
obListview.Text2.setText(bundle.getString("last_name"));
HeaderArray.add(sayi, obListview);
HeaderAdapter.notifyDataSetChanged();
// Kalem bilgilerini kayıt ediyoruz
mtable_row obMember = new mtable_row();
obMember.index = sayi;
obMember.first_name = bundle.getString("first_name");
obMember.last_name = bundle.getString("last_name");
obMember.birth_date = bundle.getString("birth_date");
itemArray.add(sayi, obMember);
}
I use for detail information Array:
private ArrayList<mtable_row> itemArray;
public class mtable_row{
int index;
String first_name;
String last_name;
String birth_date;
}
My main objective is working with two array:
first one is header and second one is item.
header has two field first_name and second_name
and I like to show this array on my main screen.
To do it this way, you would have to inflate a Layout file to pass to your class and use that to get the ids like
Text1 = (TextView) layout.findViewById(R.id.TextView01);
where layout is the inflated layout you passed in to a constructor. I haven't tried this but something like that would probably work. However, unless you have a need to do it this way it would probably be easier just to keep those Views in your Activitvy
public class YourActivity extends Activity {
TextViw Text1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.listview);
Text1 = (TextView) findViewById(R.id.TextView01);
Text2 = (TextView) findViewById(R.id.TextView02);
.....
}
}
You are getting a NPE because, as far as I can see, you haven't inflated the layout file in which these Views exist.
Also, a minor thing but you should consider adhering to Java naming conventions to not get confused or confuse others. Class names should be camel cased and variable names should be mixed case.
I want to create Listview with two textview,
For this i suggest you have a custom listview. Have a custom adapter defined. Inflate a custom layout for each row.
You can pass your values to the constructor of the CustomAdapter.
CustomAdapter cus = new CustomAdapter(this);
ListView lv= (ListView) findViewById(R.id.lv);
lv.setAdapter(cus);
public class CustomAdapter extends ArrayAdapter {
Context c;
LayoutInfator mInflater;
public CustomAdapter(CustomListView customListView) {
super(customListView, 0);
// TODO Auto-generated constructor stub
this.mInflater = LayoutInflater.from(customListView);
c=customListView;
}
public int getCount() {
return 20; //listview item count
}
public Object getItem(int arg0) {
return arg0;
}
public long getItemId(int arg0) {
return arg0;
}
public View getView(final int arg0, View arg1, ViewGroup arg2) {
final ViewHolder vh;
vh= new ViewHolder();
if(arg1==null )
{
arg1=mInflater.inflate(R.layout.customlayout, arg2,false);
vh.tv1= (TextView)arg1.findViewById(R.id.textView1);
vh.tv2= (TextView)arg1.findViewById(R.id.textView2);
}
else
{
arg1.setTag(vh);
}
vh.tv1.setText("hello");
vh.tv2.setText("hello");
return arg1;
}
static class ViewHolder
{
TextView tv1,tv2;
}
}
Once you pass data between two activities, in the second activity retrieve the data. Each screen has its own UI. You cannot refer to the UI elements like what you have done.
Have two TextViews for your second activity
public class SecondActivity extends Activity{
TextView tv1;
TextView tv2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
tv1 = (TextView) findViewById(R.id.TextView01);
tv2 = (TextView) findViewById(R.id.TextView02);
Bundle extras = getIntent().getExtras();
if (extras != null) {
tv1.setText(extras.getString("first_name"));
tv2.setText(extras.getString("last_name"));
}
}
}
I am building an app that uses ListView and a custom adapter extending BaseAdapter to handle the data to the ListView. The code is as follows:
newlist.java compiles/runs fine
public class newslist extends Activity {
public static final String tag = "newslist";
ListView listNews;
MyListAdapter listAdapter;
/** Set or Grab the URL */
public static final String parseURL = "http://www.example.com.gr/article.php";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newslist);
/** Array Lists */
ArrayList<String> titles = new ArrayList<String>();
ArrayList<String> links = new ArrayList<String>();
ArrayList<String> dates = new ArrayList<String>();
Log.d(newslist.tag, "****** parseURL = " + parseURL);
listNews = (ListView) findViewById(R.id.listNews);
try {
/** Open URL with Jsoup */
Document doc = Jsoup.connect(parseURL).get();
/** Grab classes we want */
Elements pcontent = doc.getElementsByClass("content_title");
Elements pdates = doc.getElementsByClass("content_datecreated_left");
/** Loop for grabbing TITLES within parent element */
for (Element ptitles : pcontent) {
/** Grab Anchors */
Elements ptitle = ptitles.getElementsByTag("a");
for (Element title : ptitle) {
titles.add(title.text());
}
}
/** Loop for grabbing LINKS within parent element */
for (Element plinks : pcontent) {
/** Grab anchors */
Elements plink = plinks.getElementsByTag("a");
for (Element link : plink) {
links.add(link.attr("abs:href")); /** parse absolute address */
}
}
/** Loop for grabbing DATES within parent element */
for (Element pdate : pdates) {
dates.add(pdate.text()) ;
}
//TODO: Regex on Date
//String content: Main Activity Content
int i=0;
int num = titles.size();
String[] printDates = new String[num];
for (i=0; i < num; i++)
{
//substring(25) leaves a space after the date, eg "26/6/2011 "
//content[i] = titles.get(i) + "\n Date: " + dates.get(i).substring(25);
printDates[i] = dates.get(i).substring(25);
}
/** Create an ArrayAdapter, that will actually make the Strings above
* appear in the ListView */
listAdapter = new MyListAdapter(this, titles, dates);
listNews.setAdapter(listAdapter);
} catch (Exception e) {
Log.e(newslist.tag, "****** Failed to Parse URL:" + e.getMessage());
e.printStackTrace();
}
} /*- OnCreate End -*/
} /*- Class End -*/
MyListAdapter.java runs a NPE at line 75:
public class MyListAdapter extends BaseAdapter {
public final static String tag = "MyListAdapter";
public Context context;
public ArrayList<String> title;
public ArrayList<String> date;
public LayoutInflater inflater;
public MyListAdapter(Activity context, ArrayList<String> title, ArrayList<String> date) {
super();
this.context = context;
this.title = title;
this.date = date;
this.inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
// Auto-generated method stub
return this.title.size();
}
public Object getItem(int position) {
//Auto-generated method stub
return this.title.get(position);
}
public long getItemId(int position) {
// Auto-generated method stub
return position;
}
private static class ViewHolder {
TextView titleView;
TextView dateView;
}
public View getView(int position, View convertView, ViewGroup parent)
{
// Auto-generated method stub
ViewHolder holder;
Log.d(tag, "****** convertView: " + convertView);
if (convertView == null)
{
convertView = inflater.inflate(R.layout.listrow, null);
holder = new ViewHolder();
holder.titleView = (TextView) convertView.findViewById(R.id.listTitle);
holder.dateView = (TextView) convertView.findViewById(R.id.listDate);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
Log.d(tag, "****** Title: " + title.get(position));
Log.d(tag, "****** findViewById: " + convertView.findViewById(R.id.listTitle));
Log.d(tag, "****** holder.titleView: " + holder.titleView);
holder.titleView.setText(title.get(position));
holder.dateView.setText(date.get(position));
//notifyDataSetChanged();
return convertView;
}
}
Line 75 is:
holder.titleView.setText(title.get(position));
However I have tracked the problem to line 62:
holder.titleView = (TextView) convertView.findViewById(R.id.listTitle);
where it seems from my debugging messages that holder.titleView is null
I have tried cleaning/erasing bin folder and rebuilding the project to no avail. I think the problem lies in the View R.id.listTitle not being found. But i have no idea why.
I will also include my two xml files for previewing
newslist.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="wrap_content"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/title"
android:gravity="center|top"
android:textSize="20dip"
android:textStyle="bold"
android:text="#string/titleNewslist"
/>
<ListView
android:id="#+id/listNews"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
</ListView>
</LinearLayout>
listrow.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:name="#+id/listTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="top|left"
android:textSize="18dip"
android:textStyle="bold"
android:text="TextView">
</TextView>
<TextView
android:name="#+id/listDate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="bottom|right"
android:textSize="12dip"
android:textStyle="bold"
android:textColor="#android:color/white"
android:text="TextView">
</TextView>
</LinearLayout>
You never assign anything to titleView.
You need to do the following in your onCreate() after super.onCreate()
titleView = (TextView) this.getViewById(R.id.listTitle);
Make sure to declare titleView as a field at the top of your class so the rest of your class can access it, if you need to.
Hope this helps!
EDIT:
An important note I just noticed:
android:name="#+id/myName"
is NOT the same as
android:id="#+id/myName"
You need to make sure you declare the ids, or you will not be able to access the layout elements.
I don't really understand the use of ViewHolder.
You should do :
convertView = new YourViewClass();
in this class have 2 fields for both textviews and a onCreate that inflate listRow.xml and find both views by id.
but converview and view holder should not be different and you should not try to pass one view from one component to the other.
Regards,
Stéphane
NullPointerException usually comes, when you have some problems with your XML files. Try to not end your
<TextView
android:name="#+id/listTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="top|left"
android:textSize="18dip"
android:textStyle="bold"
android:text="TextView">
</TextView>
with > and instead of > and
I'm not sure that it's the source of your problem, but it can happen.
Hope it helps.
you are passing the Activity context into the MyListAdapter constructor and assign to the Context object.
change the Activity to Context in constructor and then try it
Hi i've got a custom listview with a text view and a button in each row.
Im having trouble trying to use the buttons . Each button will fire a different intent. This is the xml file for the list view rows.
<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout
android:id="#+id/widget28"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<Button
android:id="#+id/widget29"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Remind me"
android:layout_alignParentRight="true"
/>
<TextView android:id="#+id/text12"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#ff99ccff"
android:text="Text view" />
</RelativeLayout>
Then i have another xml file which simply contains the list view in a linear layout.
This is my custom array class.
public class customArray extends ArrayAdapter<String> {
int resource;
public customArray(Context cont, int _resource, List<String> items) {
super (cont, _resource,items);
resource = _resource;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
RelativeLayout rl;
String prod = getItem(position);
if (convertView == null) {
rl = new RelativeLayout(getContext());
LayoutInflater vi = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vi.inflate(resource, rl, true);
} else {
rl = (RelativeLayout)convertView;
}
TextView t1 = (TextView)rl.findViewById(R.id.text12);
t1.setText(prod);
Button b1 = (Button)rl.findViewById(R.id.widget29);
return rl;
}
}
Then the final class which gets the data from a database and uses the custom adapter to display the information. Does anyone know how i would call each button?
`public class SatMain extends Activity {
/** Called when the activity is first created.
* #param cont */
#Override
public void onCreate(Bundle savedInstanceState)
{
List<String> results = new ArrayList<String>();
super.onCreate(savedInstanceState);
setContentView(R.layout.satmain);
dbAdapter db = new dbAdapter(this);
// button.setOnClickListener(m);
//---get all titles---
db.open();
db.InsertData();
Cursor c = db.getSat1();
if (c.moveToFirst())
{
do {
String pub = c.getString(c.getColumnIndex(db.KEY_Artist));
String pub1 = c.getString(c.getColumnIndex(db.KEY_Time));
results.add(pub + pub1 );
} while (c.moveToNext());
}
db.close();
ListView listProducts;
customArray ca = new customArray(this, R.layout.button, results);
listProducts = (ListView)findViewById(R.id.list1);
listProducts.setAdapter(ca);
ca.notifyDataSetChanged();
}
}`
In the "getView" method of your adapter, you should set an onClick listener for the button. You can do an anonymous class so that you can refer to the contents of the row in the button. I.e, add the following where you get b1 in your example.
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//create activity based on prod
}
});