I have a problem with the following exception:
exception:java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
I have an Adapter class:
public class SimpleAdapter extends BaseAdapter {
private LayoutInflater lInflater;
private String [] simpleValueList;
public SimpleAdapter(Context context, String[] simpleValueList) {
lInflater = LayoutInflater.from(context);
this.simpleValueList = simpleValueList;
}
#Override
public int getCount() {
return simpleValueList.length;
}
#Override
public Object getItem(int position) {
return simpleValueList[position];
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.test, parent, false);
TextView textSimple = view.findViewById(R.id.simple_list);
textHours.setText(simpleValueList[position]);
}
return view;
}
}
my CustomView class:
public class SimpleView extends View {
private String[] valueList = {"aa", "2", "bb", "3"};
private ListView listView;
private SimpleAdapter simpleAdapter;
public SimpleView(Context context, ViewGroup mviewGroup) {
super(context);
inflate(context, R.layout.test, mviewGroup);
listView = findViewById(R.id.simple_list);
simpleAdapter = new SimpleAdapter(context, valueList);
listView.setAdapter(simpleAdapter);
}
}
my Activity class:
public class SimpleActivity extends AppCompatActivity {
private SimpleView simpleView;
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout linearLayout = findViewById(R.id.custom_view);
simpleView = new SimpleView(this, linearLayout);
linearLayout.addView(simpleView);
}
}
test. xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="100dp"
android:layout_height="220dp"
android:layout_gravity="center">
<ListView
android:id="#+id/simple_list"
android:layout_width="100dp"
android:layout_height="100dp"
android:background="#color/orange" />
</LinearLayout>
my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/custom_view"
android:layout_width="400dp"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>
If I do not add the Adapter in the SimpleView class then it works. But if I add the Adapter in the SimpleView class I get the exception:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference. (at ...here: listView.setAdapter(simpleAdapter); (simpleView = new SimpleView(this, linearLayout));
The problem is that the code is calling the SimpleView's version of findViewById which is using test.xml, but the ListView is located in activity_main.xml in the SimpleActivity.
listView = findViewById(R.id.custom_view1);
This will return null because there is no view with the ID R.id.custom_view1 inside SimpleView.
There probably is not any need for the SimpleView class. The following lines of code could be moved into onCreate in SimpleActivity:
listView = findViewById(R.id.custom_view1);
simpleAdapter = new SimpleAdapter(context, valueList);
listView.setAdapter(simpleAdapter);
If you do want to create a CustomView on the other hand, all the views you are working with need to be in R.layout.test. You could in theory, move the ListView in there, but I think it is probably unnecessary. I would just inflate, find it and set the adapter in onCreate of the Activity.
If you do want an abstraction to contain the ListView, I would investigate putting it into a Fragment.
EDIT:
If it has to be done with a custom view then make sure the following is in test.xml:
<ListView
android:id="#+id/custom_view1"
android:layout_width="71dp"
android:layout_height="77dp"
android:orientation="vertical">
It is important to use this ID android:id="#+id/custom_view1 so that it matches up with listView = findViewById(R.id.custom_view1); in the Java code.
To void the crash you are getting now:
public SimpleView(Context context, ViewGroup mviewGroup) {
super(context);
View layout = inflate(context, R.layout.test, mviewGroup);
listView = layout.findViewById(R.id.simple_list);
simpleAdapter = new SimpleAdapter(context, valueList);
listView.setAdapter(simpleAdapter);
}
Make sure you do the find on the value being returned from inflate.
=== Code Dump ===:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/custom_view_container"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"/>
test.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center">
<ListView
android:id="#+id/simple_list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="100dp"
android:layout_height="220dp"
android:layout_gravity="center">
<TextView
android:id="#+id/txt"
android:layout_width="100dp"
android:layout_height="100dp"/>
</LinearLayout>
ActivityMain.java:
package com.example.myapplication2000;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout linearLayout = findViewById(R.id.custom_view_container);
SimpleView simpleView = new SimpleView(this, linearLayout);
linearLayout.addView(simpleView);
}
}
SimpleView.java:
package com.example.myapplication2000;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class SimpleView extends View {
private String[] valueList = {"aa", "2", "bb", "3"};
private ListView listView;
private SimpleAdapter simpleAdapter;
public SimpleView(Context context, ViewGroup mviewGroup) {
super(context);
View layout = inflate(context, R.layout.test, mviewGroup);
listView = layout.findViewById(R.id.simple_list);
simpleAdapter = new SimpleAdapter(context, valueList);
listView.setAdapter(simpleAdapter);
}
public class SimpleAdapter extends BaseAdapter {
private LayoutInflater lInflater;
private String [] simpleValueList;
public SimpleAdapter(Context context, String[] simpleValueList) {
lInflater = LayoutInflater.from(context);
this.simpleValueList = simpleValueList;
}
#Override
public int getCount() {
return simpleValueList.length;
}
#Override
public Object getItem(int position) {
return simpleValueList[position];
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.row, parent, false);
TextView textSimple = view.findViewById(R.id.txt);
textSimple.setText(simpleValueList[position]);
}
return view;
}
}
}
Sorry, I might have changed one or two of the names. I hope it does not cause any confusion.
Also, you can clean-up the layout. There are a few 'extra' LinearLayouts that I picked up from pasting in your code, but they are not really needed.
But this code is displaying 4 list items on my device.
Related
This question already has answers here:
ListView not showing at all
(1 answer)
Null pointer Exception - findViewById()
(12 answers)
Closed 4 years ago.
I have a custom Adapter called MyAdapter where i'm trying to load a layout which supposedly should be inserted into a listview, but even when Android is not giving errors the view is showing in blank.
In the next screenshot, i show what i get after build my app.
What i'm expecting to load is my layout into my listview:
ListView
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Fragments.NewsFragment">
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"></ListView>
</FrameLayout>
Layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="#+id/list_item"
android:layout_height="80dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/imageabdcf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_margin="25dp"
tools:srcCompat="#android:drawable/btn_star_big_on" />
<TextView
android:id="#+id/textabcdf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:text="TextView" />
</LinearLayout>
NewsFragment.java
public class NewsFragment extends Fragment {
private ListView listView;
private List<String> names;
public NewsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_news, container, false);
listView = (ListView) v.findViewById(R.id.listView);
names = new ArrayList<String>();
names.add("Fernando");
names.add("Roberto");
names.add("Torres");
names.add("Urban");
ArrayAdapter<String> adapter = new ArrayAdapter<>(v.getContext(), android.R.layout.simple_list_item_1, names);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getView().getContext(), "Clicked: " + names.get(position), Toast.LENGTH_LONG).show();
}
});
MyAdapter myAdapter = new MyAdapter(v.getContext(), R.layout.card_view_news, names);
listView.setAdapter(myAdapter);
// Inflate the layout for this fragment
return v;
}
}
MyAdapter.java
public class MyAdapter extends BaseAdapter {
private Context context;
private int layout;
private List<String> names;
public MyAdapter(Context context, int layout, List<String> names) {
this.context = context;
this.layout = layout;
this.names = names;
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int position) {
return this.names.get(position);
}
#Override
public long getItemId(int id) {
return id;
}
#Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
View v = convertView;
LayoutInflater layoutInflater = LayoutInflater.from(this.context);
v = layoutInflater.inflate(R.layout.fragment_news, null);
String currentName = names.get(position);
//currentName = (String) getItem(position);
TextView textView = (TextView) v.findViewById(R.id.textabcdf);
textView.setText(currentName);
return v;
}
}
And what i'm expecting for is something like:
I've utilized the following code from another StackOverflow post (How could i add a spinner in listview with its listitems by using customadapter?):
package com.android.main;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.Spinner;
public class DemoListSpinnerActivity extends Activity {
ListView _listview;
String[] itemsarray=new String[]{"one","two","three"};
ArrayAdapter<String> adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
adapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,itemsarray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
_listview=(ListView)findViewById(R.id.listView1);
_listview.setAdapter(new CustomAdapter(this));
}
private class CustomAdapter extends BaseAdapter
{
LayoutInflater inflater;
public CustomAdapter(Context context)
{
inflater=LayoutInflater.from(context);
}
public int getCount() {
// TODO Auto-generated method stub
return 1;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int arg0, View convertview, ViewGroup arg2) {
ViewHolder viewHolder;
if(convertview==null)
{
convertview=inflater.inflate(R.layout.listrow,null);
viewHolder=new ViewHolder();
viewHolder.spinner=(Spinner)convertview.findViewById(R.id.spinner1);
viewHolder.spinner.setAdapter(adapter);
convertview.setTag(viewHolder);
}
else
{
viewHolder=(ViewHolder)convertview.getTag();
}
return convertview;
}
public class ViewHolder
{
Spinner spinner;
}
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello"
/>
<ListView android:layout_height="wrap_content" android:id="#+id/listView1" android:layout_width="match_parent"></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">
<Spinner android:layout_height="wrap_content" android:layout_width="match_parent" android:id="#+id/spinner1"></Spinner>
</LinearLayout>
While the layouts are obviously different from mine... I have a button that I want to be able to add a new ListViewItem.
And this new Spinner (inside of the ListViewItem) needs to be autopopulated with the String[].
So assuming I have:
FloatingActionButton addButton= (FloatingActionButton) findViewById(R.id.addButton);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Add New Spinner Item
// Populate Spinner with String[]
}
});
I'm looking to add a new spinner item to the ListView, and then populate that list with the string[] earlier defined.
Hi All I am Using a GridView Tool From The Android To Display The Image As A menu
I am Using this Code in A class I Name It ImageAdapter extends BaseAdapter
I've Use This Code Bellow
package com.example.gridviewtest;
import com.example.gridviewtest.R;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.content.Context;
import android.widget.GridView;
import android.widget.ImageView;
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public Integer[] mThumbIds =
{
R.drawable.pic1, R.drawable.pic2, R.drawable.pic3,
R.drawable.pic4, R.drawable.pic5, R.drawable.pic6,
R.drawable.pic7, R.drawable.pic8, R.drawable.pic9
};
public ImageAdapter(Context c){
mContext = c;
}
#Override
public int getCount() {
return mThumbIds.length;
}
#Override
public Object getItem(int position) {
return mThumbIds[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
imageView.setImageResource(mThumbIds[position]);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(200, 200));
return imageView;
}
}
I try to use a
imageView.setText("Something");
but it doesn't Works With Me
the require is to add a caption under a picture in a cell
Can You Help Me On This ...
Best Regards ...
You could use a custom adapter (as for a listView):
public class CustomAdapter extends ArrayAdapter<Integer> {
Activity context;
ArrayList<Integer> objects;
public CustomAdapter(Activity context, ArrayList<Integer> objects) {
super(context, R.layout.row, objects);
this.context = context;
this.objects = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.row, parent, false);
}
ImageView i = (ImageView) convertView.findViewById(R.id.icon);
i.setBackgroundResource(objects.get(position));
TextView t = (TextView) convertView.findViewById(R.id.title);
t.setText("title");
return convertView;
}
}
And of course you will set this it as an adapter for the gridView.
EDIT: Of course instead of ArrayAdapter<Integer> you could be extending ArrayAdapter<YourHolder>.
class YourHolder {
public int ID;
public String title;
}
EDIT 2: Adding a functional piece of code.
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<GridView
android:id="#+id/grid_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:numColumns="3"
android:gravity="center_horizontal"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"
android:padding="10dp"
android:background="#600000ff"
/>
</RelativeLayout>
grid_item_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#6000ff00"
android:padding="4dp">
<TextView
android:id="#+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="label"
android:layout_gravity="center_horizontal"/>
<FrameLayout
android:id="#+id/holder"
android:layout_width="100dp"
android:layout_height="100dp">
<ImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"/>
</FrameLayout>
</LinearLayout>
CustomAdapter.class
public class CustomAdapter extends ArrayAdapter<Integer> {
private Activity context;
private ArrayList<Integer> objects;
public CustomAdapter(Activity context, ArrayList<Integer> objects) {
super(context, R.layout.grid_item_layout, objects);
this.context = context;
this.objects = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
LayoutInflater i = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = (View) i.inflate(R.layout.grid_item_layout, parent, false);
}
TextView t = (TextView) convertView.findViewById(R.id.label);
ImageView i = (ImageView) convertView.findViewById(R.id.image);
t.setText("label " + position);
i.setImageResource(objects.get(position));
return convertView;
}
MainActivity
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView g = (GridView) findViewById(R.id.grid_view);
CustomAdapter adapter = new CustomAdapter(this, getData());
g.setAdapter(adapter);
}
public ArrayList<Integer> getData(){
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(R.drawable.pic1);
// add 2 - 11
list.add(R.drawable.pic12);
return list;
}
}
Final look:
Note: From my experience when there are a lot of pictures in the gridView scrolling becomes slow and laggy, however it's not the topic of your question, so in case it's also a problem, please see Lazy load of images in ListView
I am working on Android project. I follow tutorial from http://www.vogella.com/articles/AndroidSQLite/article.html but I stuck on something. Tutorial shows how to use Class with 1 String object. I am working with 2 String objects. So I changed few things (add new String to my class, change layout.simple_list_item_1 to android.R.layout.simple_list_item_2 etc.) And now the question is - how to make something to get Stoliki class objects (override toString() gives me only 1 item, so It's useless).
Class Stoliki
public class Stoliki {
private long id;
private String numer;
private String opis;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getNumer() {
return numer;
}
public void setNumer(String numer) {
this.numer = numer;
}
public String getOpis() {
return opis;
}
public void setOpis(String opis) {
this.opis = opis;
}
}
Activity
import android.app.ListActivity;
import android.os.Bundle;
import java.util.List;
import java.util.Random;
import android.view.View;
import android.widget.ArrayAdapter;
public class FirstGridPage extends ListActivity {
private StolikiDataSource datasource;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_list_stoliki);
datasource = new StolikiDataSource(this);
datasource.open();
List<Stoliki> values = datasource.getAllStoliki();
// Use the SimpleCursorAdapter to show the
// elements in a ListView
ArrayAdapter<Stoliki> adapter = new ArrayAdapter<Stoliki>(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
}
// Will be called via the onClick attribute
// of the buttons in main.xml
public void onClick(View view) {
#SuppressWarnings("unchecked")
ArrayAdapter<Stoliki> adapter = (ArrayAdapter<Stoliki>) getListAdapter();
Stoliki stolik = null;
switch (view.getId()) {
case R.id.add:
String[] stoliki_numer = new String[] { "1", "2", "3" };
String[] stoliki_opis = new String[] { "Czerwony", "Niebieski", "Zielony" };
int nextInt = new Random().nextInt(3);
// Save the new comment to the database
stolik = datasource.createStolik(stoliki_numer[nextInt], stoliki_opis[nextInt]);
adapter.add(stolik);
break;
case R.id.delete:
if (getListAdapter().getCount() > 0) {
stolik = (Stoliki) getListAdapter().getItem(0);
datasource.deleteStolik(stolik);
adapter.remove(stolik);
}
break;
}
adapter.notifyDataSetChanged();
}
#Override
protected void onResume() {
datasource.open();
super.onResume();
}
#Override
protected void onPause() {
datasource.close();
super.onPause();
}
}
http://www.youtube.com/watch?v=wDBM6wVEO70. Listview talk by Romain guy( android developer at google).
Main.xml
<ListView android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:focusableInTouchMode="false"
android:listSelector="#android:color/transparent"
android:layout_weight="2"
android:headerDividersEnabled="false"
android:footerDividersEnabled="false"
android:dividerHeight="8dp"
android:divider="#000000"
android:cacheColorHint="#000000"
android:drawSelectorOnTop="false">
</ListView>
</LinearLayout>
Customw row. row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:background="#ffffff"
>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:background="#drawable/itembkg"
/>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:text="TextView" />
</LinearLayout>
public class CustomListView extends Activity {
/** Called when the activity is first created. */
ListView lv1;
Customlistadapter cus;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Button b= (Button) findViewById(R.id.remove);
lv1 = (ListView) findViewById(R.id.list);
cus= new Customlistadapter(this);
lv1.setAdapter(cus);
}
}
Custom list adapter. Inflate custom layout for each row.
public class Customlistadapter extends ArrayAdapter {
private LayoutInflater mInflater;
Context c;
public Customlistadapter(CustomListView customListView) {
super(customListView, 0);
// TODO Auto-generated constructor stub
this.mInflater = LayoutInflater.from(customListView);
c=customListView;
}
public int getCount() {
return 20; // number of listview rows.
}
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.row, 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 //use a viewholder for smooth scrolling and performance.
{
TextView tv1,tv2;
}
}
Edit:
Your activity will have a listview. This is set in oncreate setContentView(R.layout.activity_main);. The main layout will have a listview. You set the adapter of listview as listview.setAdapter(youradapter);
Then listview will have custom layout ie row.xml inflated for each row item. You custom adapter for listview is where the row.xml is inflated. You defined your class CustomAdapter which extends ArrayAdapter. You override a set of methods.
getCount() --- size of listview.
getItem(int position) -- returns the position
getView(int position, View convertView, ViewGroup parent)
// position is the position in the listview.
//convertview - view that is tobe inflated
// you will return the view that is infated.
You will have to use a viewholder for smooth scrolling and performance. Imagine 1000 rows is lstview with images it may cause memory exceptions. One way to get rid of this is to recycle views. The visible views(rows) are not recycled. The video in the link at the top has a detail explanation on the topic
activity_main.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"
android:background="#0095FF">
<ListView android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:focusableInTouchMode="false"
android:listSelector="#android:color/transparent"
android:layout_weight="2"
android:headerDividersEnabled="false"
android:footerDividersEnabled="false"
android:dividerHeight="8dp"
android:divider="#000000"
android:cacheColorHint="#000000"
android:drawSelectorOnTop="false">
</ListView>
</LinearLayout>
row.xml (layout inflated for each listview row)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Header" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="80dp"
android:layout_gravity="center"
android:text="TextView" />
</LinearLayout>
MainActivity
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView ll = (ListView) findViewById(R.id.list);
CustomAdapter cus = new CustomAdapter();
ll.setAdapter(cus);
}
class CustomAdapter extends BaseAdapter
{
LayoutInflater mInflater;
public CustomAdapter()
{
mInflater = (LayoutInflater) MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 30;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder vh;
vh= new ViewHolder();
if(convertView==null )
{
convertView=mInflater.inflate(R.layout.row, parent,false);
vh.tv2= (TextView)convertView.findViewById(R.id.textView2);
vh.tv1= (TextView)convertView.findViewById(R.id.textView2);
}
else
{
convertView.setTag(vh);
}
vh.tv1.setText("my text");
vh.tv2.setText("Postion = "+position);
return convertView;
}
class ViewHolder
{
TextView tv1,tv2;
}
}
}
I create a custom listview and it extend ListActivity and works fine. But I want to put a ListView in my main activity that extends Activity. How can I do this?
For example, I want to put a custom ListView in my one part of my screen not the screen filled by only ONE ListView that extends ListActivity.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/lvresult"
android:paddingTop="2dip"
android:paddingBottom="3dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
and this is MyListActivity:
package Dic.proj.pkg;
import java.util.ArrayList;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MyListActivity extends ListActivity {
EditText et;
TextView tv;
TextView tvresult;
String resulttext;
ArrayList<String> mArrayList = new ArrayList<String>();
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2" };
// Use your own layout
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.customlist, R.id.lvresult, values);
setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
String item = (String) getListAdapter().getItem(position);
Toast.makeText(this, item + " selected", Toast.LENGTH_LONG).show();
}
}
This works fine but I can see only one List view on screen. I want to put this custom Listview in my main activity. How can I do this?
you do like below:-
public class StoreListActivity extends Activity {
private List<Store> mStores;
private StoreAdapter mStoreAdapter;
private ListView mListView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.store_list);
mListView = (ListView) findViewById(R.id.store_listview);
mStores = getTheStoresFromSomewhere();
mStoreAdapter = new StoreAdapter(this, mStores);
mListView.setAdapter(mStoreAdapter);
}
// roadmapscreen.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:background="#ffffff"
android:layout_height="fill_parent"
>
<ListView
android:cacheColorHint="#00000000"
android:id="#+id/roadmaplist"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:listSelector="#android:color/transparent"
android:divider="#null"/>
</RelativeLayout>
//roadmap_list_item
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ffffff"
>
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello"
android:textColor="#000000"
android:layout_marginTop="12dp"
android:layout_marginLeft="12dp"
android:textStyle="bold"
/>
</RelativeLayout>
//Main Activity
public class RoadmapActivity extends Activity {
ListView lv;
ArrayList<String> catList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.roadmapscreen);
catList=new ArrayList<String>();
catList.add("Work");
catList.add("Time");
catList.add("Money");
catList.add("Health");
catList.add("Fun & Recreation");
catList.add("Friends & Relatives");
catList.add("Spirituality & Growth");
catList.add("Home & Housework");
catList.add("Death & Dying");
catList.add("Sexual Intimacy");
catList.add("Marriage/Commitment");
catList.add("Children");
catList.add("Miscellaneous");
lv=(ListView)findViewById(R.id.roadmaplist);
lv.setAdapter(new CustomAdapter());
}
public class CustomAdapter extends BaseAdapter
{
public int getCount() {
// TODO Auto-generated method stub
return catList.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder holder;
LayoutInflater inflater=(LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
if (convertView == null)
{
convertView=inflater.inflate(R.layout.roadmap_list_item, null);
holder = new ViewHolder();
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.txt1=(TextView)convertView.findViewById(R.id.text);
convertView.setTag(holder);
holder.txt1.setText(catList.get(position));
convertView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
return convertView;
}
class ViewHolder {
TextView txt1;
}
}
}