ListView by an ArrayList of serializable objects - android

Now I have a serializable Object Class called Tasks, I intend to make a Listview, each object represent an item within the list but when I run the code it does not work
this is the Main Activity :
public class MainActivity extends ActionBarActivity {
EditText NameET, ImportanceED, dateED, TimeED;
String Name, Importance, date, Time;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
NameET = (EditText) findViewById(R.id.NameeditText);
ImportanceED = (EditText) findViewById(R.id.ImportanceeditText2);
dateED = (EditText) findViewById(R.id.dateeditText3);
TimeED = (EditText) findViewById(R.id.timeeditText4);
public void GetTexts() {
Name = NameET.getText().toString();
Importance = ImportanceED.getText().toString();
date = dateED.getText().toString();
Time = TimeED.getText().toString();
}
public void AddTask(View view) {
String testName = NameET.getText().toString().trim();
String testImportance = ImportanceED.getText().toString().trim();
String testDate = dateED.getText().toString().trim();
String testTime = TimeED.getText().toString().trim();
GetTexts();
OpenDetailsActivity();
}
}
public void OpenDetailsActivity() {
Intent DetailsIntent = new Intent(this, DetailsActivity.class);
DetailsIntent.putExtra("Name",Name );
DetailsIntent.putExtra("Importance",Importance );
DetailsIntent.putExtra("date",date );
DetailsIntent.putExtra("Time",Time );
startActivity(DetailsIntent);
}
and this is the List containing activity :
public class DetailsActivity extends Activity {
ListView list;
String Name;
String Importance;
String date;
String Time ;
ArrayList <Tasks>TaskList = new ArrayList();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.task_list);
Intent intent = getIntent();
Name= intent.getStringExtra("Name");
Importance= intent.getStringExtra("Importance");
date= intent.getStringExtra("date");
Time= intent.getStringExtra("Time");
addToList();
}
public void addToList() {
int i ;
int N = TaskList.size();
if (N > 0 ){
i = N + 1 ;
} else {
i= 0 ;
}
Everything works fine untill here , the list appears blank
TaskList.add(i, new Tasks(Name, Importance, date, Time));
ListAdapter adapter = new ListAdapter(this, TaskList);
list = (ListView) findViewById(R.id.listView_tasks);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String SelectedTask = TaskList.get(position).getName();
Toast.makeText(getApplicationContext(), SelectedTask, Toast.LENGTH_SHORT).show();
this is Tasks Serializable class
class Tasks implements Serializable {
String name="";
String date="";
String time = "";
String importance="";
public Tasks(String name, String importance, String date , String time) {
this.date = date;
this.importance = importance;
this.name = name;
this.time = time;
}
public String getDate() {
return date;
}
public String getImportance() {
return importance;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTime() {
return time;
}
and this is the custom adapter
public class ListAdapter extends ArrayAdapter {
private final Activity context;
List<Tasks> TaskList;
public ListAdapter(Activity context, List<Tasks> TaskList) {
super(context, R.layout.row_layout);
this.context=context;
this.TaskList=TaskList;
}
public View getView(int position,View view,ViewGroup parent) {
LayoutInflater inflater=context.getLayoutInflater();
View rowView=inflater.inflate(R.layout.row_layout, null , false);
TextView Name = (TextView) rowView.findViewById(R.id.NameTV);
TextView Date = (TextView) rowView.findViewById(R.id.dateTV);
TextView Importance = (TextView) rowView.findViewById(R.id.importanceTV);
TextView Time = (TextView) rowView.findViewById(R.id.timeTV);
TaskList.get(position).getName();
Name.setText(TaskList.get(position).getName());
Date.setText(TaskList.get(position).getDate());
Importance.setText(TaskList.get(position).getImportance());
Time.setText(TaskList.get(position).getTime());
return rowView;
this is task_list Layout
<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="wrap_content"
android:id="#+id/listView_tasks" />
</LinearLayout>
and this row_layout
<LinearLayout
android:orientation="vertical"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/NameTV"
android:layout_gravity="center_horizontal" />
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/importanceTV" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:id="#+id/dateTV" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:id="#+id/timeTV" />
</LinearLayout>
</LinearLayout>

I have do some changes in your code, I tested it on my pc and it is working.
I only update ListAdapter.java and It works.
ListAdapter.java
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Usman Asghar on 23/02/2016.
*/
public class ListAdapter extends ArrayAdapter {
Context context;
List<Tasks> TaskList;
public ListAdapter(Activity context, List<Tasks> TaskList) {
super(context, R.layout.row_layout,TaskList);
this.context = context;
this.TaskList = TaskList;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.row_layout, null, false);
}
TextView Name = (TextView) view.findViewById(R.id.NameTV);
TextView Date = (TextView) view.findViewById(R.id.dateTV);
TextView Importance = (TextView) view.findViewById(R.id.importanceTV);
TextView Time = (TextView) view.findViewById(R.id.timeTV);
Name.setText(TaskList.get(position).getName());
Date.setText(TaskList.get(position).getDate());
Importance.setText(TaskList.get(position).getImportance());
Time.setText(TaskList.get(position).getTime());
return view;
}
}
I changed ArrayAdapter constructor to
super(context, R.layout.row_layout);
That
super(context, R.layout.row_layout,TaskList);
ArrayAdapter does not work until we do not specify what data we want to show on ListView.
And I Do some little Changes in getView() method.

Add to your adapter this method:
#Override
public int getCount() {
return TaskList.size();
}
Change this:
TaskList.add(i, new Tasks(Name, Importance, date, Time));
to this:
TaskList.add(new Tasks(Name, Importance, date, Time));

Related

i have array of objects. i want to display its elements in a listview

i have array of objects carts containing itemname and price. Array is coming correctly from sqlite database. i want to display it in a listview. But in a listview it is only showing the package name not itemname and price. I think problem is in this line "ListAdapter buckysAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, carts); "of Main2Activity.java
Below is my code please guide me.It is very important for me
Main2Activity.java
public class Main2Activity extends Activity {
MyDBHandler dbHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Intent intent = getIntent();
final int position = intent.getIntExtra("history",1);
Log.i("positin","position = "+String.valueOf(position));
dbHandler = new MyDBHandler(this,null,null,6);
Cart[] carts = dbHandler.databaseToArray(position);
for (Cart c : carts)
Log.i("jhnbvb1","item1 = "+c.getItemname()+" price1 = "+c.getPrice());
ListAdapter buckysAdapter = new ArrayAdapter<Cart>(this, android.R.layout.simple_list_item_1, carts);
ListView buckysListView = (ListView) findViewById(R.id.buckysListView2);
buckysListView.setAdapter(buckysAdapter);
}}
CustomAdapter2.java
public class CustomAdapter2 extends ArrayAdapter<Cart> {
public CustomAdapter2(Context context, Cart[] foods) {
super(context, R.layout.custom_row2 ,foods);
}
#Override
public Cart getItem(int position) {
return super.getItem(position);
}
#Override
public int getPosition(Cart item) {
return super.getPosition(item);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater buckysInflater = LayoutInflater.from(getContext());
View customView = buckysInflater.inflate(R.layout.custom_row2, parent, false);
Cart singleFoodItem = getItem(position);
String name = singleFoodItem.getItemname();
String price = singleFoodItem.getPrice();
Log.i("rtyiykj","item2 = "+name+" price2 = "+price);
TextView buckysText = (TextView) customView.findViewById(R.id.buckysText2);
TextView buckysText1 = (TextView) customView.findViewById(R.id.buckysText3);
buckysText.setText(name);
buckysText1.setText(price);
return customView;
}}
custom_row2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="200dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/buckysText2"
android:layout_margin="5dp" />
<TextView
android:layout_width="200dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/buckysText3"
android:layout_margin="5dp" />
activity_main2.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=".Main2Activity">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/buckysListView2"></ListView>
cart.java
public class Cart {
private String itemname,price;
public Cart(String itemname,String price) {
this.setItemname(itemname);
this.setPrice(price);
}
public Cart() {}
public void setItemname(String itemname) {
this.itemname = itemname;
}
public void setPrice(String price) {
this.price = price;
}
public String getItemname() {
return itemname;
}
public String getPrice() {
return price;
}}
You use standard ArrayAdapter instead of that one created by you. It should be
CustomAdapter2<Cart> buckysAdapter = new CustomAdapter2<Cart>(this, carts);
And array adapter itself should be modified:
public class CustomAdapter2 extends ArrayAdapter<Cart> {
private final List<Object> foods;
public CustomAdapter2(Context context, List<Cart> foods) {
super(context, 0);
this.foods = foods;
}
#Override
public int getCount() {
return foods.size();
}
#Override
public Cart getItem(int position) {
return foods.get(position);
}
//your getView
}

Android: CustomListView with CustomAdapter, Call Button is not working

In my app I have 3 views
ImagiveView
TextView
Button
ImagView displays image accordingly, TextView and Button display names and number accordingly. But the problem is when I click on the button it does not call to the number which is displaying on the button. Although it does open the android caller app.
Telephone numbers are in string.xml file.
Here I provide my all files. Please help me
strings.xml
<string-array name="names">
<item>Abdul Malik</item>
<item>Adeel ur Rehman</item>
<item>Asad Majeeb</item>
<item>Ata ul Salam</item>
<item>Atta ul Qadir</item>
<item>Bilal Scunder</item>
<item>Chaudry Adnan Ahmed</item>
<item>Chaudry Imran</item>
<item>Ejaz Ahmed Saroya</item>
<item>Hamid Joya</item>
</string-array>
<string-array name="telephones">
<item>0000000000</item>
<item>0486607636</item>
<item>0485256515</item>
<item>0485128196</item>
<item>0465922084</item>
<item>0487150005</item>
<item>0488627993</item>
<item>0484783792</item>
<item>0484688663</item>
<item>0497697050</item>
</string-array>
MainActivity.xml
package com.example.android.listview_with_custom_layout;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.ListView;
public class MainActivity extends ActionBarActivity {
ListView listView;
int [] movie_poster_resource={
R.drawable.movie_1,
R.drawable.movie_2,
R.drawable.movie_3,
R.drawable.movie_4,
R.drawable.movie_5,
R.drawable.movie_6,
R.drawable.movie_7,
R.drawable.movie_8,
R.drawable.movie_9,
R.drawable.movie_10,
};
String [] names ={};
String [] telephones ={};
MoviesAdapter moviesAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView=(ListView) findViewById(R.id.list_view);
telephones =getResources().getStringArray(R.array.telephones);
names =getResources().getStringArray(R.array.names);
int i=0;
moviesAdapter= new MoviesAdapter(getApplicationContext(),R.layout.row_layout);
listView.setAdapter(moviesAdapter);
for(String titles: names){
MovieDataProvider movieDataProvider= new MovieDataProvider(movie_poster_resource[i], titles, telephones[i]);
moviesAdapter.add(movieDataProvider);
i++;
}
}
}
MoviesDataAdapter
package com.example.android.listview_with_custom_layout;
/**
* Created by temp on 2/11/2015.
*/
public class MovieDataProvider {
private int movie_poster_resource;
private String movie_title;
private String telePhone;
public MovieDataProvider(int movie_poster_resource, String movie_title, String telePhone) {
this.setMovie_poster_resource(movie_poster_resource);
this.setMovie_title(movie_title);
this.telePhone = telePhone;
}
public int getMovie_poster_resource() {
return movie_poster_resource;
}
public String getMovie_title() {
return movie_title;
}
public String getTelePhone() {
return telePhone;
}
public void setMovie_poster_resource(int movie_poster_resource) {
this.movie_poster_resource = movie_poster_resource;
}
public void setMovie_title(String movie_title) {
this.movie_title = movie_title;
}
public void setTelePhone(String telePhone) {
this.telePhone = telePhone;
}
}
MoviesAdapter
package com.example.android.listview_with_custom_layout;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by temp on 2/11/2015.
*/
public class MoviesAdapter extends ArrayAdapter {
List list = new ArrayList();
MovieDataProvider dataProvider;
public MoviesAdapter(Context context, int resource) {
super(context, resource);
}
static class DataHandler {
ImageView Poster;
TextView title;
Button telePhone;
}
#Override
public void add(Object object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return this.list.size();
}
#Override
public Object getItem(int position) {
return this.list.get(position);
}
#Override
public View getView(int position, View convertView, final ViewGroup parent) {
View row;
row = convertView;
DataHandler handler;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.row_layout, parent, false);
handler = new DataHandler();
handler.Poster = (ImageView) row.findViewById(R.id.movie_poster);
handler.title = (TextView) row.findViewById(R.id.movie_title);
handler.telePhone = (Button) row.findViewById(R.id.btn_call);
row.setTag(handler);
} else {
handler = (DataHandler) row.getTag();
}
dataProvider = (MovieDataProvider) this.getItem(position);
handler.Poster.setImageResource(dataProvider.getMovie_poster_resource());
handler.title.setText(dataProvider.getMovie_title());
handler.telePhone.setText(dataProvider.getTelePhone());
handler.telePhone.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Intent to launch phone dialer
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:" + dataProvider.getTelePhone()));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getContext().startActivity(intent);
}
});
return row;
}
}
activity_main.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:background="#ffffd953"
tools:context=".MainActivity">
<ListView
android:id="#+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
row_layout.xml
<?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="80dp"
android:background="#000000"
android:orientation="vertical"
android:paddingTop="10dp">
<ImageView
android:id="#+id/movie_poster"
android:layout_width="100dp"
android:layout_height="75dp"
android:layout_alignParentLeft="true"
android:src="#drawable/movie_1" />
<TextView
android:id="#+id/movie_title"
android:layout_width="100dp"
android:layout_height="75dp"
android:layout_toRightOf="#+id/movie_poster"
android:gravity="center"
android:text="This is movie name"
android:textColor="#FFFFFF" />
<Button
android:id="#+id/btn_call"
android:layout_width="wrap_content"
android:layout_height="75dp"
android:layout_alignParentRight="true"
android:layout_toRightOf="#+id/movie_title"
android:gravity="center"
android:text="call"
android:textColor="#FFFF" />
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:layout_below="#+id/movie_poster"
android:background="#FFFF"></View>
</RelativeLayout>
you forgot to initialize the telephones string in your MainActivity, do same as you did for movie_poster_resource after this it should work, and dont forgot to add permission
<uses-permission android:name="android.permission.CALL_PHONE"></uses-permission>
and last you can update the button click code with
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:"+dataProvider.getTelePhone()));
startActivity(callIntent);
and update your AdapterClass with this
public class MoviesAdapter extends ArrayAdapter {
List list = new ArrayList();
public MoviesAdapter(Context context, int resource) {
super(context, resource);
}
static class DataHandler {
ImageView Poster;
TextView title;
Button telePhone;
}
#Override
public void add(Object object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return this.list.size();
}
#Override
public Object getItem(int position) {
return this.list.get(position);
}
#Override
public View getView(int position, View convertView, final ViewGroup parent) {
View row;
row = convertView;
final MovieDataProvider dataProvider = (MovieDataProvider) this.getItem(position);;
DataHandler handler;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.row_layout, parent, false);
handler = new DataHandler();
handler.Poster = (ImageView) row.findViewById(R.id.movie_poster);
handler.title = (TextView) row.findViewById(R.id.movie_title);
handler.telePhone = (Button) row.findViewById(R.id.btn_call);
} else {
handler = (DataHandler) row.getTag();
}
handler.Poster.setImageResource(dataProvider.getMovie_poster_resource());
handler.title.setText(dataProvider.getMovie_title());
handler.telePhone.setText(dataProvider.getTelePhone());
handler.telePhone.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:" + dataProvider.getTelePhone()));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getContext().startActivity(intent);
}
});
row.setTag(handler);
return row;
}
}

how to insert an image into a listview?

I would like to insert a small image to the right of each item in a listview
basically my app should do so as soon as the user clicks on an item in the list view, the image becomes visible, otherwise it must remain invisible.
below is my activity with its XML
Activity
public class EpisodiActivity extends Activity {
public class ViewModel {
private String url;
private String name;
public ViewModel(String url, String name) {
this.url = url;
this.name = name;
}
public String getUrl() {
return this.url;
}
public void setUrl(String url) {
this.url = url;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String toString() {
return this.name;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//creazione fullscreen activity
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.episodi_activity);
String[] episodi = getIntent().getStringArrayExtra("Product");
String[] urls = getIntent().getStringArrayExtra("urls");
ListView mylist = (ListView) findViewById(R.id.listView1);
// And in this loop we create the ViewModel instances from
// the name and url and add them all to a List
List<ViewModel> models = new ArrayList<ViewModel>();
for (int i = 0; i < episodi.length; i++) {
String name = episodi[i];
String url = "No value";
if (i < urls.length) {
url = urls[i];
}
ViewModel model = new ViewModel(url, name);
models.add(model);
}
// Here we create the ArrayAdapter and assign it to the ListView
// We pass the List of ViewModel instances into the ArrayAdapter
final ArrayAdapter<ViewModel> adapter = new ArrayAdapter<ViewModel>(this, android.R.layout.simple_list_item_1, models);
mylist.setAdapter(adapter);
mylist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
// Here we get the ViewModel at the given position
ViewModel model = (ViewModel) arg0.getItemAtPosition(position);
// And the url from the ViewModel
String url = model.getUrl();
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
}
});
}
XML
RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ListView
android:id="#+id/listView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#id/pubblicita"
android:cacheColorHint="#ffd700"
android:background="#drawable/sfondobottone" />
I think you want this kind of output in listview
text with image in listview
You can use custom listview . Make a class which extends BaseAdapter class
here is the exmaple that i am using
Your BaseAdapter
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class FrontListBaseAdapter extends BaseAdapter {
private static ArrayList<FrontDetails> itemDetailsrrayList;
private LayoutInflater l_Inflater;
public FrontListBaseAdapter(Context context, ArrayList<FrontDetails> results) {
itemDetailsrrayList = results;
l_Inflater = LayoutInflater.from(context);
}
public int getCount() {
return itemDetailsrrayList.size();
}
public Object getItem(int position) {
return itemDetailsrrayList.get(position);
}
public long getItemId(int position) {
return position;
}
// get the views in frontview xml file where you have
// define multiple views that will appear in listview each row
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = l_Inflater.inflate(R.layout.frontview, null);
holder = new ViewHolder();
holder.Image = (ImageView) convertView.findViewById(R.id.adminpic1);
holder.MsgType = (TextView) convertView.findViewById(R.id.msgtype1);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.Image.setImageResource(R.drawable.mainlogo); // you can set your setter here
holder.MsgType.setText(itemDetailsrrayList.get(position).getMsgType());
return convertView;
}
// holder view for views
static class ViewHolder {
ImageView Image;
TextView MsgType;
}
}
your FrontDetails class where you will make getters and setters and this class will be used in final ArrayList resultse = new ArrayList();
import android.graphics.Bitmap;
public class FrontDetails {
public int getImage() {
return image;
}
public void setImage(int imageN) {
this.image = imageN;
}
public String getMsgType() {
return MsgType;
}
public void setMsgType(String text) {
this.MsgType = text;
}
private int image;
private String MsgType;
}
your frontview.XML where you put your multiple views that will be in each row or your 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="100dp"
android:orientation="vertical"
android:layout_margin="10dp" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="80dp" >
<ImageView
android:id="#+id/adminpic1"
android:layout_width="60dp"
android:layout_height="60dp"
android:src="#drawable/ic_launcher" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/msgtype1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="4dp"
android:textSize="1sp"
android:text="MsgType" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
and your listview in xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/sync"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sync" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp" >
</ListView>
</LinearLayout>
now in your main activity
final ArrayList<FrontDetails> resultse = new ArrayList<FrontDetails>();
FrontListBaseAdapter asdf = new FrontListBaseAdapter(context, resultse);
lv1.setAdapter(new FrontListBaseAdapter(Front.this, resultse));
lv1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
Object o = lv1.getItemAtPosition(position);
FrontDetails obj_itemDetails = (FrontDetails)o;
Toast.makeText(context, "You have chosen " + ' ' + obj_itemDetails.getMsgType(), Toast.LENGTH_LONG).show();
}
});
EDIT:
From here i learned Custom Listview its a simple exmaple with image
http://www.javasrilankansupport.com/2012/05/android-listview-example-with-image-and.html
http://www.javacodegeeks.com/2012/10/android-listview-example-with-image-and.html
Use custom listview with BaseAdapter
Your Adapter
public class CustomBaseAdapter extends BaseAdapter {
Context context;
List<RowItem> rowItems;
public CustomBaseAdapter(Context context, List<RowItem> items) {
this.context = context;
this.rowItems = items;
}
/*private view holder class*/
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
TextView txtDesc;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.txtDesc = (TextView) convertView.findViewById(R.id.desc);
holder.txtTitle = (TextView) convertView.findViewById(R.id.title);
holder.imageView = (ImageView) convertView.findViewById(R.id.icon);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
RowItem rowItem = (RowItem) getItem(position);
holder.txtDesc.setText(rowItem.getDesc());
holder.txtTitle.setText(rowItem.getTitle());
holder.imageView.setImageResource(rowItem.getImageId());
return convertView;
}
#Override
public int getCount() {
return rowItems.size();
}
#Override
public Object getItem(int position) {
return rowItems.get(position);
}
#Override
public long getItemId(int position) {
return rowItems.indexOf(getItem(position));
}
}
Your list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ImageView
android:id="#+id/icon"
android:layout_width="80dp"
android:layout_height="80dp"
android:contentDescription="#string/image"
android:paddingLeft="10dp"
android:paddingRight="10dp" />
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/icon"
android:paddingBottom="10dp"
android:textColor="#CC0033"
android:textSize="16dp" />
<TextView
android:id="#+id/desc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/title"
android:layout_toRightOf="#+id/icon"
android:paddingLeft="10dp"
android:textColor="#3399FF"
android:textSize="14dp" />
</RelativeLayout>
Your Single Row item class
public class RowItem {
private int imageId;
private String title;
private String desc;
public RowItem(int imageId, String title, String desc) {
this.imageId = imageId;
this.title = title;
this.desc = desc;
}
public int getImageId() {
return imageId;
}
public void setImageId(int imageId) {
this.imageId = imageId;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Override
public String toString() {
return title + "\n" + desc;
}
}
List view implementation
listView = (ListView) findViewById(R.id.list);
CustomBaseAdapter adapter = new CustomBaseAdapter(this, rowItems);
listView.setAdapter(adapter);
I can give some tips ,but unfortunately couldn't help you by example..
First of all create one custom adapter(extends BaseAdapter) followed by one custom layout..
Here the custom layout contains the textview and one image view(by default invisible) at the right.
Just customize your list view with your adapter and put text inside TextView through get view()..
At last in your listItemClickListener make the image visible by its position.
You can set here on xml like this
android:visibility="visible"
or
android:visibility="invisible"
or
android:visibility="gone"
Java program:
ImageView imgView = (ImageView)findViewById(R.id.custom);
set your ImageView like this
imgView .setVisibility(View.VISIBLE);
imgView .setVisibility(View.INVISIBLE);
imgView .setVisibility(View.GONE);
Difference between INVISIBLE and GONE.
INVISIBLE - The widget will be invisible but space for the widget will be show.
GONE - Both space and widget is invisible.
Now you can hook your setOnItemClickListener()
listview.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
{
imgView .setVisibility(View.VISIBLE);
}
});

How to get values from dynamically created LinearLayout in android

I'm new to android. Started learning recently.
I have created a LinearLayout dynamically. I have the following fields in LinearLayout:
1. Customer name
2. Edit Button
3. Delete Button.
Orientation is horizontal.
Now I want to delete a single record when I click on delete button. How can I get row id in this case and later I can pass to database to delete the record. Here is the code.
user_list_view_item_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/bg_main"
>
<TextView android:id="#+id/txtTitle"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:textStyle="bold"
android:textSize="50dp"
android:textColor="#FFFFFF"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp" />
<Button
android:id="#+id/userListEditButton"
style="#style/SpecialText"
android:layout_width="50dp"
android:layout_height="50dp"
android:typeface="monospace"
android:text="#string/save"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp" />
<Button
android:id="#+id/userListDeleteButton"
style="#style/SpecialText"
android:layout_width="50dp"
android:layout_height="50dp"
android:typeface="monospace"
android:text="#string/reset"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp" />
</LinearLayout>
UserAdapter.java
package com.rad.mobileshop.activities;
import java.sql.SQLException;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import com.rad.mobileshop.common.entities.User;
import com.rad.mobileshop.db.DBAdapter;
public class UserAdapter extends ArrayAdapter<User> {
Context context;
int layoutResourceId;
User data[] = null;
private DBAdapter mdb;
public UserAdapter(Context context, int layoutResourceId, User[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
mdb = new DBAdapter(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
UserHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new UserHolder();
holder.txtTitle = (TextView) row.findViewById(R.id.txtTitle);
holder.editButton = (Button) row
.findViewById(R.id.userListEditButton);
holder.deleteButton = (Button) row
.findViewById(R.id.userListDeleteButton);
row.setTag(holder);
} else {
holder = (UserHolder) row.getTag();
}
User user = data[position];
holder.txtTitle.setText(user.getName());
holder.editButton.setText("Edit");
holder.deleteButton.setText("Delete");
holder.editButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
System.out.println("hello Edit");
}
});
holder.deleteButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
System.out.println("hello delete ");
}
});
return row;
}
private void deleteUserDetails(int userId) {
try {
mdb.open();
mdb.deleteUserDetails(userId);
} catch (SQLException e1) {
e1.printStackTrace();
}
}
static class UserHolder {
TextView txtTitle;
Button editButton;
Button deleteButton;
}
}
User.java
package com.rad.mobileshop.common.entities;
public class User {
private int id;
private String name;
private String type;
public User() {
super();
}
public User(int id, String name, String type) {
super();
this.id = id;
this.name = name;
this.type = type;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
#Override
public String toString() {
return this.name ;
}
}
First you need to change your User[] array into an ArrayList, because you cannot dynamically remove an element for a primitive array. (At least not as easily and ArrayAdapter is already designed to work with ArrayLists in this circumstance.)
Next let's save position in deleteButton in getView() for easy access:
holder.deleteButton.setTag(position);
Last add this to your delete OnClickListener:
public void onClick(View view) {
User user = getItem((Integer) view.getTag()));
remove(user);
deleteUserDetails(user.getId());
}
There are an couple minor adjustments that I didn't cover, like changing UserAdapter's constructor and data[position] in getView(), but they are easy fixes.
Optional advice:
You should create only one LayoutInflater in your constructor and simply re-use it in getView()
You don't need to store a copy of data in UserAdapter, it is already stored in ArrayAdapter, simply access it with getItem(position).
You can streamline getView() by moving every command that doesn't change into the if(row == null) block.
All that said, I'm not sure why you extended ArrayAdapter if you are working with a database. I suggest switching to a custom CursorAdapter, but this isn't required.

Android- Adding subrows to a ListView!

ive been attempting to add subrows to a listview. I have a taxi app which at present shows a list of taxi company names, i want to be able to add some sub rows in which show address, postcode etc.
I have had some attempts at this but none have been successful. I am calling my strings from an array in the strings.xml file. My code at the moment is :
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final String[] taxi = getResources().getStringArray(R.array.taxi_array);
setListAdapter(new ArrayAdapter<String>(this, R.layout.listtaxi, taxi));
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, final int position, long id)
{
final int selectedPosition = position;
AlertDialog.Builder adb=new AlertDialog.Builder(ListTaxi.this);
adb.setTitle("Taxi Booking");
adb.setMessage("You Have Selected: "+lv.getItemAtPosition(position));
adb.setPositiveButton("Book", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(getApplicationContext(), Booking.class);
intent.putExtra("booking", taxi[selectedPosition]);
startActivity(intent);
}
});
adb.setNegativeButton("Cancel", null);
adb.show();
}
});
If anyone can help me get round this problem it would be very much appreciated.
The original question i asked is here: Android - Adding Subitem to a listview
Thanks
Whoops, just noticed this one. I'll paste my edited answer into here:
Okay, just for kicks, I threw this together. It compiles and functions correctly, see if you can adapt it for your particular needs:
layout/taxi_list_item.xml
<?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="100dp"
android:padding="10dp"
android:orientation="vertical"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/taxi_name"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/taxi_address"
/>
</LinearLayout>
layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<ListView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
TaxiMain.java
package com.test.taxi;
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class TaxiMain extends ListActivity {
/** Called when the activity is first created.
* #return */
class Taxi {
private String taxiName;
private String taxiAddress;
public String getName() {
return taxiName;
}
public void setName(String name) {
taxiName = name;
}
public String getAddress() {
return taxiAddress;
}
public void setAddress(String address) {
taxiAddress = address;
}
public Taxi(String name, String address) {
taxiName = name;
taxiAddress = address;
}
}
public class TaxiAdapter extends ArrayAdapter<Taxi> {
private ArrayList<Taxi> items;
private TaxiViewHolder taxiHolder;
private class TaxiViewHolder {
TextView name;
TextView address;
}
public TaxiAdapter(Context context, int tvResId, ArrayList<Taxi> items) {
super(context, tvResId, items);
this.items = items;
}
#Override
public View getView(int pos, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.taxi_list_item, null);
taxiHolder = new TaxiViewHolder();
taxiHolder.name = (TextView)v.findViewById(R.id.taxi_name);
taxiHolder.address = (TextView)v.findViewById(R.id.taxi_address);
v.setTag(taxiHolder);
} else taxiHolder = (TaxiViewHolder)v.getTag();
Taxi taxi = items.get(pos);
if (taxi != null) {
taxiHolder.name.setText(taxi.getName());
taxiHolder.address.setText(taxi.getAddress());
}
return v;
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String[] taxiNames = getResources().getStringArray(R.array.taxi_name_array);
String[] taxiAddresses = getResources().getStringArray(R.array.taxi_address_array);
ArrayList<Taxi> taxiList = new ArrayList<Taxi>();
for (int i = 0; i < taxiNames.length; i++) {
taxiList.add(new Taxi(taxiNames[i], taxiAddresses[i]));
}
setListAdapter(new TaxiAdapter(this, R.layout.taxi_list_item, taxiList));
}
}

Categories

Resources