Deleting item from Listview in onActivityResult - android

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.

Related

Getting focus of EditText inside RecyclerView

I'm implementing an application in which user can store Debit Cards and later they can use it by just entering the CVV number of the same card. I have used RecyclerView for all the items(Debit Cards) stored by the user. Everything is working fine, view is rendering all good and I have used LinearLayoutManager to show Horizontal scroll.
Now the problem which I am facing is whenever I try to enter CVV of any card as soon as I click on it the view gets shifted towards the last item of the list of Stored Cards, So if I'm having three cards stored in my list and I try to enter CVV for the first one the view is shifting directly to the third card but the focus remains on the first cards EditText. I don't know what's going on with the same. I'm sharing some code part for the same.
Setting adapter and defining horizontal scroll :-
recyclerAdapter = new RecyclerStoredCardAdapter(mContext, storedCards);
LinearLayoutManager layoutManager
= new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
storedCardListRecycler.setLayoutManager(layoutManager);
storedCardListRecycler.setVisibility(View.VISIBLE);
storedCardListRecycler.setAdapter(recyclerAdapter);
Sharing the screenshots with this so it will get clear. Any help would be appreciable. Thanks.
I have did this using ListView not with RecyclerView
But you can do with RecyclerView also.
Here is my used class demo.
SettingItemListViewAdapter.java
/**
* Created by vishalchhodwani on 18/10/16.
*/
public class SettingItemListViewAdapter extends BaseAdapter {
private final String TAG = "SettingItemListViewAdapter";
Context context;
List<SettingListViewItem> settingItemList;
OnMyClickListeners onMyClickListeners;
MyDatabaseAdapter myDatabaseAdapter;
public SettingItemListViewAdapter(Context context, List<SettingListViewItem> settingItemList) {
this.context = context;
this.settingItemList = settingItemList;
myDatabaseAdapter = new MyDatabaseAdapter(context);
}
public void setMyClickListener(OnMyClickListeners onMyClickListeners) {
this.onMyClickListeners = onMyClickListeners;
}
#Override
public int getCount() {
return settingItemList.size();
}
#Override
public Object getItem(int position) {
return settingItemList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.setting_listview_item, parent, false);
holder.settingListViewForm = (RelativeLayout) convertView.findViewById(R.id.settingListViewItem_form1);
holder.vrijeTekst = (EditText) convertView.findViewById(R.id.settingListViewItem_ed_virje_row1);
holder.kenteken = (EditText) convertView.findViewById(R.id.settingListViewItem_ed_kenketen_row1);
holder.checkRow = (ImageView) convertView.findViewById(R.id.settingListViewItem_check_row1);
holder.deleteRow = (ImageView) convertView.findViewById(R.id.settingListViewItem_deleteRow);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.vrijeTekst.setText(settingItemList.get(position).getItemVrijeTekst());
holder.kenteken.setText(settingItemList.get(position).getItemKenteken());
boolean isSelected = settingItemList.get(position).isItemSelected();
holder.checkRow.setImageResource(isSelected ? R.drawable.checked : R.drawable.uncheked);
holder.vrijeTekst.setTag(position);
holder.vrijeTekst.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(final View v, boolean hasFocus) {
try {
if (!hasFocus) {
if (settingItemList.size() > 0) {
int position = (int) v.getTag();
EditText Caption = (EditText) v;
settingItemList.get(position).setItemVrijeTekst(Caption.getText().toString());
}
} else {
EditText caption = (EditText) v;
caption.setCursorVisible(true);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
holder.kenteken.setTag(position);
holder.kenteken.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(final View v, boolean hasFocus) {
try {
if (!hasFocus) {
if (settingItemList.size() > 0) {
int position = (int) v.getTag();
EditText Caption = (EditText) v;
settingItemList.get(position).setItemKenteken(Caption.getText().toString());
}
} else {
EditText caption = (EditText) v;
caption.setCursorVisible(true);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
holder.checkRow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (myDatabaseAdapter.isAvailableInTable(settingItemList.get(position).getItemId()))
onMyClickListeners.onSelectButtonClicked(position);
}
});
holder.deleteRow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onMyClickListeners.onDeleteItemButtonClicked(position);
}
});
if (getCount() == position + 1) {
holder.vrijeTekst.requestFocus();
holder.vrijeTekst.performClick();
}
return convertView;
}
public static class ViewHolder {
RelativeLayout settingListViewForm;
EditText vrijeTekst, kenteken;
ImageView checkRow, deleteRow;
}
}
SettingN_New.java (It is a fragment)
public class SettingN_New extends Fragment implements OnClickListener, OnMyClickListeners {
private final String TAG = "SettingN_New";
Context context;
private TextView tv_demo;
ToggleButton togglebtn_save;
Button btn_save, btn_add;
ListView settingItemListView;
List<SettingListViewItem> settingItemList;
SettingItemListViewAdapter settingItemListViewAdapter;
MyDatabaseAdapter myDatabaseAdapter;
TinyDB loginpref;
boolean isNewRowAdded = true;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//This line of code will stay focus on selected edittext in list
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
ActionBar bar = getActivity().getActionBar();
bar.show();
View rootView = inflater.inflate(R.layout.setting_new, container, false);
initializeViews(rootView);
setUI();
getListOfItems();
return rootView;
}
private void setUI() {
try {
if (loginpref.getBoolean(ConstantLib.PREF_AUTO_LOGIN)) {
togglebtn_save.setChecked(true);
} else {
togglebtn_save.setChecked(false);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
private void initializeViews(View rootView) {
context = getActivity();
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View headerView = inflater.inflate(R.layout.setting_listview_header, null);
btn_save = (Button) headerView.findViewById(R.id.btn_save);
btn_add = (Button) headerView.findViewById(R.id.btn_add);
togglebtn_save = (ToggleButton) headerView.findViewById(R.id.togglebtn_save);
tv_demo = (TextView) headerView.findViewById(R.id.tv_demo);
settingItemList = new ArrayList<>();
settingItemListView = (ListView) rootView.findViewById(R.id.setting_listView);
settingItemListView.setClickable(true);
settingItemListView.refreshDrawableState();
settingItemListView.addHeaderView(headerView);
settingItemListView.setItemsCanFocus(true);
settingItemListViewAdapter = new SettingItemListViewAdapter(context, settingItemList);
settingItemListViewAdapter.setMyClickListener(this);
settingItemListView.setAdapter(settingItemListViewAdapter);
myDatabaseAdapter = new MyDatabaseAdapter(context);
loginpref = new TinyDB(getActivity());
btn_save.setOnClickListener(this);
btn_add.setOnClickListener(this);
tv_demo.setOnClickListener(this);
togglebtn_save.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
loginpref.putBoolean(ConstantLib.PREF_AUTO_LOGIN, isChecked);
}
});
}
private void getListOfItems() {
settingItemList.clear();
settingItemList.addAll(myDatabaseAdapter.getAllData());
if (settingItemList.size() == 0) {
isNewRowAdded = true;
SettingListViewItem settingListViewItem = new SettingListViewItem();
settingListViewItem.setItemId(settingItemList.size() + "");
settingListViewItem.setItemVrijeTekst("");
settingListViewItem.setItemKenteken("");
settingListViewItem.setItemSelected(false);
settingItemList.add(settingListViewItem);
} else {
isNewRowAdded = false;
}
notifyDataSetChanged();
}
private void hideKeyboard() {
// Check if no view has focus:
View view = getActivity().getCurrentFocus();
if (view != null) {
InputMethodManager inputManager = (InputMethodManager) getActivity()
.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_save:
clearFocus();
hideKeyboard();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (isValidationSuccess())
saveAllData();
}
}, 200);
break;
case R.id.btn_add:
addAnotherRow();
break;
case R.id.tv_demo:
clickedOnTvDemo();
break;
}
}
private void clickedOnTvDemo() {
try {
Intent i = new Intent(getActivity(), Setting_exp_activity.class);
startActivity(i);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
private boolean isValidationSuccess() {
Log.e(TAG, "isValidationSuccess() called : settingItemList.size()==" + settingItemList.size());
for (int i = 0; i < settingItemList.size(); i++) {
if (settingItemList.get(i).getItemVrijeTekst().equalsIgnoreCase("") || settingItemList.get(i).getItemKenteken().equalsIgnoreCase("")) {
showToast("Veld mag niet leeg zijn");// showToast("Fields should not be empty!!");
return false;
}
}
return true;
}
private void saveAllData() {
Log.e(TAG, "saveAllData() called");
myDatabaseAdapter.clearTable();
for (int i = 0; i < settingItemList.size(); i++) {
isNewRowAdded = false;
SettingListViewItem settingListViewItem = new SettingListViewItem();
settingListViewItem.setItemId(i + "");
settingListViewItem.setItemVrijeTekst(settingItemList.get(i).getItemVrijeTekst());
settingListViewItem.setItemKenteken(settingItemList.get(i).getItemKenteken());
settingListViewItem.setItemSelected(settingItemList.get(i).isItemSelected());
myDatabaseAdapter.insertDataToTable(settingListViewItem);
}
DialogUtils.showInfoDialog(getActivity(),
"Instellingen opgeslagen");
}
private void addAnotherRow() {
Log.e(TAG, "addAnotherRow() called");
if (settingItemList.size() > 0 && !isNewRowAdded) {
if (!settingItemList.get(settingItemList.size() - 1).getItemVrijeTekst().equalsIgnoreCase("") && !settingItemList.get(settingItemList.size() - 1).getItemKenteken().equalsIgnoreCase("")) {
isNewRowAdded = true;
Log.e(TAG, "addAnotherRow() called check 1");
SettingListViewItem settingListViewItem = new SettingListViewItem();
settingListViewItem.setItemId(settingItemList.size() + "");
settingListViewItem.setItemVrijeTekst("");
settingListViewItem.setItemKenteken("");
settingListViewItem.setItemSelected(false);
settingItemList.add(settingListViewItem);
notifyDataSetChanged();
} else {
Log.e(TAG, "addAnotherRow() called check 2");
showToast("Al toegevoegd");// showToast("Already Added!!");
}
} else {
if (!isNewRowAdded) {
isNewRowAdded = true;
Log.e(TAG, "addAnotherRow() called check 3");
SettingListViewItem settingListViewItem = new SettingListViewItem();
settingListViewItem.setItemId("0");
settingListViewItem.setItemVrijeTekst("");
settingListViewItem.setItemKenteken("");
settingListViewItem.setItemSelected(false);
settingItemList.add(settingListViewItem);
notifyDataSetChanged();
} else {
Log.e(TAG, "addAnotherRow() called check 4");
showToast("Al toegevoegd");// showToast("Already Added!!");
}
}
settingItemListView.setSelection(settingItemList.size());
Log.e(TAG, "addAnotherRow() called check 5");
Log.e(TAG, "after settingItemList.size()==" + settingItemList.size());
}
#Override
public void onDeleteItemButtonClicked(int position) {
Log.e(TAG, "onDeleteItemButtonClicked() position==" + position);
if (myDatabaseAdapter.getAllData().size() > 0)
showAlertForDeleteItem(position);
else
showToast("Er is geen item te verwijderen"); // showToast("No item to Delete");
}
#Override
public void onSelectButtonClicked(int position) {
Log.e(TAG, "onSelectButtonClicked() position==" + position);
for (int i = 0; i < settingItemList.size(); i++) {
Log.e(TAG, "onSelectButtonClicked() called check 3");
settingItemList.get(i).setItemSelected(false);
}
settingItemList.get(position).setItemSelected(true);
notifyDataSetChanged();
}
private void showAlertForDeleteItem(final int position) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setMessage("Weet je zeker dat je dit item wilt wissen?");//alertDialog.setMessage("Are you sure you want to delete this item?");
// ja==yes
alertDialog.setPositiveButton("Ja", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
myDatabaseAdapter.deleteTableRow(settingItemList.get(position).getItemId() + "");
settingItemList.remove(position);
settingItemListViewAdapter.notifyDataSetChanged();
if (settingItemList.size() == position + 1) {
isNewRowAdded = false;
}
if (settingItemList.size() == 0) {
isNewRowAdded = false;
addAnotherRow();
}
}
});
//Annuleer==cancel
alertDialog.setNegativeButton("Annuleer", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
private void notifyDataSetChanged() {
settingItemListViewAdapter.notifyDataSetChanged();
}
private void showToast(String message) {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
public void clearFocus() {
if (getActivity().getWindow().getCurrentFocus() != null) {
getActivity().getWindow().getCurrentFocus().clearFocus();
}
}
}
I am giving you my whole class. why? Because it will give you more understanding that how I used it with ListView.
Test it and Let me know. :)
Note
This line of code is very important - getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
Not able to reproduce this issue. Let me know if the following code does what you are facing. If not, can provide more feedback if you share you Adapter's Code.
MainActivity.java
public class MainActivity
extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
MyAdapter adapter = new MyAdapter();
recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
recyclerView.setAdapter(adapter);
}
}
public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_ite, parent);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
((EditText)((MyViewHolder)holder).mBinding.findViewById(R.id.editText)).setHint(position + " ");
}
#Override
public int getItemCount() {
return 100;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
View mBinding;
public MyViewHolder(View binding) {
super(binding);
this.mBinding = binding;
}
}
}
The 2xml layouts:
<EditText
android:id="#+id/editText"
android:layout_height="200dp"
android:layout_width="300dp"/>
</android.support.v7.widget.CardView>
My main_activity.xml is as follows:
<RelativeLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_height="wrap_content"
android:layout_width="match_parent"/>
</RelativeLayout>
As you can see this is the simplest case. Let me know if I missed anything.

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();
}

Refresh ListView pressing option DialogFragment

I have a listview that clicking on an element shows a DialogFragmen with several options, options that take the user will be shown in the item of listview TextView and I get the following error in execution:
Activity app.gepv.Inventario has leaked IntentReceiver com.immersion.android.haptics.HapticFeedbackManager$HapticFeedbackBroadcastReceiver#426e94b8 that was originally registered here. Are you missing a call to unregisterReceiver()?
Enter the code that I think is important, if you need anything else edit the question :)
This is mi DialogFragment:
final String[] items= equiDisp.toArray(new String[equiDisp.size()]);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Asigne equipo/equipos:")
.setOnKeyListener(new Dialog.OnKeyListener(){
public boolean onKey(DialogInterface arg0, int keyCode,KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_BACK)
{
finish();
//dialog.dismiss();
actualizarDisplay();
}
return true;
}
})
.setMultiChoiceItems(items, null, new DialogInterface.OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog, int item, boolean isChecked) {
Log.i("Dialogos", "OpciĆ³n elegida: " + items[item]);
if(isChecked)
{
marcado.add(items[item]);
Log.i("Dialogos", "Marcado: " + items[item]);
obras.get(pulsado).equiA.add(Integer.parseInt(items[item]));
for( int k=0; k< obras.get(pulsado).equiA.size(); k++)
{
Log.i("Dialogos", "Equipos: " + obras.get(pulsado).equiA.get(k) );
}
}
}
});
So far everything is running well because I check with Log.i
This is the function ActualizarDisplay():
public void actualizarDisplay()
{
adapter = new ObrasAdapter(this, obras);
lvObras = (ListView) findViewById(R.id.lvItems);
lvObras.setAdapter(adapter);
lvObras.setOnItemClickListener(this);
}
And this is my custom dataApdapter for the listview:
public class ObrasAdapter extends ArrayAdapter<Obra> {
private Context context;
private ArrayList<Obra> datos;
public ObrasAdapter(Context context, ArrayList<Obra> datos) {
super(context, R.layout.listview_item, datos);
this.context = context;
this.datos = datos;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View item = convertView;
ObrasHolder holder;
if (item == null) {
item = LayoutInflater.from(context).inflate(R.layout.listview_item,
null);
holder = new ObrasHolder();
holder.foto = (ImageView) item.findViewById(R.id.imgAnimal);
holder.num = (TextView) item.findViewById(R.id.numC);
holder.iden = (TextView) item.findViewById(R.id.idenC);
holder.ubi = (TextView) item.findViewById(R.id.ubiC);
holder.hombres = (TextView) item.findViewById(R.id.homC);
holder.material = (TextView) item.findViewById(R.id.matC);
holder.eq1 = (TextView) item.findViewById(R.id.eq1);
holder.eq2 = (TextView) item.findViewById(R.id.eq2);
holder.eq3 = (TextView) item.findViewById(R.id.eq3);
holder.eq4 = (TextView) item.findViewById(R.id.eq4);
holder.fondo = (RelativeLayout) item.findViewById(R.id.fondobra);
item.setTag(holder);
}
holder = (ObrasHolder) item.getTag();
holder.foto.setImageResource(datos.get(position).getDrawableImageID());
if(datos.get(position).getPrioridad()==1)
{
holder.num.setTextColor(Color.RED);
holder.iden.setTextColor(Color.RED);
holder.ubi.setTextColor(Color.RED);
holder.hombres.setTextColor(Color.RED);
holder.material.setTextColor(Color.RED);
holder.eq1.setTextColor(Color.RED);
holder.eq2.setTextColor(Color.RED);
holder.eq3.setTextColor(Color.RED);
holder.eq4.setTextColor(Color.RED);
}
if(datos.get(position).getPrioridad()==2)
{
holder.num.setTextColor(Color.parseColor("#FF8000"));
holder.iden.setTextColor(Color.parseColor("#FF8000"));
holder.ubi.setTextColor(Color.parseColor("#FF8000"));
holder.hombres.setTextColor(Color.parseColor("#FF8000"));
holder.material.setTextColor(Color.parseColor("#FF8000"));
holder.eq1.setTextColor(Color.parseColor("#FF8000"));
holder.eq2.setTextColor(Color.parseColor("#FF8000"));
holder.eq3.setTextColor(Color.parseColor("#FF8000"));
holder.eq4.setTextColor(Color.parseColor("#FF8000"));
}
if(datos.get(position).getPrioridad()==3)
{
holder.num.setTextColor(Color.GREEN);
holder.iden.setTextColor(Color.GREEN);
holder.ubi.setTextColor(Color.GREEN);
holder.hombres.setTextColor(Color.GREEN);
holder.material.setTextColor(Color.GREEN);
holder.eq1.setTextColor(Color.GREEN);
holder.eq2.setTextColor(Color.GREEN);
holder.eq3.setTextColor(Color.GREEN);
holder.eq4.setTextColor(Color.GREEN);
}
holder.num.setText(datos.get(position).getNum());
holder.iden.setText(datos.get(position).getIden());
holder.ubi.setText(datos.get(position).getUb());
holder.hombres.setText(datos.get(position).getHom());
holder.material.setText(datos.get(position).getMat());
if(datos.get(position).getEstado()==1)
{
holder.fondo.setBackgroundColor(Color.GREEN);
holder.num.setTextColor(Color.WHITE);
holder.iden.setTextColor(Color.WHITE);
holder.ubi.setTextColor(Color.WHITE);
holder.hombres.setTextColor(Color.WHITE);
holder.material.setTextColor(Color.WHITE);
holder.eq1.setTextColor(Color.WHITE);
holder.eq1.setTextColor(Color.WHITE);
holder.eq1.setTextColor(Color.WHITE);
holder.eq1.setTextColor(Color.WHITE);
}
if(! datos.get(position).equiA.isEmpty())
{
for(int i=0; i<datos.get(position).equiA.size();i++)
{
if(i == 0)
{
holder.eq1.setText(String.valueOf(datos.get(position).equiA.get(i)));
}
if(i == 1)
holder.eq2.setText(String.valueOf(datos.get(position).equiA.get(i)));
if(i == 2)
holder.eq3.setText(String.valueOf(datos.get(position).equiA.get(i)));
if(i == 3)
holder.eq4.setText(String.valueOf(datos.get(position).equiA.get(i)));
}
}
else
{
holder.eq1.setVisibility(View.INVISIBLE);
holder.eq2.setVisibility(View.INVISIBLE);
holder.eq3.setVisibility(View.INVISIBLE);
holder.eq4.setVisibility(View.INVISIBLE);
}
return item;
}
}
Can anyone help me?
I think i must to do something as:
#Override
protected void onStop()
{
unregisterReceiver(sendBroadcastReceiver);
unregisterReceiver(deliveryBroadcastReceiver);
super.onStop();
}

App crashes on android 4.0+

I have and android app that works on android 4.0 great, but it crashes on android 4.3 and 4.4. I get this from the logCat
01-11 14:40:27.669: E/ACRA(25835): ACRA caught a IllegalStateException exception for quran. Building report.
01-11 14:40:27.789: E/AndroidRuntime(25835): java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread. [in ListView(2131099688, class android.widget.ListView) with Adapter(class quran.functions.PlaylistAdapter)]
Here is my code:
public class Playlist extends FragmentActivity {
private ListView list;
private Button manager, downloadAll;
private TextView reciter;
public static PlaylistAdapter adapter;
private ArrayList<Songs> songs;
private int RECITER_ID;
private String url, title, label;
private SlidingMenu slidingMenu;
private DatabaseHelper db;
private ImageView nowPlaying, back;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playlist);
initWidgets();
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
Intent intent = new Intent(Playlist.this, PlayerFinal.class);
intent.putExtra("songs", songs);
if (getIntent().getIntExtra("duaa", -1) == 115)
intent.putExtra("lang", 115);
intent.putExtra("position", position);
intent.putExtra("fromClass", this.getClass() + "");
// intent.putExtra("mp3link", mp3link);
startActivity(intent);
}
});
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
XmlMapParser m = new XmlMapParser(Playlist.this, RECITER_ID);
HashMap<String, ArrayList<String>> map = m.convert();
map.keySet();
label = map.get("RecitorLabel").get(0);
title = map.get("Title").get(0);
url = map.get("Link").get(0);
back = (ImageView) findViewById(R.id.playlist_back);
back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
finish();
}
});
db.openDB();
for (int i = 1; i < map.get("Link").size(); i++) {
if (db.isDownloaded(i, title, RECITER_ID)) {
songs.add(new Songs(i, map.get("Title").get(i),
Environment.getExternalStorageDirectory()
.getPath()
+ "/"
+ getString(R.string.app_name)
+ "/"
+ title
+ "/"
+ map.get("Title").get(i)
+ ".mp3", title, true, RECITER_ID,
false));
} else
songs.add(new Songs(i, map.get("Title").get(i), url
+ label + "/"
+ new DecimalFormat("000").format(i) + ".mp3",
title, false, RECITER_ID, false));
}
db.closeDB();
// Log.v("--",m.convert().get("Link").get(1));
// [RecitorLabel, Title, Link] THIS ARE THE KEYS m
// Log.v("--", map.get("RecitorLabel").get(0));
// Log.v("--", map.get("Link").get(1));
return null;
}
protected void onPostExecute(Void result) {
adapter = new PlaylistAdapter(Playlist.this, songs);
list.setAdapter(adapter);
reciter.setText(songs.get(0).getRecitorName());
};
}.execute();
}
#Override
public void onBackPressed() {
if (slidingMenu.isMenuShowing()) {
slidingMenu.toggle();
} else {
super.onBackPressed();
}
}
#Override
protected void onResume() {
super.onResume();
try {
if (Tplayer.getInstance().isPlaying()) {
adapter = new PlaylistAdapter(this, songs);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU) {
this.slidingMenu.toggle();
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
this.slidingMenu.toggle();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void initWidgets() {
db = new DatabaseHelper(this);
manager = (Button) findViewById(R.id.playlist_download_manager);
manager.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Playlist.this, DownloadManager.class);
startActivity(intent);
}
});
reciter = (TextView) findViewById(R.id.playlist_reciter_name_top);
list = (ListView) findViewById(R.id.playlist_list);
downloadAll = (Button) findViewById(R.id.playlist_download_all);
manager = (Button) findViewById(R.id.playlist_download_manager);
songs = new ArrayList<Songs>();
RECITER_ID = getIntent().getIntExtra("filename", -1);
// downloadAll.setOnClickListener(new OnClickListener() {
//
// #Override
// public void onClick(View v) {
// new DownloadAll(Playlist.this, songs);
// db.openDB();
// for (int i = 0; i < songs.size(); i++) {
// db.addDownloaded(songs.get(i).getNumber(), songs.get(i)
// .getLink(), 0, songs.get(i).getRecitorID(), "",
// songs.get(i).getTitle());
// }
// db.closeDB();
// }
// });
nowPlaying = (ImageView) findViewById(R.id.playlist_now_playing);
nowPlaying.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Tplayer tplayer = Tplayer.getInstance();
if (tplayer.isPlaying()) {
Intent intent = new Intent(Playlist.this, PlayerFinal.class);
if (tplayer.isPlaying())
intent.putExtra("songs", tplayer.getSongs());
else
intent.putExtra("songs", songs);
if (tplayer.getSongs().size() == 14)
intent.putExtra("lang", 115);
intent.putExtra("position", tplayer.getPosition());
startActivity(intent);
}
}
});
// Jeremy Feinstein slidinglistadapter line 94
slidingMenu = new SlidingMenu(this);
slidingMenu.setMode(SlidingMenu.LEFT);
slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
slidingMenu.setShadowWidthRes(R.dimen.slidingmenu_shadow_width);
slidingMenu.setShadowDrawable(R.drawable.slidingmenu_shadow);
slidingMenu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
slidingMenu.setFadeDegree(0.35f);
slidingMenu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
slidingMenu.setMenu(R.layout.slidingmenu);
}
}
and my playlist adapter class:
public class PlaylistAdapter extends BaseAdapter {
private Activity activity;
private static LayoutInflater inflater = null;
private ArrayList<Songs> data;
private DatabaseHelper db;
private SharedPreferences prefs;
int playpos;
int recitorID;
public PlaylistAdapter(Activity a, ArrayList<Songs> songs) {
activity = a;
data = songs;
db = new DatabaseHelper(a);
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
prefs = activity.getSharedPreferences("quantic.Quran",
Context.MODE_PRIVATE);
recitorID = prefs.getInt("recID", -1);
playpos = prefs.getInt("posPlaying", -1);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView,
final ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.song_item, parent, false);
ImageView download = (ImageView) vi
.findViewById(R.id.playlist_item_download);
db.openDB();
if (db.isDownloaded(data.get(position).getNumber(), data.get(position)
.getRecitorName(), data.get(position).getRecitorID()))
download.setImageResource(R.drawable.download_yes);
else {
download.setImageResource(R.drawable.download_no);
download.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new DownloadFileFromURL(activity, data.get(position)
.getRecitorName(), data.get(position).getTitle(),
data.get(position).getLink(), data.get(position)
.getNumber(), data.get(position)
.getRecitorID()).execute();
if (!db.isDBOpen())
db.openDB();
db.addDownloaded(data.get(position).getNumber(),
data.get(position).getLink(), 0, data.get(position)
.getRecitorID(), "", data.get(position)
.getTitle());
Toast.makeText(activity,
"Downloading " + data.get(position).getTitle(),
Toast.LENGTH_SHORT).show();
}
});
}
db.closeDB();
TextView number = (TextView) vi.findViewById(R.id.playlist_item_num);
TextView reciterName = (TextView) vi
.findViewById(R.id.playlist_item_reciterName);
reciterName.setText(data.get(position).getRecitorName());
if (activity.getClass() == Playlist.class) {
reciterName.setVisibility(View.GONE);
}
TextView title = (TextView) vi.findViewById(R.id.playlist_item_reciter);
title.setText(data.get(position).getTitle());
number.setText((position + 1) + "");
ImageView eq = (ImageView) vi.findViewById(R.id.playlist_item_equlizer);
if (Tplayer.getInstance().isPlaying())
if (Tplayer.getInstance().getPosition() == position
&& data.get(position).getRecitorID() == Tplayer
.getInstance().getSong().getRecitorID()) {
eq.setVisibility(View.VISIBLE);
Ion.with(eq).load("http://darkodev.info/quran/dots.gif");
} else {
eq.setVisibility(View.GONE);
}
return vi;
}
}
Very old question, but no answer. I'm sure you have found a fix by now, but anyway.
You're changing the songs list object in background, and if Android decides to redraw your list (user scrolls your list), effectively accessing the songs list object, it may have changed and cause this exception to be thrown.
You need to use a temporary songs list and create a new adapter with it to update your list, thus not changing the current adapter list until you set a new adapter from the main UI thread.

listview of songs with checkbox using Aquery unable to save the State of chekckbox while list scrolldown?

Hi i have listview of songs with checkbox using Aquery i am unable to save the State of chekckbox while list scrolldown. i have two arraylist one is for by clicking song image & other is for checkbox if user select the chekbox it should play song accordingly to checkbox arraylist. i have used this also check.setChecked(SelectedBox.get(clickedposition).getisCheck()); . But no help
so far what i have done is here
private void createList() {
listAq = new AQuery(this);
adapter = new ArrayAdapter<Audio>(SongList.this, R.layout.list_row,details) {
#Override
public View getView(final int position, View convertView,final ViewGroup parent) {
if (convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.list_row, parent, false);
}
final int clickedposition = position;
final AQuery aq = listAq.recycle(convertView);
Audio item = getItem(position);
aq.id(R.id.MovieName).text(item.getAlbumName());
aq.id(R.id.SongName).text(item.getTitle());
aq.id(R.id.checkBox1).getCheckBox().setSelected(item.getisCheck());
aq.id(R.id.nameLayout).clicked(new OnClickListener() {
#Override
public void onClick(View v) {
DialogBuilder(position);
}
});
check = (CheckBox) convertView.findViewById(R.id.checkBox1);
check.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
try {
if (isChecked) {
checkbox = true;
if (details.get(clickedposition).getisCheck() == false) {
SelectedBox.add(details.get(clickedposition));
System.out.println(SelectedBox.size());
details.get(clickedposition).setisCheck(true);
}
} else {
final String name = details.get(clickedposition).getFilename();
for (int i = 0; i <= SelectedBox.size(); i++) {
if (name.equals(SelectedBox.get(i).getFilename())) {
SelectedBox.remove(i);
details.get(clickedposition).setisCheck(false);
}
}
}
notifyDataSetChanged();
}
catch (Exception e) {
e.getMessage();
}
}
});
try{
}
catch (Exception e) {
// TODO: handle exception
}
url = "drawable/" + item.getThumbnail();
imageResource = getResources().getIdentifier(url, null,getPackageName());
aq.id(R.id.song_image).image(imageResource);
if (position != playingValue) {
aq.id(R.id.imageplay).invisible();
aq.id(R.id.imageplay).getImageView().bringToFront();
} else {
aq.id(R.id.imageplay).visible();
}
ImageView img = (ImageView)convertView.findViewById(R.id.song_image);
img.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
checkbox = false;
SelectedBox.clear();
currentSongIndex = position;
try {
if (ChannelService.playerFlag == 0) {
playSong(currentSongIndex);
} else if ((ChannelService.playerFlag == 1)
|| ((ChannelService.playerFlag == 2))) {
if (currentSongIndex != playingValue) {
try {
final Intent serviceIntent = new Intent(
getApplicationContext(),
ChannelService.class);
stopService(serviceIntent);
mPlay.setBackgroundResource(R.drawable.play_btn);
playSong(currentSongIndex);
} catch (final IllegalStateException e) {
e.printStackTrace();
}
}
mPlay.setBackgroundResource(R.drawable.pause_btn);
final Intent in = new Intent("updateNotification");
sendBroadcast(in);
}
} catch (final IllegalStateException e) {
e.getMessage();
}
notifyDataSetChanged();
}
});
return convertView;
}
};
aq.id(R.id.listView1).adapter(adapter);
}
When you scroll down a list in Android, it destroys the rows that doesn't fit in the screen.
I allways use an array of objects to save the state of each row so when android calls getView you can ask the state of them:
public class AudioRow{
public int id;
public boolean checked;
...
}
Then at getView you can do something like that:
public View getView(final int position, View convertView,final ViewGroup parent) {
if (convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.list_row, parent, false);
}
final int clickedposition = position;
AudioRow ar = audioRows.get(position);
if(ar.checked) {
//do something;
}
...
#Override
public void onClick(View v) {
if(ar.checked) ar.checked = false;
else ar.checked = true;
DialogBuilder(position);
}
});
I hope it helps you.

Categories

Resources