Multiple Custom Spinner always sets values to one spninner - android

I have two Spinner in my layout. First one to select vehicle, second one for choose color from the shorted list of that particular vehicle. eg.(selected Bajaj, second need to show list of color of that vehicle already saved)
Here I did getting all datas from database for vehicle and for color. Both values are in my hand. But if I select vehicle type in Spinner1, it was showing the color of that vehicles in same spinner instead of, showing in Spinner2. First I had same (Spinner getset class, adapter class,custom layout). Now I created all three as different. Even now also getting the same problem.
How to find, where I am doing wrong. Below is the code I am using.
public void setListData()// gets vehicles value from DB
{
List<VehicleGetSetter> contacts = vdb.getVehicleListToCustomer(vendor_id);
for (VehicleGetSetter cn : contacts) {
final BikeSpinner sched = new BikeSpinner();
sched.setBikeName("Select Bike");
CustomListBikeName.add(sched);
}}
private void setBikeAdapterValues() {// set Vehicle value in Spinner1
Resources res = getResources();
adapter = new BikeSpinnerAdapter(NewCustomer.this, R.layout.bike_spinner, CustomListBikeName,res);
mySpinner.setAdapter(adapter);
mySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View v, int position, long id) {
bike_no_from_adapter = ((TextView) v.findViewById(R.id.textbike_numbr)).getText().toString();
what_bike = ((TextView) v.findViewById(R.id.textbike)).getText().toString();
String OutputMsg = "Selected : \n\n"+bike_no_from_adapter;
if(position!=0){
setListBikeColor(bike_no_from_adapter);
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
//Toast.makeText(getApplicationContext(), "You Must Select Vehicle", Toast.LENGTH_LONG).show();
}
});
}
public void setListBikeColor(String bike_no_from_adapter){// get color of selected vehicles from DB
List<VehicleGetSetter> contacts1 = vdb.getVehicleColorListToCustomer(vendor_id,bike_no_from_adapter);
for (VehicleGetSetter cn1 : contacts1) {
final BikeSpinn sched1 = new BikeSpinn();
sched1.setBikeNumber(cn1.getColor());
CustomListBikeColor.add(sched1);
setBikeAdapterValuesColor();
}
}
private void setBikeAdapterValuesColor() {// trying to set value in second spinner, but setting in same vehicle spinner.
Resources res2 = getResources();
coloradapter = new BikeSpinnerColor(NewCustomer.this, R.layout.bike_spinner_color, CustomListBikeColor,res2);
cust_bike_color.setAdapter(coloradapter);
cust_bike_color.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View v, int position, long id) {
// Get selected row data to show on screen
bike_no_from_adapter = ((TextView) v.findViewById(R.id.textbike_numbr)).getText().toString();
what_bike = ((TextView) v.findViewById(R.id.textbike)).getText().toString();
#Override
public void onNothingSelected(AdapterView<?> parentView) {
//Toast.makeText(getApplicationContext(), "You Must Select Vehicle", Toast.LENGTH_LONG).show();
}
});
}
MainLayout which contain Spinner
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg_blue"
android:orientation="vertical"
>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/bike"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:textSize="22dp"
android:textColor="#000000"
android:text="Bike Details" />
<Spinner
android:id="#+id/cust_bike"
android:layout_width="120dp"
android:layout_height="40dp"
android:paddingBottom="1dp"
android:paddingLeft="5dp" />
<Spinner
android:id="#+id/cust_bike_color"
android:layout_width="120dp"
android:layout_height="40dp"
android:paddingBottom="1dp"
android:paddingLeft="5dp" />
<Spinner
android:id="#+id/cust_bike_number"
android:layout_width="120dp"
android:layout_height="40dp"
android:paddingBottom="1dp"
android:paddingLeft="5dp" />
</LinearLayout>
</LinearLayout>
Custom layout for spinners(Similar for both spinner(named differently))
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:id="#+id/textbike"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18dp"
android:layout_marginRight="5dp"
android:textColor="#000000" />
<TextView
android:id="#+id/textbike_numbr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18dp"
android:textColor="#000000" />
</LinearLayout>
Custom ArrayAdapterClass(Having Two similar class for two Spinners)
public class BikeSpinnerAdapter extends ArrayAdapter<String>{
private Activity activity;
private ArrayList data;
public Resources res;
BikeSpinner tempValues=null;
LayoutInflater inflater;
public BikeSpinnerAdapter(NewCustomer activitySpinner,
int textViewResourceId,
ArrayList objects,
Resources resLocal
)
{
super(activitySpinner, textViewResourceId, objects);
activity = activitySpinner;
data = objects;
res = resLocal;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getDropDownView(int position, View convertView,ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
public View getCustomView(int position, View convertView, ViewGroup parent) {
View row = inflater.inflate(R.layout.bike_spinner, parent, false);
tempValues = null;
tempValues = (BikeSpinner) data.get(position);
TextView label = (TextView)row.findViewById(R.id.textbike_numbr);
TextView sub = (TextView)row.findViewById(R.id.textbike);
label.setText(tempValues.getBikeName());
sub.setText(tempValues.getBikeNumber());
return row;
}
}

Like this I achieved with multiple Spinner related with one another
Seperate class to set Dropdown List Adapters
public void setListBikeName(String vr_id)
{ vendor_id=vr_id;
List<VehicleGetSetter> contacts = ((NewCustomer)context).vdb.getVehicleListToCustomer(vendor_id);
for (VehicleGetSetter cn : contacts) {
final BikeSpinner sched = new BikeSpinner();
if(cn.getModelYear().equals(""))
sched.setBikeName("Select Bike");
else
sched.setBikeName(cn.getModelYear());
((NewCustomer)context).CustomListBikeName.add(sched); /** Take Model Object in ArrayList */
}
}
public void setListBikeColor(String name){
((NewCustomer)context).CustomListBikeColor.clear();
List<VehicleGetSetter> contacts = ((NewCustomer)context).vdb.getVehicleColorListToCustomer(vendor_id,name);
for (VehicleGetSetter cn : contacts) {
final BikeSpinner sched = new BikeSpinner();
sched.setBikeName(cn.getColor());
((NewCustomer)context).CustomListBikeColor.add(sched); /** Take Model Object in ArrayList */
((NewCustomer)context).colorAdapterIntermediater();
}
}
public void setListBikeNumber(String name,String color){
((NewCustomer)context).CustomListBikeNumber.clear();
List<VehicleGetSetter> contacts = ((NewCustomer)context).vdb.getVehicleNumberListToCustomer(vendor_id,name,color);
for (VehicleGetSetter cn : contacts) {
final BikeSpinner sched = new BikeSpinner();
sched.setBikeName(cn.getNumber());
((NewCustomer)context).CustomListBikeNumber.add(sched); /** Take Model Object in ArrayList */
((NewCustomer)context).numberAdapterIntermediater();
}
}
public void setBikeAdapterValues(ArrayList<BikeSpinner> CustomListBikeName,BikeSpinnerAdapter adapter,
Spinner mySpinner,final String str,Resources res) {
res = context.getResources();
Spinner temp=mySpinner;
adapter = new BikeSpinnerAdapter((NewCustomer) context, R.layout.bike_spinner, CustomListBikeName,res);
temp.setAdapter(adapter);
temp.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View v, int position, long id) {
if(str.equals("name")){
bike_name_from_adapter = ((TextView) v.findViewById(R.id.textbike_numbr)).getText().toString();
setListBikeColor(bike_name_from_adapter);
}
else if(str.equals("color")){
bike_color_from_adapter = ((TextView) v.findViewById(R.id.textbike_numbr)).getText().toString();
setListBikeNumber(bike_name_from_adapter, bike_color_from_adapter);
}
else if(str.equals("number")){
bike_no_from_adapter = ((TextView) v.findViewById(R.id.textbike_numbr)).getText().toString();
if(bike_no_from_adapter.length()>=10){
((NewCustomer)context).last_layout.setVisibility(View.VISIBLE);
}
else
((NewCustomer)context).last_layout.setVisibility(View.GONE);
((NewCustomer)context).passBikeValueToCustomer(bike_name_from_adapter,bike_color_from_adapter,bike_no_from_adapter);
}
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
}
});
}
}
In the Main Class:
bikeadapterobj.setListBikeName(_id);
bikeadapterobj.setBikeAdapterValues(CustomListBikeName,adapter,mySpinner,"name",res);
public void colorAdapterIntermediater(){
bikeadapterobj.setBikeAdapterValues(CustomListBikeColor,coloradapter,cust_bike_color,"color",res);
}
public void numberAdapterIntermediater(){
bikeadapterobj.setBikeAdapterValues(CustomListBikeNumber,numberadapter,cust_bike_number,"number",res);
}
public void passBikeValueToCustomer(String name,String colr,String bkno){
bike_name=name;
bike_color=colr;
bike_reg_number=bkno;
Log.d("Bike Details : ", bike_name+" "+bike_color+" "+bike_reg_number);
}

Related

Drawable is not printed correctly in a listview

I want to create a listview that displays the same clickable icon several times. I tried many ways, including a custom adapter with layout inflater but failed... At this point my ListView displays numbers instead of the icon. Can you help me please? here is my code
public class UserSelectionActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
static ArrayList<Integer> arrayOfIcons = new ArrayList<Integer>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_selection);
arrayOfIcons.clear();
for (int i=0; i<3; i++) {arrayOfIcons.add(R.drawable.edit);}
ArrayAdapter<Integer> adapter2 = new ArrayAdapter<Integer>(this, android.R.layout.simple_list_item_1, arrayOfIcons);
ListView listView2 = (ListView) findViewById(R.id.usersListView2);
listView2.setAdapter(adapter2);
listView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//TODO
}
});
}
}
I don't do anything in onResume method, that's why I didn't share it
And my xml file :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/usersListView2"
android:layout_width="80dp"
android:layout_height="450dp"
android:layout_alignParentEnd="true"
android:paddingTop="4dip"
android:paddingBottom="3dip" />
</RelativeLayout>
Hy, I suggest you to create a custom adapter:
1) create your list_item:
In res -> layout create a new file named list_item.xml. It contains only one imageView inserted into a ConstraintLayout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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">
<ImageView
android:id="#+id/imageViewIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0"
app:srcCompat="#mipmap/ic_launcher" />
2) In your activity_main.xml you have to inser your listView:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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"
tools:context=".MainActivity">
<ListView
android:id="#+id/listViewIcon"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
3) Now you have to create a new class call, for example, IconAdapter, where you create your custom adapter:
public class IconAdapter extends BaseAdapter {
Context context;
List<Integer> iconIDList;
/**
*
* #param context = activity context
* #param iconIDList = list with icon's id
*/
public IconAdapter(Context context, List<Integer> iconIDList) {
this.context = context;
this.iconIDList = iconIDList;
}
#Override
public int getCount() {
//return the size of my list
return iconIDList.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View convertView, ViewGroup viewGroup) {
//inflate my view
if (convertView == null) {
LayoutInflater inflater;
inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.list_item, null);
}
//istantiate my imageView
ImageView imageView = convertView.findViewById(R.id.imageViewIcon);
//set imageView's icon
imageView.setImageResource(iconIDList.get(i));
//return my view
return convertView;
}
}
4) Now in your MainActivity, put all together:D
public class MainActivity extends AppCompatActivity {
List<Integer> iconIDList;
IconAdapter iconAdapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//istantiate my components
iconIDList = new ArrayList<>();
listView = findViewById(R.id.listViewIcon);
iconAdapter = new IconAdapter(this, iconIDList);
int myIcon = R.drawable.ic_launcher_background;
//populate the list with icon's id
for (int i = 0; i < 5; i++) {
iconIDList.add(myIcon);
}
//set my custom adapter to the listView
listView.setAdapter(iconAdapter);
//set clickListner to the elements of my listView
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//i is the index of the clicked element
Toast.makeText(MainActivity.this, "Click on element n. " + i, Toast.LENGTH_SHORT).show();
}
});
}
}
I hope that can help you!!! Good job!! If you have a question, comment my answer!!
In your comment you ask me how to add one listener for the name (textView) clicked and one for the icon clicked.
1) modify your list_item.xml file. Now we can use:
a LinearLayout instead of ConstraintLayout;
a textView;
a ImageButton instead of ImageView.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:descendantFocusability="blocksDescendants" > <!--this is very important to detect click-->
<TextView
android:id="#+id/textViewIcon"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="3"
android:gravity="left|center"
android:text="TextView"
android:textSize="24sp" />
<ImageButton
android:id="#+id/imageButtonIcon"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginRight="8dp"
android:layout_weight="1"
app:srcCompat="#mipmap/ic_launcher" />
</LinearLayout>
2) Is better if you create a class that contains your data. We can call this class IconData:
public class IconData {
int iconID;
String text;
//constructor
public IconData(int iconID, String text) {
this.iconID = iconID;
this.text = text;
}
//getter and setter
public int getIconID() {
return iconID;
}
public void setIconID(int iconID) {
this.iconID = iconID;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
3) Now we have to change our IconAdapter.
We'll add an Interface to detect clicks on the ImageButton;
We'll change the list's data type;
We'll instatiate the newest TextView and ImageButton:
//create custom adapter -> I extend my class using BaseAdapter
public class IconAdapter extends BaseAdapter {
//create an interface to comunicate the clicks on the imageButton
public interface MyIconAdapterInterface {
void setOnClickListnerMyImageButton (int position);
}
Context context;
//change the list's name and data type
List<IconData> iconIDTextList;
MyIconAdapterInterface myIconAdapterInterface;
/**
* #param context = activity context
* #param iconIDTextList = list with icon's id and text
* #param myIconAdapterInterface = the interface that mainActivity will implements
*/
public IconAdapter(Context context, List<IconData> iconIDTextList, MyIconAdapterInterface myIconAdapterInterface) {
this.context = context;
this.iconIDTextList = iconIDTextList;
this.myIconAdapterInterface = myIconAdapterInterface;
}
#Override
public int getCount() {
//return the size of my list
return iconIDTextList.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(final int i, View convertView, ViewGroup viewGroup) {
//inflate my view
if (convertView == null) {
LayoutInflater inflater;
inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.list_item, null);
}
//istantiate my imageView and textView
ImageButton imageButton = convertView.findViewById(R.id.imageButtonIcon);
TextView textView = convertView.findViewById(R.id.textViewIcon);
//set imageView's button
int image = iconIDTextList.get(i).getIconID();
imageButton.setImageResource(image);
//set text
String text = iconIDTextList.get(i).getText();
textView.setText(text);
//setOnclickListner on my imageButton
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//pass the position of my clicks to the myIconAdapterInterface
myIconAdapterInterface.setOnClickListnerMyImageButton(i);
}
});
return convertView;
}
}
4) Finally we have to change the MainActivity.java's code:
implement our class with the new interface that we have create in our IconAdapter;
modify our list data type;
pass the newest list and the interface to the IconAdapter;
implement the interface's methods.
//I implement my MainActivity with IconAdapter.MyIconAdapterInterface. I create this interface
//in the iconAdapter class
public class MainActivity extends AppCompatActivity implements IconAdapter.MyIconAdapterInterface {
//change to iconIDTextList and change List data type
List<IconData> iconIDTextList;
IconAdapter iconAdapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//istantiate my components
iconIDTextList = new ArrayList<>();
listView = findViewById(R.id.listViewIcon);
//the second "this" is refer to the IconAdapter.MyIconAdapterInterface
iconAdapter = new IconAdapter(this, iconIDTextList, this);
int myIcon = R.drawable.ic_launcher_background;
String myText = "Hello! ";
//populate the list with icon's id and text
for (int i = 0; i < 5; i++) {
iconIDTextList.add(new IconData(myIcon, myText + i));
}
//set my custom adapter to the listView
listView.setAdapter(iconAdapter);
//set clickListner to the elements of my listView
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//i is the index of the clicked element
Toast.makeText(MainActivity.this, "Click on element n. " + i, Toast.LENGTH_SHORT).show();
}
});
}
//this is IconAdapter.MyIconAdapterInterface's method that I have to implement
#Override
public void setOnClickListnerMyImageButton(int position) {
//position = click's position
Toast.makeText(this, "Click on image n. "
+ position, Toast.LENGTH_SHORT).show();
}
}
Good Job!!

select multiple related rows of same group onlongclick for list view

i plan to have a list view which when onlongclick, will be able to select all the subrows/related rows.
Example
Input:
Long click on user name/age/birthday
Output:
Return the username, age and birthday.
Problem
Will only return the user name if you long click on it and not the age and birthday.
I didn't include the age and birthday value to be display in the toast cause the app will display an error and stop functioning.
Latest:
Have shown the Adapter and object class on 26th Nov17
Custom layout of list view
<?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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Username:"
android:background="#FF2400"
android:textColor="#FFFFFF" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/text_user_name"
android:textColor="#FFFFFF"
android:background="#FF2400"
android:text="Username"
android:gravity="left"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Age:"
android:background="#FFFFFF"
android:textColor="#000000" />
<EditText
android:layout_width="match_parent"
android:layout_weight="0.5"
android:textColor="#000000"
android:layout_height="wrap_content"
android:id="#+id/text_user_age"
android:background="#FFFFFF"
android:text="Age"
android:gravity="left"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Birthday:"
android:background="#FFFFFF"
android:textColor="#000000" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:textColor="#000000"
android:background="#FFFFFF"
android:id="#+id/text_user_birthday"
android:text="Birthday"
android:gravity="left"/>
</LinearLayout>
</LinearLayout>
DataListActivity (Listview activity)
listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener(){
public boolean onItemLongClick(AdapterView<?> arg0, View v,
int index, long arg3)
{
AlertDialog.Builder builder = new AlertDialog.Builder(DataListActivity.this);
builder.setTitle("Notice");
builder.setMessage("Launching this missile will destroy the entire universe. Is this what you intended to do?");
final View clicklist = v;
final int position = index;
builder.setPositiveButton("Launch missile", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String selname= ((EditText) clicklist.findViewById(R.id.text_user_name)).getText().toString();
// String selage= ((EditText) clicklist.findViewById(R.id.text_user_age)).getText().toString();
String selbirthday= ((EditText) clicklist.findViewById(R.id.text_user_birthday)).getText().toString();
Toast.makeText(DataListActivity.this,selname + selage + selbirthday,Toast.LENGTH_LONG).show();
}
});
builder.setNegativeButton("Cancel", null);
AlertDialog dialog = builder.create();
dialog.show();
return false;
}
});
LayoutAdapter
public class ListDataAdapter extends ArrayAdapter{
List list = new ArrayList();
static class LayoutHandler
{
TextView NAME,AGE,BIRTHDAY;
}
public ListDataAdapter(Context context, int resource) {
super(context, resource);
}
#Override
public void add (Object object)
{
super.add(object);
list.add(object);
}
#Override
public int getCount(){
return list.size();
}
#Override
public Object getItem(int position)
{
return list.get(position);
}
#Override
public View getView (int position, View convertView, ViewGroup parent){
View row = convertView;
LayoutHandler layoutHandler;
if (row==null)
{
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.row_layout,parent,false);
layoutHandler = new LayoutHandler();
layoutHandler.NAME = (TextView) row.findViewById(R.id.text_user_name);
layoutHandler.AGE = (TextView) row.findViewById(R.id.text_user_age);
layoutHandler.BIRTHDAY = (TextView) row.findViewById(R.id.text_user_birthday);
}
else
{
layoutHandler = (LayoutHandler) row.getTag();
}
DataProvider dataProvider = (DataProvider) this.getItem(position);
layoutHandler.NAME.setText(dataProvider.getName());
layoutHandler.AGE.setText(dataProvider.getAge());
layoutHandler.BIRTHDAY.setBIRTHDAY(dataProvider.getBirthday());
return row;
}
#Override
public void clear()
{
list.clear();
}
}
public class DataProvider {
private String Name;
private String Age;
private String Birthday;
....getter and setters method
After analyzing your code, i found following problems :-
In List adapter you didn't set the tag to row so it always return null layoutHandler and your casting EditText to TextView , i didn't get your point here if you want TextView then use same view in XML.
So the ListAdapter Looks like this.
public class ListAdapter extends ArrayAdapter {
List list = new ArrayList();
static class LayoutHandler
{
EditText NAME,AGE,BIRTHDAY;
}
public ListAdapter(Context context, int resource) {
super(context, resource);
}
#Override
public void add (Object object)
{
super.add(object);
list.add(object);
}
#Override
public int getCount(){
return list.size();
}
#Override
public Object getItem(int position)
{
return list.get(position);
}
#Override
public View getView (int position, View convertView, ViewGroup parent){
View row = convertView;
LayoutHandler layoutHandler;
if (row==null)
{
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.custom_layout,parent,false);
layoutHandler = new LayoutHandler();
layoutHandler.NAME = (EditText) row.findViewById(R.id.text_user_name);
layoutHandler.AGE = (EditText) row.findViewById(R.id.text_user_age);
layoutHandler.BIRTHDAY = (EditText) row.findViewById(R.id.text_user_birthday);
row.setTag(layoutHandler);
}
else
{
layoutHandler = (LayoutHandler) row.getTag();
}
DataProvider dataProvider = (DataProvider) this.getItem(position);
layoutHandler.NAME.setText(dataProvider.getName());
layoutHandler.AGE.setText(dataProvider.getAge());
layoutHandler.BIRTHDAY .setText(dataProvider.getBirthday());
return row;
}
#Override
public void clear()
{
list.clear();
}
}
and coming to the actual problem i.e. ListView OnItemLongClickListener crashing. You just have to change
final View clicklist = v;
to
final View clicklist = arg0.getChildAt(index);
and then you go. :)
A better way to this is to
1) Create a Custom Class for example Data and add properties that you
want to display within that class.
2) Create an Adapter and populate your adapter with arraylist of Data class.
3) Retrieve the values from listview using onItemClicklistener.
modify your toast
Toast.makeText(DataListActivity.this,"name"+selname+"age"+
selage+"DOB"+ selbirthday,Toast.LENGTH_LONG).show();

For creating custom list view as a library in android

we want to create a list view using adapter and we want to set the properties of the the list item outside the adapter.
For instance ,the list view contains 200 rows and 14 column, then we need to create the list item using adapter.Here the objects in adapter is creating based on the which items shown in screen.
After creating adapter ,after outside adapter we want to put getter,setter for the item 198 means .If initially in device the items upto 10 is diplayed means then then 10 items objects is created in adapter but the remaining is created when user scroll down
So null pointer execption is arised for the item 198.
I want to create a ListView as a custom component.In that the user can add any number of rows,any number of columns,etc
Any items as a list view,etc.
My aim is to create library for list view .In that list view user can add any number of rows,any number of columns,any items textview,spinner,etc.I need suggestions how to achieve it
All are welcome to give their ideas.
try use:
your xml list file item.xml:
<LinearLayout>
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<CheckBox
android:id="#+id/cbBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</CheckBox>
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="5dp"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="#+id/tvDescr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:text=""
android:textSize="20sp">
</TextView>
<TextView
android:id="#+id/tvPrice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_marginRight="10dp"
android:text="">
</TextView>
</LinearLayout>
<ImageView
android:id="#+id/ivImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher">
</ImageView>
<LinearLayout/>
And your class adapter
public class BoxAdapter extends BaseAdapter {
Context ctx;
LayoutInflater lInflater;
ArrayList<Product> objects;
BoxAdapter(Context context, ArrayList<Product> products) {
ctx = context;
objects = products;
lInflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return objects.size();
}
#Override
public Object getItem(int position) {
return objects.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.item, parent, false);
}
Product p = getProduct(position);
((TextView) view.findViewById(R.id.tvDescr)).setText(p.name);
((TextView) view.findViewById(R.id.tvPrice)).setText(p.price + "");
((ImageView) view.findViewById(R.id.ivImage)).setImageResource(p.image);
CheckBox cbBuy = (CheckBox) view.findViewById(R.id.cbBox);
cbBuy.setOnCheckedChangeListener(myCheckChangList);
cbBuy.setTag(position);
cbBuy.setChecked(p.box);
return view;
}
Product getProduct(int position) {
return ((Product) getItem(position));
}
ArrayList<Product> getBox() {
ArrayList<Product> box = new ArrayList<Product>();
for (Product p : objects) {
if (p.box)
box.add(p);
}
return box;
}
OnCheckedChangeListener myCheckChangList = new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
getProduct((Integer) buttonView.getTag()).box = isChecked;
}
};
}
And your class for product
public class Product {
String name;
int price;
int image;
boolean box;
Product(String _describe, int _price, int _image, boolean _box) {
name = _describe;
price = _price;
image = _image;
box = _box;
}
}
And your main activity use the create adapter
boxAdapter = new BoxAdapter(this, products);
ArrayList<Product> products = new ArrayList<Product>();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState)
...
//create adapter
fillData()
boxAdapter = new BoxAdapter(this, products);
// use lists
ListView lvMain = (ListView) findViewById(R.id.lvMain);
lvMain.setAdapter(boxAdapter);
}
// data for adapter
void fillData() {
for (int i = 1; i <= 20; i++) {
products.add(new Product("Product " + i, i * 1000, R.drawable.ic_launcher, false));
}
What you need is to implement LazyListView.
And I think you have a nice tutorial here to start with.

When clicking on a row Cannot find the index or position in listview using arrayadapter

I have created a listview using following tutorial link http://www.ezzylearning.com/tutorial.aspx?tid=1763429
Outcome of this is, List of Activity as below image
Now, I want to navigate to different activity screen by clicking on individual row. I do have idea of navigating to next screen, However I'm not able to find the correct position of each row. I don't have much knowledge of android so please bare with my question if it is too silly.
although the code is available on the above link I'm attaching the .xml files and .java. here as well.
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FFFFFF">
<ListView
android:id="#+id/listView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
listview_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:padding="10dp">
<ImageView android:id="#+id/imgIcon"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_marginRight="15dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp" />
<TextView android:id="#+id/txtTitle"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:textStyle="bold"
android:textSize="22dp"
android:textColor="#000000"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp" />
</LinearLayout>
Weather.java
public class Weather {
public int icon;
public String title;
public Weather(){
super();
}
public Weather(int icon, String title) {
super();
this.icon = icon;
this.title = title;
}
}
WeatherAdapter.java
public class WeatherAdapter extends ArrayAdapter<Weather>{
Context context;
int layoutResourceId;
Weather data[] = null;
public WeatherAdapter(Context context, int layoutResourceId, Weather[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
WeatherHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new WeatherHolder();
holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon);
holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);
row.setTag(holder);
}
else
{
holder = (WeatherHolder)row.getTag();
}
Weather weather = data[position];
holder.txtTitle.setText(weather.title);
holder.imgIcon.setImageResource(weather.icon);
return row;
}
static class WeatherHolder
{
ImageView imgIcon;
TextView txtTitle;
}
}
MainActivity.java
public class MainActivity extends Activity {
private ListView listView1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Weather weather_data[] = new Weather[]
{
new Weather(R.drawable.weather_cloudy, "Cloudy"),
new Weather(R.drawable.weather_showers, "Showers"),
new Weather(R.drawable.weather_snow, "Snow"),
new Weather(R.drawable.weather_storm, "Storm"),
new Weather(R.drawable.weather_sunny, "Sunny")
};
WeatherAdapter adapter = new WeatherAdapter(this,
R.layout.listview_item_row, weather_data);
listView1 = (ListView)findViewById(R.id.listView1);
View header = (View)getLayoutInflater().inflate(R.layout.listview_header_row, null);
listView1.addHeaderView(header);
listView1.setAdapter(adapter);
}
any help will be appreciated
Thanks
You need to attach OnItemClickListener
listView1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView <?> adapterView, View view, int position, long id) {
// position is index of the row that was clicked
}
});
where is listView1.setOnItemClickListener ? have you set setOnItemClickListener to listView1?.and in below code onItemClick have position.
listView1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
}
});
You should do something like this
listView1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //do something
}
});
use setOnItemSelectedListener with list http://developer.android.com/reference/android/widget/AdapterView.OnItemSelectedListener.html
listView1.addHeaderView(header);
listView1.setAdapter(adapter);
listView1.setOnItemSelectedListener(
new OnItemSelectedListener() {
#Override
public void onItemSelected(
AdapterView<?> parent, View view, int pos, long id
) {
//where pos is your index
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {}
}
);
Try this way...
listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
Toast.makeText(context, position+"", Toast.LENGTH_LONG).show();
Intent go_detail_Activity_Intent= new Intent(context,Target_Activity.class);
go_detail_Activity_Intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(go_detail_Activity_Intent);
}
});
I think it help you.

Spinner in ListView preventing highlighting in android

I'm trying to place a spinner inside a list view item in android. The problem is this seems to prevent the row from being highlighted during a press and the onItemClickListener is not getting called by the ListView. Basically I am trying to mimic the functionality in the Google Music app. Does anyone know how to do this? This is the code I have been trying (I know it may not be the best... just throwing together a quick sample which shows the problem):
Activity:
public class ListViewTestActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView listView = (ListView) findViewById(R.id.listView1);
DataHolder data = new DataHolder(this);
DataHolder data1 = new DataHolder(this);
DataHolder data2 = new DataHolder(this);
DataHolder data3 = new DataHolder(this);
DataHolder data4 = new DataHolder(this);
DataAdapter d = new DataAdapter(this, R.layout.rowview, new DataHolder[] { data, data1, data2, data3, data4 });
listView.setAdapter(d);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Log.e("ERROR", "look at me!");
}
});
}
}
public class DataHolder {
private int selected;
private ArrayAdapter<CharSequence> adapter;
public DataHolder(Context parent) {
adapter = ArrayAdapter.createFromResource(parent, R.array.choices, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
}
public ArrayAdapter<CharSequence> getAdapter() {
return adapter;
}
public String getText() {
return (String) adapter.getItem(selected);
}
public int getSelected() {
return selected;
}
public void setSelected(int selected) {
this.selected = selected;
}
}
This is the list adapter:
public class DataAdapter extends ArrayAdapter<DataHolder> {
private Activity myContext;
public DataAdapter(Activity context, int textViewResourceId, DataHolder[] objects) {
super(context, textViewResourceId, objects);
myContext = context;
}
// We keep this ViewHolder object to save time. It's quicker than findViewById() when repainting.
static class ViewHolder {
protected DataHolder data;
protected TextView text;
protected Spinner spin;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
// Check to see if this row has already been painted once.
if (convertView == null) {
// If it hasn't, set up everything:
LayoutInflater inflator = myContext.getLayoutInflater();
view = inflator.inflate(R.layout.rowview, null);
// Make a new ViewHolder for this row, and modify its data and spinner:
final ViewHolder viewHolder = new ViewHolder();
viewHolder.text = (TextView) view.findViewById(R.id.text);
viewHolder.data = new DataHolder(myContext);
viewHolder.spin = (Spinner) view.findViewById(R.id.spin);
viewHolder.spin.setAdapter(viewHolder.data.getAdapter());
// Used to handle events when the user changes the Spinner selection:
viewHolder.spin.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
viewHolder.data.setSelected(arg2);
viewHolder.text.setText(viewHolder.data.getText());
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
Log.d("DBGINF", "asdf");
}
});
// Update the TextView to reflect what's in the Spinner
viewHolder.text.setText(viewHolder.data.getText());
view.setTag(viewHolder);
Log.d("DBGINF", viewHolder.text.getText() + "");
} else {
view = convertView;
}
// This is what gets called every time the ListView refreshes
ViewHolder holder = (ViewHolder) view.getTag();
holder.text.setText(getItem(position).getText());
holder.spin.setSelection(getItem(position).getSelected());
return view;
}
}
Main layout for activity
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<ListView android:id="#+id/listView1" android:layout_height="match_parent" android:layout_width="match_parent" />
</LinearLayout>
Layout for a row:
<?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="wrap_content" android:weightSum="1" >
<TextView android:layout_width="wrap_content"
android:layout_height="match_parent" android:id="#+id/text"
android:layout_weight="0.5" android:textSize="25sp" />
<Spinner android:layout_width="0dp" android:layout_height="wrap_content"
android:id="#+id/spin" android:prompt="#string/choice_prompt"
android:layout_weight="0.5" />
</LinearLayout>
Thanks for any help!
I had the same problem with ImageButton, and what was needed was to do
mImageButton.setFocusable(false);
I can't garantee it's the same for Spinner, but my money is on it.
Best regards.

Categories

Resources