I'm trying to make a custom listview. I'm not getting error and data are correctly added to my ArrayList but I see nothing on screen. Is there a problem with a layout or the adapter ?
Here is my list row layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/nomtv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"/>
<TextView
android:id="#+id/desctv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/debuttv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/nomtv"
android:layout_toEndOf="#+id/nomtv"/>
<TextView
android:id="#+id/fintv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/desctv"
android:layout_toEndOf="#+id/desctv"/>
</RelativeLayout>
Here is my custom adapter:
public class ListTacheAdapter extends ArrayAdapter<String> {
ArrayList<Tache> taches;
ListView listView = null;
final Context context;
View rowView = null;
TextView nom = null, desc = null, debut = null, fin = null;
public ListTacheAdapter(Context context, ArrayList<Tache> taches) {
super(context, R.layout.row_tache);
// TODO Auto-generated constructor stub
this.context = context;
this.taches = taches;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.row_tache, parent, true);
nom = (TextView) rowView.findViewById(R.id.nomtv);
desc = (TextView) rowView.findViewById(R.id.desctv);
debut = (TextView) rowView.findViewById(R.id.debuttv);
fin = (TextView) rowView.findViewById(R.id.fintv);
nom.setText(taches.get(position).getNom());
desc.setText(taches.get(position).getDescription());
debut.setText(taches.get(position).getDebut());
fin.setText(taches.get(position).getFin());
return rowView;
}
}
My activity layout:
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.testapp.ShowActivity" >
<ListView
android:id="#+id/list"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#D46A6A"
android:dividerHeight="1dp"/>
</RelativeLayout>
And my activity class:
public class ShowActivity extends Activity {
ArrayList<Tache> taches;
ListView listView;
TacheDAO td = new TacheDAO(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show);
td.open();
taches = td.getAllTache();
td.close();
ListTacheAdapter lta = new ListTacheAdapter(this, taches);
listView = (ListView) findViewById(R.id.list);
listView.setAdapter(lta);
}
}
I'm also a beginner, so i tell what i'd try:
I believe that the problem is in the calling to super() on the onCreate method of the adapter. Try passing super(context, -1) insted of super(context, R.layout.row_tache).
Let me know.
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am creating a ViewPager in activity_table.xml.
This ViewPager has two pages which both share the same layout: list.xml.
This layout contains a ListView which I am trying to create an Adapter for.
The app compiles correctly but crashes when it tries to add the said Adapter to the ListView with a
NullPointerException when attempting to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference.
I have heard that I have to "load" a layout before I can use the Views it contains, but I how do I do that?
I have tried setContentView(R.layout.list), but it throws the same error...
Table.java
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
ViewPager viewPager = (ViewPager) findViewById(R.id.container);
viewPager.setAdapter(sectionsPagerAdapter);
String[] tmp = new String[mainTable.length-2];
ListView listView = (ListView)findViewById(R.id.listView);
ListAdapter listAdapter = new ListAdapter(this,R.layout.list_item,tmp);
listView.setAdapter(listAdapter);
public static class TableFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section number";
public TableFragment() {
}
public static TableFragment newInstance(int sectionNumber) {
TableFragment fragment = new TableFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER,sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.list,container,false);
TextView title = (TextView) rootView.findViewById(R.id.title);
if(getArguments().getInt(ARG_SECTION_NUMBER) == 1)
title.setText("Heute");
else if(getArguments().getInt(ARG_SECTION_NUMBER) == 2)
title.setText("Morgen");
return rootView;
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return TableFragment.newInstance(position + 1);
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "today";
case 1:
return "tomorrow";
}
return null;
}
}
public class ListAdapter extends ArrayAdapter<String> {
public ListAdapter(Context context, int textViewResourceId) {
super(context,textViewResourceId);
}
public ListAdapter(Context context, int resource, String[] items) {
super(context,resource,items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if(v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.list_item, null);
}
String p = getItem(position);
if(p!=null) {
TextView grade = (TextView) v.findViewById(R.id.grade);
TextView hour = (TextView) v.findViewById(R.id.hour);
TextView course = (TextView) v.findViewById(R.id.course);
TextView teacher = (TextView) v.findViewById(R.id.teacher);
TextView room = (TextView) v.findViewById(R.id.room);
TextView description = (TextView) v.findViewById(R.id.description);
try {
grade.setText(tableData[position][1]);
hour.setText(tableData[position][2]);
course.setText(tableData[position][3]);
teacher.setText(tableData[position][4]);
room.setText(tableData[position][5]);
description.setText(tableData[position][6]);
} catch (ArrayIndexOutOfBoundsException e) {
return v;
}
}
return v;
}
}
activity_table.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="de.fuchstim.vertretungsplan.Table">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/appbar_padding_top"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/AppTheme.PopupOverlay">
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"/>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/fab_margin"
android:layout_gravity="bottom|right"
app:srcCompat="#drawable/reload_arrow_white" />
</android.support.design.widget.CoordinatorLayout>
list.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:text="Heute (25.10.16)"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/title"
android:textAppearance="#android:style/TextAppearance.DeviceDefault.DialogWindowTitle"
android:textAlignment="center" />
<GridLayout android:layout_gravity="start"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/grade"
android:layout_height="wrap_content"
android:text="Klasse"
android:layout_row="0"
android:layout_column="0"
android:layout_width="0dp"
android:textSize="14sp"
android:layout_columnWeight="40"
android:paddingStart="10dp" />
<TextView
android:text="Stunde"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/hour"
android:layout_row="0"
android:layout_column="1"
android:layout_columnWeight="15"/>
<TextView
android:text="Lehrer"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/teacher"
android:layout_row="0"
android:layout_column="3"
android:layout_columnWeight="15"/>
<TextView
android:text="Kurs"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/course"
android:layout_row="0"
android:layout_column="2"
android:layout_columnWeight="15"/>
<TextView
android:text="Raum"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/room"
android:layout_row="0"
android:layout_column="4"
android:layout_columnWeight="15"/>
</GridLayout>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:id="#+id/listView" />
</LinearLayout>
I have tried setContentView(R.layout.list), but it throws the same error...
First, you need to use setContentView(R.layout.activity_table) instead.
Second, you cannot find the ListView from the Activity, since it is contained within the Fragment layout.
See here? Your ListView is in the same layout as this title element, so you need to find the ListView here...
View rootView = inflater.inflate(R.layout.list,container,false);
TextView title = (TextView) rootView.findViewById(R.id.title);
Move that ListView code from the Activity to the Fragment. And use getActivity() for the Adapter within the Fragment instead of this to get the Context.
That is where the #+id/listView value exists. That layout is searched with rootView.findViewById.
Since, you did not get null pointer at this location :
ViewPager viewPager = (ViewPager) findViewById(R.id.container);
viewPager.setAdapter(sectionsPagerAdapter);
So, this means you are using :
setContentView(R.layout.activity_table);
Because viewpager is only in above layout, and since listview is not in this layout xml file, you get null pointer on :
ListView listView = (ListView)findViewById(R.id.listView);
ListAdapter listAdapter = new ListAdapter(this,R.layout.list_item,tmp);
listView.setAdapter(listAdapter);
because listview in null, not present in activity_table xml file.
You need to set adapter in OnCreateView() :
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.list,container,false);
TextView title = (TextView) rootView.findViewById(R.id.title);
// Add below ...
String[] tmp = new String[mainTable.length-2];
ListView listView = (ListView)rootView.findViewById(R.id.listView);
ListAdapter listAdapter = new ListAdapter(getActivity(),R.layout.list_item,tmp);
listView.setAdapter(listAdapter);
// ends here ...
if(getArguments().getInt(ARG_SECTION_NUMBER) == 1)
title.setText("Heute");
else if(getArguments().getInt(ARG_SECTION_NUMBER) == 2)
title.setText("Morgen");
return rootView;
}
Hope this helps !
The problem is getView method does not get called even when I do setAdapter on listView. Please see may code below. I dont get any error message. It just does not display reviewer data. Would you please suggest what I am doing incorrect.
MovieReviewerFragmemt class I have below code:
#Override
protected void onPostExecute (ArrayList movieDetailsArray){
getMovieArrayList(movieDetailsArray);
ListView listView = (ListView) rootView.findViewById(R.id.movie_detail_reviewerlist);
MovieAddlDetail detail = (MovieAddlDetail) movieDetailsArray.get(0);
MovieReviewers[] list = detail.getReviewerArrayList();
Log.v(LOG_TAG, "MovieReviewerFragment - CustomReviewerAdapter - calling adapter");
movieDetailAdapter = new CustomReviewerAdapter(getActivity(), list);
movieDetailAdapter.notifyDataSetChanged();
listView.setAdapter(movieDetailAdapter);
}
CustomerReviewAdapter:
public class CustomReviewerAdapter extends ArrayAdapter {
private Context context;
private LayoutInflater inflater;
private final String LOG_TAG1 = CustomReviewerAdapter.class.getSimpleName();
private MovieReviewers[] reviewers;
public CustomReviewerAdapter(Context context, MovieReviewers[] reviewers) {
super(context, R.layout.fragment_detail, reviewers);
Log.v(LOG_TAG1, "CustomReviewerAdapter - constructor");
this.context = context;
this.reviewers = reviewers;
inflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.v(LOG_TAG1, "CustomReviewerAdapter - getView");
if (convertView == null) {
inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.fragment_detail_reviewer, parent, false);
Log.v(LOG_TAG1, "CustomReviewerAdapter - getView - convertview was null");
}
TextView textView1 = (TextView) convertView.findViewById(R.id.movie_detail_reviewerlist_author);
TextView textView2 = (TextView) convertView.findViewById(R.id.movie_detail_reviewerlist_content);
textView1.setText(reviewers[position].getAuthor());
textView2.setText(reviewers[position].getContent());
Log.v(LOG_TAG1, "CustomReviewerAdapter - getView - data set");
return convertView;
}
}
Fragment Detail Reviewer:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id ="#+id/imageView_layout"
android:orientation = "vertical">
<TextView
android:layout_width="match_parent" android:layout_height="wrap_content"
android:id="#+id/movie_detail_reviewerlist_author"
android:textAlignment="center"
android:textStyle="bold"
android:gravity="center_vertical"
android:focusable="false"
android:focusableInTouchMode="false"
android:textAppearance="?android:attr/textAppearanceLarge"
android:descendantFocusability="blocksDescendants"/>
<TextView
android:layout_width="match_parent" android:layout_height="wrap_content"
android:id="#+id/movie_detail_reviewerlist_content"
android:textAlignment="center"
android:textStyle="bold"
android:gravity="center_vertical"
android:focusable="false"
android:focusableInTouchMode="false"
android:textAppearance="?android:attr/textAppearanceLarge"
android:descendantFocusability="blocksDescendants"/>
Fragment Detail:
<?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">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/movie_detail_list"
android:editable="false" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/movie_detail_reviewerlist"
android:editable="false" />
Below is activity from which fragment is being initiated. The first fragment is working fine and is being displayed. However the second fragment is where I dont get anything displayed. Is below correct way to initiate two fragments?
Detail Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Bundle extras = getIntent().getExtras();
intentData = extras.getStringArray("moviedetails");
MovieDetailFragment movieDetailFragment = new MovieDetailFragment();
movieDetailFragment.setMovieDetails(intentData);
MovieReviewerFragment movieReviewerFragment = new MovieReviewerFragment();
movieReviewerFragment.setMovieDetails(intentData);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container_1, movieDetailFragment)
.add(R.id.container_2, movieReviewerFragment)
.commit();
}
}
You must call the LayoutInflater like this:
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
You have to switch the lines
movieDetailAdapter.notifyDataSetChanged();
listView.setAdapter(movieDetailAdapter);
To
listView.setAdapter(movieDetailAdapter);
movieDetailAdapter.notifyDataSetChanged();
First you set the adapter, then you send the notification. If you do this the reverse way, there is no ListView which may display the updated data.
You can automate these notifications with
movieDetailAdapter.setNotifyOnChange(true)
I have one activity that contains text view, buttons, spinner and list view
my main XML file contains :
<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"
android:background="#ffff00"
tools:context="com.example.taxitabriz.MainActivity"
tools:ignore="MergeRootFrame" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="8dp"
android:text="#string/app_name"
android:textSize="35dp"
android:textStyle="bold"
android:textColor="#996600"
android:textAppearance="?android:attr/textAppearanceLarge" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:id="#+id/linearlayout1" >
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#996600"
android:text="#string/exit"
android:background="#drawable/backbutton" />
<Button
android:id="#+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#996600"
android:text="#string/about"
android:background="#drawable/backbutton" />
</LinearLayout>
<Spinner
android:id="#+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="#+id/textView1"
android:layout_marginTop="19dp" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/spinner1"
android:layout_above="#+id/linearlayout1"
android:layout_alignParentRight="true"
android:layout_weight="49.94" >
</ListView>
and part of my java code is here:
ArrayAdapter<String> ard=new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line,s1);
sp.setAdapter(ard);
lv1=(ListView) findViewById(R.id.listView1);
ArrayAdapter<String> ard1=new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line,s1);
lv1.setAdapter(ard1);
but i can't change font color or font type in list view or spinner. how can i do it?
You need to create a CustomListAdapter.
private class CustomListAdapter extends ArrayAdapter {
private Context mContext;
private int id;
private List <String>items ;
public CustomListAdapter(Context context, int textViewResourceId , List<String> list )
{
super(context, textViewResourceId, list);
mContext = context;
id = textViewResourceId;
items = list ;
}
#Override
public View getView(int position, View v, ViewGroup parent)
{
View mView = v ;
if(mView == null){
LayoutInflater vi = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mView = vi.inflate(id, null);
}
TextView text = (TextView) mView.findViewById(R.id.textView);
if(items.get(position) != null )
{
text.setTextColor(Color.WHITE);
text.setText(items.get(position));
text.setBackgroundColor(Color.RED);
int color = Color.argb( 200, 255, 64, 64 );
text.setBackgroundColor( color );
}
return mView;
}
}
The list item looks like this (custom_list.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">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/textView"
android:textSize="20px" android:paddingTop="10dip" android:paddingBottom="10dip"/>
</LinearLayout>
Use the TextView api's to decorate your text to your liking
and you will be using it like this
listAdapter = new CustomListAdapter(YourActivity.this , R.layout.custom_list , mList);
mListView.setAdapter(listAdapter);
If you really want to use androids simple list layout, we see that they declare their textview's identifier as such:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/text1"
style="?android:attr/dropDownItemStyle"
android:textAppearance="?android:attr/textAppearanceLargeInverse"
android:singleLine="true"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:ellipsize="marquee" />
So just make your custom adapter, inflate their layout & find that text view's id. Something like the following:
public final class CustomAdapter extends ArrayAdapter<String> {
private Context context;
ViewHolder holder;
private ArrayList<String> messages;
public CustomAdapter(Context context, ArrayList<String> data) {
this.context = context;
this.messages = data;
Log.d("ChatAdapter", "called constructor");
}
public int getCount() {
return messages.size();
}
public View getView(int position, View convertView, ViewGroup viewGroup) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.simple_dropdown_item_1line, null);
holder = new ViewHolder();
holder.message = (TextView) convertView
.findViewById(R.id.text1);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.message.setText(data.get(position));
holder.message.setTextColor(Color.BLUE);
// don't do this, remember the face variable once just showing explicitly for u
Typeface face=Typeface.createFromAsset(getAssets(), "fonts/HandmadeTypewriter.ttf");
holder.message.setTypeface(face);
return convertView;
}
public static class ViewHolder {
public TextView message;
}
}
Edit: The following is how you would use the custom array adapter in your activity.
// I'm not sure if your sp or lv1 wants the adapter, but
// whatever you require your list view's data to be just
// set the custom adapter to it
CustomAdapter<String> myAdapter = new ArrayAdapter<String>(this, s1);
lv1=(ListView) findViewById(R.id.listView1)
lv1.setAdapter(myAdapter);
You can do like this, add a ListView item in xml,at res/layout/list_item1.xml:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/text1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#0000ff"
android:testStyle="italic"
android:gravity="center_vertical"
android:paddingLeft="6dip"
android:minHeight="?android:attr/listPreferredItemHeight"
/>
then,
ArrayAdapter<String> ard=new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line,s1);
sp.setAdapter(ard);
lv1=(ListView) findViewById(R.id.listView1);
ArrayAdapter<String> ard1=new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line,s1);// **change R.layout.list_item1**
lv1.setAdapter(ard1);
You have to put the .ttf file of font(which you want to add ) in asstes/fonts/ folder and write code in onCreate method like below. i have puted Chalkduster.ttf in my asstes/fonts/ folder
TextView txttest = (TextView) findViewById(R.id.txttest);
Typeface custom_font = Typeface.createFromAsset(getAssets(),
"fonts/Chalkduster.ttf");
txttest.setTypeface(custom_font);
You can handle clicks of selected item by write code just like below
ListView lvNews = (ListView) findViewById(R.id.lvNews);
lvNews.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// Write your code here
//int newsId = newsArray.get(position).getId();
//Intent i = new Intent(NewsListActivity.this,
// NewsDetailActivity.class);
//i.putExtra(Constants.NEWS_ID, newsId);
//i.putExtra("isFromNotification", false);
//startActivity(i);
}
});
I've been dealing with this for a few weeks now. I've already seen all other related questions and it does not help. I'm trying to populate a custom ListView and can't for the life of me get it to work. I'll post all the relevant information hoping someone will notice my mistake.
Activity Layout:
<?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:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:background="#000000">
<ListView
android:id="#+id/deviceListView"
android:layout_width="400px"
android:layout_height="fill_parent"
android:textColor="#ffffff"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"/>
</LinearLayout>
Custom Row layout:
<?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="wrap_content"
android:orientation="horizontal"
android:background="#000000">
<TextView android:id="#+id/textId"
android:textSize="50sp"
android:text="ID"
android:textColor="#FFFFFF"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:orientation="vertical">
<TextView android:id="#+id/textTimestamp"
android:textSize="16sp"
android:text="Timestamp"
android:textColor="#FFFFFF"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
android:layout_height="wrap_content"/>
<TextView android:id="#+id/textCoordinates"
android:textSize="16sp"
android:text="Coordinates"
android:textColor="#FFFFFF"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView android:id="#+id/textDistance"
android:textSize="16sp"
android:text="Distance"
android:textColor="#FFFFFF"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>
Adapter model:
public class DeviceList {
public static ArrayList<Device> list;
public static void loadModel(int quantity) {
ArrayList<Device> listTmp = new ArrayList<Device>();
for (int i = 0; i < quantity; i++) {
listTmp.add(new Device(System.currentTimeMillis(), i, new float[]{0, 0}, System.currentTimeMillis() / (i + 1)));
}
list = listTmp;
}
public static Device GetById(int id){
Device tmp = null;
for(Device device : list){
if (device.getID() == id){
tmp = device;
}
}
return tmp;
}
}
Adapter:
public class DeviceArrayAdapter extends ArrayAdapter<Device> {
private Context context;
private int rowResourceId;
private String[] ids;
public DeviceArrayAdapter(Context context, int rowResourceId, String[] devices) {
super(context, rowResourceId);
this.context = context;
this.ids = devices;
this.rowResourceId = rowResourceId;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.device_row, parent, false);
TextView idTextview = (TextView) rowView.findViewById(R.id.textId);
TextView timeStampTextview = (TextView) rowView.findViewById(R.id.textTimestamp);
TextView coordinatesTextview = (TextView) rowView.findViewById(R.id.textCoordinates);
TextView distanceTextview = (TextView) rowView.findViewById(R.id.textDistance);
int id = Integer.parseInt(ids[position]);
timeStampTextview.setText(Long.toString(DeviceList.GetById(id).getTimestamp()));
idTextview.setText(DeviceList.GetById(id).getID());
coordinatesTextview.setText(DeviceList.GetById(id).getCoordinates()[0] + "," + DeviceList.GetById(id).getCoordinates()[1]);
distanceTextview.setText(DeviceList.GetById(id).getDistance() + "");
return rowView;
}
}
And finally the Activity's onCreate method:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// setContentView(R.layout.activity_main);
// ArrayList<Device> list = createDummyDeviceList(5);
DeviceList.loadModel(5);
String[] ids = new String[DeviceList.list.size()];
for (int i= 0; i < ids.length; i++){
ids[i] = Integer.toString(i+1);
}
ListView listView = (ListView) findViewById(R.id.deviceListView);
DeviceArrayAdapter adapter = new DeviceArrayAdapter(this, R.layout.device_row, ids);
listView.setAdapter(adapter);
}
Note: I'm sorry to post like this but I'm desperate. I've already debugged it up to the last line and everything is loaded and there are no Exceptions. But it just won't populate.
[EDIT]
Together with the selected answer I also had different numbered arrays and ids. The ids I generated started from 1 and not 0.
You never pass the dataset to the super class. Change
super(context, rowResourceId);
with
super(context, rowResourceId, devices);
this way the getCount of the ArrayAdapter, returns the devices length and the getView would be invoked. Also to avoid waste of memory and better performance, you should inflate the convertView only once.
Edit. The super is expecting an Array or ArrayList of Device objects. Instead your devices in a String array. Your choice should be consistent. You can either change
extends ArrayAdapter<Device>
with
extends ArrayAdapter<String>
or pass as paramter a Device[] as parameter to your custom Adapter. For instance
public DeviceArrayAdapter(Context context, int rowResourceId, Device[] devices) {
Check sources of ArrayAdapter http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.3_r2.1/android/widget/ArrayAdapter.java#ArrayAdapter.getCount%28%29
In your case you should override method getCount().
i have created a listView in my Fragment and my own adapter to create my own layout for the listView but its not showing anything
the xml for my listView layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="fill|right" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" >
<TextView
android:id="#+id/textView_listViewText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/imageView_adressList1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/bronze_pin_level" />
<ImageView
android:id="#+id/imageView_adressList2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/bronze_pin_level" />
<ImageView
android:id="#+id/imageView_adressList3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/bronze_pin_level" />
</LinearLayout>
</LinearLayout>
the xml for my listView
<?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="vertical" >
<ListView
android:id="#+id/listView_adressList"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2.25" >
</ListView>
<ImageView
android:id="#+id/imageView_adressList1"
android:layout_width="match_parent"
android:layout_height="43dp"
android:src="#drawable/bottom_me" />
the fragment code:
public class FragList extends Fragment {
ListView listView;
View myFragmentView;
List<String> adressList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
myFragmentView = inflater.inflate(R.layout.frag_list, container, false);
listView = (ListView) myFragmentView
.findViewById(R.id.listView_adressList);
adressList = new ArrayList<String>();
adressList.add("Marvin");
adressList.add("Markus");
adressList.add("Bob");
ArrayAdapter<String> adapter = new MyAdapter(getActivity(),
R.layout.adress_list_layout, adressList);
listView.setAdapter(adapter);
return myFragmentView;
}
public class MyAdapter extends ArrayAdapter<String>{
private List<String> values;
ImageView btn1, btn2, btn3;
Context cont;
int layoutID;
public MyAdapter(Context context, int resource, List<String> values) {
super(context, resource);
this.values = values;
this.cont = context;
this.layoutID = resource;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) this.cont
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(this.layoutID,
parent, false);
TextView tv1 = (TextView) rowView
.findViewById(R.id.textView_listViewText);
tv1.setText(values.get(position));
btn1 = (ImageView) rowView
.findViewById(R.id.imageView_adressList1);
btn2 = (ImageView) rowView
.findViewById(R.id.imageView_adressList2);
btn3 = (ImageView) rowView
.findViewById(R.id.imageView_adressList3);
return rowView;
}
}
}
The Problem is that the listView is not shown on the screen. It´s just a white screen.
Apparently I am doing something quite wrong, but I cant figure out what.
try with
view = View.inflate(cont, R.layout.name_of_your_listView_layout , null);
and not
View rowView = inflater.inflate(this.layoutID,
parent, false);
change the value for height and try again......