Remove selected dynamic checked items from listview - android

Here, in a listview I have added a custom row in which Checkbox and EditText are there and with a add button I just add multiple views to my listview. Adding is working perfectly but when it comes to removing part the checked items are not removing and apart from that suppose I selected two items, then two items from last deleted. I don't know whats going on with my code please help me.
Here is my code:
MainActivity.java
public class MainActivity extends AppCompatActivity {
AdapterCustom customAdapter;
ArrayList<String> stringArrayList;
ListView listView;
ArrayList<Integer> listOfItemsToDelete;
AdapterCustom.ViewHolder item;
int POS;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listOfItemsToDelete = new ArrayList<Integer>();
stringArrayList = new ArrayList<String>();
LinearLayoutManager layoutManager
= new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
listView = (ListView) findViewById(R.id.list_item);
customAdapter = new AdapterCustom(MainActivity.this, R.layout.main, stringArrayList);
}
public void addItems(View v) {
stringArrayList.add("");
listView.setAdapter(customAdapter);
customAdapter.notifyDataSetChanged();
}
public void removeItems(View v) {
if (listOfItemsToDelete.isEmpty()) {
Toast.makeText(getBaseContext(), "No items selected.",
Toast.LENGTH_SHORT).show();
} else {
Log.i("Delete Pos", POS + "");
if (!listOfItemsToDelete.equals("")) {
for (int j = 0; j < listOfItemsToDelete.size(); j++) {
stringArrayList.remove(listOfItemsToDelete.get(j) - j);
customAdapter.notifyDataSetChanged();
}
}
}
}
AdapterCustom.java
public class AdapterCustom extends ArrayAdapter<String> {
Context context;
ArrayList<String> stringArrayList;
ArrayList<Boolean> positionArray;
MainActivity activity;
public AdapterCustom(Context context, int resourceId, ArrayList<String> arrayList) {
super(context, resourceId, arrayList);
this.context = context;
this.stringArrayList = arrayList;
positionArray = new ArrayList<Boolean>(stringArrayList.size());
for (int i = 0; i < stringArrayList.size(); i++) {
positionArray.add(false);
}
activity = new MainActivity();
}
#Override
public int getCount() {
return stringArrayList.size();
}
#Override
public String getItem(int position) {
return stringArrayList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public class ViewHolder {
EditText ediText;
CheckBox checkBox;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
item = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.main, null);
item.ediText = (EditText) convertView.findViewById(R.id.ediText);
item.checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);
item.checkBox.setTag(new Integer(position));
convertView.setTag(item);
final View finalConvertView1 = convertView;
item.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b) {
int getPosition = (Integer) compoundButton.getTag();
POS = getPosition;
listOfItemsToDelete.add(POS);
Log.i("position after check", POS + "");
Log.i("position check array", listOfItemsToDelete + "");
}
}
});
} else {
item = (ViewHolder) convertView.getTag();
}
item.checkBox.setTag(position);
return convertView;
}
}
activity_main.xml
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:weightSum="10">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="horizontal"
android:weightSum="10">
<Button
android:id="#+id/addBtn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="5"
android:onClick="addItems"
android:text="Add New Item" />
<Button
android:id="#+id/goBtn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="5"
android:onClick="goItems"
android:text="Go to Item" />
</LinearLayout>
<ListView
android:id="#+id/list_item"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="8"
android:drawSelectorOnTop="false"
android:visibility="visible" />
<Button
android:id="#+id/removeBtn"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:onClick="removeItems"
android:text="Remove Item" />
</LinearLayout>
main.xml
<LinearLayout
android:id="#+id/custom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="5dp"
android:weightSum="10">
<CheckBox
android:id="#+id/checkBox"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
<EditText
android:id="#+id/ediText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="9"
android:background="#android:color/white"
android:hint="Type Anything You Want" />
</LinearLayout>

You only remove the item from the array. Try removing the item also from the list view adapter with adapter.remove(itemPosition);

What does mean
- j
in this code:
for (int j = 0; j < listOfItemsToDelete.size(); j++) {
stringArrayList.remove(listOfItemsToDelete.get(j) - j);
customAdapter.notifyDataSetChanged();
}
?
I think that:
for (String itemToRemove:listOfItemsToDelete) {
stringArrayList.remove(itemToRemove);
}
customAdapter.notifyDataSetChanged();
listOfItemsToDelete.clear();
would be appropriate.

Related

Retrieving Data from External Site using Asynctask

I'm new to Asynctask and JSon.
May i know how to start to retrieve the currency rates from this site?
http://api.fixer.io/latest?base=SGD
I did look at this post but i'm not too sure how to start..
AsyncTask Android example
From the rates retrieved, i'd like to add the values into this ListView, by using a custom ListView adapter class.
Codes for xml file
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0.0dp"
android:orientation="horizontal"
android:layout_weight="0.4"
android:weightSum="1" >
<LinearLayout
android:layout_width="0.0dp"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_weight="0.8" >
<TextView
android:id="#+id/convertedAmtTV"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="0.00"
android:textSize="70dp"
android:gravity="right" />
<EditText
android:id="#+id/inputAmtET"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="0"
android:textAlignment="textEnd" />
</LinearLayout>
<LinearLayout
android:layout_width="0.0dp"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_weight="0.2">
<TextView
android:id="#+id/convertedCurrTV"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="SGD"
android:textSize="28dp"
android:paddingLeft="2dp"
android:paddingTop="29dp"
android:paddingBottom="19dp"
android:gravity="center_horizontal" />
<TextView
android:id="#+id/inputCurrTV"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="AUD"
android:textSize="28dp"
android:paddingLeft="2dp"
android:layout_marginTop="3dp"
android:gravity="center_horizontal" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_weight="0.6"
android:layout_width="match_parent"
android:layout_height="0.0dp">
<TextView
android:text="From"
android:textSize="21dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ListView
android:id="#+id/currencyLV"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Codes for MainActivity.class
public class MainActivity extends AppCompatActivity {
CurrencyRatesDetails crd = new CurrencyRatesDetails();
CurrencyRates cr = new CurrencyRates();
TextView inputCurrTV, convertedAmtTV;
ListView currencyLV;
EditText inputAmtET;
ArrayAdapter<String> adapter;
String[] currNameArr = crd.getNames();
String[] currCodeArr = crd.getCodes();
String[] currRateArr = crd.getRates();
String[] dbName;
String[] dbCode;
String[] dbRate;
Context context;
int index = 0;
//String[] rateCurrArr = {"AUD", "BGN", "BRL", "CAD", "CHF", "CNY"};
//double[] rateArr = {0.944, 1.2824, 2.2842, 0.96158, 0.70946, 4.8624}
Menu myMenu = null;
double amtInput, finalConversion;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
//context.deleteDatabase("currency.db");
inputAmtET = (EditText) findViewById(R.id.inputAmtET);
convertedAmtTV = (TextView) findViewById(R.id.convertedAmtTV);
inputCurrTV = (TextView) findViewById(R.id.inputCurrTV);
currencyLV = (ListView) findViewById(R.id.currencyLV);
/*for (int i = 0; i < currNameArr.length; i++) {
cr.addToDataBase(currNameArr[i], currCodeArr[i], currRateArr[i], getApplicationContext());
}*/
//cr.addToDataBase(currNameArr, getApplicationContext());
//Resources myRes = this.getResources();
//currArr = myRes.getStringArray(R.array.currencyList);
//adapter = ArrayAdapter.createFromResource(this, R.array.currencyList, android.R.layout.simple_selectable_list_item);
//adapter = new ArrayAdapter<String>(this, android.R.layout.simple_selectable_list_item, currNameArr);
//currencyLV.setAdapter(adapter);
dbName = cr.retrieveAllName(getApplicationContext());
dbCode = cr.retrieveAllCode(getApplicationContext());
dbRate = cr.retrieveAllRate(getApplicationContext());
currencyLV.setAdapter(new CustomAdapter(this, dbName, dbCode, dbRate));
currencyLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
inputCurrTV.setText(dbCode[i]);
index = i;
//Getting rate based on selected currency code
//rate = rateArr[i];
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
this.myMenu = menu;
addMenuItems(menu);
getMenuInflater().inflate(R.menu.mainmenu, menu);
return true;
}
private void addMenuItems(Menu menu) {
int index = 200;
menu.add(index, index, index, "Settings");
menu.add(index, index + 1, index + 1, "Add Custom Rate");
menu.add(index, index + 2, index + 2, "Load Default Rates");
}
public boolean onOptionsItemSelected(MenuItem item) {
//getOrder() to get Menu Item at this specific orderId
if (item.getItemId() == R.id.menu_convert) {
amtInput = Double.parseDouble(inputAmtET.getText().toString());
//finalConversion = amtInput / rate;
finalConversion = crd.conversion(amtInput, index);
//Formatting converted value to 2d.p
String finalValue = String.format("%.2f", finalConversion);
convertedAmtTV.setText(finalValue);
} else if (item.getItemId() == 201) {
Intent myIntent = new Intent(MainActivity.this, CustomXchangeRate.class);
startActivity(myIntent);
}
return true;
}
}
Custom ListView Adapter Class
public class CustomAdapter extends BaseAdapter{
String[] resultNames;
String[] resultCodes;
String[] resultRates;
Context context;
private static LayoutInflater inflater = null;
public CustomAdapter(CustomXchangeRate customXchangeRate, String[] names, String[] codes, String[] rates) {
resultNames = names;
resultCodes = codes;
resultRates = rates;
context = customXchangeRate;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public CustomAdapter(MainActivity mainActivity, String[] names, String[] codes, String[] rates) {
resultNames = names;
resultCodes = codes;
resultRates = rates;
context = mainActivity;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return resultNames.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
public class ViewHolder{
TextView tvName;
TextView tvCode;
TextView tvRate;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder vh = new ViewHolder();
View rowView;
rowView = inflater.inflate(R.layout.activity_custom_adapter, null);
vh.tvName = (TextView) rowView.findViewById(R.id.currencyNameTV);
vh.tvCode = (TextView) rowView.findViewById(R.id.currencyCodeTV);
vh.tvRate = (TextView) rowView.findViewById(R.id.currencyRateTV);
vh.tvName.setText(resultNames[position]);
vh.tvCode.setText(resultCodes[position]);
vh.tvRate.setText(resultRates[position]);
return rowView;
}
}
Would appreciate any help...
The best way to get this JSON inside ur app will be to use Volley :
https://developer.android.com/training/volley/simple.html
Check this link you will find what ur asking for.
Cheers

Button click event with Custom List view

I have two button at bottom i.e after listview ends.
I am using a custom listview which display list items with alternate colors.
how to set setOnClickListener for both button at bottom?
public class PieMainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mRes = getResources();
new Random(new Date().getTime());
solbtn = (Button)findViewById(R.id.solution);
String recive ;
Bundle b = getIntent().getExtras();
final int piewrong=b.getInt("piewrong");
final int pieright=b.getInt("pieright");
final int pieunclick=b.getInt("pieunclick");
setContentView(R.layout.piechart_result);
recive = pieright+"/20";
mPie.setUnit(recive);
data1 = new ArrayList<String>();
fillData() ;
listtotal =getIntent().getStringArrayListExtra("listtotal");
timeuse =getIntent().getStringArrayListExtra("timeused");
adapter1 = new ListAdapter(this, data1, listtotal,timeuse);
ListView lvMain = (ListView) findViewById(R.id.list);
lvMain.setAdapter(adapter1);
lvMain.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
int questionno = position+1;
Bundle b = new Bundle();
b.putInt("questionno",questionno);
b.putInt("piewrong",piewrong);
b.putInt("pieright",pieright);
b.putInt("pieunclick",pieunclick);
Intent in=new Intent(PieMainActivity.this,Solution.class);
in.putStringArrayListExtra("listtotal", (ArrayList<String>) listtotal);
in.putStringArrayListExtra("timeused", (ArrayList<String>) timeuse);
in.putExtras(b);
startActivity(in);
finish();
}
});
}
void fillData() {
for (int i = 1; i <= 20; i++) {
data1.add("Question " + i);
}
}
void fillcmp() {
for (int i = 1; i <= 20; i++) {
cmp.add("cmp " + i);
}
}
}
xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res/com.staritsolutions.apptitude"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1.0"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="5dp"
android:layout_weight="1.0">
<ListView
android:id="#+id/list"
android:layout_height="wrap_content"
android:layout_width="match_parent"
>
</ListView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginBottom="10dp"
android:layout_marginTop="5dp"
android:orientation="horizontal"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp">
<Button
android:id="#+id/home"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="bottom|center_horizontal"
android:layout_marginLeft="6dp"
android:layout_marginRight="3dp"
android:textSize="12dp"
android:layout_weight="1"
android:clickable="true"
android:gravity="center"
android:text="Main Menu"
android:background="#drawable/btn_blue"
android:textColor="#fff"
android:textStyle="bold" />
<Button
android:id="#+id/solution"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="bottom|center_horizontal"
android:layout_marginLeft="6dp"
android:layout_marginRight="3dp"
android:textSize="12dp"
android:layout_weight="1"
android:clickable="true"
android:gravity="center"
android:text="Solutions"
android:background="#drawable/btn_blue"
android:textColor="#fff"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
BaseAdapter file
public class ListAdapter extends BaseAdapter{
Context ctx;
LayoutInflater lInflater;
List<String> data1;
List<String> cmp;
List<String> timeused;
ListAdapter(Context context, List<String> data1 ,List<String> cmp ,List<String> timeused) {
ctx = context;
this.data1 = data1;
this.cmp = cmp;
this.timeused = timeused;
lInflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return data1.size();
}
public int getCount1() {
return cmp.size();
}
#Override
public Object getItem(int position) {
return data1.get(position);
}
public Object getItem1(int position1) {
return cmp.get(position1);
}
#Override
public long getItemId(int position) {
return position;
}
public long getItemId1(int position1) {
return position1;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.listitem, parent, false);
}
/*if (position % 2 == 0) {
view.setBackgroundResource(R.drawable.artists_list_backgroundcolor);
} else {
view.setBackgroundResource(R.drawable.artists_list_background_alternate);
}*/
TextView text = (TextView) view.findViewById(R.id.heading);
int no = position;
if(cmp.get(position).equals("GREEN"))
{
text.setTextColor(Color.parseColor("#00D50E"));
}else if(cmp.get(position).equals("RED"))
{
text.setTextColor(Color.parseColor("#e84040"));
}else
{
text.setTextColor(Color.parseColor("#B441E9"));
}
((TextView) view.findViewById(R.id.heading)).setText(data1.get(position));
((TextView) view.findViewById(R.id.duration)).setText(timeused.get(position));
return view;
//String.valueOf(value);
}
}
So these buttons are not part of your ListView? Well, than in your onCreate do something like:
solbtn = (Button)findViewById(R.id.solution);
solbth.setOnClickListener( toolbar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
yourMethod();
}
});
And the same goes for the second button.
Or you can make your Activity implement View.OnClickListener, after doing this you can set your click listeners like this:
//this two lines in your OnCreate
button1.setOnClickListener(this);
button2.setOnClickListener(this);
//somewhere later in the code
#Override
public void onClick(View v) {
//do something
}
Just add the clickListeners in your onCrete() method:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
.....
solbtn = (Button) findViewById(R.id.home);
homebtn = (Button) findViewById(R.id.solution);
solbtn.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
// do stuff for solution button
}
});
homebtn.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
// do stuff for home button
}
});
.....
}

Get listitem from listview(Customized using Radio Button) when clicked on the Particular Item

I have prepared custom Listview in that i want to select one item from view so for that i have used RadioButton view for single choice item,but i customized it.Following is my total code ,because there may be error in the layout so please help me in solving this.
Activity:-
public class MainActivity extends Activity {
TextView tvEmpty;
ListView listView;
Spinner spnStage;
Button btnGet;
String sfrom;
ArrayList<String> arrayList;
StartFromAdapter arrayAdapter;
String[] stages = { "School", "Collage", "Office" };
String resultdata = "{\"Age\":{\"School\":[{\"Stage\":\"class1\",\"Name\":\"Classname1\"},{\"Stage\":\"class2\",\"Name\":\"ClassName2\"}],\"Collage\":[],\"Office\":[{\"Stage\":\"Office1\",\"Name\":\"Officename1\"},{\"Stage\":\"Office2\",\"Name\":\"Officename2\"}]}}";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tvEmpty = (TextView) findViewById(R.id.emptytv);
listView = (ListView) findViewById(R.id.lstDemo);
spnStage = (Spinner) findViewById(R.id.spinner1);
btnGet = (Button) findViewById(R.id.button1);
ArrayAdapter<String> stageAdapter = new ArrayAdapter<String>(
MainActivity.this, android.R.layout.simple_spinner_item, stages);
stageAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnStage.setAdapter(stageAdapter);
arrayList = new ArrayList<String>();
spnStage.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View v, int pos,
long id) {
if (arrayList.size() > 0 && arrayList != null) {
arrayList.clear();
}
loadListView(parent.getSelectedItem().toString());
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
btnGet.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int selectedPosition = (Integer) v.getTag();
Log.i("SELECTED IN GET", "" + selectedPosition);
}
});
}
public void loadListView(String selectedItem) {
try {
JSONObject jObject = new JSONObject(resultdata);
JSONObject jAge = jObject.getJSONObject("Age");
JSONArray jSelectedItem = jAge.getJSONArray(selectedItem);
if (jSelectedItem.length() != 0) {
for (int i = 0; i < jSelectedItem.length(); i++) {
JSONObject jObj = jSelectedItem.getJSONObject(i);
arrayList.add(jObj.getString("Name"));
}
}
arrayAdapter = new StartFromAdapter(this, arrayList);
arrayAdapter.notifyDataSetChanged();
listView.setAdapter(arrayAdapter);
listView.setEmptyView(tvEmpty);
Log.i("BEFORE LISTVIEW ONCLICK", "THIS IS ADDRESSLIST");
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int pos,
long id) {
sfrom = ((RadioButton) v.findViewById(R.id.startfromrb))
.getText().toString();
Log.i("STARTFROM", sfrom);
}
});
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Adapter:-
public class StartFromAdapter extends BaseAdapter {
ArrayList<String> detailsArrayList;
Context context;
int selectedPosition = 0;
public StartFromAdapter(Context context, ArrayList<String> detailsArrayList) {
this.detailsArrayList = detailsArrayList;
this.context = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return detailsArrayList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return detailsArrayList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout rowLayout = null;
if (convertView == null) {
rowLayout = (LinearLayout) LayoutInflater.from(context).inflate(
R.layout.listitem_view, parent, false);
} else {
rowLayout = (LinearLayout) convertView;
}
RadioButton rbStartFrom = (RadioButton) rowLayout
.findViewById(R.id.startfromrb);
rbStartFrom.setChecked(position == selectedPosition);
rbStartFrom.setTag(position);
rbStartFrom.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
selectedPosition = (Integer) v.getTag();
notifyDataSetInvalidated();
Log.i("IN ADAPTER", "" + selectedPosition);
}
});
rbStartFrom.setText(detailsArrayList.get(position));
return rowLayout;
}
}
MAINLAYOUT:-
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Spinner
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ListView
android:id="#+id/lstDemo"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_below="#+id/spinner1"
android:layout_marginBottom="60dp" >
</ListView>
<TextView
android:id="#+id/emptytv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/spinner1"
android:layout_marginBottom="60dp"
android:gravity="center_vertical|center_horizontal"
android:text="No Records Found."
android:textSize="25sp" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginLeft="31dp"
android:text="Button" />
</RelativeLayout>
listitem_view:-
<?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:descendantFocusability="blocksDescendants"
android:orientation="horizontal" >
<RadioButton
android:id="#+id/startfromrb"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:button="#null"
android:drawableRight="#android:drawable/btn_radio"
android:focusable="false"
android:focusableInTouchMode="false"
android:lines="3"
android:paddingLeft="20dp"
android:text="RadioButton" />
</LinearLayout>
Update use code as per below
// On item click listener
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,long itemId) {
RadioButton btn=(RadioButton) view.findViewById(R.id.startfromrb);
String sfrom = btn.getText().toString();
arrayAdapter.setSelected((int)itemId);
Log.i("STARTFROM", sfrom);
}
});
//Add below function in adapter class
public void setSelected(int selectedPosition){
this.selectedPosition=selectedPosition;
notifyDataSetChanged();
}
Also remove from adapter
rbStartFrom.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
selectedPosition = (Integer) v.getTag();
notifyDataSetInvalidated();
Log.i("IN ADAPTER", "" + selectedPosition);
}
});
And add android:clickable="false" and set selectedPosition to -1 by default
The first I see is, that You have to change the reference to the Views where You want to set the other views below :
<Spinner
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ListView
android:id="#+id/lstDemo"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_below="#+id/spinner1" <!-- correct: #id/spinner1 -->
android:layout_marginBottom="60dp" >
</ListView>
<TextView
android:id="#+id/emptytv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/spinner1" <!-- correct: #id/spinner1 -->
android:layout_marginBottom="60dp"
android:gravity="center_vertical|center_horizontal"
android:text="No Records Found."
android:textSize="25sp" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginLeft="31dp"
android:text="Button" />
</RelativeLayout>
But anyway, Your TextView is sitten directly above the listView, is this Your intention? If not, You have to set
android:layout_below="#+id/lstDemo"
Also, if You get any errors, please post the logcat output. If You just have problems with Your layout, please explain clear enough what exactly You want.
EDIT
try to get the selected item String like this:
final String item = (String) parent.getItemAtPosition(position);
loadListView(item);

Unable to select an item in a ListView whose content is set by an Array Adapter

I couldn't select an item on ListView. I use Custom Adapter to set content of ListView. I have set OnItemClickListener of ListView. However, it didn't respond. I appriciate your help. Here is my code:
List Item (connections.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="wrap_content"
android:orientation="horizontal"
android:padding="6dip" >
<LinearLayout
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="0.90"
android:orientation="vertical" >
<TextView
android:id="#+id/connname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/acc1" />
<TextView
android:id="#+id/conntype"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="9sp"
android:text="#string/acctype1" />
</LinearLayout>
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
The screen which containt ListView (groupconnections.xml):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:layout_marginBottom="5dip"
android:orientation="vertical"
android:id="#+id/textOperLayout">
<TextView
android:id="#+id/connectionsLabel"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/connections"
android:textColor="#color/conn_text"
android:textSize="25sp"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:paddingLeft="15dp"
android:background="#color/conn_back"/>
<EditText
android:id="#+id/searchEditText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="#string/searchhint"
android:layout_marginTop="10dp"
android:inputType="textPersonName" />
</LinearLayout>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="100dip"
android:layout_marginBottom="50dip"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_above="#+id/textOperLayout"
android:id="#+id/listviewlayout">
<ListView
android:id="#+id/connectionlist"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:choiceMode="singleChoice" />
</LinearLayout>
<Button
android:id="#+id/addConnCommitButton"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginLeft="15dp"
android:text="#string/commitToAdd" />
</RelativeLayout>
The related activity (AddMoreConnections.xml):
public class AddMoreConnections extends Activity implements OnItemClickListener{
private ListView mainListView ;
private ArrayAdapter<AbstractHolder> listAdapter ;
private TextView searchConnTextView;
private Button commitButton;
private ArrayList<AbstractHolder> connlist;
private ArrayList<AbstractHolder> listNotOnView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Generate list View from ArrayLis
setContentView(R.layout.groupconnections);
addListenerOnSearchConnTextView();
//Initialize properties
mainListView = (ListView) findViewById( R.id.connectionlist );
mainListView.setOnItemClickListener(this);
// Create and populate a List of planet names.
listNotOnView = new ArrayList<AbstractHolder>();
connlist = new ArrayList<AbstractHolder>(5);
Iterator<AbstractHolder> iter = SocialRssModel.holders.values().iterator();
while(iter.hasNext())
connlist.add(iter.next());
// Create ArrayAdapter using the planet list.
listAdapter = new CustomAdapter(this,
R.layout.connlist, connlist);
mainListView.setAdapter( listAdapter );
}
public void addListenerToFinishButton(){
commitButton = (Button) findViewById(R.id.addConnCommitButton);
commitButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
public void addListenerOnSearchConnTextView(){
searchConnTextView = (TextView) findViewById(R.id.searchEditText);
searchConnTextView.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
int listNotOnViewsize = listNotOnView.size();
int connlistsize = connlist.size();
for(int i= 0; i < connlistsize; i++){
if(!connlist.get(i).connNameContains(s.toString())){
listNotOnView.add(connlist.remove(i));
i--;
connlistsize--;
}
}
for(int i=0; i < listNotOnViewsize; i++){
if(listNotOnView.get(i).connNameContains(s.toString())){
connlist.add(listNotOnView.remove(i));
i--;
listNotOnViewsize--;
}
}
((CustomAdapter) listAdapter).updateList(connlist);
listAdapter.notifyDataSetChanged();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
AbstractHolder temp = (AbstractHolder)mainListView.getItemAtPosition(arg2);
Intent i = new Intent(this, CategoryContentViewerController.class);
Bundle b = new Bundle();
b.putInt("AbstractHolderKey", temp.getId());
i.putExtras(b);
startActivity(i);
finish();
}
private class CustomAdapter extends ArrayAdapter<AbstractHolder> {
private ArrayList<AbstractHolder> connectionList;
public CustomAdapter(Context context, int textViewResourceId, ArrayList<AbstractHolder> connList) {
super(context, textViewResourceId, connList);
this.connectionList = new ArrayList<AbstractHolder>();
this.connectionList.addAll(connList);
}
public void updateList(ArrayList<AbstractHolder> connList){
connectionList.clear();
connectionList.addAll(connList);
}
private class ViewHolder {
TextView name;
TextView acctype;
CheckBox sel;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
LayoutInflater vi = (LayoutInflater)(((Activity)this.getContext()).getSystemService(Context.LAYOUT_INFLATER_SERVICE));
convertView = vi.inflate(R.layout.connlist, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.connname);
holder.acctype = (TextView) convertView.findViewById(R.id.conntype);
holder.sel = (CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
AbstractHolder conn = connectionList.get(position);
holder.name.setText(conn.getName());
holder.acctype.setText(conn.getConntype());
holder.sel.setChecked(conn.isSelected());
holder.sel.setTag(conn);
return convertView;
}
}
}
It is related to checkbox item in connections.xml which is the list row item. If I remove checkbox, related listeners responses. I think, it may be thought there is no need a setItemOnClickListener(..) method since each row has a checkbox. Or it is a bug.

CheckedTextView doesnt Toggle

I have a custom listview that has CheckedTextView. When i click the the items it doesn't toggle the checked state of the object and reflect in the ui.
dialog_categories.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/parentPanel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="8dip"
android:layout_marginStart="8dip"
android:background="#color/primary_white"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/title_template"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="16dip"
android:layout_marginStart="16dip"
android:gravity="center_vertical|start"
android:orientation="horizontal"
android:paddingTop="5dp" >
<TextView
android:id="#+id/textView1"
style="?android:attr/textAppearanceLarge"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:paddingLeft="10dp"
android:text="#string/dialog_category_title"
android:textColor="#color/primary_color"
android:textSize="22sp" />
<TextView
android:id="#+id/all"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/dialog_category_checkbox"
android:textColor="#color/primary_color" />
<CheckBox
android:id="#+id/checkBoxAll"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="6dp" />
</LinearLayout>
<View
android:id="#+id/titleDivider"
android:layout_width="match_parent"
android:layout_height="2dip"
android:background="#color/black" />
<LinearLayout
android:id="#+id/contentPanel"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:minHeight="64dp"
android:orientation="vertical" >
<ListView
android:id="#+id/listViewDialog"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
<LinearLayout
android:id="#+id/buttonPanel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<Button
android:id="#+id/button_category_ok"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/dialog_category_btn_ok"
android:textSize="14sp" />
</LinearLayout>
</LinearLayout>
dialog_list_item_category.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<CheckedTextView
android:id="#+id/categories_checkbox"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:checkMark="?android:attr/listChoiceIndicatorMultiple"
android:gravity="center_vertical"
android:onClick="toggle"
android:text="sss" />
</RelativeLayout>
CategoriesDialogFragment.java
public class CategoriesDialogFragment extends SherlockDialogFragment {
CheckBox checkAll;
ListView categoriesListView;
CategoriesListAdapter adapter;
static Category category;
String[] categories = new String[] { "Hill Station", "Beach", "Historic",
"Wild Life", "Waterfall", "River", "Archeology" };
String[] categories_state = new String[] { "1", "0", "1", "1", "1", "1",
"0" };
public static CategoriesDialogFragment newInstance() {
CategoriesDialogFragment frag = new CategoriesDialogFragment();
Bundle args = new Bundle();
frag.setArguments(args);
return frag;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Dialog dialog = new Dialog(MainActivity.context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog_categories);
categoriesListView = (ListView) dialog
.findViewById(R.id.listViewDialog);
List<Category> theCategories = new ArrayList<Category>();
for (int i = 0; i < categories.length; i++) {
Category pl = new Category(categories[i], false);
theCategories.add(pl);
}
categoriesListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
adapter = new CategoriesListAdapter(MainActivity.context,
R.layout.dialog_list_item_category, theCategories);
categoriesListView.setAdapter(adapter);
checkAll = (CheckBox) dialog.findViewById(R.id.checkBoxAll);
checkAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
Toast.makeText(MainActivity.context, "Check",
Toast.LENGTH_SHORT).show();
if (isChecked) {
for (int i = 0; i < adapter.getCount(); i++) {
category = adapter.getItem(i);
category.setChecked(true);
}
adapter.notifyDataSetChanged();
} else {
for (int i = 0; i < adapter.getCount(); i++) {
category = adapter.getItem(i);
category.setChecked(false);
}
adapter.notifyDataSetChanged();
}
}
});
return dialog;
}
private static class CategoriesListAdapter extends ArrayAdapter<Category> {
public Context mContext;
List<Category> mCategories;
public CategoriesListAdapter(Context context, int resource,
List<Category> categories) {
super(context, resource, categories);
// TODO Auto-generated constructor stub
this.mCategories = categories;
this.mContext = context;
}
public int getCount() {
return mCategories.size();
}
#Override
public Category getItem(int position) {
// TODO Auto-generated method stub
return mCategories.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) {
LayoutInflater viewInflater;
viewInflater = LayoutInflater.from(getContext());
convertView = viewInflater.inflate(
R.layout.dialog_list_item_category, null);
holder = new ViewHolder();
holder.categoryName = (CheckedTextView) convertView
.findViewById(R.id.categories_checkbox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.categoryName.setText(mCategories.get(position)
.getCategoryName());
return convertView;
}
static class ViewHolder {
CheckedTextView categoryName;
}
}
}
Could you just use android.R.layout.simple_list_item_multiple_choice instead of dialog_list_item_category.xml?
Update: #Luksprog's comment is the solution: Remove the RelativeLayout and it works just like with android.R.layout.simple_list_item_multiple_choice.
Are You using the proper xml?
There's
dialog_list_item_categories.xml
but in your code You use everywhere
R.layout.dialog_list_item_category

Categories

Resources