retrieve data from ArrayList<Object> to Listview Android - android

i have a problem with my ListView , I cannot get the data from an arraylist to listview . Data from arraylist was loaded successful from the data and when I put it in the ArrayAdapter the app always say ArrayAdapter requires the resource ID to be a TextView
Here my code
EventList.java
public class EventList extends Activity {
ListView listView;
DBHelper db;
List<String> event_name;
private TextView e_name,e_location,e_date,e_time,e_or;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_list);
db = new DBHelper(this);
listView = (ListView) findViewById(R.id.eventlist);
db.open();
ArrayList<Event> elist= db.getEventlist();
db.close();
e_name=(TextView) findViewById(R.id.e_name);
e_date=(TextView) findViewById(R.id.e_date);
e_location =(TextView) findViewById(R.id.e_location);
e_time =(TextView) findViewById(R.id.e_time);
e_or =(TextView) findViewById(R.id.e_or);
// for(int i=0;i<elist.size();i++)
// {
// e_name.setText(elist.get(i).getEventName());
// e_date.setText(elist.get(i).getDate());
// e_location.setText(elist.get(i).getLocation());
// e_time.setText(elist.get(i).getTime());
// e_or.setText(elist.get(i).getOrganizer());
// }
ArrayAdapter<Event> arrayAdapter = new ArrayAdapter<Event>(
this,
R.layout.each_event,elist);
listView.setAdapter(arrayAdapter);
}
}
activity_event_list.xml
<?xml version="1.0" encoding="utf-8"?>
<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.greenwich.thaotb.eventmanagement.EventList">
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Event List"
android:id="#+id/textView2"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Event"
android:id="#+id/textView3"
android:layout_marginTop="26dp"
android:layout_below="#+id/textView2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:text="Event"
android:ems="10"
android:id="#+id/event_name"
android:layout_alignBottom="#+id/textView3"
android:layout_toRightOf="#+id/textView3"
android:layout_toEndOf="#+id/textView3"
android:layout_marginLeft="33dp"
android:layout_marginStart="33dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search"
android:id="#+id/bnt_search"
android:layout_below="#+id/event_name"
android:layout_alignRight="#+id/event_name"
android:layout_alignEnd="#+id/event_name" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/eventlist"
android:layout_below="#+id/bnt_search"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:choiceMode="singleChoice" />
</RelativeLayout>
each_event.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:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/e_name" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/e_location" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/e_date" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/e_time" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/e_or" />
</LinearLayout>

Take a look at the documentation for the the constructor for ArrayAdapter that you're using. It says the resource ID must be a layout with a TextView. It turns out, in this case, that the layout must contain ONLY a single TextView. If you have a different case, use a different constructor.
ArrayAdapter populates a ListView by taking the toString() value of the object in its array, then putting that into the TextView identified by the layout you passed.

Two problems
You can't use the ArrayAdapter constructor for displaying any complex data objects. It will just toString all the objects.
Calling findViewById(R.id.e_name) (and the others) from within the Activity will return null because #+id/e_name isn't from the activity_event_list.xml file.
To solve these, you'll need to implement a custom ArrayAdapter for your Event objects.
Something like so
public class EventAdapter extends ArrayAdapter<Event> {
public EventAdapter(Context context, ArrayList<Event> events) {
super(context, 0, events);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
Event event = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.each_event, parent, false);
}
TextView eName = (TextView) convertView.findViewById(R.id.e_name);
// get other views ...
eName.setText(event.getEventName());
// set other views...
return convertView;
}
}
Then in the Activity, you can do
ArrayList<Event> elist= db.getEventlist();
EventAdapter adapter = new EventAdapter(this, elist);
listView.setAdapter(adapter);

I have read your code, and I think it's worth first checking how ListViews and and Adapters work together. Here's a great article I think you should take a look at.
Solution
You can achieve what you want by
Creating a custom class that represents an event, it should be something like this
class Event{
private String mName;
private String mLocation;
private String mDate;
//you get the idea ...
public Event (String name, String location, String date){
mName = name;
mLocation = location;
mDate = date;
}
//some getters
public String getName (){
return mName;
}
public String getLocation (){
return mLocation;
}
public String getDate (){
return mDate;
}
//you can add other logic here depending on what you want your event to do
}
Creating you collection of Events, a List<Event> will do
Creating your custom EventAdapter, I would recommend to extend the BaseAdapter class (any other Adapter class would do)
A tutorial might help you more
Here is a great step by step tutorial showing how to implement what I have mentioned above.

Related

Cannot set Custom Adapter to ListView

I try to set a Customer Adapter to ListView but always receive NullException.
This is my Adapter:
public class MovieAdapter extends BaseAdapter{
private Context mContext;
// Add mVar of resource, an array for example
private List<Movie> mMovies;
// Automatically create constructor for all mVar
public MovieAdapter(Context context, List<Movie> movies) {
mContext = context;
mMovies = movies;
}
public MovieAdapter(Callback<NowPlaying> callback, List<Movie> movies) {
}
// Automatically create required methods and override them with mVar
#Override
public int getCount() {
return mMovies.size();
}
#Override
public Object getItem(int position) {
return mMovies.get(position);
}
#Override
public long getItemId(int position) {
return 0; // Use to easier get position reference
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
// If the ListView is brand new
convertView = LayoutInflater.from(mContext).inflate(R.layout.list_movie_item,
parent, false);
// Get layout from the context and inflate it the daily_list_item.
// Use ViewHolder to create smooth scrolling list
holder = new ViewHolder(convertView);
// Set the tag for reuse the View
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
//Set content to holderVar from get
//Create the ModelClass object as an element in the array
// Remember even the Image need to be set (different from MainAct)
Movie movie = mMovies.get(position);
holder.mTvLeftTitle.setText(movie.getTitle());
holder.mTvLeftOverview.setText(movie.getOverview());
// holder.mTvLeftCast.setText(movie.getCast());
Glide.with(mContext)
.load(movie.getPosterPath())
.into(holder.mImgLeftPoster);
holder.mTvRightTitle.setText(movie.getTitle());
holder.mTvRightOverview.setText(movie.getOverview());
// holder.mTvLeftCast.setText(movie.getCast());
Glide.with(mContext)
.load(movie.getPosterPath())
.into(holder.mImgRightPoster);
return convertView;
}
// Create class ViewHolder with Widget as variable based on Model class
static class ViewHolder {
// Using ButterKnife to create and hook Widget (remember the Image, too)
#BindView(R.id.rlLeftLayout)
RelativeLayout mRlLeftLayout;
#BindView(R.id.tvLeftTitle)
TextView mTvLeftTitle;
#BindView(R.id.tvLeftOverview)
TextView mTvLeftOverview;
#BindView(R.id.tvLeftCast)
TextView mTvLeftCast;
#BindView(R.id.imgLeftPoster)
ImageView mImgLeftPoster;
#BindView(R.id.rlRightLayout)
RelativeLayout mRlRightLayout;
#BindView(R.id.tvRightTitle)
TextView mTvRightTitle;
#BindView(R.id.tvRightOverview)
TextView mTvRightOverview;
#BindView(R.id.tvRightCast)
TextView mTvRightCast;
#BindView(R.id.imgRightPoster)
ImageView mImgRightPoster;
ViewHolder(View view) {
ButterKnife.bind(this, view);
}
}
}
This is my Activity:
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
MovieAdapter mAdapter;
List<Movie> mMovies = new ArrayList<Movie>();
private NowPlaying mNowPlaying;
#BindView(android.R.id.list)
ListView mListView;
#BindView(android.R.id.empty)
TextView mEmptyView;
private MovieApi mMovieApi;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
// final MovieAdapter adapter = new MovieAdapter(this, mMovies);
//
mMovieApi = RetrofitUtils.get(getString(R.string.api_key)).create(MovieApi.class);
mMovieApi.getNowPlaying().enqueue(new Callback<NowPlaying>() {
#Override
public void onResponse(Call<NowPlaying> call, Response<NowPlaying> response) {
Log.d("Response", String.valueOf(response.isSuccessful()));
mMovies = response.body().getMovies();
mAdapter = new MovieAdapter(this, mMovies);
mListView.setAdapter(mAdapter);
mListView.setEmptyView(mEmptyView);
}
#Override
public void onFailure(Call<NowPlaying> call, Throwable t) {
Log.e("Error", t.getMessage());
Toast.makeText(MainActivity.this, "OK", Toast.LENGTH_SHORT).show();
}
});
}
}
My Stack Trace:
10-15 23:04:19.480 12537-12537/com.example.rubit1359.bigcornbox E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.rubit1359.bigcornbox, PID: 12363
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at com.example.rubit1359.bigcornbox.ui.MainActivity$1.onResponse(MainActivity.java:57)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5637)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
I have debugged the app to make sure that the mMovies ListView are filled. However I cannot set the Adapter. Anyone can help me spotting the error.
Thank you.
UPDATE XML
XML activity
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/darkness"
tools:context="com.example.rubit1359.bigcornbox.ui.MainActivity">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:id="#+id/ListView"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"/>
<TextView
android:text="There is no data to display"
android:textStyle="bold"
android:textSize="20sp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:textColor="#color/colorWhite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/EmptyView"
/>
</RelativeLayout>
Adapter xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:layout_height="match_parent"
android:background="#color/darkness">
<RelativeLayout
android:id="#+id/rlLeftLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:background="#color/skypeGray">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imgLeftScoreBackground"
android:layout_alignTop="#+id/imgLeftPoster"
android:layout_toEndOf="#+id/imgLeftScoreBackground"
android:layout_toRightOf="#+id/imgLeftScoreBackground"
android:gravity="center_vertical"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:id="#+id/tvLeftTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:lineSpacingExtra="5dp"
android:text="Captain America: Civil War"
android:textAlignment="viewEnd"
android:textColor="#color/redmilk"
android:textSize="15sp"
android:textStyle="bold"/>
<TextView
android:id="#+id/tvLeftOverview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:ellipsize="end"
android:lineSpacingExtra="5dp"
android:maxLines="5"
android:text="Following the events of Age of Ultron, the collective goverments of the world pass an act designed to regulate all superhuman activity. This polarizes opinion amongst the Avengers, causing two factions to side..."
android:textAlignment="viewEnd"
android:textColor="#color/colorWhite"
android:textSize="12sp"/>
<TextView
android:id="#+id/tvLeftCast"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="Chris Evans, Robert Downey Jr."
android:textAlignment="viewEnd"
android:textColor="#color/colorWhite"
android:textSize="12sp"
android:textStyle="bold|italic"/>
</LinearLayout>
<ImageView
android:id="#+id/imgLeftPoster"
android:layout_width="120dp"
android:layout_height="180dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
app:srcCompat="#drawable/poster"/>
<ImageView
android:id="#+id/imgLeftScoreBackground"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/imgLeftPoster"
android:layout_marginTop="3dp"
app:srcCompat="#drawable/background"/>
</RelativeLayout>
<RelativeLayout
android:id="#+id/rlRightLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#color/skypeGray">
<ImageView
android:id="#+id/imgRightPoster"
android:layout_width="120dp"
android:layout_height="180dp"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
app:srcCompat="#drawable/poster"/>
<ImageView
android:id="#+id/imgRightScoreBackground"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/imgRightPoster"
android:layout_marginTop="3dp"
app:srcCompat="#drawable/background_right"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imgRightScoreBackground"
android:layout_alignTop="#+id/imgRightPoster"
android:layout_toLeftOf="#+id/imgRightScoreBackground"
android:layout_toStartOf="#+id/imgRightScoreBackground"
android:gravity="center_vertical"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:id="#+id/tvRightTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:lineSpacingExtra="5dp"
android:text="Captain America: Civil War"
android:textAlignment="viewStart"
android:textColor="#color/redmilk"
android:textSize="15sp"
android:textStyle="bold"/>
<TextView
android:id="#+id/tvRightOverview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:ellipsize="end"
android:lineSpacingExtra="5dp"
android:maxLines="5"
android:text="Following the events of Age of Ultron, the collective goverments of the world pass an act designed to regulate all superhuman activity. This polarizes opinion amongst the Avengers, causing two factions to side..."
android:textAlignment="viewStart"
android:textColor="#color/colorWhite"
android:textSize="12sp"/>
<TextView
android:id="#+id/tvRightCast"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="Chris Evans, Robert Downey Jr."
android:textAlignment="viewStart"
android:textColor="#color/colorWhite"
android:textSize="12sp"
android:textStyle="bold|italic"/>
</LinearLayout>
</RelativeLayout>
</RelativeLayout>
You are getting a wrong id:
Change these lines:
#BindView(android.R.id.list)
ListView mListView;
to :
#BindView(R.id.ListView)
ListView mListView;
You are using listview id which is inbuild android.R.id.list which requires you to extend your activity with ListActivity.
So extend your activity with ListActivity. like this
public class MainActivity extends ListActivity
Or, If you use use custom listview with your id, then use same activity, just give proper id which you defined in your xml file and initialize it.
Something like this
ListView list = (ListView) view.findViewById(R.id.yourlistviewid);

Very custom listview row?

i a have a specific design in my photoshop, but i cant figure out how to make it in android for a table row. As you can see bellow in the picture, i need a list of alarms. So i was thinking to make it as table row for every row same so i can input stuff to that table row via *.java.
Heres picture
and here is my code what i have now
<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="#162030"
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=".MainActivity" >
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/textView1"
android:layout_marginTop="76dp"
android:background="#131b29"
>
<TableLayout
android:layout_width="fill_parent"
android:layout_height="774dp"
android:orientation="vertical" >
<TableRow
android:id="#+id/TableRow04"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:layout_marginBottom="0dp"
android:background="#162030"
android:minHeight="60dp" >
</TableRow>
<TableRow
android:id="#+id/TableRow05"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:layout_marginBottom="0dp"
android:background="#162030"
android:minHeight="60dp" >
</TableRow>
</TableLayout>
</ScrollView>
<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="76dp"
android:shadowColor="#62f1fa"
android:shadowDx="0.0"
android:shadowDy="0.0"
android:shadowRadius="20"
android:text="0:00"
android:textColor="#5ee6ef"
android:textSize="50sp" />
Make your main xml layout as this :
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent" ... >
<ListView
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" ... />
Create a layout for your custom styled item list (alarm_item.xml in layout folder) :
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<!-- This is your clock icon -->
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<!-- This is your alarm clock name -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<!-- Create imageview and textview for all other needed data -->
</RelativeLayout >
Create an adapter to fill listview with item (take a look there for more details) :
public class AlarmAdapter extends BaseAdapter {
Context context;
Arraylist data;
private static LayoutInflater inflater = null;
public yourAdapter(Context context, Arraylist data) {
// TODO Auto-generated constructor stub
this.context = context;
this.data = data;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get object from list that contains Alarm data for this view
// I assume that your alarm data correspond to an object name AlarmData
AlarmData alarmData = getItem(position)
View rootView = convertView;
if (rootView == null)
rootView = inflater.inflate(R.layout.alarm_item, parent, false);
TextView alarmClockName= (TextView) rootView.findViewById(R.id.alarm_clock_name);
ImageView clockIcon = (ImageView ) rootView.findViewById(R.id.alarm_clock_name);
// Set your data there
clockIcon.setImageResource(iconRes);
alarmClockName.setText(alarmData.getName());
return rootView;
}
}
Finally get and fill listview with items in MainActivity :
public class AlarmActivity extends Activity {
// I assume that your alarm data correspond to an object name AlarmData
// so I define a Arraylist that will contains all alarms to display
ArrayList<AlarmData> alarmList = new ArrayList<Alarmdata>();
ListView listview;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Get listivew from main layout
listview = (ListView) findViewById(R.id.listview);
// Add alarm to display in alarmlist
alarmList.add(new AlarmData());
alarmList.add(new AlarmData());
// Create alarm listview adapter with current context (this) and alarmlist
AlarmAdapter alarmAdapter = new AlarmAdapter(this, alarmList);
// Set previous adapter on listview
listview.setAdapter(alarmAdapter);
}
}
This is just a simple example of Custom listview adapter, hope this helps you.
After creating this mecanisme you just have to work on your item layout

Custom ListAdapter Never Calling GetView

I've been trying to figure out what is going on with this for a little while, maybe I have been staring at it too long... I feel like it's something simple.
Here is my ListActivity class
public class ResultsListActivity extends ListActivity {
private ArrayList<Result> results = new ArrayList<Result>();
private ListView list;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sp_history);
//set up list
list = new ListView(this);
}
#Override
protected void onResume()
{
super.onResume();
results = openAndQueryDatabase();
displayResultList();
}
private void displayResultList() {
list.setAdapter(new HistoryArrayAdapter(this.getBaseContext(), results));
}
private ArrayList<Result> openAndQueryDatabase() {
DatabaseHandler dbh = new DatabaseHandler(getBaseContext());
ArrayList<Result> toReturn = dbh.getAllResults();
return toReturn;
}//open and query database
public int getCount() {
return null == results ? 0 : results.size();
}
}
Here is my ListAdapterClass
public class HistoryArrayAdapter extends ArrayAdapter<Result> {
private final Context context;
private final ArrayList<Result> values;
private int layoutId;
public HistoryArrayAdapter(Context context, ArrayList<Result> results) {
super(context, R.layout.history_row, results);
this.context = context;
this.layoutId = R.layout.history_row;
this.values = results;
}
#Override
public int getCount() {
return values.size();// more than zero
}
#Override
public Result getItem(int position) {
return values.get(position);// may be in your case
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null)
{
// inflate the layout
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
convertView = inflater.inflate(layoutId, parent, false);
}// if convertView == null
//set up our views
TextView uploadSpeed = (TextView) convertView.findViewById(R.id.upload_speed_history);
TextView downloadSpeed = (TextView) convertView.findViewById(R.id.download_speed_history);
TextView pingTime = (TextView) convertView.findViewById(R.id.ping_history_text);
TextView networkName = (TextView) convertView.findViewById(R.id.history_network_name);
TextView dateTime = (TextView) convertView.findViewById(R.id.history_dateTime);
ImageView imageView = (ImageView) convertView.findViewById(R.id.history_connection);
//set up our values
Result row = values.get(position);
uploadSpeed.setText(row.getUpload());
downloadSpeed.setText(row.getDownload());
pingTime.setText(row.getPingTime());
networkName.setText(row.getNetworkName());
dateTime.setText(row.getDateTime());
if(row.getNetworkType() == "NETWORK_WIFI")
imageView.setImageResource(R.drawable.ico_wifi);
else
imageView.setImageResource(R.drawable.ico_cell);
return convertView;
}//getView
}
Here is the .xml for the ListView
<?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">
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#b5b5b5"
android:dividerHeight="1dp" />
</LinearLayout>
And Here is the 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="wrap_content"
android:orientation="vertical" >
<RelativeLayout
android:id="#+id/realtive_line_1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/history_network_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginLeft="26dp"
android:layout_toRightOf="#+id/imageView1"
android:text="TextView" />
<ImageView
android:id="#+id/history_connection"
android:layout_width="20dip"
android:layout_height="20dip"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft = "20dip"
android:layout_marginTop = "5dip"
android:src="#drawable/ico_wifi" />
<TextView
android:id="#+id/history_dateTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="65dp"
android:layout_below="#+id/network_name"
android:text="2013-08-15 12:35:00 PM"
android:textSize="10sp" />
</RelativeLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/realtive_line_1"
>
<ImageView
android:id="#+id/imageView2"
android:layout_width="15dip"
android:layout_height="15dip"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="23dp"
android:layout_marginTop = "15dip"
android:src="#drawable/ico_ping" />
<TextView
android:id="#+id/ping_history_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="25dp"
android:layout_toRightOf="#+id/imageView2"
android:text="30 ms"
android:textSize = "15sp"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ImageView
android:id="#+id/results_icon_up"
android:layout_width="20dip"
android:layout_height="20dip"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:src="#drawable/ico_up"
android:layout_marginRight = "40dip" />
<ImageView
android:id="#+id/results_icon_down"
android:layout_width="20dip"
android:layout_height="20dip"
android:layout_alignParentRight="true"
android:layout_marginTop="5dip"
android:layout_below ="#+id/results_icon_up"
android:src="#drawable/ico_down"
android:layout_marginRight = "40dip" />
<TextView
android:id="#+id/upload_speed_history"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/results_icon_down"
android:layout_marginRight="15dp"
android:layout_toLeftOf="#+id/results_icon_up"
android:text="4.26 Mbps"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/download_speed_history"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/upload_speed_history"
android:layout_alignTop="#+id/results_icon_down"
android:text="24.56 Mbps"
android:textAppearance="?android:attr/textAppearanceSmall" />
</RelativeLayout>
<ImageView
android:id="#+id/imageView3"
android:layout_width="20dip"
android:layout_height="20dip"
android:layout_alignParentRight ="true"
android:layout_centerVertical="true"
android:src="#drawable/arrow" />
</RelativeLayout>
Things that I do know... I do have results. I can see it in the debugger and they are populated fine. I know I have a few things that look like unnecessary methods, there is work to be done there to make sure the app isn't in the middle of a process before it populates the list.
Change your onCreate() like below,
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sp_history);
//set up list
list = getListView();
}
AS you've stated that you are using Asynchronous call to get the Database results... even though while debugging you are getting the results, chances are that while actually running, the results might be getting after the adapter has been set in the following line hence the length of results in adapter is 0, so your getView() isn't getting a callback.
Either can have a Custom Listener that will get a call back when the results have been fetched and then you can set the adapter to the listview OR another solution might be to hold the instance of your adapter and then add the acquired results to the adapter using the Adapter.add() method and then call Adapter.notifyDataSetChanged() method.
Edit:- Also as you are using ListActivity, there's no need to create a new ListView instance. Just call getListView() method to obtain the ListView instance as the above answerer suggested.

Issue trying to change ImageView in List Activity

I am having problems when I try to alter the image in a list view.
Below is the layout XML for the row in the list:
<?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="?android:attr/listPreferredItemHeight"
android:orientation="horizontal"
android:gravity="left">
<ImageView
android:id="#+id/flagIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="0.1"
android:src="#drawable/orange_flag"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center_vertical"
android:orientation="vertical" >
<TextView
android:id="#+id/location_row_item_main_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/location_row_item_secondary_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:textAppearance="?android:attr/textAppearanceSmall"/>
</LinearLayout>
Runs ok and shows the drawable stated (i.e. orange_flag), but this doesn't change when I try and alter it in the following code:
private class MyListAdapter extends ResourceCursorAdapter {
// In your ListActivity class, create a new inner class that extends ResourceCursorAdapter.
//This inner class is the custom CursorAdapter we will use to manage how data is bound to a list item:
public MyListAdapter(Context context, Cursor cursor) {
super(context, R.layout.row_location, cursor);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView title = (TextView) view.findViewById(R.id.location_row_item_main_text);
title.setText(cursor.getString(
cursor.getColumnIndex(RMDbAdapter.RACKING_SYSTEM)));
ImageView flagIcon = (ImageView) view.findViewById(R.id.flagIcon);
String risk = cursor.getString(cursor.getColumnIndex(RMDbAdapter.RISK));
if (risk == "Red Risk"){
flagIcon.setImageResource(R.drawable.red_flag);
}
else if (risk == "Green Risk"){
flagIcon.setImageResource(R.drawable.green_flag);
}
else if (risk =="No Risk"){
flagIcon.setImageResource(R.drawable.note);
}
Any ideas?!
Always use equals() or equalsIgnoreCase() when comparing String data type for the contents.
For strings in java:
== compares whether strings are same Object or not.
equals() compares whether strings have same sequence of characters or not.
Try adding flagIcon.invalidate() after setting the resource.
Instead of trying
flagIcon.setImageResource(R.drawable.red_flag);
You can try this :
flagIcon.setBackgroundResource(R.drawable.red_flag);

android list inside layout

i am working on an Android app that needs showing a list[table], inside the layout[view]
I come from iPhone dev objC land, and i have an app that shows a table[list] inside the view[layout]
So how to show a list inside my layout, and place it to specified location [center],
ps. I havent found a list in the graphical layout editor of the xml, where is the list[table]?
2. I have done some tests with list views, but is a view, that replace the xml view, i want it inside my xml,,
thanks a lot!
Yes, of course, you can do that
1) you need to have listholder.xml here, you can scratch anything in you layout view, either imageview, textview..etc. just don't forget to add ListView inside it. for example:
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/head_logo_bg">
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/background_label">
<TextView
android:id="#+id/city_txt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:layout_gravity="center"
android:text="Sydney"
android:textStyle="bold"
android:textSize="17sp"/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="40sp">
<ListView
android:id="#android:id/list"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_centerVertical="true"
android:scrollingCache="false"/>
</LinearLayout>
2) For custom your own list item, you have to create listitem.xml i.e.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/listitemone"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="10sp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:orientation="vertical">
<ImageView android:id="#+id/user_image"
android:layout_width="80px" android:layout_height="80px"
android:layout_alignParentLeft="true"
android:layout_marginRight="5px"
android:src="#drawable/icon"
/>
</LinearLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="5sp"
android:orientation="vertical">
<TextView
android:id="#+id/date_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/date"
android:textStyle="bold"
android:textSize="16sp" />
<TextView
android:id="#+id/date_value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignBaseline="#id/date_label"
android:layout_marginRight="20sp"
android:textColor="#FFF"
android:text="MM/dd/YYYY"
android:textStyle="bold"
android:textSize="16sp" />
</RelativeLayout>
</LinerLayout>
3) create customAdapter in your activity, it would look like this;
public class MyListActivity extends ListActivity {
private ArrayList<Yourdata> yourdata = new ArrayList<Youdata>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listholder);
// yourdata might be array, arraylist etc.
MyCustomAdapter listadapter = new MyCustomAdapter(this, R.layout.listitem, yourdata);
setListAdapter(listadapter);
}
private class MyCustomAdapter extends ArrayAdapter<Yourdata>{
//this case, i use Yourdata as type
private ArrayList<Yourdata> items;
public PreviousAdapter(Context context, int textViewResourceId,
ArrayList<Yourdata> items) {
super(context, textViewResourceId, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if(v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.listitem, null);
}
Yourdata yt = items.get(position);
if(yt != null){
// Don't forget to use v.findView...., otherwise, it might force close when run app.
TextView dateStr = (TextView)v.findViewById(R.id.date_value);
dateStr.setText(yt.getDate());
}
return v;
}
}
}
P.S. the above code might not exactly right... just give you an idea :)
Here is a source about custom list (you might have seen it) hope it useful
http://www.vogella.de/articles/AndroidListView/article.html
I have try these example it's very nice.
you can get the example from
http://www.codeproject.com/Articles/507651/Customized-Android-ListView-with-Image-and-Text?msg=4567162#xx4567162xx

Categories

Resources