Get Selected value from Spinner inside ListView Android - java

I have a ListView of Spinners I'm trying to get the selected values out of. Some of the Spinners have the first selection automatically selected if there is only 1 item in the list, so I feel
setOnItemSelectedListener
won't necessarily work? Either way, I'm unsure how to code this scenario. Even if I had the listener coded correctly, How do I use it in my class to work with the adapter?
CustomAdapter
public class CustomPLNViewAdapter extends BaseAdapter{
private static ArrayList<ArrayList<String>> partLotNumbersArrayList;
private static ArrayList<String> partNames;
private LayoutInflater mInflater;
private Context myContext;
public CustomPLNViewAdapter(Context context, ArrayList<ArrayList<String>> results, ArrayList<String> parts){
partLotNumbersArrayList = results;
partNames = parts;
mInflater = LayoutInflater.from(context);
myContext = context;
}
#Override
public int getCount() {
return partLotNumbersArrayList.size();
}
#Override
public Object getItem(int position) {
return partLotNumbersArrayList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.view_assembly_parts, null);
holder = new ViewHolder();
holder.txtName = (TextView) convertView.findViewById(R.id.partName);
holder.spinner = (Spinner) convertView.findViewById(R.id.LotNumbers);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtName.setText(partNames.get(position));
ArrayAdapter<String> adp1=new ArrayAdapter<String>(myContext, android.R.layout.simple_list_item_1, partLotNumbersArrayList.get(position));
adp1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//set the adapter to the spinnner
holder.spinner.setAdapter(adp1);
//if there is only one other part besides "" then set that as default part
if(partLotNumbersArrayList.get(position).size() == 2){
holder.spinner.setSelection(1);
}
return convertView;
}
static class ViewHolder {
TextView txtName;
Spinner spinner;
}
}
Where I am calling the code. Obviously I get an error here because an ArrayList cannot be cast to Spinner, but I'm unsure how to get the View of the Adapter and then the subsequent spinner?
// save button click event
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Log.d("lv count", Integer.toString(lv.getCount()));
//iterate through listview,
for(int i = 0; i < lv.getCount(); i++){
Spinner temp = (Spinner) lv.getItemAtPosition(i);
Log.d("lv isItemCheck", temp.getSelectedItem().toString());
}
//check to make sure all items have been selected
if(!checkAllParts()){
Toast.makeText(getApplicationContext(), "Please Select All List Items", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), "All items have been selected", Toast.LENGTH_SHORT).show();
}
//go back to previous intent, return 100 that saving succeeded
//close intent
}
});

Related

How to fix Android Java ListView Adapter

I need help to fix the following problem:
When i scroll down my ListView Adapter the list that contains the country change to only one country.
This is my Adapter:
public class Nraeby_ListViewAdapter extends BaseAdapter {
private String Liked;
Context mContext;
// Declare Variables
LayoutInflater inflater;
private ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
public Nraeby_ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.data = arraylist;
mContext = context;
imageLoader = new ImageLoader(mContext);
inflater = LayoutInflater.from(mContext);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public class ViewHolder {
// Declare Variables
TextView rank;
TextView country;
TextView population;
test.Droidlogin.CircleImage flag;
test.Droidlogin.material.AnimateCheckBox checkBox;
ImageButton btnFavourite;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.nearby_listview_item, null);
// Get the position
resultp = data.get(position);
// Locate the TextViews in nearby_listview_item.xmltem.xml
holder.rank = (TextView) view.findViewById(R.id.rank);
holder.country = (TextView) view.findViewById(R.id.country);
// Locate the ImageView in nearby_listview_item.xmltem.xml
holder.flag = (test.Droidlogin.CircleImage) view.findViewById(R.id.flag);
holder.checkBox = (test.Droidlogin.material.AnimateCheckBox) view.findViewById(R.id.checkbox);
holder.btnFavourite = (ImageButton) view.findViewById(R.id.like);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Capture position and set results to the TextViews
holder.rank.setText(resultp.get(NearbyUsers.RANK));
holder.country.setText(resultp.get(NearbyUsers.COUNTRY));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(NearbyUsers.FLAG), holder.flag);
TinyDB tinydb = new TinyDB(mContext);
Liked = tinydb.getString("MyUsers");
//This handle and change icon when click on.
holder.btnFavourite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TinyDB tinydb = new TinyDB(mContext);
holder.btnFavourite.setImageResource(R.drawable.icon_liked);
tinydb.putString("MyUsers",resultp.get(NearbyUsers.COUNTRY));
holder.btnFavourite.setImageResource(R.drawable.icon_liked);
}
});
// Capture ListView item click
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
Intent intent = new Intent(mContext, SingleItemViewNearbyProfile.class);
// Pass all data rank
intent.putExtra("rank", resultp.get(NearbyUsers.RANK));
// Pass all data country
intent.putExtra("country", resultp.get(NearbyUsers.COUNTRY));
// Pass all data population
intent.putExtra("population",resultp.get(NearbyUsers.POPULATION));
// Pass all data flag
intent.putExtra("flag", resultp.get(NearbyUsers.FLAG));
// Start SingleItemView Class
mContext.startActivity(intent);
}
});
return view;
}
}
pls i need help on how to fix the error
so that when scroll down it will show the list of all country and a button
You should move the line in getView to outside the if block. Like this
final ViewHolder holder;
resultp = data.get(position);
if (view == null) {
///
}
You are only updating the resultp when you create a new view. For a recycled view, you are using a stale data and that's the reason you see some incorrect country data after you scroll.

SetChecked RadioButton of SingleChoice ListView on Activity Launch

I've been working on creating a single choice ListView populated by a custom ArrayAdapter (which works), except I need to set a pre-determined RadioButton in the ListView as setChecked(true) when the activity launches.
I'm populating my ListView with a List<Server> servers object at inflation that contains a boolean 'default_server' used to determine which row / RadioButton should be setChecked(true).
Selecting the various ListView items after the activity has launched correctly flags the specific RadioButton as setChecked(true) in Single Choice mode as desired.
My code:
ServerActivity.java
public class ServersActivity extends FragmentActivity
//FragmentActivity needed to display dialog fragment when ListView item clicked
...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.server_list);
servers = getServers();
lv = (ListView) findViewById(android.R.id.list);
lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
adapter = new ServerActivityArrayAdapter(this, R.layout.server_list_item, servers);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// show dialog if not long clicked
if (!longClicked) {
lv.setItemChecked(position, true);
showServerDialog(position);
}
}
});
}
ServerActivityArrayAdapter.java
public class ServerActivityArrayAdapter extends ArrayAdapter<Server> {
private int layout;
private int mSelectedPosition = -1;
private RadioButton mSelectedRB;
private static LayoutInflater inflater;
public ServerActivityArrayAdapter(Context context, int layout, List<Server> servers) {
super(context, layout, servers);
ListArrays listArrays = new ListArrays(context);
this.layout = layout;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
private static class ServerViewHolder {
private TextView textView;
private RadioButton radioButton;
public ServerViewHolder() {
// EMPTY DEFAULT CONSTRUCTOR
}
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final Server server = this.getItem(position);
final ServerViewHolder viewHolder;
if (convertView == null) {
convertView = inflater.inflate(layout, parent, false);
viewHolder = new ServerViewHolder();
viewHolder.textView = (TextView) convertView.findViewById(R.id.tvServerName);
viewHolder.radioButton = (RadioButton) convertView.findViewById(R.id.rbDefault);
convertView.setTag(viewHolder);
} else {
viewHolder = (ServerViewHolder) convertView.getTag();
}
// TODO: SET THE DEFAULT SERVER
viewHolder.radioButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (position != mSelectedPosition && mSelectedRB != null) {
mSelectedRB.setChecked(false);
}
mSelectedPosition = position;
notifyDataSetChanged();
mSelectedRB = (RadioButton) v;
server.setDefaultServer(mSelectedRB.isChecked());
}
});
if (mSelectedPosition != position) {
viewHolder.radioButton.setChecked(false);
} else {
viewHolder.radioButton.setChecked(true);
if (mSelectedRB != null && viewHolder.radioButton != mSelectedRB) {
mSelectedRB = viewHolder.radioButton;
}
}
viewHolder.textView.setText(server.getName());
return convertView;
}
}
Again, my List<Server> servers object is populating the ListView, the subsequent dialog popups (when a row is clicked) correctly and the RadioButtons on each row are currently functioning in Single Choice mode. I'm using server.setDefaultServer(mSelectedRB.isChecked()); in the setOnClickListener of ServerActivityArrayAdapter to update which server has default_server(true).
Everything I've tried so far in the ServerActivityArrayAdapter seems to break the Single Choice mode requirement of the RadioButton. How can I fix this?
I did go back and implement Shared Preferences into my project as Mridul suggested, but the solution really didn't require them.
Basically, I updated the constructor of my ServerActivityArrayAdapter class to let me pass the ID of the default server from the ServerActivity class when it's created. Also, I set mSelectionPostion = defServer, so the correct RadioButton in my ListView is checked when everything is inflated.
public ServerActivityArrayAdapter(Context context, int layout, List<Server> servers, int defServer) {
super(context, layout, servers);
ListArrays listArrays = new ListArrays(context);
this.layout = layout;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mSelectedPosition = defServer;
}

Android JSON Data not parsing into ListView

Android not parsing JSON data into ListView, I am using this tutorial and just made few changes in ListViewAdapter.java
Like in my new implementation i used ViewHolder, and my code looks like this:
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
ViewHolder holder;
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
static class ViewHolder {
public ViewHolder(View convertView) {
// TODO Auto-generated constructor stub
}
TextView rank;
TextView country;
TextView population;
ImageView flag;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
// Avoid unneccessary calls to findViewById() on each row, which is expensive!
holder = null;
/*
* If convertView is not null, we can reuse it directly, no inflation required!
* We only inflate a new View when the convertView is null.
*/
if (convertView == null) {
convertView = ((Activity) context).getLayoutInflater().inflate(R.layout.listview_item, null);
// Create a ViewHolder and store references to the two children views
holder = new ViewHolder(convertView);
holder.rank = (TextView) convertView.findViewById(R.id.rank);
holder.country = (TextView) convertView.findViewById(R.id.country);
holder.population = (TextView) convertView.findViewById(R.id.population);
// Locate the ImageView in listview_item.xml
holder.flag = (ImageView) convertView.findViewById(R.id.flag);
// The tag can be any Object, this just happens to be the ViewHolder
convertView.setTag(holder);
} else {
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
holder = (ViewHolder) convertView.getTag();
}
// Capture position and set results to the TextViews
holder.rank.setText(resultp.get(MainActivity.RANK));
holder.country.setText(resultp.get(MainActivity.COUNTRY));
holder.population.setText(resultp.get(MainActivity.POPULATION));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(MainActivity.FLAG), holder.flag);
// Capture ListView item click
return convertView;
}
}
Edited: Click on ListItem code
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
listview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// code to handle click
}
});
}
But i don't no why i am not getting data into ListView !
The issue is that you are not assigning the HashMap to `resultp that has the information you want to display
public View getView(final int position, View convertView, ViewGroup parent) {
holder = null;
if (convertView == null) {
convertView = ((Activity) context).getLayoutInflater().inflate(R.layout.listview_item, null);
holder = new ViewHolder(convertView);
holder.rank = (TextView) convertView.findViewById(R.id.rank);
holder.country = (TextView) convertView.findViewById(R.id.country);
holder.population = (TextView) convertView.findViewById(R.id.population);
holder.flag = (ImageView) convertView.findViewById(R.id.flag);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// Here's the change
resultp = data.get(position);
// Here's the change
holder.rank.setText(resultp.get(MainActivity.RANK));
holder.country.setText(resultp.get(MainActivity.COUNTRY));
holder.population.setText(resultp.get(MainActivity.POPULATION));
imageLoader.DisplayImage(resultp.get(MainActivity.FLAG), holder.flag);
return convertView;
}
To attach OnItemClickListener to your ListView, in the Activity that contains the ListView, add the following:
public class MyActivity implements OnItemClickListener{
ListView lv;
#Override
public void onCreate(Bundle savedInstanceState() {
....
....
// lv initialized here
// adapter of lv set here
attachListeners();
}
private void attachListeners() {
....
....
// attach listeners to other views if you like
lv.setOnItemClickListener(this);
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// code to handle click
}
}
Or, if you don't want your Activity to implement OnItemClickListener, then,
public class MyActivity {
ListView lv;
#Override
public void onCreate(Bundle savedInstanceState() {
....
....
// lv initialized here
// adapter of lv set here
attachListeners();
}
private void attachListeners() {
....
....
// attach listeners to other views if you like
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// code to handle click
}
});
}
}
First of all try to fix this:
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}

Android Refresh ListActivity from BaseAdapter

I have a ListActivity and a custom adapter that extends BaseAdapter.
On each row of the ListView, there is a button and a few more views. onClickListener is declared in the adapter.
How can I refresh list view after button is clicked ?
Here is the code
List Activity:
.........
super.onCreate(savedInstanceState);
here im reading content from a file and then creating adapter with that content
adapter = new UvArrayAdapter(this, strarray3, strarray2, intarray);
setListAdapter(adapter);
..........
Adapter:
.......
public class UvArrayAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater linflater;
private TextView txt_1, txt_2, txt_3;
private ProgressBar pr1;
private String[] str1;
private String[] str2;
private String[] str3;
private Integer[] int1;
private class OnItemClickListener implements OnClickListener{
private int mPosition;
OnItemClickListener(int position){
mPosition = position;
}
#Override
public void onClick(View arg0) {
Log.v("TAG", "onItemClick at position" + mPosition);
}
}
public UvArrayAdapter(Context context, String[] s1, String[] s2, Integer[] i1) {
mContext = context;
str1 = s1;
str2 = s2;
int1 = i1;
linflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return str1.length;
}
#Override
public Object getItem(int arg0) {
return str1[arg0];
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = linflater.inflate(R.layout.uv_rowlayout, null);
}
convertView.setOnClickListener(new OnItemClickListener(position));
txt_1 = (TextView) convertView.findViewById(R.id.textView1);
pr1 = (ProgressBar) convertView.findViewById(R.id.progressBar1);
pr1.setProgress(int1[position]);
txt_1.setText(str1[position]);
txt_2 = (TextView) convertView.findViewById(R.id.textView2);
txt_2.setText(str2[position]+"mV");
Button btn = (Button) convertView.findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
Log.v("onClickListener", "button - clicked at position " position);
do some changes in mentioned file and after that i need to update the list view with new data
}});
return convertView;
}
}
adapter.notifyDataSetChanged(); // to notify the adapter that your data has been updated
Note: If you get any errors with the above line, you could try the following code (where mListView is the name of my ListView object)
((BaseAdapter) mListView.getAdapter()).notifyDataSetChanged();
Another way would be to invalidate the List so that it is redrawn form the updated data set once again.
mListView=(ListView) findViewById(R.id.MyListView);
mListView.invalidate();
Use notifyDataSetChanged()
adapter = new UvArrayAdapter(this, strarray3, strarray2, intarray);
setListAdapter(adapter);
UvArrayAdapter.notifyDataSetChanged();
// To make the adapter aware of the changes

Adding a new row on button click to a list view

I want to add a new row on clicking add button in a list view in android.
Can someone help me out?
Here is the code I have so far:
public class prsnlhstry<EventArgs> extends Activity implements OnItemClickListener {
public static ArrayList<String> arr_sort_textview1= null;
public static ArrayList<String> arr_sort_textview2=null;
public static ArrayList<String> arr_sort_textview3=null;
public Resources ApptResources= null;
private ContextWrapper mycontext;
tododata todo;
int clickcounter = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView lv= (ListView)findViewById(R.id.listview);
todo = new tododata(this);
List<listObject> List = new ArrayList<listObject>();
for(int i = 0; i <= 5; i++){
listObject lo = new listObject();
lo.grade = Integer.toString(i);
lo.reason = Integer.toString(i);
lo.school = Integer.toString(i);
List.add(lo);
}
CustomAdapter ca = new CustomAdapter(this);
lv = (ListView)findViewById(R.id.listview);
lv.setAdapter(ca);
lv.setOnItemClickListener(this);
ca.notifyDataSetChanged();
Button button = (Button) findViewById(R.id.btn);
button.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
Toast.makeText(prsnlhstry.this, "Row Added Successfully", Toast.LENGTH_SHORT).show();
}
});
}
private class listObject {
String grade;
String school;
String reason;
}
public class CustomAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public CustomAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return todo.getLength();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
String temp = null;
// to reinflate it. We only inflate a new View when the convertView supplied
// by ListView is null.
if (convertView == null) {
convertView = mInflater.inflate(R.layout.grid_item, null);
// Creates a ViewHolder and store references to the views
// we want to bind data to.
holder = new ViewHolder();
holder.textview1 = (TextView) convertView.findViewById(R.id.item2);
holder.textview2 = (TextView) convertView.findViewById(R.id.item3);
holder.textview3 = (TextView) convertView.findViewById(R.id.item4);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textview1.setText(todo.getgrade(position));
holder.textview2.setText(todo.getschool(position));
holder.textview3.setText(todo.getreason(position));
return convertView;
}
}
static class ViewHolder {
TextView textview1;
TextView textview2;
TextView textview3;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
}
Just add the item to your list and refresh the adapter, nothing special.
You need to increment your "tododata" data structure on button click and then call to notifyDataSetChanged() method:
Button button = (Button) findViewById(R.id.btn);
button.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
todo.addNewRow();
ca.notifyDataSetChanged();
Toast.makeText(prsnlhstry.this, "Row Added Successfully", Toast.LENGTH_SHORT).show();
}
});
To compile the above code you will need to define "ca" variable as the final one, or make it class member.
I hope it helps.

Categories

Resources