I have a ListView with the name of the timer, and the time of the timer, I don't know how to implement the countdown part. In each row in the ListView I have two TextViews: the time and the name of the timer, and then a Button which should start and stop the timer. This is my custom ListViewAdapter class, where I believe the timer should start stop in the OnClick method, to have the timer reacting to each line:
public class CustomTimerRowAdapter extends ArrayAdapter<TimerRow> {
Context context;
int height;
public CustomTimerRowAdapter(Context context, int resourceId,
List<TimerRow> items) {
super(context, resourceId, items);
this.context = context;
// Height of screen from not Activity subclass
height = context.getResources().getDisplayMetrics().heightPixels;
}
/* private view holder class */
private class ViewHolder {
TextView txtTimer;
TextView txtName;
Button bStartStop;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
TimerRow rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.timer_row, null);
holder = new ViewHolder();
// make layout params
holder.txtTimer = (TextView) convertView.findViewById(R.id.tvTimes);
holder.txtTimer.getLayoutParams().height = height / 10;
holder.txtName = (TextView) convertView.findViewById(R.id.tvName);
holder.txtName.getLayoutParams().height = height / 10;
holder.bStartStop = (Button) convertView
.findViewById(R.id.bStartStopTimer);
holder.bStartStop.getLayoutParams().height = height / 10;
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.txtName.setText(rowItem.getName());
holder.txtTimer.setText(rowItem.getTimer());
final String name = holder.txtName.getText().toString();
holder.bStartStop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// THIS IS WHERE THE TIMER SHOULD START AND STOP.
Toast.makeText(context, "Selected " + name + " timer.",
Toast.LENGTH_SHORT).show();
}
});
return convertView;
}
}
The length of the timers can be up to 99 hours, 59 minutes and 59 seconds. The timers are formatted as strings like this "hh:mm:ss".
Please use RecyclerView instead of Listview. Here you can check and download the source code of Countdown timers in a ListView
activity_main.xml
<RelativeLayout android:layout_width=”match_parent”
android:layout_height=”match_parent”
xmlns:android=”http://schemas.android.com/apk/res/android”>
<android.support.v7.widget.RecyclerView
android:id=”#+id/recycler_view”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:scrollbars=”vertical” />
</RelativeLayout>
adapter_layout.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="wrap_content"
android:layout_height="wrap_content"
android:textSize="15dp"
android:padding="10dp"
android:id="#+id/tv_timer"/>
</LinearLayout>
MainActivity.java
package com.androidsolutionworld.multipletimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.LinearLayout;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private ArrayList al_data = new ArrayList<>();
private Adapter obj_adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView)findViewById(R.id.recycler_view);
al_data.add("1234");
al_data.add("1257");
al_data.add("100");
al_data.add("1547");
al_data.add("200");
al_data.add("500");
al_data.add("2000");
al_data.add("1000");
obj_adapter = new Adapter(al_data);
LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext(),LinearLayoutManager.VERTICAL,false);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(obj_adapter);
}
}
Custom Adapter:
import android.os.CountDownTimer;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
public class Adapter extends RecyclerView.Adapter{
private ArrayList al_data;
public class MyViewHolder extends RecyclerView.ViewHolder{
public TextView tv_timer;
CountDownTimer timer;
public MyViewHolder (View view){
super(view);
tv_timer = (TextView)view.findViewById(R.id.tv_timer);
}
}
public Adapter(ArrayList al_data) {
this.al_data = al_data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_layout,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
holder.tv_timer.setText(al_data.get(position));
if (holder.timer != null) {
holder.timer.cancel();
}
long timer = Long.parseLong(al_data.get(position));
timer = timer*1000;
holder.timer = new CountDownTimer(timer, 1000) {
public void onTick(long millisUntilFinished) {
holder.tv_timer.setText("" + millisUntilFinished/1000 + " Sec");
}
public void onFinish() {
holder.tv_timer.setText("00:00:00");
}
}.start();
}
#Override
public int getItemCount() {
return al_data.size();
}
}
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I'm getting error in crimeholder class , which states
'java.lang.NullPointerException:Attempt to invoke virtual method
'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference'
I copied pasted most of the code from the book which I bought from amazon.
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
public class CrimeListFragment extends Fragment {
private RecyclerView mCrimeRecyclerView;
private CrimeAdapter mAdapter;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_crime_list, container, false);
mCrimeRecyclerView = (RecyclerView) view
.findViewById(R.id.crime_recycler_view);
mCrimeRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
updateUI();
return view;
}
private void updateUI() {
CrimeLab crimeLab = CrimeLab.get(getActivity());
List<Crime> crimes = crimeLab.getCrimes();
mAdapter = new CrimeAdapter(crimes);
mCrimeRecyclerView.setAdapter(mAdapter);
}
//
private class CrimeHolder extends RecyclerView.ViewHolder {
private Crime mCrime;
private TextView mTitleTextView;
private TextView mDateTextView;
public CrimeHolder(LayoutInflater inflater, ViewGroup parent) {
super(inflater.inflate(R.layout.list_item_crime, parent, false));
mTitleTextView = (TextView) itemView.findViewById(R.id.crime_title);
mDateTextView = (TextView) itemView.findViewById(R.id.crime_date);
}
public void bind(Crime crime) {
mCrime = crime;
mTitleTextView.setText(mCrime.getmTitle());
mDateTextView.setText(mCrime.getmDate().toString());
}
}
private class CrimeAdapter extends RecyclerView.Adapter<CrimeHolder> {
private List<Crime> mCrimes;
public CrimeAdapter(List<Crime> crimes) {
mCrimes = crimes;
}
#Override
public CrimeHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
return new CrimeHolder(layoutInflater, parent);
}
#Override
public void onBindViewHolder(CrimeHolder holder, int position) {
Crime crime = mCrimes.get(position);
holder.bind(crime);
}
#Override
public int getItemCount() {
return mCrimes.size();
}
}
}
//
import android.support.v4.app.Fragment;
public class CrimeActivity extends SingleFragmentActivity {
#Override
protected Fragment createFragment() {
return new CrimeFragment();
}
}
//
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
public class CrimeFragment extends Fragment {
private Crime mCrime;
private EditText mTitleField;
private Button mDateButton;
public CheckBox mSolvedCheckBox;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCrime = new Crime();
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.fragment_crime, container, false);
mTitleField = (EditText) v.findViewById(R.id.crime_title);
mTitleField.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
mCrime.setmTitle(s.toString());
}
#Override
public void afterTextChanged(Editable s) {
}
});
mDateButton = (Button) v.findViewById(R.id.crime_date);
mDateButton.setText(mCrime.getmDate().toString());
mDateButton.setEnabled(false);
mSolvedCheckBox = (CheckBox)v.findViewById(R.id.crime_solved);
mSolvedCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mCrime.setmSolved(isChecked);
}
});
return v;
}
}
//
import android.content.Context;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class CrimeLab {
private static CrimeLab sCrimeLab;
private List<Crime> mCrimes;
public static CrimeLab get(Context context) {
if (sCrimeLab == null) {
sCrimeLab = new CrimeLab(context);
}
return sCrimeLab;
}
private CrimeLab(Context context) {
mCrimes = new ArrayList<>();
for (int i = 0; i < 100; i++) {
Crime crime = new Crime();
crime.setmTitle("Crime #" + i);
crime.setmSolved(i % 2 == 0); // Every other one
mCrimes.add(crime);
}
}
public List<Crime> getCrimes() {
return mCrimes;
}
public Crime getCrime(UUID id) {
for (Crime crime : mCrimes) {
if (crime.getmId().equals(id)) {
return crime;
}
}
return null;
}
}
//
import android.support.v4.app.Fragment;
public class CrimeListActivity extends SingleFragmentActivity {
#Override
protected Fragment createFragment() {
return new CrimeListFragment();
}
}
//
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
public class CrimeListFragment extends Fragment {
private RecyclerView mCrimeRecyclerView;
private CrimeAdapter mAdapter;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_crime_list, container, false);
mCrimeRecyclerView = (RecyclerView) view
.findViewById(R.id.crime_recycler_view);
mCrimeRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
updateUI();
return view;
}
private void updateUI() {
CrimeLab crimeLab = CrimeLab.get(getActivity());
List<Crime> crimes = crimeLab.getCrimes();
mAdapter = new CrimeAdapter(crimes);
mCrimeRecyclerView.setAdapter(mAdapter);
}
private class CrimeHolder extends RecyclerView.ViewHolder {
private Crime mCrime;
private TextView mTitleTextView;
private TextView mDateTextView;
public CrimeHolder(LayoutInflater inflater, ViewGroup parent) {
super(inflater.inflate(R.layout.list_item_crime, parent, false));
mTitleTextView = (TextView) itemView.findViewById(R.id.crime_title);
mDateTextView = (TextView) itemView.findViewById(R.id.crime_date);
}
public void bind(Crime crime) {
mCrime = crime;
mTitleTextView.setText(mCrime.getmTitle());
mDateTextView.setText(mCrime.getmDate().toString());
}
}
private class CrimeAdapter extends RecyclerView.Adapter<CrimeHolder> {
private List<Crime> mCrimes;
public CrimeAdapter(List<Crime> crimes) {
mCrimes = crimes;
}
#Override
public CrimeHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
return new CrimeHolder(layoutInflater, parent);
}
#Override
public void onBindViewHolder(CrimeHolder holder, int position) {
Crime crime = mCrimes.get(position);
holder.bind(crime);
}
#Override
public int getItemCount() {
return mCrimes.size();
}
}
}
//
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
public abstract class SingleFragmentActivity extends AppCompatActivity {
protected abstract Fragment createFragment();
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment);
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragment_container);
if (fragment == null) {
fragment = createFragment();
fm.beginTransaction()
.add(R.id.fragment_container, fragment)
.commit();
}
}
}
//activity_fragment.xmml
FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/fragment_container"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".CrimeActivity">
</FrameLayout>
//fragment_crime.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="16dp"
android:orientation="vertical">
<TextView
style="?android:listSeparatorTextViewStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/crime_title_label"/>
<EditText
android:id="#+id/crime_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/crime_title_hint" />
<TextView
style="?android:listSeparatorTextViewStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/crime_details_label"/>
<Button
android:id="#+id/crime_date"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<CheckBox
android:id="#+id/crime_solved"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/crime_solved_label"/>
</LinearLayout>
//
//fragment_crime_list.xml
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/crime_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
//list_item_crime.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="crime_title"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/crime_date"
android:text="crime_date"/>
Try as follows
In your CrimeAdapter under onCreateViewHolder, Pass views to CrimeHolder
class
#NonNull
#Override
public CrimeHolder onCreateViewHolder(#NonNull ViewGroup viewGroup,int i){
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate( R.layout.list_item_crime, viewGroup, false );
// here pass view as a constructor
return new CrimeHolder(view);
}
In your CrimeHolder, set to superclass and retrieve other property as follows
private class CrimeHolder extends RecyclerView.ViewHolder{
private TextView mTitleTextView;
private TextView mDateTextView;
CrimeHolder(View view){
super(view);
mTitleTextView = view.findViewById(R.id.textView);
mDateTextView = view.findViewById(R.id.textView2);
}
}
You are not finding the views properly, you are calling super() and in the same time trying to find the textviews from itemView which I don't where are you initialing it. Do the following:
Replace
mTitleTextView = (TextView) itemView.findViewById(R.id.crime_title);
mDateTextView = (TextView) itemView.findViewById(R.id.crime_date);
with
mTitleTextView = (TextView) findViewById(R.id.crime_title);
mDateTextView = (TextView) findViewById(R.id.crime_date);
OR
Replace
super(inflater.inflate(R.layout.list_item_crime, parent, false));
with
itemView = (ViewGroup) inflater.inflate(R.layout.list_item_crime, parent, false);
fragment reminder image - current problem
This current class that I am using called Fragment Reminder is used to display a list of the medications that have been entered. However this class before was a Fragment and I decided to change it to an Activity and the method which displays the list called onCreateView is unused now. When I click on that button to run this class the screen goes dark for some reason. Now that this class is an Activity the onCreateView cannot be used since that is for a Fragment. What should I change that to so I can create the list.
FragmentReminder:
package com.example.junai.mrtest2;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import static android.view.View.GONE;
public class FragmentReminder extends Activity implements View.OnClickListener{
private ArrayList al;
private List list=new ArrayList();
private ArrayAdapter<String> adapter;
ListView lv;
TextView tv;
FloatingActionButton fab;
public void receiveData(ArrayList al)
{
this.al=al;
list.add(al.get(0));
}
//data for customlist
private String desc[] = {};
// #Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
this.setTitle("Medicine Reminder");
View v=inflater.inflate(R.layout.fragment_reminder, container, false);
fab=(FloatingActionButton)v.findViewById(R.id.floatingActionButton);
lv=(ListView)v.findViewById(R.id.rem_lv);
tv=(TextView) v.findViewById(R.id.reminder_tv);
fab.setOnClickListener(this);
DatabaseHandler db=new DatabaseHandler(this);
list=db.getAllReminders();
if(list.size()==0)
{
lv.setVisibility(GONE);
return v;
}
tv.setVisibility(GONE);
adapter = new CustomList(this,list,desc);
lv.setAdapter(adapter);
//***Customised list view add***********************************************************************
/* CustomList customList = new CustomList(getActivity(),list, desc);
lv.setAdapter(customList);*/
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//Toast.makeText(getActivity(),"You Clicked "+list.get(i),Toast.LENGTH_SHORT).show();
//addReminderInCalendar();
Intent in=new Intent(FragmentReminder.this,MedRemInfo.class);
in.putExtra("id",list.get(i).toString());
startActivity(in);
}
});
//***************************************************************************
return v;
}
#Override
public void onClick(View v) {
Intent in=new Intent(this,AddReminder.class);
startActivity(in);
}
}
fragment_reminder.xml:
<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="match_parent"
android:orientation="vertical"
tools:context="com.example.junai.mrtest2.FragmentReminder">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="20dp"
android:id="#+id/reminder_tv"
android:textSize="20dp"
android:text="No Reminders to show, Add a reminder.."
android:gravity="center"
/>
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:src="#drawable/ic_add_black_24dp"
android:tint="#ffffff"
android:layout_gravity="bottom|center"
android:id="#+id/floatingActionButton" />
<ListView
android:layout_width="match_parent"
android:id="#+id/rem_lv"
android:layout_height="match_parent"
/>
</LinearLayout>
MainActivity:
package com.example.junai.mrtest2;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
/**
* Created by junai on 20/03/2018.
*/
public class MainActivity extends Activity {
private Button btn_addReminder, btn_reminderinfo;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_addReminder = (Button) findViewById(R.id.btn_addReminder);
btn_addReminder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, AddReminder.class));
}
});
btn_reminderinfo = (Button) findViewById(R.id.btn_reminderinfo);
btn_reminderinfo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, FragmentReminder.class));
}
});
}
}
CustomList:
package com.example.junai.mrtest2;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.Typeface;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
import java.util.Random;
public class CustomList extends ArrayAdapter<String> {
private List names;
private String[] desc;
private Activity context;
public CustomList(Activity context, List names, String[] desc) {
super(context, R.layout.list_medinfo, names);
this.context = context;
this.names = names;
this.desc = desc;
}
String color_hex[]={"#ff4000","#0000ff","#003EFF","#5C246E","#8B668B","#CD2990","#D41A1F","#FBDB0C","#FF6600"};
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//********************************************************************
ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
// If holder not exist then locate all view from UI file.
if (convertView == null) {
// inflate UI from XML file
convertView = inflater.inflate(R.layout.list_medinfo, parent, false);
// get all UI view
holder = new ViewHolder(convertView);
// set tag for holder
convertView.setTag(holder);
} else {
// if holder created, get tag from view
holder = (ViewHolder) convertView.getTag();
}
holder.textView.setText(getItem(position));
String firstLetter = null;
//get first letter of each String item
Log.d("String",getItem(position));
String str=getItem(position);
firstLetter=String.valueOf(str.charAt(0)).toUpperCase();
// firstLetter.toUpperCase();
ColorGenerator generator = ColorGenerator.MATERIAL; // or use DEFAULT
// generate random color
//int color = generator.getColor(getItem(position));
int color = generator.getRandomColor();
int pos= new Random().nextInt(color_hex.length);
color = Color.parseColor(color_hex[pos]);
Log.d("Color",""+pos);
TextDrawable drawable = TextDrawable.builder()
.buildRound(firstLetter, color); // radius in px
holder.imageView.setImageDrawable(drawable);
return convertView;
//***********************************************************************
/* LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.list_medinfo, null, true);
TextView textViewName = (TextView) listViewItem.findViewById(R.id.medname);
TextView textViewDesc = (TextView) listViewItem.findViewById(R.id.textViewDesc);
ImageView image = (ImageView) listViewItem.findViewById(R.id.imageView);
textViewName.setText(names.get(position).toString());
textViewDesc.setText(desc[position]);
image.setImageResource(imageid[position]);
return listViewItem;*/
}
private class ViewHolder {
private ImageView imageView;
private TextView textView;
public ViewHolder(View v) {
imageView = (ImageView) v.findViewById(R.id.medimage);
textView = (TextView) v.findViewById(R.id.medname);
Typeface typeface=Typeface.createFromAsset(context.getAssets(), "fonts/georgia.ttf");
textView.setTypeface(typeface);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP,20);
}
}
}
I've refactored your code:
public class FragmentReminder extends Activity implements View.OnClickListener {
private ArrayList al;
private List list = new ArrayList();
private ArrayAdapter<String> adapter;
ListView lv;
TextView tv;
FloatingActionButton fab;
public void receiveData(ArrayList al) {
this.al = al;
list.add(al.get(0));
}
//data for customlist
private String desc[] = {};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_reminder);
fab = (FloatingActionButton) findViewById(R.id.floatingActionButton);
lv = (ListView) findViewById(R.id.rem_lv);
tv = (TextView) findViewById(R.id.reminder_tv);
fab.setOnClickListener(this);
DatabaseHandler db = new DatabaseHandler(this);
list = db.getAllReminders();
if (list.size() == 0) {
lv.setVisibility(GONE);
}
tv.setVisibility(GONE);
adapter = new CustomList(this, list, desc);
lv.setAdapter(adapter);
//***Customised list view add***********************************************************************
/* CustomList customList = new CustomList(getActivity(),list, desc);
lv.setAdapter(customList);*/
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//Toast.makeText(getActivity(),"You Clicked "+list.get(i),Toast.LENGTH_SHORT).show();
//addReminderInCalendar();
Intent in = new Intent(FragmentReminder.this, MedRemInfo.class);
in.putExtra("id", list.get(i).toString());
startActivity(in);
}
});
}
#Override
public void onClick(View v) {
Intent in = new Intent(this, AddReminder.class);
startActivity(in);
}
}
You need only to move the code to onCreate() instead of onCreateView() and also you don't need to access the recently inflated view V to do findViewByID, all you have to do is setContentView() beforehand.
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
I am getting a NullPointerException at line 67 while trying to set a listView with a chat adapter. Here is the class:
I have placed ** around the line I am getting the NullPointerException on. I'm not really understading why its returning as null when I'm setting messageAdapter to a new object of an inner class called ChatAdapter(this).
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MessageListActivity extends AppCompatActivity {
/**
* Whether or not the activity is in two-pane mode, i.e. running on a tablet
* device.
*/
ListView listView;
Button sendButton;
ArrayList<String> arrayList = new ArrayList<String>();
ChatDatabaseHelper Cdb;
private boolean mTwoPane;
ChatAdapter messageAdapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle(getTitle());
listView = (ListView)findViewById(R.id.chatListView);
final EditText editText = (EditText)findViewById(R.id.messageText);
sendButton = (Button)findViewById(R.id.sendButton);
messageAdapter = new ChatAdapter(this); // chatAdapter is a built in adapater
**listView.setAdapter(messageAdapter);**
Cdb = new ChatDatabaseHelper(this);
Cursor cursor = Cdb.getMessages(); // get messages method is of type Cursor from database helper class
// cursor will move through the database to find the next text if there is any.
while (cursor.moveToNext()) { arrayList.add(cursor.getString(cursor.getColumnIndex(Cdb.KEY_MESSAGE))); }
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { // on click listener for the send button
String chatText = editText.getText().toString(); // changing editText to String
arrayList.add(chatText); // adding the string from EditTest to arrayList
boolean isInserted = Cdb.insertData(chatText); // inserting the message text into the database
if(isInserted = true)
{ Toast.makeText(MessageListActivity.this,"Message Sent",Toast.LENGTH_SHORT).show(); } // if the message inserts into the database this toast will show
else {
Toast.makeText(MessageListActivity.this,"Message not Sent",Toast.LENGTH_SHORT).show(); } // if message does not nter the database this toast will show
messageAdapter.notifyDataSetChanged(); // notifying the adapter that a message has been sent, changing from incoming to outgoing
editText.setText(" "); // set the text on the send button to blank.
} // end of onClick view
}); // end of onClickListener
if (findViewById(R.id.message_detail_container) != null) {
// The detail container view will be present only in the
// large-screen layouts (res/values-w900dp).
// If this view is present, then the
// activity should be in two-pane mode.
mTwoPane = true;
}
}
class ChatAdapter extends ArrayAdapter<String> { // custom adapter class // when youc all the adapter it forms the for loop for you.
public ChatAdapter(MessageListActivity ctx) {
super(ctx, 0);
} // default constructor
// method to return the number of rows that will be in your array
// will tell how many times to run a for loop
public int getCount(){ return arrayList.size(); } // will return the size of the array
public String getItem(int position){ return arrayList.get(position); } // will return the item at position
// getview method
#Override
public View getView(int position, final View convertView, ViewGroup parent) {// inner class
LayoutInflater Inflater = MessageListActivity.this.getLayoutInflater(); // an inflater inflates the xml layout into a view.
View result = null;
if(position%2 == 0){ // if position number in the array is odd do this, if number is even, do this.
result = Inflater.inflate(R.layout.chat_row_incoming, null); // depending on the position, show layout incoming
} else {
result = Inflater.inflate(R.layout.chat_row_outgoing,null); // depending on the position, show layout outgoing
}
TextView message = (TextView)result.findViewById(R.id.messageText); // creating a message of type TextView connected to messageText
final String messageText = getItem(position) ;
message.setText(messageText);
result.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(MessageDetailFragment.ARG_ITEM_ID,messageText );
MessageDetailFragment fragment = new MessageDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.message_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, MessageDetailActivity.class);
intent.putExtra(MessageDetailFragment.ARG_ITEM_ID,messageText );
context.startActivity(intent);
}
}
});
return result; // return the view which is the Inflater.
}
} // end of chat adapter class
private void setupRecyclerView(#NonNull RecyclerView recyclerView) {
recyclerView.setAdapter(new SimpleItemRecyclerViewAdapter(DummyContent.ITEMS));
}
public class SimpleItemRecyclerViewAdapter
extends RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.ViewHolder> {
private final List<DummyContent.DummyItem> mValues;
public SimpleItemRecyclerViewAdapter(List<DummyContent.DummyItem> items) {
mValues = items;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.message_list_content, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mItem = mValues.get(position);
holder.mIdView.setText(mValues.get(position).id);
holder.mContentView.setText(mValues.get(position).content);
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(MessageDetailFragment.ARG_ITEM_ID, holder.mItem.id);
MessageDetailFragment fragment = new MessageDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.message_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, MessageDetailActivity.class);
intent.putExtra(MessageDetailFragment.ARG_ITEM_ID, holder.mItem.id);
context.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mIdView;
public final TextView mContentView;
public DummyContent.DummyItem mItem;
public ViewHolder(View view) {
super(view);
mView = view;
mIdView = (TextView) view.findViewById(R.id.id);
mContentView = (TextView) view.findViewById(R.id.content);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
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"
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.ChatWindow">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/chatListView"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="false"
android:layout_alignWithParentIfMissing="false"
android:layout_above="#+id/sendButton" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/sendButton"
android:id="#+id/sendButton"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:singleLine="true" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/messageText"
android:layout_toStartOf="#id/sendButton"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:enabled="true"
/>
</RelativeLayout>
just try
messageAdapter = new ChatAdapter(MessageListActivity .this);
So what I want to do is have a different image for each list item in my App. I've been attempting to do this for a little while now and have no idea what I'm doing.
Here's what I'm trying to do:
How do I go about this? Here's my current code:
package net.androidbootcamp.gamesandcoffee;
import android.app.ListActivity;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[ ] attraction = {"Games", "Coffee Shops"};
setListAdapter(new ArrayAdapter<String>(this, R.layout.activity_main, R.id.games, attraction));
}
protected void onListItemClick(ListView l, View v, int position, long id) {
switch (position) {
case 0:
startActivity(new Intent(MainActivity.this, games.class));
break;
case 1:
startActivity(new Intent(MainActivity.this, coffee.class));
break;
}
}
}
and my 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" 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">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/games"
android:textSize="20sp"
android:text="#+id/games"
android:drawableLeft="#drawable/games"/>
</RelativeLayout>
For that you have to create a custom adapter, where you can customize all the ListView items.
public class ListAdapter extends ArrayAdapter<Item> {
public ListAdapter(Context context, int imageViewResourceId) {
super(context, imageViewResourceId);
}
public ListAdapter(Context context, int resource, List<Item> 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.itemlistrow, null);
}
Item p = getItem(position);
if (p != null) {
ImageView iv = (ImageView ) v.findViewById(R.id.id);
if (iv != null) {
iv .setImageResource(R.id.xyz);
}
}
return v;
}
}
load the image resource id's to the array and pass to the list adapter in this way
int[] images = {R.drawables.firstimg,R.drawables.secondimg};
setListAdapter(new CustomAdapter(this,images, attraction));
Crate CustomAdapter Class
public class CustomAdapter extends BaseAdapter{
private Context context;
int[] images;
String[] textdata;
public CustomAdapter(Context context, int[] images,String[] textdata) {
this.context = context;
this.images=images;
this.textdata=textdata;
}
#Override
public Object getItem(int position) {
return textdata.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = null;
if (convertView == null){
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.drawer_listitem,parent,false);
}else {
row = convertView;
}
TextView name = (TextView) row.findViewById(R.id.draweritemtext);
ImageView image = (ImageView) row.findViewById(R.id.draweritemimage);
name.setText(textdata[position]);
image.setImageResource(images[position]);
return row;
}
#Override
public int getCount() {
return textdata.size();
}
}
Following these two video tutorials, geared towards beginners, I was able to arrive to my desired result. Thank you those who contributed, but none of the answers or resources provided were geared towards beginners that lack experience.
These are the videos I watched
Android Studio Tutorial - 18 - ListView with Custom Adapter part-1
Android Studio Tutorial - 19 - ListView with Custom Adapter part-2
How can I modify the code below so that each item has two lines instead of one? I want the code in the mSample section the same layout as I've posted so please do not inappropriately modify it unless it is necessary. Below is an image depicting what the list looks like with one line.
I know that the click event and list adapter codes needs to change, but I don't know what to.
I also have an xml called list_item_entry.xml that contains two text views (1 bigger than the other) in a linear layout but I'm not sure if I need to use that.
package com.example.android.animationsdemo;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
/**
* The launchpad activity for this sample project. This activity launches other activities that
* demonstrate implementations of common animations.
*/
public class MainActivity extends ListActivity {
/**
* This class describes an individual sample (the sample title, and the activity class that
* demonstrates this sample).
*/
private class Sample {
private CharSequence title;
private Class<? extends Activity> activityClass;
public Sample(int titleResId, Class<? extends Activity> activityClass) {
this.activityClass = activityClass;
this.title = getResources().getString(titleResId);
}
#Override
public String toString() {
return title.toString();
}
}
/**
* The collection of all samples in the app. This gets instantiated in {#link
* #onCreate(android.os.Bundle)} because the {#link Sample} constructor needs access to {#link
* android.content.res.Resources}.
*/
private static Sample[] mSamples;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Instantiate the list of samples.
mSamples = new Sample[]{
new Sample(R.string.title_crossfade, CrossfadeActivity.class),
new Sample(R.string.title_card_flip, CardFlipActivity.class),
new Sample(R.string.title_screen_slide, ScreenSlideActivity.class),
new Sample(R.string.title_zoom, ZoomActivity.class),
new Sample(R.string.title_layout_changes, LayoutChangesActivity.class),
};
setListAdapter(new ArrayAdapter<Sample>(this,
android.R.layout.simple_list_item_1,
android.R.id.text1,
mSamples));
}
#Override
protected void onListItemClick(ListView listView, View view, int position, long id) {
// Launch the sample associated with this list position.
startActivity(new Intent(MainActivity.this, mSamples[position].activityClass));
}
}
list_item_entry.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="wrap_content"
android:minHeight="?android:attr/listPreferredItemHeight"
android:gravity="center_vertical"
android:paddingRight="?android:attr/scrollbarSize"
android:baselineAligned="false">
<RelativeLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:layout_marginRight="6dip"
android:layout_marginTop="6dip"
android:layout_marginBottom="6dip"
android:layout_weight="1">
<TextView android:id="#+id/list_item_entry_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:textAppearance="?android:attr/textAppearanceLarge"
android:ellipsize="marquee"
android:fadingEdge="horizontal"
/>
<TextView android:id="#+id/list_item_entry_summary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/list_item_entry_title"
android:layout_alignLeft="#id/list_item_entry_title"
android:textAppearance="?android:attr/textAppearanceSmall"
android:singleLine="true"
android:textColor="?android:attr/textColorSecondary"
/>
</RelativeLayout>
</LinearLayout>
class errors
package com.example.android.animationsdemo;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
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.TextView;
/**
* The launchpad activity for this sample project. This activity launches other activities that
* demonstrate implementations of common animations.
*/
public class MainActivity extends ListActivity {
/**
* This class describes an individual sample (the sample title, and the activity class that
* demonstrates this sample).
*/
private class Sample {
private CharSequence title;
private CharSequence summary;
private Class<? extends Activity> activityClass;
public Sample(int titleResId, int summaryResId, Class<? extends Activity> activityClass) {
this.activityClass = activityClass;
this.title = getResources().getString(titleResId);
this.summary = getResources().getString(summaryResId);
}
#Override
public String toString() { return title.toString(); return summary.toString(); }
}
/**
* The collection of all samples in the app. This gets instantiated in {#link
* #onCreate(android.os.Bundle)} because the {#link Sample} constructor needs access to {#link
* android.content.res.Resources}.
*/
private static Sample[] mSamples;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Instantiate the list of samples.
mSamples = new Sample[]{
new Sample(R.string.title_crossfade, R.string.summary_crossfade, CrossfadeActivity.class),
new Sample(R.string.title_card_flip, R.string.summary_card_flip, CardFlipActivity.class),
new Sample(R.string.title_screen_slide, R.string.summary_screen_slide, ScreenSlideActivity.class),
new Sample(R.string.title_zoom, R.string.summary_zoom, ZoomActivity.class),
new Sample(R.string.title_layout_changes, R.string.summary_layout_changes, LayoutChangesActivity.class),
};
}
#Override
protected void onListItemClick(ListView listView, View view, int position, long id) {
// Launch the sample associated with this list position.
startActivity(new Intent(MainActivity.this, mSamples[position].activityClass));
}
static class MyAdapter extends BaseAdapter {
static class ViewHolder {
TextView title;
TextView summary;
}
LayoutInflater inflater;
Sample[] mSamples;
public MyAdapter(Context contexts, Sample[] samples) {
this.mSamples = samples;
inflater = LayoutInflater.from(contexts);
}
#Override
public int getCount() {
return mSamples.length;
}
#Override
public Object getItem(int position) {
return mSamples[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.entry, null);
viewHolder = new ViewHolder();
viewHolder.title = (TextView) convertView.findViewById(R.id.list_item_entry_title);
viewHolder.summary = (TextView) convertView.findViewById(R.id.list_item_entry_summary);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.title.setText(mSamples[position].title);
viewHolder.summary.setText(mSamples[position].summary);
return convertView;
}
}
}
maybe it will help you
public class MainActivity extends ListActivity {
/*
current code
*/
public void onCreate(Bundle savedInstanceState) {
//
//
setListAdapter(new SampleAdapter(this,
android.R.layout.simple_list_item_1,
mSamples));
}
#Override
protected void onListItemClick(ListView listView, View view, int position, long id) {
// Launch the sample associated with this list position.
startActivity(new Intent(MainActivity.this, mSamples[position].activityClass));
}
public static class SampleAdapter extends ArrayAdapter<Sample>{
SampleAdapter(Context context, int resource, Sample[] objects) {
super(context, resource, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rootView = super.getView(position, convertView, parent);
TextView firstLine = rootView.findViewById(R.id.list_item_entry_title);
TextView secondLine = rootView.findViewById(R.id.list_item_entry_summary);
firstLine.setText(getItem(position)./*Sample class field*/);
secondLine.setText(getItem(position)./*Sample class field*/);
return rootView;
}
}
}
If you want to customise the rows with more than one TextView then you should implement your own Adapter. The xml you have posted is useless because you are using android.R.layout.simple_list_item_1 and android.R.id.text1. To achieve what you want to do try this:
public class MyAdapter extends BaseAdapter {
static class ViewHolder {
TextView title;
TextView summary;
}
LayoutInflater inflater;
Sample[] mSamples;
public MyAdapter(Context contexts, Sample[] samples) {
this.mSamples = samples;
inflater = LayoutInflater.from(contexts);
}
#Override
public int getCount() {
return mSamples.length;
}
#Override
public Object getItem(int position) {
return mSamples[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.entry, null);
viewHolder = new ViewHolder();
viewHolder.title = (TextView) convertView.findViewById(R.id.list_item_entry_title);
viewHolder.summary = (TextView) convertView.findViewById(R.id.list_item_entry_summary);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.title.setText(mSamples[position].title);
viewHolder.summary.setText(mSamples[position].summary);
return convertView;
}
}
And you can use it like this:
list.setAdapter(new MyAdapter(this, samples));