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.
Related
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.
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!
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>
I'm trying to add a button in a list View, I searched a lot on google but nothing was good enough for me.
Here's my code: I have 2 classes :
Menu.java
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class Menu extends ListActivity implements OnItemClickListener {
String[] listaMeniu = { "1", "2", "3"};
Button butonNota;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setListAdapter(new ListAdapter(this, listaMeniu));
ListView listView = getListView();
listView.setOnItemClickListener (this);
Button btnLoadMore = new Button(this);
btnLoadMore.setText("show me");
}
}
Menu.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="5dp">
<ImageView
android:id="#+id/1"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="20dp"
android:layout_marginTop="5dp"
android:src="#drawable/1" />
<TextView
android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize = "30dp"
android:text="1" />
</LinearLayout>
ListAdapter.java
package com.example.a;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class ListAdapter extends ArrayAdapter {
private Context context;
private String[] values;
public ListAdapter(Context context, String[] values) {
// TODO Auto-generated constructor stub
super (context, R.layout.menu, values);
this.context = context;
this.values = values;
}
}
I already made the list view, but I don't know how to add the button above the list. I tried to add it in menu.xml but it's shows up a button for every item in the list. Hope you guys understand what I want.
Thank you!
The best way is to create your custom adapter. For example :
import android.content.Context;
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.Button;
public class MySimpleArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
public MySimpleArrayAdapter(Context context, String[] values) {
super(context, R.layout.rowlayout, values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.rowlayout, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.label);
Button buttonView = (Button) rowView.findViewById(R.id.button);
buttonView.setText(values[position]);
return rowView;
}
}
And here is the xml from "rowlayout.xml". You have to put the layout file in the res/layout project folder.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="#+id/button"
android:layout_width="22px"
android:layout_height="22px"
android:layout_marginLeft="4px"
android:layout_marginRight="10px"
android:layout_marginTop="4px">
</Button>
<TextView
android:id="#+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#+id/label"
android:textSize="20px" >
</TextView>
</LinearLayout>
And then just update your Menu.java
public class Menu extends ListActivity implements OnItemClickListener {
String[] listaMeniu = { "1", "2", "3"};
Button butonNota;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setListAdapter(new MySimpleArrayAdapter(this, listaMeniu));
...
}
}
You need to override method getView in your adapter to return Button.
It appears that you want your 10th item in the list to be a button.
That means that when you overwrite your ArrayAdapter class, you need to modify GetView() so it returns the button instead of a picture. Create two different layout XML files, rowlayout_picture.xml and rowlayout_button.xml, and then:
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = null;
if (position < 10)
rowView = inflater.inflate(R.layout.rowlayout_picture, parent, false);
else
rowView = inflater.inflate(R.layout.rowlayout_button, parent, false);
return rowView;
}
I use a ListView with a custom adapter to build a list with ckeckboxes. Now I dont know how i can fetch the "ID" from the selected box.
The xml file for the items look like this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp">
<TextView android:id="#+id/class_open"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone" />
<CheckBox
android:id="#+id/checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:onClick="clickHandler" />
<TextView
android:id="#+id/medi_name"
android:text="Test"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="#id/checkbox" />
</RelativeLayout>
I need the value from: "class_open"
this is my activity:
package de.bodprod.dkr;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class MediNotmediUserListNew extends Activity{
LayoutInflater inflater;
ArrayList<HashMap<String, Object>> medi_notmedi_items;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.medi_notmedi_user_list_new);
ListView mediListCheck = (ListView) findViewById(android.R.id.list);
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
medi_notmedi_items = new ArrayList<HashMap<String,Object>>();
SystemDatabaseHandler db = new SystemDatabaseHandler(getApplicationContext());
medi_notmedi_items = db.getAllNotmedis();
final CustomAdapter adapter = new CustomAdapter(this, R.layout.medi_notmedi_user_list_new, medi_notmedi_items);
mediListCheck.setAdapter(adapter);
}
public void clickHandler(View view) {
}
private class CustomAdapter extends ArrayAdapter<HashMap<String, Object>>{
public CustomAdapter(Context context, int textViewResourceId, ArrayList<HashMap<String, Object>> Strings) {
super(context, textViewResourceId, Strings);
}
private class ViewHolder{
TextView class_open, title;
}
ViewHolder viewHolder;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null){
convertView=inflater.inflate(R.layout.medi_notmedi_user_list_new_item, null);
viewHolder=new ViewHolder();
viewHolder.class_open=(TextView) convertView.findViewById(R.id.class_open);
viewHolder.title=(TextView) convertView.findViewById(R.id.medi_name);
convertView.setTag(viewHolder);
}else{
viewHolder=(ViewHolder) convertView.getTag();
}
viewHolder.class_open.setText(medi_notmedi_items.get(position).get("sql_id").toString());
viewHolder.title.setText(medi_notmedi_items.get(position).get("wirk").toString());
return convertView;
}
}
}
How I can get the value from the class_open field in the clickHandler?
Is it possible to assign the value directly to the checkbox and request it?
Is it possible to request the value from the class_open field?
Please excuse my bad english
Markus