Android Local public class textview creating on constructor - android

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

Related

Showing graphical instead of strings in an imagelist with title

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

How do I populate spinner with global string array variable?

I am trying to populate a a spinner but I am getting an error with my String array saying "Array constants can only be used in initializers". My code works fine when i employ the string array as a local variable, but as a global variable it doesn't. I really need to be able to use my string array as a global variable. Thank you in advance. Here is my code:
deleteselection = (Spinner)view.findViewById(R.id.deletespinner);
ArrayAdapter<String> adapterdeletetype;
//createdenominationsarray = getResources().getStringArray(R.array.createdenominations); //<--works
//String [] createdenominationsarray = {"Select Portfolio", "Two", "Three"}; //<--works
createdenominationsarray = {"Select Portfolio", "Two", "Three"};// <--doesn'twork
adapterdeletetype = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,createdenominationsarray){
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent)
{
View v = null;
// If this is the initial dummy entry, make it hidden
if (position == 0) {
TextView tv = new TextView(getContext());
tv.setHeight(0);
tv.setVisibility(View.GONE);
v = tv;
}
else {
// Pass convertView as null to prevent reuse of special case views
v = super.getDropDownView(position, null, parent);
}
// Hide scroll bar because it appears sometimes unnecessarily, this does not prevent scrolling
parent.setVerticalScrollBarEnabled(false);
return v;
}
};
adapterdeletetype.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
denominationselection.setAdapter(adapterdeletetype);
I did the same thing for one of my project and it works for me. Below is the code snippet for your reference..
ArrayList<String> languages = new ArrayList<String>();
languages.add("English");
languages.add("German");
languages.add("French");
ArrayAdapter<String> langAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,languages);
ListView lv =(ListView)findViewById(R.id.listmain);
lv.setAdapter(langAdapter);
lv.setOnItemClickListener(new listclklisten(MainActivity.this));
public class listclklisten implements OnItemClickListener{
private Context parent;
public listclklisten(Context p){
parent=p;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TO DO your code here
}
}
inside string.xml Write:
<string-array name="spinner_array_environtment">
<item>Test</item>
<item>Production</item>
</string-array>
Inside your MainActivity.java :
public class MainActivity extends Activity {
Spinner spinner_environment;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner_environment = (Spinner) findViewById(R.id.spinnerview);
adapter =ArrayAdapter.createFromResource(this, R.array.spinner_array_environtment,R.layout.spinner_phone);
adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinner_environment.setAdapter(adapter);
}
Inside spinner_phone.xml :
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/spinnerTarget"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="13dp"
android:textColor="#4C4646" />
try this out. Hope it will help you.

Android, Null Pointer Exception on ListView test code

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

Android Spinner databind using array list

I have a array list like this:
private ArrayList<Locations> Artist_Result = new ArrayList<Location>();
This Location class has two properties: id and location.
I need to bind my ArrayList to a spinner. I have tried it this way:
Spinner s = (Spinner) findViewById(R.id.SpinnerSpcial);
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item, Artist_Result);
s.setAdapter(adapter);
However, it shows the object's hexadecimal value. So I think I have to set display the text and value for that spinner controller.
The ArrayAdapter tries to display your Location-objects as strings (which causes the Hex-values), by calling the Object.toString()-method. It's default implementation returns:
[...] a string consisting of the name of the class of which the object
is an instance, the at-sign character `#', and the unsigned
hexadecimal representation of the hash code of the object.
To make the ArrayAdadpter show something actually useful in the item list, you can override the toString()-method to return something meaningful:
#Override
public String toString(){
return "Something meaningful here...";
}
Another way to do this is, to extend BaseAdapter and implement SpinnerAdapter to create your own Adapter, which knows that the elements in your ArrayList are objects and how to use the properties of those objects.
[Revised] Implementation Example
I was playing around a bit and I managed to get something to work:
public class Main extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create and display a Spinner:
Spinner s = new Spinner(this);
AbsListView.LayoutParams params = new AbsListView.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT
);
this.setContentView(s, params);
// fill the ArrayList:
List<Guy> guys = new ArrayList<Guy>();
guys.add(new Guy("Lukas", 18));
guys.add(new Guy("Steve", 20));
guys.add(new Guy("Forest", 50));
MyAdapter adapter = new MyAdapter(guys);
// apply the Adapter:
s.setAdapter(adapter);
// onClickListener:
s.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
/**
* Called when a new item was selected (in the Spinner)
*/
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
Guy g = (Guy) parent.getItemAtPosition(pos);
Toast.makeText(
getApplicationContext(),
g.getName()+" is "+g.getAge()+" years old.",
Toast.LENGTH_LONG
).show();
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
});
}
/**
* This is your own Adapter implementation which displays
* the ArrayList of "Guy"-Objects.
*/
private class MyAdapter extends BaseAdapter implements SpinnerAdapter {
/**
* The internal data (the ArrayList with the Objects).
*/
private final List<Guy> data;
public MyAdapter(List<Guy> data){
this.data = data;
}
/**
* Returns the Size of the ArrayList
*/
#Override
public int getCount() {
return data.size();
}
/**
* Returns one Element of the ArrayList
* at the specified position.
*/
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int i) {
return i;
}
/**
* Returns the View that is shown when a element was
* selected.
*/
#Override
public View getView(int position, View recycle, ViewGroup parent) {
TextView text;
if (recycle != null){
// Re-use the recycled view here!
text = (TextView) recycle;
} else {
// No recycled view, inflate the "original" from the platform:
text = (TextView) getLayoutInflater().inflate(
android.R.layout.simple_dropdown_item_1line, parent, false
);
}
text.setTextColor(Color.BLACK);
text.setText(data.get(position).name);
return text;
}
}
/**
* A simple class which holds some information-fields
* about some Guys.
*/
private class Guy{
private final String name;
private final int age;
public Guy(String name, int age){
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
}
I fully commented the code, if you have any questions, don't hesitate to ask them.
Simplest Solution
After scouring different solutions on SO, I found the following to be the simplest and cleanest solution for populating a Spinner with custom Objects. Here's the full implementation:
Location.java
public class Location{
public int id;
public String location;
#Override
public String toString() {
return this.location; // What to display in the Spinner list.
}
}
res/layout/spinner.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="14sp"
android:textColor="#FFFFFF"
android:spinnerMode="dialog" />
res/layout/your_activity_view.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="fill_parent"
android:orientation="vertical">
<Spinner
android:id="#+id/location" />
</LinearLayout>
In Your Activity
// In this case, it's a List of Locations, but it can be a List of anything.
List<Location> locations = Location.all();
ArrayAdapter locationAdapter = new ArrayAdapter(this, R.layout.spinner, locations);
Spinner locationSpinner = (Spinner) findViewById(R.id.location);
locationSpinner.setAdapter(locationAdapter);
// And to get the actual Location object that was selected, you can do this.
Location location = (Location) ( (Spinner) findViewById(R.id.location) ).getSelectedItem();
Thanks to Lukas' answer above (below?) I was able to get started on this, but my problem was that his implementation of the getDropDownView made the dropdown items just a plain text - so no padding and no nice green radio button like you get when using the android.R.layout.simple_spinner_dropdown_item.
So as above, except the getDropDownView method would be:
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent)
{
if (convertView == null)
{
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(android.R.layout.simple_spinner_dropdown_item, null);
}
TextView textView = (TextView) convertView.findViewById(android.R.id.text1);
textView.setText(items.get(position).getName());
return convertView;
}
Well, am not gonna confuse with more details.
Just create your ArrayList and bind your values like this.
ArrayList tExp = new ArrayList();
for(int i=1;i<=50;i++)
{
tExp.add(i);
}
Assuming that you have already a spinner control on your layout say with id, spinner1. Add this code below.
Spinner sp = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> adp1=new ArrayAdapter<String>this,android.R.layout.simple_list_item_1,tExp);
adp1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(adp1);
All the above code goes under your onCreate function.
Thank Lukas, you help me a lot.
I d'like to improve your answer.
If you just want to access the selected item later, you can use this :
Spinner spn = (Spinner) this.findViewById(R.id.spinner);
Guy oGuy = (Guy) spn.getSelectedItem();
So you don't have to use the setOnItemSelectedListener() in your initialisation :)

Android custom listview

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

Categories

Resources