Android how to mange spinner with radio button in listview? - android

My problem is that when I am clicking on radio button it will change the spinner value randomly at any position..please help here is my adapter class..
public class ManageAdapter extends BaseAdapter {
ArrayList<String> _manageArrayList = null;
private Context _Context = null;
private Integer selectedPosition = 0;
String List1[]=new String[]{"In use","Lost" ,"Stolen" , "For sale"};
private int flag = 0;
public ManageAdapter(ArrayList<String> _manageArrayList, Context _Context) {
super();
this._manageArrayList = _manageArrayList;
this._Context = _Context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return _manageArrayList != null? _manageArrayList.size():0;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public static class ViewHolder
{
public TextView itemTextView;
public RadioButton myitemButton;
public Spinner inUseSpinner;
public RelativeLayout managelayout;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
final ViewHolder holder;
LayoutInflater inflater = (LayoutInflater)_Context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(v == null)
{
holder = new ViewHolder();
v = inflater.inflate(R.layout.manage_single_row, null,false);
holder.managelayout = (RelativeLayout)v.findViewById(R.id.single_row_layout);
holder.itemTextView = (TextView)v.findViewById(R.id.item_name_txt);
holder.myitemButton = (RadioButton)v.findViewById(R.id.manage_radio_buton);
holder.inUseSpinner = (Spinner)v.findViewById(R.id.Status_spinner);
v.setTag(holder);
ArrayAdapter<String> Adapter = new ArrayAdapter<String>(_Context,R.layout.spinner_color,List1);
Adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Setting the ArrayAdapter data on the Spinner
holder.inUseSpinner.setAdapter(Adapter);
}else {
holder = (ViewHolder) v.getTag();
}
holder.itemTextView.setText(_manageArrayList.get(position));
holder.inUseSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// int getPosition = (Integer) arg0.getTag();
// Toast.makeText(_Context,List1[position] ,Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
if(flag == 0)
{
flag = 1;
holder.myitemButton.setChecked(false);
holder.myitemButton.setTag(position);
}else {
holder.myitemButton.setChecked(position == selectedPosition);
holder.myitemButton.setTag(position);
}
holder.myitemButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
selectedPosition = (Integer)v.getTag();
notifyDataSetInvalidated();
}
});
return v;
}
}
Thanks in advance
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manage_item);
_backButton = (Button)findViewById(R.id.back);
_backButton.setOnClickListener(this);
_headerTextView = (TextView)findViewById(R.id.header_TextView);
_headerTextView.setText("My Items");
_uploadButton = (ImageButton)findViewById(R.id.Upload_file_button);
_uploadButton.setOnClickListener(this);
_addmanullyButton = (ImageButton)findViewById(R.id.add_item_manually);
_addmanullyButton.setOnClickListener(this);
_addphoneButton = (ImageButton)findViewById(R.id.auto_add_phone);
_addphoneButton.setOnClickListener(this);
_modifyButton = (ImageButton)findViewById(R.id.modify_button);
_modifyButton.setOnClickListener(this);
_transferButton = (ImageButton)findViewById(R.id.transfer_ownership);
_transferButton.setOnClickListener(this);
_hideenButton = (Button)findViewById(R.id.hideen_button);
_hideenButton.setOnClickListener(this);
_manageListView = (ListView)findViewById(R.id.manage_listview);
prepareList();
_adapter = new ManageAdapter(listItem, this);
_manageListView.setAdapter(_adapter);
}
public void prepareList() {
listItem = new ArrayList<String>();
listItem.add("Android smart");
listItem.add("sony");
listItem.add("samsung");
listItem.add("micromax");
listItem.add("tablet");
}
#Override
public void onClick(View view) {
Intent intent = null;
switch (view.getId()) {
case R.id.Upload_file_button:
intent = new Intent(ManageItems.this, UploadFileActivity.class);
startActivity(intent);
break;
case R.id.modify_button:
intent = new Intent(ManageItems.this, ModifyActivity.class);
startActivity(intent);
break;
case R.id.transfer_ownership:
intent = new Intent(ManageItems.this, TransferOwnerShip.class);
startActivity(intent);
break;
case R.id.add_item_manually:
intent = new Intent(ManageItems.this, AddManuallyActivity.class);
startActivity(intent);
break;
case R.id.auto_add_phone:
intent = new Intent(ManageItems.this, AutoAddActivity.class);
startActivity(intent);
break;
case R.id.back:
intent = new Intent(ManageItems.this, MenuActivtiy.class);
startActivity(intent);
break;
case R.id.hideen_button:
intent = new Intent(ManageItems.this, MenuActivtiy.class);
startActivity(intent);
break;
}

Thanks all but I got the solution of my question..
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = convertView;
final ViewHolder holder;
MyItemListDataHolder myItemListDataHolder = _manageArrayList.get(position);
LayoutInflater inflater = (LayoutInflater)_Context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(v == null)
{
holder = new ViewHolder();
v = inflater.inflate(R.layout.manage_single_row, null,false);
holder.managelayout = (RelativeLayout)v.findViewById(R.id.single_row_layout);
holder.itemTextView = (TextView)v.findViewById(R.id.item_name_txt);
holder.myitemButton = (RadioButton)v.findViewById(R.id.manage_radio_buton);
holder.inUseSpinner = (Spinner)v.findViewById(R.id.Status_spinner);
v.setTag(holder);
}else {
holder = (ViewHolder) v.getTag();
}
holder.itemTextView.setText(myItemListDataHolder.get_itemName());
Adapter = new ArrayAdapter<String>(_Context,R.layout.spinner_color,List1);
Adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Setting the ArrayAdapter data on the Spinner
holder.inUseSpinner.setAdapter(Adapter);
if(myItemListDataHolder.get_selectedItem() > 0){
holder.inUseSpinner.setSelection(myItemListDataHolder.get_selectedItem());
}else{
holder.inUseSpinner.setSelection(0);
}
holder.inUseSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
private Intent intent;
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position1, long arg3) {
_manageArrayList.get(position).set_selectedItem(position1);
// notifyDataSetChanged();
String status=holder.inUseSpinner.getSelectedItem().toString();
if(status.equalsIgnoreCase("Lost"))
{
intent = new Intent (_Context, LostItemActivity.class);
startActivity(intent);
}else if (status.equalsIgnoreCase("Stolen")) {
intent = new Intent (_Context, StolenItemActivity.class);
startActivity(intent);
}else if (status.equalsIgnoreCase("Stolen")) {
intent = new Intent (_Context, LostFoundActivity.class);
startActivity(intent);
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
if(flag == 0)
{
flag = 1;
holder.myitemButton.setChecked(false);
}else {
holder.myitemButton.setChecked(position == selectedPosition);
}
holder.myitemButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
selectedPosition = position;
notifyDataSetChanged();
//_adapter.notifyDataSetChanged();
}
});
return v;
}
}

Related

How to select two list items at same time ? To be specific ONLY TWO items not more than that

I have a list view like the below image.
Now I want to select Only Any two items from the list view at a time and pass the values of both listview items with Intent to next activity. How can I achieve it.?
If Both items are not selected set validation on it?
AdapterClass
public class LoadAdapter extends BaseAdapter {
private ArrayList<DataBase> mProductItems;
private LayoutInflater mLayoutInflater;
private Context mContext;
DBHelper mydb;
DataBase stringItem;
public LoadAdapter(Context context, ArrayList<DataBase> arrayList){
mContext = context;
mProductItems = arrayList;
mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
Log.e("testtt", String.valueOf(mProductItems.size()));
return mProductItems.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mLayoutInflater.inflate(R.layout.load_chart_item, parent, false);
holder.txtv_name = (TextView) convertView.findViewById(R.id.text);
holder.nameid = (TextView) convertView.findViewById(R.id.nameid);
holder.btn_delete = (Button) convertView.findViewById(R.id.btn_delete);
holder.btn_edit = (Button)convertView.findViewById(R.id.btn_edit);
holder.location = (TextView)convertView.findViewById(R.id.loc);
holder.img= (ImageView)convertView.findViewById(R.id.img);
holder.btn_delete.setTag(position);
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
mydb = new DBHelper(mContext);
stringItem = mProductItems.get(position);
if (stringItem != null) {
if (holder.txtv_name != null) {
holder.txtv_name.setText(stringItem.getName());
holder.nameid.setText(stringItem.getId());
holder.location.setText(stringItem.getLocation());
Log.e("saved Location values",stringItem.getLocation());
}
}
if(selected.get(position))
{
//for selected row
holder.img.setBackgroundResource(R.drawble.myimg)
}
else
{
// for not selected row
}
holder.btn_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
DataBase test = mProductItems.get(position);
String id = test.getId();
mydb.deleteContact(Integer.valueOf(id));
mProductItems.remove(mProductItems.get(position));
LoadAdapter.this.notifyDataSetChanged();
if (mProductItems.size() == 0){
mProductItems.clear();
LoadAdapter.this.notifyDataSetChanged();
}
}
});
Log.e("DataBase", String.valueOf(mydb.getAllCotacts()));
holder.btn_edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(mContext,UpdateData.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
SharedPreferences preff = PreferenceManager.getDefaultSharedPreferences(mContext);
SharedPreferences.Editor edi = preff.edit();
edi.putString("key",String.valueOf(position+1));
edi.apply();
mContext.startActivity(intent);
}
});
return convertView;
}
public void refresh(ArrayList<DataBase> items)
{
this.mProductItems = items;
notifyDataSetChanged();
}
private static class ViewHolder {
ImageView img;
TextView txtv_name,nameid,location;
Button btn_delete,btn_edit;
}
}
Main Class
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import java.util.ArrayList;
public class LoadChart extends AppCompatActivity {
public final static String EXTRA_MESSAGE = "MESSAGE";
private SwipeListView listView;
DBHelper mydb;
Button det;
LoadAdapter loadAdapter;
ArrayList<DataBase> array_list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.load_chart);
mydb = new DBHelper(this);
array_list = mydb.getAllCotacts();
Log.e("logging", String.valueOf(array_list));
// ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(this,R.layout.load_chart_item,R.id.text, array_list);
det = (Button)findViewById(R.id.reli);
listView = (SwipeListView) findViewById(R.id.listview);
listView.setAdapter(new LoadAdapter(getApplicationContext(),array_list));
det.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String str = "";
str = relationAdapter.getSelected();
Toast.makeText(RelationShipChartList.this, str, Toast.LENGTH_SHORT).show();
}
});
listView.setSwipeListViewListener(new BaseSwipeListViewListener() {
int openItem = -1;
int lastOpenedItem = -1;
int lastClosedItem = -1;
#Override
public void onOpened(int position, boolean toRight) {
lastOpenedItem = position;
int index = position - listView.getFirstVisiblePosition();
View view = listView.getChildAt(index);
Button delete = (Button) view.findViewById(R.id.btn_delete);
Button edit = (Button) view.findViewById(R.id.btn_edit);
if (!toRight) {
delete.setVisibility(View.VISIBLE);
edit.setVisibility(View.VISIBLE);
}
if (openItem > -1 && lastOpenedItem != lastClosedItem) {
listView.closeAnimate(openItem);
}
openItem = position;
}
#Override
public void onStartClose(int position, boolean right) {
Log.d("swipe", String.format("onStartClose %d", position));
lastClosedItem = position;
}
#Override
public void onClosed(int position, boolean fromRight) {
int index = position - listView.getFirstVisiblePosition();
View view = listView.getChildAt(index);
Button delete = (Button) view.findViewById(R.id.btn_delete);
Button edit = (Button) view.findViewById(R.id.btn_edit);
if (!fromRight) {
delete.setVisibility(View.INVISIBLE);
edit.setVisibility(View.INVISIBLE);
}
}
#Override
public void onListChanged() {
}
#Override
public void onMove(int position, float x) {
}
#Override
public void onStartOpen(int position, int action, boolean right) {
}
#Override
public void onClickFrontView(int position) {
int id_To_Search = position;
DataBase test = array_list.get(position);
String id = test.getId();
String name = test.getName();
String loc = test.getLocation();
String dt = test.getDate();
String time = test.getTime();
Bundle dataBundle = new Bundle();
dataBundle.putString("name",name);
dataBundle.putString("date",dt);
dataBundle.putString("time",time);
dataBundle.putString("location",loc);
dataBundle.putInt("id", Integer.parseInt(id));
Intent intent = new Intent(getApplicationContext(),LoadedChart.class);
intent.putExtras(dataBundle);
startActivity(intent);
}
#Override
public void onClickBackView(int position) {
Log.e("swipe", String.format("onClickBackView %d", position));
}
#Override
public void onDismiss(int[] reverseSortedPositions) {
}
});
}
public int convertDpToPixel(float dp) {
DisplayMetrics metrics = getResources().getDisplayMetrics();
float px = dp * (metrics.densityDpi / 160f);
return (int) px;
}
#Override
public void onResume()
{
super.onResume();
Set_Referash_Data();
}
public void Set_Referash_Data() {
array_list.clear();
mydb = new DBHelper(this);
ArrayList<DataBase> con = mydb.getAllCotacts();
for (int i = 0; i < con.size(); i++) {
String tidno = con.get(i).getId();
String name = con.get(i).getName();
String cons = con.get(i).getCon();
String loc = con.get(i).getLocation();
DataBase cnt = new DataBase();
cnt.setId(tidno);
cnt.setName(name);
cnt.setCon(cons);
cnt.setLocation(loc);
array_list.add(cnt);
Log.e(String.valueOf(array_list),"RefreshData");
}
mydb.close();
array_list = mydb.getAllCotacts(); //reload the items from database
LoadAdapter ld = new LoadAdapter(getApplicationContext(),array_list);
listView.setAdapter(ld);
ld.refresh(array_list);
ld.notifyDataSetChanged();
Log.e(String.valueOf(array_list),"RefreshData Final");
}
}
Logcat
05-09 14:47:50.706 29939-29939/com.example.user.humandesignsample E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.humandesignsample, PID: 29939
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.user.humandesignsample.RelationAdapter.getSelected()' on a null object reference
at com.example.user.humandesignsample.RelationShipChartList$1.onClick(RelationShipChartList.java:45)
at android.view.View.performClick(View.java:5204)
at android.view.View$PerformClick.run(View.java:21153)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
I would use Action Mode with MultiChoiceModeListener.
http://developer.android.com/reference/android/widget/AbsListView.MultiChoiceModeListener.html
There is a callback onItemCheckedStateChanged(ActionMode mode, int position, boolean checked).
You can easily get values of already checked list items ListView.getCheckedItemPositions. So you can prevent selection, if you already selected two or even at once pass the values(or ids) of selected ones without any effort.
You can simply put a counter on item selection.
Take a variable say for ex.
int count = 0;
Check this variable before marking item as selected/deselected:
if(item.isSelected())
{
// you need to make is disable
if(count>0)
{
count--;
// // mark item as deselected
}
}
else
{
// make it selected
if(count<2)
{
count++;
// mark item as selected
}
}
This will make you select ONLY TWO items at a time.
Modify your adapter like this:
public class LoadAdapter extends BaseAdapter {
private ArrayList<DataBase> mProductItems;
private LayoutInflater mLayoutInflater;
private Context mContext;
DBHelper mydb;
DataBase stringItem;
ArrayList<Boolean> selected = new ArrayList<>();
private int count=0;
public LoadAdapter(Context context, ArrayList<DataBase> arrayList){
mContext = context;
mProductItems = arrayList;
mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (int i = 0; i < arrayList.size(); i++) {
selected.add(false);
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
Log.e("testtt", String.valueOf(mProductItems.size()));
return mProductItems.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mLayoutInflater.inflate(R.layout.load_chart_item, parent, false);
holder.txtv_name = (TextView) convertView.findViewById(R.id.text);
holder.nameid = (TextView) convertView.findViewById(R.id.nameid);
holder.btn_delete = (Button) convertView.findViewById(R.id.btn_delete);
holder.btn_edit = (Button)convertView.findViewById(R.id.btn_edit);
holder.location = (TextView)convertView.findViewById(R.id.loc);
holder.btn_delete.setTag(position);
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
mydb = new DBHelper(mContext);
stringItem = mProductItems.get(position);
if (stringItem != null) {
if (holder.txtv_name != null) {
holder.txtv_name.setText(stringItem.getName());
holder.nameid.setText(stringItem.getId());
holder.location.setText(stringItem.getLocation());
Log.e("saved Location values",stringItem.getLocation());
}
}
if(selected.get(position))
{
//for selected row
holder.txtv_name.setTextColor(color.red);
}
else
{
// for not selected row
holder.txtv_name.setTextColor(color.black);
}
holder.txtv_name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(holder.txtv_name.getCurrentTextColor()== R.color.black)
{
//is not selected
if(count<2)
{
count++;
selected.set(position,true);
// mark item as selected
}
}
else
{
//is selected
if(count>0)
{
count--;
selected.set(position,false);
// // mark item as deselected
}
}
notifyDataSetChanged();
}
});
holder.btn_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
DataBase test = mProductItems.get(position);
String id = test.getId();
mydb.deleteContact(Integer.valueOf(id));
mProductItems.remove(mProductItems.get(position));
LoadAdapter.this.notifyDataSetChanged();
if (mProductItems.size() == 0){
mProductItems.clear();
LoadAdapter.this.notifyDataSetChanged();
}
}
});
Log.e("DataBase", String.valueOf(mydb.getAllCotacts()));
holder.btn_edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(mContext,UpdateData.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
SharedPreferences preff = PreferenceManager.getDefaultSharedPreferences(mContext);
SharedPreferences.Editor edi = preff.edit();
edi.putString("key",String.valueOf(position+1));
edi.apply();
mContext.startActivity(intent);
}
});
return convertView;
}
public void refresh(ArrayList<DataBase> items)
{
this.mProductItems = items;
notifyDataSetChanged();
}
private static class ViewHolder {
TextView txtv_name,nameid,location;
Button btn_delete,btn_edit;
}}
EDIT 2: For getting selected items from adapter define below method in
adapter and call it with an adapter object like : adp.getSelected()
public String getSelected() {
String selectedString = "";
int num=0;
for (int i = 0; i < selected.size(); i++) {
if (selected.get(i)) {
num++;
if (num == 1) {
selectedString = mProductItems.get(i).getName();
} else {
selectedString += "," + mProductItems.get(i).getName();
}
}
}
return selectedString;
}
Answer to issue 2 : If you want to use ImageView instead of text color change. The do the same things as above but replace the TextView + Color with ImageView + Image.
EDIT 3:
You have called the getSelected() method from a Null object. Modify your code like this:
listView = (SwipeListView) findViewById(R.id.listview);
loadAdapter = new LoadAdapter(getApplicationContext(),array_list);
listView.setAdapter(loadAdapter);
det.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String str = "";
str = loadAdapter.getSelected();
Toast.makeText(RelationShipChartList.this, str, Toast.LENGTH_SHORT).show();
}

Deleting item from Listview in onActivityResult

I'm hoping that someone here could help me. I'm trying to delete an item from my Listview by clicking a button from another activity. I'm sending a an intent and resultcode in the onActivityResult to the activity that contains the listview but nothing is happening. Any help would be greatly appreciated. Thanks
Delete Button Activity
private void deleteClicked() {
Intent result = new Intent();
result.putExtra("myReminder", item);
getActivity() .setResult(12, result);
getActivity().finish();
}
ListView Activity
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
Log.e(TAG, "REMOVE CALLEDcode");
if (requestCode == 05) {
if (resultCode == 12) {
Chops item = (Chops) data.getSerializableExtra("myReminder");
removeChop(item);
refreshFragment();
}
}
}
private void removeChop(Chops item) {
// TODO Auto-generated method stub
Log.d(TAG, "REMOVE CALLED");
for (Iterator iterator = SaveTheChops.listofchops.iterator(); iterator.hasNext(); ) {
Chops deleteChop = (Chops) iterator.next();
if (match(item, deleteChop)) {
iterator.remove();
//SaveTheChops.addChop(getActivity());
return;
}
}
}
private boolean match(Chops item, Chops deleteChop) {
if (item.getmAlbum().equals(deleteChop.getmAlbum()) &
item.getmArtist().equals(deleteChop.getmArtist()) &
item.getmSong().equals(deleteChop.getmSong()) &
item.getmAudio().equals(deleteChop.getmAudio()) &
item.getmPic().equals(deleteChop.getmPic()) &
item.getmSection().equals(deleteChop.getmSection()))
{ Log.e(TAG, "MATCH");
return true;
}
Log.e(TAG, " NO MATCH");
return false;
}
private void refreshFragment() {
Log.e(TAG, "REFRESHED");
Fragment frg = null;
frg = getFragmentManager().findFragmentByTag("ListFragmenttag");
final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.detach(frg);
ft.attach(frg);
ft.commit();
}
}
If it helps here is my ListAdapter
public static class ListViewDemoAdapter extends ArrayAdapter<Chops> implements MediaPlayer.OnCompletionListener {
final String TAG = "MyChopActivty";
private boolean isPlaying;
private boolean isRecording;
private List<Chops> mItems;
MediaPlayer mPlayer;
public Chops item;
File audiofile = null;
private int length;
Intent intent, fileIntent;
String mAudio;
public ListViewDemoAdapter(Context context, List<Chops> items) {
super(context, R.layout.each_item, items);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
if (convertView == null) {
final LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.each_item, parent, false);
viewHolder = new ViewHolder();
viewHolder.ivIcon = (ImageView) convertView.findViewById(R.id.cover_photo);
viewHolder.tvAlbum = (TextView) convertView.findViewById(R.id.tvAlbum);
viewHolder.tvPlay = (Button) convertView.findViewById(R.id.listPly);
viewHolder.tvSong = (TextView) convertView.findViewById(R.id.tvSong);
convertView.setTag(viewHolder);
final Button PIL = (Button) convertView.findViewById(R.id.listPly);
final Button PAUSIL = (Button) convertView.findViewById(R.id.listPause);
PAUSIL.setEnabled(false);
PAUSIL.setVisibility(View.INVISIBLE);
PIL.setTag(position);
PIL.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (Integer) v.getTag();
Chops item = getItem(position);
Toast.makeText(getContext(), "PLAY FROM LIST?", Toast.LENGTH_SHORT).show();
if (item.getmAudio() != null) {
mAudio = item.getmAudio();
Log.d(TAG, " from LISTPLAY " + mAudio);
try {
playAudio(mAudio);
if (isPlaying) {
PAUSIL.setEnabled(true);
PAUSIL.setVisibility(View.VISIBLE);
PIL.setEnabled(false);
PIL.setVisibility(View.INVISIBLE);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
PAUSIL.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "PAUSING", Toast.LENGTH_SHORT).show();
stopPlaying();
isPlaying = false;
PAUSIL.setEnabled(false);
PAUSIL.setVisibility(View.INVISIBLE);
PIL.setEnabled(true);
PIL.setVisibility(View.VISIBLE);
}
});
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
Chops item = getItem(position);
viewHolder.ivIcon.setImageBitmap(StringToBitMap(item.getmPic()));
viewHolder.tvAlbum.setText(item.getmAlbum());
viewHolder.tvSong.setText(item.getmSong());
return convertView;
}
Instead, Add a method to remove an item from your dataset inside your Adapter class. Something along the lines of:
public void remove(int position){
mItems.remove(position);
notifyDataSetChanged();
}
Then call yourAdapter.remove(positionToRemove); from the onClick of the Activity with the button.

ListView CheckBox getting multi selected on just clicking only one time

I'm trying to use CheckBox in my ListView with an ArrayAdapter. When I select any CheckBox onlytime in the list, multiple entries are selected automatically in a random order. Can anyone please tell how I can avoid this.
Here's my code for your reference:
public class SearchListAdapterQ2 extends BaseAdapter {
int layoutId;
ArrayList<SearchListView> searchresultList = new ArrayList<SearchListView>();
public static int companyCpsId;
public static String companyCpsType = "", search_companyName = "",
search_countryName = "", handShakeStatus = "";
public static String handShakeCPSName = "";
public static boolean searchListAdapter_Q2 = false;
SharedPreferences sharedpreferences;
boolean markfavStatus = false;
ListView searchResults_listView;
Context context;
public SearchListAdapterQ2(Context context, int layoutId,
ArrayList<SearchListView> searchresultList,
ListView searchResults_listView) {
// TODO Auto-generated constructor stub
this.layoutId = layoutId;
this.searchresultList = searchresultList;
Log.i("inside searchListAdapter", "inside searchListAdapter");
this.context = context;
sharedpreferences = context.getSharedPreferences("MyPrefs",
Context.MODE_PRIVATE);
this.searchResults_listView = searchResults_listView;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
Log.i("searchresultList",
"searchresultList: " + searchresultList.size());
return searchresultList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return searchresultList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder1 holder1;
// LayoutInflater inflater = (LayoutInflater)
// context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
char color;
String text = "";
String address = "";
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(R.layout.qq_searchlist_repeat_items,
parent, false);
holder1 = new ViewHolder1();
holder1.companyName_textView = (TextView) convertView
.findViewById(R.id.companyName_textView);
holder1.companyLogo_textView = (TextView) convertView
.findViewById(R.id.companyLogo_textView);
holder1.companyAddress_textView = (TextView) convertView
.findViewById(R.id.companyAddress_textView);
holder1.handShakeIcon_imageView = (ImageView) convertView
.findViewById(R.id.handShakeIcon_imageView);
holder1.favouritesIcon_imageView = (ImageView) convertView
.findViewById(R.id.favouritesIcon_imageView);
holder1.referIcon_imageView = (ImageView) convertView
.findViewById(R.id.referIcon_imageView);
holder1.sendEnquiry_imageView = (ImageView) convertView
.findViewById(R.id.sendEnquiry_imageView);
holder1.icons_searchResultsPage_relLayout = (RelativeLayout) convertView
.findViewById(R.id.icons_searchResultsPage_relLayout);
holder1.chckbx1 = (CheckBox) convertView.findViewById(R.id.chckbx1);
if (SearchListActivity_Q2.broadcastMode) {
Log.i("icons_searchResultsPage_relLayout is visible",
"icons_searchResultsPage_relLayout is visible");
holder1.icons_searchResultsPage_relLayout
.setVisibility(View.GONE);
holder1.chckbx1.setVisibility(View.VISIBLE);
} else {
holder1.icons_searchResultsPage_relLayout
.setVisibility(View.VISIBLE);
holder1.chckbx1.setVisibility(View.GONE);
}
convertView.setTag(holder1);
} else {
holder1 = (ViewHolder1) convertView.getTag();
}
holder1.id = position;
search_companyName = searchresultList.get(position).getCpsName();
search_countryName = searchresultList.get(position).getCountryName();
try {
String ssearch_companyName = URLDecoder.decode(search_companyName,
"UTF-8");
holder1.companyName_textView.setText(ssearch_companyName);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (searchresultList.get(position).getCpsName().contains(" ")) {
String[] splitText = searchresultList.get(position).getCpsName()
.split("\\s+");
char a = splitText[0].charAt(0);
char b = splitText[1].charAt(0);
text = String.valueOf(a) + String.valueOf(b);
color = b;
} else {
text = searchresultList.get(position).getCpsName().substring(0, 1);
color = searchresultList.get(position).getCpsName().charAt(1);
}
holder1.companyLogo_textView.setText(text.toUpperCase());
if (searchresultList.get(position).getCpsAddress().isEmpty()) {
address = searchresultList.get(position).getCountryName();
} else {
if (searchresultList.get(position).getCpsAddress().length() > 1) {
address = searchresultList.get(position).getCpsAddress() + ", "
+ searchresultList.get(position).getCountryName();
} else {
address = searchresultList.get(position).getCountryName();
}
}
holder1.companyAddress_textView.setText(address);
holder1.companyName_textView
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
searchListAdapter_Q2 = true;
companyCpsId = searchresultList.get(position)
.getCpsId();
Log.i("$$$ companyCpsId", "companyCpsId" + companyCpsId);
companyCpsType = searchresultList.get(position)
.getCpsType();
Intent intent = new Intent(context,
CompanyProfile_Activity.class);
context.startActivity(intent);
}
});
holder1.referIcon_imageView
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
holder1.sendEnquiry_imageView
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<Q2_SendEnquiryList> sendEnquiry = new ArrayList<Q2_SendEnquiryList>();
sendEnquiry.add(new Q2_SendEnquiryList(searchresultList
.get(position).getCpsId(), searchresultList
.get(position).getCpsName()));
sendEnquiry.add(new Q2_SendEnquiryList(1, "abcdefgh"));
sendEnquiry.add(new Q2_SendEnquiryList(2, "abcdefg"));
sendEnquiry.add(new Q2_SendEnquiryList(3, "abcdef"));
sendEnquiry.add(new Q2_SendEnquiryList(4, "abcde"));
sendEnquiry.add(new Q2_SendEnquiryList(5, "abcd"));
sendEnquiry.add(new Q2_SendEnquiryList(6, "abc"));
sendEnquiry.add(new Q2_SendEnquiryList(7, "ab"));
Intent intent = new Intent(context,
Q2_SendEnquiryActivity.class);
intent.putParcelableArrayListExtra("sendEnquiry",
sendEnquiry);
context.startActivity(intent);
}
});
holder1.handShakeIcon_imageView
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
companyCpsId = searchresultList.get(position)
.getCpsId();
handShakeCPSName = searchresultList.get(position)
.getCpsName();
handShakeStatus = searchresultList.get(position)
.getHandShakeStatus();
ConstantVariables.handShakeFromAdapter = true;
if (sharedpreferences.getInt("userId_sp", 0) != 0) {
if (sharedpreferences.getInt("profileActiveStatus",
0) > 0) {
if (sharedpreferences.getInt("organizationId",
0) != 0) {
if (handShakeStatus.equalsIgnoreCase("d")) {
ConstantVariables
.handShakeRequest(
context,
companyCpsId,
0,
ConstantVariables.handShakeFromAdapter,
searchResults_listView,
position);
} else if (handShakeStatus
.equalsIgnoreCase("p")) {
ConstantVariables
.handShakeRequestAccept(
context,
companyCpsId,
1,
ConstantVariables.handShakeFromAdapter,
searchResults_listView,
position,
handShakeCPSName);
}
} else {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
context);
// Setting Dialog Title
// alertDialog.setTitle("Please Add Company");
// Setting Dialog Message
alertDialog
.setMessage("Please add your company details");
// Setting Positive "Yes" Button
alertDialog
.setPositiveButton(
"Add",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
Intent intent = new Intent(
context,
Profile_Activity.class);
context.startActivity(intent);
}
});
// Setting Negative "NO" Button
alertDialog
.setNegativeButton(
"Later",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
} else {
ConstantVariables
.requestEmailVerification(context);
}
} else {
ConstantVariables.requestLogin(context);
}
}
});
holder1.favouritesIcon_imageView
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return convertView;
}
static class ViewHolder1 {
TextView companyName_textView, companyAddress_textView,
companyLogo_textView;
ImageView handShakeIcon_imageView, favouritesIcon_imageView,
referIcon_imageView, sendEnquiry_imageView;
CheckBox chckbx1;
int id;
RelativeLayout icons_searchResultsPage_relLayout;
}
}
in your adapter getView() method set the status of the clicked checkbox in model and call notify data set changed, try that
I added the following lines with my code and it started working fine:
ArrayList<Integer> checkedPositions = new ArrayList<Integer>();
final Integer index = new Integer(position);
holder1.chckbx1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
// if checked, we add it to the list
checkedPositions.add(index);
} else if (checkedPositions.contains(index)) {
// else if remove it from the list (if it is present)
checkedPositions.remove(index);
}
}
});
// set the state of the checbox based on if it is checked or not.
holder1.chckbx1.setChecked(checkedPositions.contains(index));

application not working in API 21

I have an application which has a gridview with images in it. The problem is its showing in all phones except for API 21 i.e. Lollipop version. In Lollipop its shows just background and no gridview. The targetSDK is 21 and minSDK is 8. Any help in this would be much appreciated.
MainActivity
public class MainView extends Activity {
ImageView back, home, site, header;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setTheme(android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER);
setContentView(R.layout.mainview);
GridView gridView = (GridView)findViewById(R.id.gridview);
gridView.setAdapter(new MyAdapter(this));
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Intent myIntent = null;
if(position == 0){
myIntent = new Intent(v.getContext(), TheShow.class);
}
if(position == 1){
myIntent = new Intent(v.getContext(), Exhibitor.class);
}
if(position ==2){
myIntent = new Intent(v.getContext(), Visitor.class);
}
if(position ==3){
myIntent = new Intent(v.getContext(), Conference.class);
}
if(position ==4){
myIntent = new Intent(v.getContext(), ContactUs.class);
}
if(position == 5){
myIntent = new Intent(v.getContext(), ExhibitorReg.class);
}
if(position == 6){
myIntent = new Intent(v.getContext(), VisitorReg.class);
}
if(position == 7){
myIntent = new Intent(v.getContext(), FlrPlan.class);
}
if(myIntent!=null){
startActivity(myIntent);
}
}
});
back=(ImageView)findViewById(R.id.imageView2);
home=(ImageView)findViewById(R.id.imageView3);
site=(ImageView)findViewById(R.id.imageView4);
back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
MainView.this.onBackPressed();
}
});
home.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Same Page", Toast.LENGTH_LONG).show();
}
});
site.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String url = "http://india-aviation.in/";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
header=(ImageView)findViewById(R.id.imageView1);
header.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
final Dialog dialog = new Dialog(MainView.this);
dialog.setContentView(R.layout.custom_dialog);
dialog.setTitle("About Us");
dialog.setCancelable(true);
Button button = (Button) dialog.findViewById(R.id.buttonOK);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
});
}
private class MyAdapter extends BaseAdapter
{
private List<Item> items = new ArrayList<Item>();
private LayoutInflater inflater;
public MyAdapter(Context context)
{
inflater = LayoutInflater.from(context);
items.add(new Item("The Show", R.drawable.globecopy1));
items.add(new Item("Exhibitor", R.drawable.workcopy1));
items.add(new Item("Visitor", R.drawable.visitor1copy1));
items.add(new Item("Conference", R.drawable.conferencecopy1));
items.add(new Item("Contact Us", R.drawable.contactus1copy1));
items.add(new Item("Exhibitor Registration", R.drawable.exregistercopy1));
items.add(new Item("Visitor Registration", R.drawable.anothercopy1));
items.add(new Item("Layout Plan", R.drawable.registercopy1));
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int i)
{
return items.get(i);
}
#Override
public long getItemId(int i)
{
return items.get(i).drawableId;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup)
{
View v = view;
ImageView picture;
TextView name;
if(v == null)
{
v = inflater.inflate(R.layout.gridview_item, viewGroup, false);
v.setTag(R.id.picture, v.findViewById(R.id.picture));
v.setTag(R.id.text, v.findViewById(R.id.text));
}
picture = (ImageView)v.getTag(R.id.picture);
name = (TextView)v.getTag(R.id.text);
Item item = (Item)getItem(i);
picture.setImageResource(item.drawableId);
name.setText(item.name);
return v;
}
private class Item
{
final String name;
final int drawableId;
Item(String name, int drawableId)
{
this.name = name;
this.drawableId = drawableId;
}
}
}
}
If you app has a values-21 folder in res folder, either set the layout there or delete the folder if you want persistent layout for all APIs.

Android Color Rows

does anyone know how to color the background of each row in a listview as they are created?
I have an arraylist which is pulled from my database and populates a layout with a listview in it.
I suspect there might be a way to do it with a simpleadaptor but cant figure it out.
Any help would be much appreciated :)
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.item_list);
// Read var from Intent
Intent intent= getIntent();
final String ListID = intent.getStringExtra("ListID");
golbalItemID = ListID;
ivAdd = (ImageView) findViewById(R.id.ivAdd);
ivCancel = (ImageView) findViewById(R.id.ivCancel);
tvTotItems = (TextView) findViewById(R.id.tvTotItems);
final myDBClass myDb = new myDBClass(this);
final ArrayList<HashMap<String, String>> MebmerList = myDb.SelectAllItemData(ListID);
myData = myDb.SelectItemData(Integer.parseInt(ListID.toString()));
// listView1
final ListView lisView1 = (ListView)findViewById(R.id.listView1);
registerForContextMenu(lisView1);
MyAdapter sAdap;
sAdap = new MyAdapter(ListItems.this, MebmerList, R.layout.activity_column, new String[] {"Name", "Price", "Quan"}, new int[] {R.id.ColName, R.id.ColTel, R.id.ColQuan});
lisView1.setAdapter(sAdap);
lisView1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter, View myView, int position, long mylng) {
int iChk = 0;
// Show Data
String arrData[] = myDb.SelectItemData((MebmerList.get(position).get("ItemID").toString()));
if(arrData != null)
{
iChk = Integer.parseInt(arrData[4]);
}
if(iChk == 1)
{
ischkCheck(Integer.parseInt(MebmerList.get(position).get("ItemID").toString()), 0);
change_color(lisView1, position, 255, 255, 255);
System.out.println("POSITION!ichk=1" + myAdapter.getItemAtPosition(position).toString());
setTitle(myAdapter.getItemAtPosition(position).toString());
}
else if(iChk == 0)
{
ischkCheck(Integer.parseInt(MebmerList.get(position).get("ItemID").toString()), 1);
change_color(lisView1, position, 155, 155, 138);
System.out.println("POSITION!ichk=0" + myAdapter.getItemAtPosition(position).toString());
}
}});
ivAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent newActivity = new Intent(ListItems.this,AddItem.class);
newActivity.putExtra("ListID", ListID);
startActivity(newActivity);
finish();
}
});
ivCancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent newActivity = new Intent(ListItems.this,MenuScreen.class);
startActivity(newActivity);
finish();
}
});
Create an Adapter Class, and control each Row's color in it, then set it as adapter of ListView
Here is a sample code from one of my projects, check getView function:
public class ListAdapter extends BaseAdapter {
private LayoutInflater myInflater;
private List<Poet> list;
public ListAdapter(Context context) {
super();
myInflater = LayoutInflater.from(context);
Log.d("Ganjoor", "Data passed to the adapter.");
}
static class ViewHolder {
TextView tvName;
}
public void setData(List<Poet> list) {
this.list = list;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Poet getItem(int position) {
return (null == list) ? null : list.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 = myInflater.inflate(R.layout.list_adapter, parent,
false);
holder = new ViewHolder();
holder.tvName = (TextView) convertView.findViewById(R.id.tvName);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tvName.setTag(list.get(position).getId());
holder.tvName.setText(list.get(position).getName());
// Log.d("Ganjoor", "Adapter: " + list.get(position).getName());
if (position % 2 == 0) {
convertView.setBackgroundResource(R.drawable.grad_blue);
} else {
convertView.setBackgroundResource(R.drawable.row_style);
}
return convertView;
}
}
As #Nikita Beloglazov states, you can do this by implementing a custom ArrayAdapter, putting your coloring scheme in the getView Override method. See ArrayAdapter doc.

Categories

Resources