How to retrieve widgets from Single Layout ArrayAdapters - android

So I have a Listview full of rows, each with a textview and a spinner. I use an ArrayAdapter to fill in each row. There is a single layout for all the rows.
I want to have a button underneath all the rows that I can press so that it saves all the selections of the spinners in a Text file.
My problem though is I dont know how to reference the spinners anymore since I use the single layout approach. I no longer have unique IDs: (spinner1, spinner2, spinner3, etc.) for each one because they are filled in row by row.
Any advice on how to approach this problem so I can reference each spinner and call their "get text" method?
The more detail the better, thanks in advance!

This is how I would do it: If the model object type of your array doesn't have a variable for the current spinner selection, you need to update your model or extend your Adapter so that you can capture the current selection of the spinner for that item.
In your adapter's getView(), when you create the spinner, add an OnItemSelectedListener to it that updates the model for its corresponding item in the array.
Then when the save button is pressed, you simply loop through the items in the adapter's array and get all the current spinner values.
Here is a code example:
MainActivity.java
package com.example.spinnerdemo;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
private static final String[] mValues = {
"Strongly Agree",
"Agree",
"Neutral",
"Disagree",
"Strongly Disagree"
};
public static class MyModel {
public String text;
public int spinnerVal;
public MyModel(String txt, int val) {
text = txt; spinnerVal = val;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final List<MyModel> items = createItemList();
ListView listView = (ListView) findViewById(R.id.listView1);
final MyListAdapter adapter = new MyListAdapter(this, items);
listView.setAdapter(adapter);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// here is where we get all the spinner values
Log.d(TAG, "------- save button clicked");
for (MyModel model : items) {
Log.d(TAG, model.text + " : " + mValues[model.spinnerVal]);
}
Log.d(TAG, "-------");
}
});
}
public static class MyListAdapter extends ArrayAdapter<MyModel> {
public MyListAdapter(Context context, List<MyModel> objects) {
super(context, 0, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) parent.getContext().getSystemService(LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item, parent, false);
}
final MyModel model = (MyModel) getItem(position);
TextView textView = (TextView) convertView.findViewById(R.id.textView1);
textView.setText(model.text);
Spinner spinner = (Spinner) convertView.findViewById(R.id.spinner1);
spinner.setAdapter(new ArrayAdapter<String>(parent.getContext(),
android.R.layout.simple_spinner_dropdown_item,
android.R.id.text1, mValues));
// here is where the spinner gets the value from the model
spinner.setSelection(model.spinnerVal);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
// here is where we update the model with the current position of the spinner
model.spinnerVal = position;
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
return convertView;
}
}
private List<MyModel> createItemList() {
List<MyModel> items = new ArrayList<MyModel>();
// initialize with "Neutral" spinner setting
items.add(new MyModel("question 1", 2));
items.add(new MyModel("question 2", 2));
items.add(new MyModel("question 3", 2));
items.add(new MyModel("question 4", 2));
items.add(new MyModel("question 5", 2));
return items;
}
}
activity_main.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"
tools:context="com.example.spinnerdemo.MainActivity" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Save" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/button1"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" >
</ListView>
</RelativeLayout>
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="match_parent"
android:gravity="center_vertical"
android:orientation="horizontal" >
<TextView
android:id="#+id/textView1"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="TextView" />
<Spinner
android:id="#+id/spinner1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>

Related

getView() does not work in my Custom List View

My problem is that my listView doesn't show any items. I entered multi columns data to my SQLite database and I want to show it in a custom listview, but my listView doesn't show anything. I think the the problem is in my custom adapter and specifically in the getView() method. I track the data flow with Log messages and and the data stored in the database into an ArrayList but seems that getView() don't put values into TextView. I tried many tutorials but it keeps make me made Custom Data Class and change my hole code. PLEASE help me. I have been in this problem for weeks.
My custom adapter
ListAdapter
import android.app.Activity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class ListAdapter extends ArrayAdapter<String> {
private final Activity context;
private final ArrayList<String> items;
public ListAdapter(Activity context, ArrayList<String> items) {
super(context, R.layout.custom_list, items);
// TODO Auto-generated constructor stub
this.context=context;
this.items=items;
}
#Override
public int getCount() {
return items.size();
}
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater=context.getLayoutInflater();
View rowView=inflater.inflate(R.layout.custom_list, null,true);
TextView nameTV = rowView.findViewById(R.id.nameTV);
TextView priceTV = rowView.findViewById(R.id.priceTV);
//nameTV.setText(names[position]);
//priceTV.setText(prices[position].toString());
nameTV.setText(items.get(2*position));
priceTV.setText(items.get(2*position+1));
Log.d("ListAdapter", "nameTV.setText: items.get(2*position) "+nameTV+"/////////////////////////////");
Log.d("ListAdapter", "priceTV.setText: items.get(2*position) "+priceTV+"/////////////////////////////");
Log.d("ListAdapter", "getView : -----------------------------");
return rowView;
}
}
my main activity
ListDataActivity
import android.content.Intent;
import android.database.Cursor;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.support.v7.widget.SearchView;
import android.widget.Toast;
import java.util.ArrayList;
public class ListDataActivity extends AppCompatActivity {
DatabaseHelper databaseHelper;
ListView listView;
ArrayList<String> listData;
ListAdapter listAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_data);
databaseHelper = new DatabaseHelper(this);
listView = findViewById(R.id.listView);
listData = new ArrayList<String>();
listAdapter = new com.example.barcodescanner.ListAdapter(this,listData);
listView.setAdapter(listAdapter);
popListView();
}
private void popListView() {
Log.d("ListDataActivity","Displaying data in the ListView");
//get data and append to a list
Cursor data = databaseHelper.getData();
listData = new ArrayList<>();
while (data.moveToNext()) {
//get the data from the columns
//then add it to the ArrayList
listData.add(data.getString(1));
listData.add(data.getString(2));
Log.d("DatabaseHelper", "addData: Adding "+data.getString(1)+"+++++++++++++++++++++++++++++");
Log.d("DatabaseHelper", "addData: Adding "+data.getString(2)+"+++++++++++++++++++++++++++++");
//create the list adapter and set the adapter
//final ListAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listData);
listView.setAdapter(listAdapter);
//set an OnClickListener to the listView
//we can use Object for data type here
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String name = adapterView.getItemAtPosition(i).toString();
String price = adapterView.getItemAtPosition(i).toString(); // we can use Object for data type here
Log.d("ListDataActivity", "onItemClick: You Clicked on " + name);
Cursor data = databaseHelper.getItemID(name); //get the id associated with that name
int itemID = -1;
while (data.moveToNext()){
itemID = data.getInt(0);
}
if (itemID > -1){
Log.d("ListDataActivity","onItemClick: the ID is : "+itemID);
Intent editScreenIntent = new Intent(ListDataActivity.this,EditDataActivity.class);
editScreenIntent.putExtra("id",itemID);
editScreenIntent.putExtra("name",name);
editScreenIntent.putExtra("price",price);
startActivity(editScreenIntent);
//finish();
}else {
toastMessage("No ID associate with this name");
}
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.search_menu,menu);
MenuItem searchItem = menu.findItem(R.id.item_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
ArrayList<String> userslist = new ArrayList<>();
for(String user : listData){
if(user.toLowerCase().contains(newText.toLowerCase())){
userslist.add(user);
}
}
//ArrayAdapter<String> adapter = new ArrayAdapter<>(ListDataActivity.this,
// android.R.layout.simple_list_item_1,userslist);
listView.setAdapter(listAdapter);
return true;
}
});
return super.onCreateOptionsMenu(menu);
}
//customized toast message
private void toastMessage(String message){
Toast.makeText(this,message,Toast.LENGTH_SHORT).show();
}
}
my custom list layout
custom_list
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/nameTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_marginLeft="20dp"
android:layout_marginRight="100dp"
android:layout_marginTop="5dp"
android:textColor="#4d4d4d"
/>
<TextView
android:id="#+id/priceTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Price"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_marginLeft="20dp"
android:layout_marginRight="10dp"
android:layout_marginTop="5dp"
android:textColor="#4d4d4d"
/>
</LinearLayout>
</LinearLayout>
</android.support.constraint.ConstraintLayout>
activity_list_data
<?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=".ListDataActivity">
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</ListView>
</android.support.constraint.ConstraintLayout>
In your onCreate method you are passing an empty ArrayList into your adapter. You then call popListView and then re-initialize your listData variable to a new object (new ArrayList()). So your adapter never receives any data.
Move the call to popListView up 2 lines to before you create your adapter.
UPDATE
Create a new class as follows:
class DataStructure {
private String name;
private String price;
DataStructure(String name, String price) {
this.name = name;
this.price = price;
}
String getName() {
return name;
}
String getPrice() {
return price;
}
}
Then change your adapter type with class ListAdapter extends ArrayAdapter<DataStructure>
Change listData to type ArrayList<DataStructure>.
When you read from the database create a new instance of DataStructure and add each instance to your list.

Android Spinner: on click show or hide imageview

I have spinner with one Text View and one Image View and when click on one of its item I only want to show the text not the Image View , how can I get the image view plus I have a custom spinner layout , any help will be appreciated:
spinner_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- Single Item Design -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/txt"
android:layout_width="60dp"
android:layout_height="40dp"
android:padding="10dp"
android:layout_gravity="center_vertical"
>
</TextView>
<ImageView
android:id="#+id/img"
android:layout_width="40dp"
android:layout_height="40dp"
android:padding="10dp"
android:layout_gravity="center_vertical"
/>
<ImageView
android:id="#+id/imageView2"
android:layout_width="40dp"
android:layout_height="40dp"
android:padding="10dp" />
</LinearLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
private Spinner spinner;
int count=0;
int pre_pos=-1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<ItemData> list = new ArrayList<>();
list.add(new ItemData("EUR", R.drawable.ger));
list.add(new ItemData("USD", R.drawable.usa));
list.add(new ItemData("JPY", R.drawable.jap));
list.add(new ItemData("GBP", R.drawable.gb));
list.add(new ItemData("AUD", R.drawable.aus));
list.add(new ItemData("CHF", R.drawable.swiss));
list.add(new ItemData("CAD", R.drawable.can));
list.add(new ItemData("SEK", R.drawable.sweden));
list.add(new ItemData("NZD", R.drawable.newz));
list.add(new ItemData("KRW", R.drawable.skorea));
//list.add(new ItemData("Usd",R.drawable.usd));
//list.add(new ItemData("Jpy",R.drawable.jpy));
//list.add(new ItemData("Aud",R.drawable.aud));
Spinner sp = (Spinner) findViewById(R.id.spinner);
SpinnerAdapter adapter = new SpinnerAdapter(this,
R.layout.spinner_layout, R.id.txt, list);
ArrayList<ItemData> list2= new ArrayList<>();
list2.add(new ItemData("EUR", R.drawable.imag1));
list2.add(new ItemData("USD", R.drawable.imag2));
list2.add(new ItemData("JPY", R.drawable.imag3));
//listener of spinner
sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// how could i hide the image view of selected item
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
}
}
SpinnerAdapter.java
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Created by Abbas on 12/11/2016.
*/
public class SpinnerAdapter extends ArrayAdapter<ItemData> {
static int count=0;
int groupid;
Activity context;
ArrayList<ItemData> list;
LayoutInflater inflater;
SharedPreferences sharedPreferences;
public SpinnerAdapter(Activity context, int groupid, int id, ArrayList<ItemData>
list){
super(context,id,list);
this.list=list;
inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.groupid=groupid;
}
public View getView(int position, View convertView, ViewGroup parent ){
View itemView=inflater.inflate(groupid,parent,false);
ImageView imageView=(ImageView)itemView.findViewById(R.id.img);
imageView.setImageResource(list.get(position).getImageId());
TextView textView=(TextView)itemView.findViewById(R.id.txt);
textView.setText(list.get(position).getText());
return itemView;
}
public View getDropDownView(int position, View convertView, ViewGroup
parent){
return getView(position,convertView,parent);
}
}

Radio Buttons Deselected on scrolling in custom listview

Radio Buttons Deselected on scrolling in custom listview
i have made custom listview that add
run time radiobutton added autimatically
but it deselected on scroll
my code given below of adapter and mainclass and activity files
Layout file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="#drawable/gradient11"
android:layout_width="match_parent" android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioGroup
android:layout_width="match_parent"
android:layout_height="match_parent">
<RadioButton
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="option one is selected now so you can"
android:textColor="#00ff00"
android:id="#+id/op1"/>
<RadioButton
android:checked="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="op2"
android:textColor="#00ff00"
android:id="#+id/op2"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="op3"
android:textColor="#00ff00"
android:id="#+id/op3"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="op4"
android:textColor="#00ff00"
android:id="#+id/op4"/>
</RadioGroup>
</LinearLayout>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/quest"
android:textColor="#e2000000"/>
</LinearLayout>
The Adapter file
package com.patel.ravin.com.domparsing;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RadioButton;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by lenovo on 08-08-2016.
*/
public class Adpt extends BaseAdapter
{
Context context;
ArrayList<MyBean> arrayList;
public Adpt(Context context,ArrayList<MyBean> arrayList)
{
this.context=context;
this.arrayList=arrayList;
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup parent) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.listview, null);
TextView txtFName = (TextView) view.findViewById(R.id.qid);
TextView txtLName = (TextView) view.findViewById(R.id.quest);
RadioButton op1=(RadioButton)view.findViewById(R.id.op1);
RadioButton op2=(RadioButton)view.findViewById(R.id.op2);
RadioButton op3=(RadioButton)view.findViewById(R.id.op3);
RadioButton op4=(RadioButton)view.findViewById(R.id.op4);
MyBean myBean = arrayList.get(i);
txtFName.setText("" + myBean.getQid());
txtLName.setText(" Answer= " + myBean.getQname());
op1.setText(myBean.getOp1());
op2.setText(myBean.getOp2());
op3.setText(myBean.getOp3());
op4.setText(myBean.getOp4());
return view;
}
}
The Activity file
package com.patel.ravin.com.domparsing;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.patel.ravin.com.domparsing.AsyncTask.AsyncTaskLoader;
import com.patel.ravin.com.domparsing.AsyncTask.OnAsyncResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
TextView textView;
ListView listView1;
Adpt adpt;
ArrayList<MyBean> arrayList=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// textView= (TextView) findViewById(R.id.tv1);
listView1=(ListView)findViewById(R.id.llv);
// Adpt adpt=new Adpt(getApplicationContext(),arrayList);
//listView.setAdapter(new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,arrayList));
OnAsyncResult onAsyncResult=new OnAsyncResult() {
#Override
public void onAsyncResult(String result) {
Log.e("h", result.toString());
try {
// textView.setText(""+result.toString());
// String co=result.toString();
JSONArray jsonArray=new JSONArray(result);
MyBean myBean;
arrayList = new ArrayList<>();
for(int i=1;i<=jsonArray.length();i++)
{
JSONObject jsonObject=jsonArray.getJSONObject(i);
myBean = new MyBean();
myBean.setQid(jsonObject.getString("que"));
myBean.setQname(jsonObject.getString("ans"));
myBean.setOp1(jsonObject.getString("a"));
myBean.setOp2(jsonObject.getString("b"));
myBean.setOp3(jsonObject.getString("c"));
myBean.setOp4(jsonObject.getString("d"));
arrayList.add(myBean);
listView1.setAdapter(new Adpt(getApplicationContext(),arrayList));
}
//JSONObject object = new JSONObject(result);
//String contact = object.getString("que");
// textView.setText(co);
} catch (Exception e) {
e.printStackTrace();
}
}
};
AsyncTaskLoader asyncTaskLoader=new AsyncTaskLoader(MainActivity.this,onAsyncResult,null,"http://quiz/jsonapi.php");
asyncTaskLoader.execute();
}
}
Radio Buttons Deselected on scrolling in custom listview
i have made custom listview that add
run time radiobutton added autimatically
but it deselected on scroll
This is a very common problem in Android with Listviews and Radio buttons.
First, I would recommend you to check this post:
Using radio button in custom listview in Android
Now, I'm going to tell you which solution fits for me. In my case I use GridView, but it also works for ListView.
In your Adapter's class you have to have a variable for the selected item and his index, it could be something like:
private int mSelectedPosition = -1;
private RadioButton mSelectedRB;
Then, define a function to retrieve this information:
public int getItemSelected(){
return mSelectedPosition;
}
Now, In order to make it works properly, you have to user a ViewHolder (in my case every item in the GridView has a Image and a RadioButton), so you define your ViewHolder in the Adapter's class as well:
private class ViewHolder {
ImageView image;
RadioButton radio;
}
Then, in your getView function, you have to work with the ViewHolder. In the code I write comments to follow.
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView; // assign the view
ViewHolder holder; // declare the ViewHolder
if(view == null){
// cutom layout for each row (item) of the ListView
view = mLayoutInflater.inflate(R.layout.item_list_company, parent, false);
holder = new ViewHolder();
// initialize the ViewHolder's field
holder.image = (ImageView) view.findViewById(R.id.c1);
holder.radio = (RadioButton)view.findViewById(R.id.cN1);
view.setTag(holder); // set the tag
}else{ // already initialized
holder = (ViewHolder)view.getTag(); // so we only set the tag
}
// on click triggered for each RadioButton in the ListView
holder.radio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(position != mSelectedPosition && mSelectedRB != null){
mSelectedRB.setChecked(false); // uncheck the last one
}
mSelectedPosition = position; // change the item selected index
mSelectedRB = (RadioButton)v; // assign the new item selected
}
});
// just to control the right item checked
if(mSelectedPosition != position){
holder.radio.setChecked(false);
}else{
holder.radio.setChecked(true);
if(mSelectedRB != null && holder.radio != mSelectedRB){
mSelectedRB = holder.radio;
}
}
return view;
}
Finally, in the custom layout (item_list_company.xml in my case) for each item in the ListView, I have the following code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent">
<ImageView android:id="#+id/c1"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:layout_gravity="center"
android:scaleType="centerInside" />
<RadioButton
android:id="#+id/cN1"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:buttonTint="#color/colorPrimary"
android:textColor="#color/colorAccent"
android:focusable="false"
android:layout_gravity="left"
android:clickable="false"
android:focusableInTouchMode="false"
android:textSize="20dp"/>
</LinearLayout>
Special attention for this three attributes of the RadioButton:
android:focusable="false"
android:clickable="false"
android:focusableInTouchMode="false"
So, with all of this, you only have to set your adapter and ListView in your Activity and call to the right function to retrieve the selected item:
ArrayList<MyBean> arrayList = new ArrayList<>();
ListView listView1 = (ListView)findViewById(R.id.llv);
Adpt adpt = new Adpt(getApplicationContext(), arrayList);
// add data to the ArrayList
adpt.notifyDataSetChanged(); // notify for the new data in the ArrayList
// retrieve the item selected
int selected = adpt.getItemSelected();
Hope it helps!

Save adapter array when new item added to Listview

I just started learn Android. I'm not sure if my question is correct or not. My purpose is when user press on button add item to listview. Each single item (row) have 3 inputs. Currently my code adds item (row) when press on button. But its creating new array and deleting all user inputs. I also almost don't know Java (have very very little OOP skill). Can you answer what am I doing wrong?
Activity:
package com.example.gereltod.test7;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import java.util.ArrayList;
public class SellActivity extends Activity {
ArrayList<Items> items = new ArrayList<Items>();
ItemsAdapter adapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sell);
adapter = new ItemsAdapter(this, items);
listView = (ListView) findViewById(R.id.listView_main);
listView.setAdapter(adapter);
}
public void add_item(View view) {
Log.i("clicked add item", "yes");
items.add(new Items("", "", ""));
adapter.notifyDataSetChanged();
}
}
Layout
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView_main"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_above="#+id/btn_add_item" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/btn_add_item"
android:id="#+id/btn_add_item"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:onClick="add_item" />
Items Adapter
package com.example.gereltod.test7;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class ItemsAdapter extends ArrayAdapter<Items> {
private static class ViewHolder {
TextView name;
TextView qty;
TextView price;
}
public ItemsAdapter(Context context, ArrayList<Items> items) {
super(context, 0, items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
Items items = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder; // view lookup cache stored in tag
if (convertView == null) {
// convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent, false);
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.list_item, parent, false);
viewHolder.name = (TextView) convertView.findViewById(R.id.edittxt_name);
viewHolder.qty = (TextView) convertView.findViewById(R.id.edittxt_qty);
viewHolder.price = (TextView) convertView.findViewById(R.id.edittxt_price);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.name.setText(items.name);
viewHolder.qty.setText(items.qty);
viewHolder.price.setText(items.price);
return convertView;
}
}
List item
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_weight="1">
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp">
<EditText
android:id="#+id/edittxt_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:background="#drawable/input_shape"
android:hint="#string/hint_item_name"
android:padding="5dp"
android:singleLine="true" />
<EditText
android:id="#+id/edittxt_qty"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_weight="0.2"
android:background="#drawable/input_shape"
android:gravity="right"
android:hint="#string/hint_item_qty"
android:inputType="number"
android:padding="5dp"
android:singleLine="true" />
<EditText
android:id="#+id/edittxt_price"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_weight="0.3"
android:background="#drawable/input_shape"
android:gravity="end"
android:hint="#string/hint_item_price"
android:inputType="number"
android:padding="5dp"
android:singleLine="true" />
</TableRow>
</TableLayout>
Edit: Since my English sucks, I can't exactly describe whats going on. So I added screenshot. See here: http://i.imgur.com/Yzw2s7D.jpg
You are creating every time a new list and adding an item to the list and then setting the adapter of single list to listview.
Set the adapter on create of activity and then add items to adapter and call notifyDataSetChanged() method. Here is the code for activity:
public class SellActivity extends Activity {
ArrayList<Items> items = new ArrayList<Items>();
private ItemsAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sell);
ListView listView = (ListView) findViewById(R.id.listView_main);
adapter = new ItemsAdapter(this);
listView.setAdapter(adapter);
}
public void add_item(View view) {
Log.i("clicked add item", "yes");
adapter.add(new Items("", "", ""));
adapter.notifyDataSetChanged();
}
}
In your add_item method you should not create new adapter and new reference to listView. move these lines in your onCreate() method
ItemsAdapter adapter = new ItemsAdapter(this, items);
ListView listView = (ListView) findViewById(R.id.listView_main);
listView.setAdapter(adapter);
add_item should only adding item and notifyDataSetChanged().
I am not quit sure but try this
package com.example.gereltod.test7;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
public class SellActivity extends Activity {
ArrayList<Items> items = new ArrayList<Items>();
ItemsAdapter adapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sell);
adapter = new ItemsAdapter(this, items);
listView = (ListView) findViewById(R.id.listView_main);
listView.setAdapter(adapter);
}
public void add_item(View view) {
Log.i("clicked add item", "yes");
items.add(new Items("", "", ""));
adapter.notifyDataSetChanged();
}
}
i have a feeling this should work...
You must change this method . first initialize your adapter into
onCreate() {
adapter = new ItemsAdapter(this, items);
listView = (ListView) findViewById(R.id.listView_main);
listView.setAdapter(adapter);
}
ItemsAdapter adapter;
ListView listView;
public void add_item(View view) {
Log.i("clicked add item", "yes");
items.add(new Items("", "", ""));
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
I think you don't set the information taken from the input to the arraylist so, it doesn't have any information inside.

Android ListView setOnItemClickListener not registering click with custom adapter

Well, I am not sure what is up. I've been through many SO "answers" without any results. I have a custom adapter running on my listview. I want to be able to click on the list item to "see more" but I cannot even get the click to register.
Here is my activity:
import java.util.ArrayList;
import java.util.List;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.actionbarsherlock.app.SherlockActivity;
import com.androidquery.AQuery;
import com.androidquery.callback.AjaxStatus;
import com.androidquery.util.XmlDom;
public class MainActivity extends SherlockActivity {
private AQuery aq;
private ProgressDialog dialog;
private static final String TAG = "INCIWEB";
private ListView lv;
protected Object IncidentAdapter;
EditText inputSearch;
String url;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setContentView(R.layout.activity_main);
getSupportActionBar().setSubtitle("Incidents across the USA");
aq = new AQuery(this);
dialog = new ProgressDialog(this);
dialog.setCancelable(true);
dialog.setInverseBackgroundForced(false);
dialog.setCanceledOnTouchOutside(true);
dialog.setMessage("Fetching Latest...");
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.USStates, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner s = (Spinner) findViewById(R.id.stateSpinner);
s.setAdapter(adapter);
s.setPrompt("Select a location...");
final String USStates = s.getSelectedItem().toString();
Log.e("STATE", USStates);
s.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView,
View selectedItemView, int position, long id) {
try {
getFeed(position);
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
}
});
}
public void getFeed(int num) {
if (num == 0) {
// latest updates - front page
url = "http://inciweb.org/feeds/rss/incidents/";
} else {
// states
url = "http://inciweb.org/feeds/rss/incidents/state/" + num + "/";
}
Log.e("URL", url);
long expire = -1;
aq.progress(dialog).ajax(url, XmlDom.class, expire, this,
"getFeedCallback");
}
public void getFeedCallback(String url, XmlDom xml, AjaxStatus status) {
List<XmlDom> entries = xml.tags("item");
List<Incidents> incidents = new ArrayList<Incidents>();
for (XmlDom entry : entries) {
incidents.add(new Incidents(entry.text("title"),
entry.text("link"), entry.text("description"), entry
.text("published"), entry.text("geo:lat"), entry
.text("geo:long"), entry.text("georss:point")));
}
lv = (ListView) findViewById(R.id.list);
lv.setTextFilterEnabled(true);
lv.setAdapter(new IncidentAdapter(this,
android.R.layout.simple_list_item_1, incidents));
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view,
int position, long id) {
Toast.makeText(MainActivity.this, id + "' was clicked.",
Toast.LENGTH_LONG).show();
}
});
}
private class IncidentAdapter extends ArrayAdapter<Incidents> {
private List<Incidents> items;
public IncidentAdapter(Context context, int textViewResourceId,
List<Incidents> items) {
super(context, textViewResourceId, items);
this.items = items;
}
// Create a title and detail
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.incidents_item, null);
}
Incidents o = items.get(position);
if (o != null) {
TextView title = (TextView) v.findViewById(R.id.title);
TextView published = (TextView) v.findViewById(R.id.published);
TextView link = (TextView) v.findViewById(R.id.link);
link.setMovementMethod(LinkMovementMethod.getInstance());
TextView description = (TextView) v
.findViewById(R.id.description);
TextView geoLat = (TextView) v.findViewById(R.id.geoLat);
TextView geoLon = (TextView) v.findViewById(R.id.geoLon);
TextView geoLatLon = (TextView) v.findViewById(R.id.geoLatLon);
if (title != null) {
title.setText(o.getTitle());
}
if (published != null) {
published.setText(o.getPublished());
}
if (link != null) {
link.setText(o.getLink());
}
if (description != null) {
description.setText(o.getDescription());
}
if (geoLat != null) {
geoLat.setText(o.getGeoLat());
}
if (geoLon != null) {
geoLon.setText(o.getGeoLon());
}
if (geoLatLon != null) {
geoLatLon.setText(o.getGeoLatLon());
}
}
return v;
}
}
}
What am I missing?
edit:
Here is my XML files...
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Spinner
android:id="#+id/stateSpinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/inputSearch" />
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/stateSpinner" />
</RelativeLayout>
incident_items.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:textSize="20sp" />
<TextView
android:id="#+id/published"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical" />
<TextView
android:id="#+id/link"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical" />
<TextView
android:id="#+id/description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical" />
<TextView
android:id="#+id/geoLat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical" />
<TextView
android:id="#+id/geoLon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical" />
<TextView
android:id="#+id/geoLatLon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical" />
</LinearLayout>
</LinearLayout>
EDIT:
What I'd like to do is show the Title from the XML, then show the other XML fields onClick of the XML title from the listview...
Maybe your custom Views in ListView has clickable items and consume click event?
Make sure your ListView has the focus and there are no other clickable items that could steal the click events.
Well I cannot be 100% sure why it is working now, however, I think it has to do with going back through my XML and making sure nothing was missing or even a bit off according to Eclipse.
Thanks for all the comments.
For future folks: CHECK YOUR XML.

Categories

Resources