I have to set the Background color of the visitedItem(imageView of listView row).
It shows a list of item, if you visited (itemclick) on row its item backgroundColor must be changed. I use sharedPreferences for it. And also debug it(in debug it show false). But don't know why first item is set to green after first time itemClick on any listView row.
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View view = convertView;
if(view == null)
{
view = inflater.inflate(R.layout.item_ads, parent, false);
}
final HashMap<String, String> map = list.get(position);
ImageView imageAd = (ImageView)view.findViewById(R.id.ad_image);
if(sessionManager.ItemVisited(position))// && position!=0)// && !sessionManager.getFirstRun())
{
imageAd.setBackgroundColor(Color.GREEN);
}
}
SessionManager
public class SessionManager
{
public static ArrayList<Boolean> listBoolTrain = new ArrayList<Boolean>();
private int giftRemaining;
private SharedPreferences prefs;
// Editor for Shared preferences
Editor editor;
// Context
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharedpref file name
private static final String PREF_NAME = "AndroidHivePref";
public SessionManager(Context context)
{
this._context = context;
prefs = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = prefs.edit();
}
public void setNumberOfGits(int numberOfGifts)
{
editor.putInt("numberOfGifts", numberOfGifts);
editor.commit();
}
public int getNumberOfGits()
{
int nog = prefs.getInt("numberOfGifts", -5);
return nog;
}
public void initializerBooleans(int arraySiz)
{
int arraySize = prefs.getInt("arraySize", 10);
for(int x = 0 ; x < arraySize; x++)
{
editor.putBoolean("Bool"+x, false);
editor.commit();
}
}
public void setItemVisited(int x)
{
editor.putBoolean("Bool"+x, true);
editor.commit();
}
public boolean isItemVisited(int x)
{
return prefs.getBoolean("Bool"+x, false);
}
public int getUnVisitedItemCount()
{
int count = 0;
int arraySize = prefs.getInt("arraySize", 10);
for(int x = 0 ; x < arraySize ; x++)// listBoolTrain.size(); x++)
{
boolean bol= prefs.getBoolean("Bool"+x, false);
if(!bol)
{
count++;
}
}
return count;
}
public void remainingGift()
{
}
public void setFirstRun(boolean status)
{
editor.putBoolean("firstrun", status);
editor.commit();
}
public boolean getFirstRun()
{
return prefs.getBoolean("firstrun", true);
}
public void removeAllPreferences()
{
prefs.edit().clear().commit();
}
public void removeKey(String keyName)
{
prefs.edit().remove(keyName).commit();
}
public void showAll()
{
Map<String,?> keys = prefs.getAll();
for(Map.Entry<String,?> entry : keys.entrySet())
{
Log.d("map values",entry.getKey() + ": " + entry.getValue().toString());
}
}
public void setArraySize(int boolSize)
{
editor.putInt("arraySize", boolSize);
editor.commit();
initializerBooleans(boolSize);
}
public int getArraySize()
{
return prefs.getInt("arraySize", -1);
}
public boolean ItemVisited(int position)
{
return prefs.getBoolean("Bool"+position, false);
}
}
And listView itemClicked..
listView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long arg3)
{
Log.e("TAG_ADS","Item Visited " + position);
sessionManager.setItemVisited(position);
view.findViewById(R.id.ad_image).setBackgroundColor(Color.BLUE);
final String appPackageName = arl.get(position).get("packageName"); //map.get("packageName"); // getPackageName() from Context or Activity object
Intent marketIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id="+ appPackageName));
startActivity(marketIntent);
}
});
I have to create session for visited links. In a listView i have urls, Once a url is visited,its backgroundColor must be replaced.I have tried multiple ways but nothing happens.
Once i clicked on any item, position 0 background color also changed as it is a visited link.
You set the backgroundcolor only to green. The next time getView is called, convertView will be some sort of copy so you don't have to inflate it and do some findViewById, but the background color is also already set to green.
If you add an else statement to set the color to white (for example), it will work.
if(sessionManager.ItemVisited(position))// && position!=0)// && !sessionManager.getFirstRun())
{
imageAd.setBackgroundColor(Color.GREEN);
} else {
imageAd.setBackgroundColor(Color.WHITE);
}
You have to do something like below:-
View rowView = convertView;
if (rowView == null)
{
LayoutInflater inflater = context.getLayoutInflater();
rowView = inflater.inflate(R.layout.partner_list_element, null);
// configure view holder
ViewHolder viewHolder = new ViewHolder();
viewHolder.price = (TextView) rowView.findViewById(R.id.price);
viewHolder.header = (TextView) rowView.findViewById(R.id.header);
viewHolder.location = (TextView) rowView.findViewById(R.id.location);
viewHolder.space = (TextView) rowView.findViewById(R.id.space);
viewHolder.main_image = (ImageView) rowView.findViewById(R.id.main_image);
viewHolder.logo_image = (ImageView) rowView.findViewById(R.id.logo_image);
rowView.setTag(viewHolder);
}
// fill data
ViewHolder holder = (ViewHolder) rowView.getTag();
make below class on adapter
class ViewHolder {
public TextView header,location,space,price;
public ImageView main_image,logo_image;
}
Listview recycle his element that's why you facing problem.
Related
I have a custom listview with textview and checkbox. I want to save the checkbox state in sharedpreferences and get and set it again adapter when activity open. I have also done this but issue is this: I save the checkbox checked position in sharedpreferences and get it. When listview item position change then my checked checkbox position got wrong checked. How can I handle this?
adaptor code:
public class Listadapter extends BaseAdapter {
CheckBox checkBox;
boolean index[];
boolean[] itemChecked;
ResolveInfo entry;
String[] itempkg;
private Context mContext;
private List<ResolveInfo> mListAppInfo;
private PackageManager mPackManager;
private ArrayList<Boolean> checkList = new ArrayList<Boolean>();
public Listadapter(Context applicationContext, List<ResolveInfo> installedApplication, PackageManager packageManager)
{
//super(applicationContext,textViewResourceId,installedApplication);
super();
this.mContext = applicationContext;
this.mListAppInfo = installedApplication;
index = new boolean[installedApplication.size()];
this.mPackManager = packageManager;
for (int i = 0; i < installedApplication.size(); i++) {
checkList.add(false);
itemChecked = new boolean[installedApplication.size()];
itempkg = new String[installedApplication.size()];
}
}
#Override
public int getCount()
{
return mListAppInfo.size();
//return ((null != mListAppInfo) ? mListAppInfo.size() : 0);
}
#Override
public Object getItem(int position)
{
// index = new boolean[mListAppInfo.size()];
return mListAppInfo.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
final ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
// reference to convertView
holder.tvAppName = (TextView) convertView
.findViewById(R.id.textView1);
holder.tvPkgName = (TextView) convertView
.findViewById(R.id.textView);
holder.checkBox = (CheckBox) convertView
.findViewById(R.id.checkBox1);
holder.ivAppIcon = (ImageView) convertView
.findViewById(R.id.imageView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
entry = mListAppInfo.get(position);
holder.ivAppIcon.setImageDrawable(entry.loadIcon(mPackManager));
holder.tvAppName.setText(entry.loadLabel(mPackManager));
holder.tvPkgName.setText(entry.activityInfo.packageName);
holder.checkBox.setChecked(false);
if (itemChecked[position])
holder.checkBox.setChecked(true);
else
holder.checkBox.setChecked(false);
final View finalConvertView = convertView;
holder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (holder.checkBox.isChecked()) {
itemChecked[position] = true;
} else {
itemChecked[position] = false;
}
}
});
return convertView;
}
public void setItemChecked5(boolean[] items5) {
itemChecked = items5;
}
private class ViewHolder
{
private ImageView ivAppIcon;
private TextView tvAppName;
private TextView tvPkgName;
private CheckBox checkBox;
}
}
activity code:
public class Profile5Activity extends AppCompatActivity implements AdapterView.OnItemClickListener {
ListView apps5;
PackageManager packageManager5;
static ArrayList<String> checkedValue5;
Button bt5;
ResolveInfo pi5 = new ResolveInfo();
Context context = this;
static String currentApp5 = "NULL";
CheckBox cb5;
Listadapter Adapter5 = null;
boolean[] itemChecked5;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile5);
itemChecked5 = new boolean[AllApps.getInstalledApplication(this).size()];
//needPermissionForBlocking(MainActivity.mainContext);
apps5 = (ListView) findViewById(R.id.list5);
packageManager5 = getPackageManager();
SharedPreferences preferencess2 = context.getSharedPreferences("YOUR_APP_NAME5", Context.MODE_PRIVATE);
Set<String> seta = preferencess2.getStringSet("pkgname5", null);
if (seta != null && !seta.isEmpty() && !seta.equals("null")) {
checkedValue5 = new ArrayList<String>(seta);
}
else
{
checkedValue5 = new ArrayList<String>();
}
final boolean[] items5 = new boolean[AllApps.getInstalledApplication(this).size()];
SharedPreferences preferences5 = context.getSharedPreferences("YOUR_APP_NAME5", Context.MODE_PRIVATE);
for (int i = 0; i < AllApps.getInstalledApplication(this).size(); ++i) {
items5[i] = preferences5.getBoolean("checkbox_5" + i, false);
}
Adapter5 = new Listadapter(this, AllApps.getInstalledApplication(this), packageManager5);
Adapter5.setItemChecked5(items5);
apps5.setAdapter(Adapter5);
apps5.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> arg0, final View v, final int position, long arg3)
{
// TODO Auto-generated method stub
cb5 = (CheckBox) v.findViewById(R.id.checkBox1);
final TextView tv5 = (TextView) v.findViewById(R.id.textView);
final TextView tvv5 = (TextView) v.findViewById(R.id.textView1);
//pi5 = (ResolveInfo) arg0.getItemAtPosition(position);
cb5.performClick();
if (cb5.isChecked()) {
checkedValue5.add(tv5.getText().toString());
itemChecked5[position] = true;
String pname = (tvv5.getText().toString());
SharedPreferences preferences1 = context.getSharedPreferences("YOUR_APP_NAME5", Context.MODE_PRIVATE);
SharedPreferences.Editor edit = preferences1.edit();
Set<String> setttt1 = new HashSet<String>();
setttt1.addAll(checkedValue5);
edit.putBoolean("checkbox_5" + position, true);
edit.putStringSet("pkgname5", setttt1);
edit.commit();
} else if (!cb5.isChecked()) {
checkedValue5.remove(tv5.getText().toString());
String pname = (tvv5.getText().toString());
SharedPreferences preferences1 = context.getSharedPreferences("YOUR_APP_NAME5", Context.MODE_PRIVATE);
SharedPreferences.Editor edit = preferences1.edit();
Set<String> setttt1 = new HashSet<String>();
setttt1.addAll(checkedValue5);
edit.putBoolean("checkbox_5" + position, false);
edit.putStringSet("pkgname5", setttt1);
edit.commit();
}
}
}
All things working fine in this code until the list item position change when list item position changed then I got wrong checked value. Please help me with some code or edit my code where I made mistake.
To know which item is checked, you should save unique and constant value of each item (position in your case is unique but not constant because it can change). With another object type we will always use id
But in your case, the item is ResolveInfo so you can save entry.activityInfo.packageName to SharedPrefrences because it is diffirent among all items
I have same problem for that I have used following:
For that I have saved item detail in sharedpreferences and when I add value in list I have checked(compare value with new arraylist(With loop)) then item will added list then it will be worked.
I have problem with removing items from ArrayList. I tried it maybe 100 times but I can't fix it. Saving to list isn't problem but it's very hard to remove for me.
When I remove SharedPrefs key (position) It's good first time but if I first time remove first position it's deleted from list but its still in preferences so when I try to remove first position second time I cant remove it because there is still saved preference with value "" but I need to remove this preference totally that first position have to contain preferences with value on second position not "".
I tried to make some images for better understanding.
Thats before remove 1st position:
And this is after remove 1st position
There is my CustomListAdapter class
public class CustomListAdapterInterests extends ArrayAdapter < String > {
private final Activity context;
private final ArrayList < String > mItemInterest;
public CustomListAdapterInterests(Activity context, ArrayList < String > itemInterest) {
super(context, R.layout.list_item_interests, itemInterest);
this.context = context;
this.mItemInterest = itemInterest;
}
#Override
public int getCount() {
return mItemInterest.size();
}
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.list_item_interests, null, true);
TextView itemInterestTV = (TextView) rowView.findViewById(R.id.textInterest);
itemInterestTV.setText(mItemInterest.get(position));
return rowView;
}
}
And here is my fragment
public class InterestsFragment extends BaseFragment {
private ArrayList < String > mInterestList;
private static final int MAX_STORED_LINES_INTERESTS = 50;
private FloatingActionButton plusInterestsBTN;
private CustomListAdapterInterests adapterInterests;
private ListView listInterests;
private EditText interestET;
private Button confirmInterestBTN;
public SharedPreferences sharedPreferences;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_interests, container, false);
plusInterestsBTN = (FloatingActionButton) v.findViewById(R.id.plusInterests);
sharedPreferences = getActivity().getSharedPreferences(Constants.PREFERENCES_INTERESTS, Context.MODE_PRIVATE);
mInterestList = new ArrayList < String > ();
loadInterestFromPreferences(mInterestList);
adapterInterests = new CustomListAdapterInterests(getActivity(), mInterestList);
listInterests = (ListView) v.findViewById(R.id.listViewInterests);
listInterests.setAdapter(adapterInterests);
listInterests.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView <? > arg0, View v, int position, long arg3) {
if (sharedPreferences.contains(Constants.INTEREST + position)) {
SharedPreferences.Editor editor = sharedPreferences.edit();
mInterestList.remove(position);
adapterInterests.notifyDataSetChanged();
editor.remove(Constants.INTEREST + position);
editor.commit();
}
}
});
listInterests.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {#Override
public boolean onItemLongClick(AdapterView <? > arg0, View arg1,
final int position, long id) {
onShowDialogSetItem(position);
return true;
}
});
plusInterestsBTN.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View v) {
onShowDialogAddItem();
}
});
listInterests.setOnScrollListener(new AbsListView.OnScrollListener() {#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
int btn_initPosY = plusInterestsBTN.getScrollY();
if (scrollState == SCROLL_STATE_TOUCH_SCROLL) {
plusInterestsBTN.animate().cancel();
plusInterestsBTN.animate().translationXBy(350);
} else {
plusInterestsBTN.animate().cancel();
plusInterestsBTN.animate().translationX(btn_initPosY);
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
});
return v;
}
private void loadInterestFromPreferences(ArrayList < String > mInterestList) {
for (int x = 0; x < 5; x++) {
String interests = sharedPreferences.getString(Constants.INTEREST + x, Constants.DEFAULT);
Toast.makeText(getActivity(), interests, Toast.LENGTH_SHORT).show();
if (interests != "") {
mInterestList.add(interests);
}
}
}
private void onShowDialogSetItem(final int position) {
final Dialog dialogInterest = new Dialog(getActivity());
dialogInterest.getWindow().getAttributes().windowAnimations = R.anim.abc_slide_in_top;
dialogInterest.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialogInterest.getWindow().getAttributes().windowAnimations = R.style.animationName;
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.fragment_interests_add_event, null, false);
dialogInterest.setCanceledOnTouchOutside(true);
dialogInterest.setContentView(view);
final EditText interestET = (EditText) dialogInterest.findViewById(R.id.editTextInterest);
Button confirmInterestBTN = (Button) dialogInterest.findViewById(R.id.confirmInterest);
TextView title = (TextView) dialogInterest.findViewById(R.id.textView2);
title.setText("Edit Interest");
interestET.setText(mInterestList.get(position));
confirmInterestBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("2", "" + position);
String interest = sharedPreferences.getString(Constants.INTEREST + position, Constants.DEFAULT);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(Constants.INTEREST + position, interestET.getText().toString());
editor.commit();
String interests = sharedPreferences.getString(Constants.INTEREST + position, Constants.DEFAULT);
mInterestList.set(position, interestET.getText().toString());
Toast.makeText(getActivity(), "Upravené: " + interests, Toast.LENGTH_SHORT).show();
adapterInterests.notifyDataSetChanged();
dialogInterest.dismiss();
}
});
dialogInterest.show();
}
private void onShowDialogAddItem() {
if (mInterestList.size() >= MAX_STORED_LINES_INTERESTS) {
return;
}
final Dialog dialogInterest = new Dialog(getActivity());
dialogInterest.getWindow().getAttributes().windowAnimations = R.anim.abc_slide_in_top;
dialogInterest.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialogInterest.getWindow().getAttributes().windowAnimations = R.style.animationName;
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.fragment_interests_add_event, null, false);
dialogInterest.setCanceledOnTouchOutside(true);
dialogInterest.setContentView(view);
interestET = (EditText) dialogInterest.findViewById(R.id.editTextInterest);
confirmInterestBTN = (Button) dialogInterest.findViewById(R.id.confirmInterest);
confirmInterestBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = listInterests.getAdapter().getCount();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(Constants.INTEREST + position, interestET.getText().toString());
editor.commit();
String interests = sharedPreferences.getString(Constants.INTEREST + position, Constants.DEFAULT);
Toast.makeText(getActivity(), "Přidané: " + interests, Toast.LENGTH_SHORT).show();
mInterestList.add(interestET.getText().toString());
//adapterInterests.notifyDataSetChanged();
dialogInterest.dismiss();
}
});
dialogInterest.show();
adapterInterests.notifyDataSetChanged();
}
}
Thank you for help. Sorry for my English. If do you will help me I can do any material design app icon for you or google play designs. Thank you. If there is few informations please say me.
I think if you save all of your string list to single property of preferences will make it easy to manage.
see this sample:
//for save
StringBuilder sb = new StringBuilder();
for (String interest : mInterestList) {
sb.append(interest).append(",");
}
prefsEditor.putString("MyInterests", sb.toString());
prefsEditor.commit();
//for read
String [] interests= sharedPreferences.getString("MyInterests");
mInterestList = new ArrayList<String>(Arrays.asList(interests));
in every change to your mInterestList just save it again. no need to remove and adding. change your mInterestList and save again in shared preferences.
Looks to me like your adapter runs off of mInterestList .
I don't see you removing the data item from mInterestsList when your remove the Preference?
Rather than checking whether shared preferences contains, see if it is set to null instead or not, that is do,
if (sharedPreferences.getString(Constants.INTEREST + position)!=null) {
SharedPreferences.Editor editor = sharedPreferences.edit();
mInterestList.remove(position);
adapterInterests.notifyDataSetChanged();
editor.remove(Constants.INTEREST + position);
editor.commit();
}
I have a ListView with songs and a player. In my ListView I want to add a function to button to save ListView row and add it in different ListView in different Activity(Favorites Activity). How can I do this?
This is my code for Adapter:
public class Adapter extends ArrayAdapter<String> {
Context context;
int[] song_icon;
boolean pausedSamePos = false;
String[] song_name;
String[] song_duration;
String[] song_duration_sb;
private final int mLcdWidth = 0;
private final float mDensity = 0;
public static MediaPlayer mp = new MediaPlayer();
public static Boolean isPlaying = Boolean.valueOf(false);
public static int pos = 55;
Ids holder;
private final Handler handler = new Handler();
Runnable updateTimeProgressBar;
public Adapter(Context c, String[] song_titles, int song_Icons[],
String[] song_durations) {
super(c, R.layout.item, R.id.textview_song_duration,
song_titles);
this.context = c;
this.song_icon = song_Icons;
this.song_name = song_titles;
this.song_duration = song_durations;
this.song_duration_sb = song_durations;
}
final int[] songPos = { R.raw.song1, R.raw.song2, R.raw.song3,
R.raw.song4, R.raw.song5, R.raw.song6, R.raw.song7,
R.raw.song8, R.raw.song9, R.raw.song10,
R.raw.song11, R.raw.song12, R.raw.song13,
R.raw.song14, R.raw.song15, R.raw.song16,
R.raw.song17, R.raw.song18, R.raw.song19,
R.raw.song20, R.raw.song21, R.raw.song22,
R.raw.song23, R.raw.song24, R.raw.song25,
R.raw.song26, R.raw.song27, R.raw.song28,
R.raw.song29, R.raw.song30, };
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getAdapterViewType(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
holder = null;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.item, parent, false);
holder = new Ids(row);
row.setTag(holder);
} else {
holder = (Ids) row.getTag();
}
if (Adapter.isPlaying && Adapter.pos == position) {
if (pausedSamePos == true) {
holder.pauseed_play.setVisibility(View.VISIBLE);
holder.playing_pause.setVisibility(View.GONE);
} else {
holder.pauseed_play.setVisibility(View.GONE);
holder.playing_pause.setVisibility(View.VISIBLE);
}
holder.song_currenttime_sb.setVisibility(View.VISIBLE);
holder.song_duration.setVisibility(View.INVISIBLE);
holder.song_duration_sb.setVisibility(View.VISIBLE);
holder.seekbar.setVisibility(View.VISIBLE);
} else {
holder.seekbar.setVisibility(View.GONE);
holder.song_currenttime_sb.setVisibility(View.GONE);
holder.song_icon.setImageResource(song_icon[position]);
holder.song_duration_sb.setVisibility(View.INVISIBLE);
holder.song_duration.setVisibility(View.VISIBLE);
holder.pauseed_play.setVisibility(View.GONE);
holder.playing_pause.setVisibility(View.GONE);
}
holder.song_name.setText(song_name[position]);
holder.song_duration.setText(song_duration[position]);
holder.song_duration_sb.setText(song_duration_sb[position]);
final Ids finalHolder = holder;
holder.favorite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "The favorite", Toast.LENGTH_SHORT)
.show();
}
holder.clickRegister
.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
stopPlaying();
return true;
}
});
finalHolder.song_currenttime_sb.setTag(position);
holder.seekbar.setFocusable(true);
holder.seekbar.setTag(position);
holder.clickRegister.setTag(position);
holder.song_icon.setTag(position);
holder.song_name.setTag(position);
holder.song_duration.setTag(position);
holder.song_duration_sb.setTag(position);
int widthSpec = MeasureSpec.makeMeasureSpec(
(int) (mLcdWidth - 10 * mDensity), MeasureSpec.EXACTLY);
holder.menu_options.measure(widthSpec, 0);
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) holder.menu_options
.getLayoutParams();
params.bottomMargin = -holder.menu_options.getMeasuredHeight();
holder.menu_options.setVisibility(View.GONE);
return row;
}
What I want TLDR: To get song_name,song_duration,songPos on Clicked Row, and save it and then use that data to populat ListView in Favorites Activity.
If some more details are required I will be glad to provide.
basically the correct way is:
1) Create a Song model class and declare all required attributes inside this class
2) Extend the BaseAdapter and use an ArrayList<Song> as its data
Using this approach you will be able to easily retrieve a Song object from the clicked row and pass it anywhere you want. If you have no clue what I'm talking about then you are missing some basic knowledge about the ListView and its pointless to just throw code at you. There are tons of tutorials, check out this one or that one.
there is so much ways to imp this , here is a way that i would use
save your data (song_name,song_duration,songPos) in an object in the shared preferences
and when you go to the fav activity read that shared preferences you saved
#Override
public void onClick(View v) {
Toast.makeText(context, "The favorite", Toast.LENGTH_SHORT)
.show();
//for example get the fav here and save it in object
YoursongInfoObject yourSongInfoObject=new YoursongInfoObject();
yourSongInfoObject.name=holder.song_name.getText();
.
.
.
.
SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);
Editor editor = prefs.edit();
try {
editor.putString("YourSongInfoID", ObjectSerializer.serialize(yourSongInfoObject));
} catch (IOException e) {
e.printStackTrace();
}
editor.commit();
}
and your fav activity
public void onCreate() {
super.onCreate();
if (null == currentFavSong) {
currentFavSong = new YourSongInfoObject();
}
// load tasks from preference
SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);
try {
currentFavSong = (YourSongInfoObject) ObjectSerializer.deserialize(prefs.getString("YourSongInfoObject", ObjectSerializer.serialize(new YourSongInfoObject())));
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
my app contains a list view which is being populated by a spinner value
this list contains toggle button in each row and for customization purpose i have used baseadapter in list view
i am changing image of toggle button on checked and unchecked
the functionality is going well on toggle button and listview but the problem occurrs when i closes the app and then again opens it it gets refreshed and the toggle state become unchecked and the unchecked image is shown every where
so to solve this i have saved the value of toggle button in shared preferences but now i dont know where to check this in base adapter class plz help me
the necessary code for this
public class DDListAdapter extends BaseAdapter {
ArrayList<DataModelDD> listArray;
int curIndex=1000, pIndex;
public DDListAdapter(String[] str, String[] str1) {
listArray = new ArrayList<DataModelDD>();
for (int i=0; i < str.length; i++) {
listArray.add(new DataModelDD(str[i],str1[i], " Day Alert on " + str[i],false));
}
}
public void DDListUpdate(String[] str, String[] str1){
listArray = new ArrayList<DataModelDD>();
for (int i=0; i < str.length; i++) {
listArray.add(new DataModelDD(str[i],str1[i], " Day Alert on " + str[i],false));
}
this.notifyDataSetChanged();
}
#Override
public int getCount() {
return listArray.size(); // total number of elements in the list
}
#Override
public Object getItem(int i) {
return listArray.get(i); // single item in the list
}
#Override
public long getItemId(int i) {
return i; // index number
}
#Override
public View getView(final int index, View view, final ViewGroup parent) {
lIndex = index;
pIndex = index;
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
view = inflater.inflate(R.layout.lstdd, parent, false);
final DataModelDD dmFl = listArray.get(index);
final TextView lbl1 = (TextView) view.findViewById(R.id.txtDDate);
final TextView lbl2 = (TextView) view.findViewById(R.id.txtDres);
lbl1.setText(dmFl.getDDate());
lbl2.setText(dmFl.getDres());
final ToggleButton btnlock = (ToggleButton) view.findViewById(R.id.btnDAlarm);
if (dmFl.getdSel()) {
//selected
btnlock.setButtonDrawable(a_icon);
} else {
//not selected
btnlock.setButtonDrawable(a_dicon);
}
btnlock.setTag(pIndex);
btnlock.setOnCheckedChangeListener(new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(btnlock.isChecked()){
btnlock.setButtonDrawable(a_icon);
btnlock.setChecked(true);
dmFl.setdSel(true);
Integer position = (Integer) buttonView.getTag();
sp = context.getSharedPreferences("MyPref", 0);
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean("value"+month+"_"+state+"_"+cday, true);
editor.commit();
}
else{
final String alarmTime = dmFl.getDDate();
disableAlarm(buttonView,alarmTime);
btnlock.setButtonDrawable(a_dicon);
btnlock.setChecked(false);
dmFl.setdSel(false);
Integer position = (Integer) buttonView.getTag();
}
}
});
return view;
}
}
and the data model class
package com.example.dd;
public class DataModelDD {
private String DDate;
private String Dres;
private String ShrStr;
private Boolean dSel;
public DataModelDD(String DDate, String Dres, String ShrStr, Boolean dSel){
this.DDate = DDate;
this.Dres = Dres;
this.ShrStr = ShrStr;
this.dSel = dSel;
}
public String getDDate(){
return this.DDate;
}
public void setDDate(String DDate){
this.DDate = DDate;
}
public String getDres(){
return this.Dres;
}
public void setDres(String Dres){
this.Dres = Dres;
}
public String getShrStr(){
return this.ShrStr;
}
public void setShrStr(String ShrStr){
this.ShrStr = ShrStr;
}
public Boolean getdSel(){
return this.dSel;
}
public void setdSel(Boolean dSel){
this.dSel = dSel;
}
}
you need to do
is
SharedPreferences prefs = getSharedPreferences(settingsTAG, 0);
boolean rb0 = prefs.getBoolean("rb0", true);
if (dmFl.getdSel()||rb0) {
//selected
btnlock.setButtonDrawable(a_icon);
} else {
//not selected
btnlock.setButtonDrawable(a_dicon);
}
I am using a baseadapter for my customize spinner with checkbox that allow the user to choose multiple values. I have an update button in my application, and I need to set the values from the database as true in the checkbox. My problem is I don't know how to do it. For example I have ["A","B","C","D"] values in my spinner, in my database I got B and D. How will i automatically check that values when I open the activity.
Here is my code that populate my customize spinner
private void initializeCustomerSegment() {
final ArrayList<String> consumerSegments = new ArrayList<String>();
List<String> consumerSegment = databaseHandler.setItemOnConsumerSeg();
consumerSegments.addAll(consumerSegment);
checkSelectedConsumerSegment = new boolean[consumerSegments.size()];
//initialize all values of list to 'unselected' initially
for (int i = 0; i < checkSelectedConsumerSegment.length; i++) {
checkSelectedConsumerSegment[i] = false;
}
final TextView tv_ConsumerSegment = (TextView) findViewById(R.DropDownList.tv_ConsumerSegment);
tv_ConsumerSegment.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(!expandedConsumerSegment) {
// display all selected values
String selected = "";
int flag = 0;
for (int i = 0; i < consumerSegments.size(); i++) {
if (checkSelectedConsumerSegment[i] == true) {
selected += consumerSegments.get(i);
selected += ", ";
flag = 1;
}
}
if(flag == 1) {
tv_ConsumerSegment.setText(selected);
}
expandedConsumerSegment =true;
} else {
//display shortened representation of selected values
tv_ConsumerSegment.setText(BrandListAdapter.getSelected());
expandedConsumerSegment = false;
}
}
});
//onClickListener to initiate the dropDown list
TextView tv_customerSegment = (TextView)findViewById(R.DropDownList.tv_ConsumerSegment);
tv_customerSegment.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
initiatePopUpCustomerSegment(consumerSegments,tv_ConsumerSegment);
}
});
}
private void initiatePopUpCustomerSegment(ArrayList<String> customerSegments, TextView tv_CustomerSegment) {
LayoutInflater inflater = (LayoutInflater)S_10th_IReportMain.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//get the pop-up window i.e. drop-down layout
LinearLayout layoutCustomerSegment = (LinearLayout)inflater.inflate(R.layout.pop_up_window_customersegment, (ViewGroup)findViewById(R.id.PopUpView1));
//get the view to which drop-down layout is to be anchored
RelativeLayout layout4 = (RelativeLayout)findViewById(R.id.relativeLayout4);
pwConsumerSegment = new PopupWindow(layoutCustomerSegment, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, true);
//Pop-up window background cannot be null if we want the pop-up to listen touch events outside its window
pwConsumerSegment.setBackgroundDrawable(new BitmapDrawable());
pwConsumerSegment.setTouchable(true);
//let pop-up be informed about touch events outside its window. This should be done before setting the content of pop-up
pwConsumerSegment.setOutsideTouchable(true);
pwConsumerSegment.setHeight(LayoutParams.WRAP_CONTENT);
//dismiss the pop-up i.e. drop-down when touched anywhere outside the pop-up
pwConsumerSegment.setTouchInterceptor(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
pwConsumerSegment.dismiss();
return true;
}
return false;
}
});
//provide the source layout for drop-down
pwConsumerSegment.setContentView(layoutCustomerSegment);
//anchor the drop-down to bottom-left corner of 'layout1'
pwConsumerSegment.showAsDropDown(layout4);
//populate the drop-down list
final ListView listCustomerSegment = (ListView) layoutCustomerSegment.findViewById(R.DropDownList.dropDownCustomerSegment);
ConsumerSegmentListAdapter adapter = new ConsumerSegmentListAdapter(this, customerSegments, tv_CustomerSegment);
listCustomerSegment.setAdapter(adapter);
}
here is my ConsumerSegmentListAdapter. The listview acts as my spinner.
public class ConsumerSegmentListAdapter extends BaseAdapter {
private ArrayList<String> mListCustomerSegment;
private LayoutInflater mInflater;
private TextView mSelectedItems;
private static int selectedCount = 0;
private static String firstSelected = "";
private ViewHolder holder;
private static String selected = ""; //shortened selected values representation
public static String getSelected() {
return selected;
}
public void setSelected(String selected) {
ConsumerSegmentListAdapter.selected = selected;
}
public ConsumerSegmentListAdapter(Context context, ArrayList<String> customerSegment,
TextView tv) {
mListCustomerSegment = new ArrayList<String>();
mListCustomerSegment.addAll(customerSegment);
mInflater = LayoutInflater.from(context);
mSelectedItems = tv;
}
#Override
public int getCount() {
return mListCustomerSegment.size();
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.drop_down_customersegment, null);
holder = new ViewHolder();
holder.tv = (TextView) convertView.findViewById(R.DropDownList.SelectOptionCustomerSegment);
holder.chkbox = (CheckBox) convertView.findViewById(R.DropDownList.checkboxCustomerSegment);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tv.setText(mListCustomerSegment.get(position));
final int position1 = position;
//whenever the checkbox is clicked the selected values textview is updated with new selected values
holder.chkbox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
setText(position1);
}
});
if(S_10th_IReportMain.checkSelectedConsumerSegment[position])
holder.chkbox.setChecked(true);
else
holder.chkbox.setChecked(false);
return convertView;
}
/*
* Function which updates the selected values display and information(checkSelectedConsumerSegment[])
* */
private void setText(int position1){
if (!S_10th_IReportMain.checkSelectedConsumerSegment[position1]) {
S_10th_IReportMain.checkSelectedConsumerSegment[position1] = true;
selectedCount++;
} else {
S_10th_IReportMain.checkSelectedConsumerSegment[position1] = false;
selectedCount--;
}
if (selectedCount == 0) {
mSelectedItems.setText(R.string.select_consumersegment);
} else if (selectedCount == 1) {
for (int i = 0; i < S_10th_IReportMain.checkSelectedConsumerSegment.length; i++) {
if (S_10th_IReportMain.checkSelectedConsumerSegment[i] == true) {
firstSelected = mListCustomerSegment.get(i);
break;
}
}
mSelectedItems.setText(firstSelected);
setSelected(firstSelected);
} else if (selectedCount > 1) {
for (int i = 0; i < S_10th_IReportMain.checkSelectedConsumerSegment.length; i++) {
if (S_10th_IReportMain.checkSelectedConsumerSegment[i] == true) {
firstSelected = mListCustomerSegment.get(i);
break;
}
}
mSelectedItems.setText(firstSelected + " & "+ (selectedCount - 1) + " more");
setSelected(firstSelected + " & "+ (selectedCount - 1) + " more");
}
}
private class ViewHolder {
TextView tv;
CheckBox chkbox;
}
}
I think You need to manage another storage for selected / unselected items and move it to the adapter. E.g. it can be HashSet<String>. Then code would look the following (note, that I made it compilable, because it's impossible to compile one provided in the question):
public class S_10th_IReportMain extends Activity {
boolean expandedConsumerSegment;
ConsumerSegmentListAdapter mAdapter;
private static class DatabaseHandler {
List<String> setItemOnConsumerSeg() {
return Collections.emptyList();
}
}
private static class BrandListAdapter {
static String getSelected() {
return "string";
}
}
DatabaseHandler databaseHandler = new DatabaseHandler();
private void initializeCustomerSegment() {
final ArrayList<String> consumerSegments = new ArrayList<String>();
List<String> consumerSegment = databaseHandler.setItemOnConsumerSeg();
consumerSegments.addAll(consumerSegment);
final TextView tv_ConsumerSegment = (TextView) findViewById(R.id.tv_ConsumerSegment);
tv_ConsumerSegment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!expandedConsumerSegment) {
// display all selected values
String selected = "";
int flag = 0;
for (String segment : consumerSegments) {
if (mAdapter.isChecked(segment)) {
selected += segment;
selected += ", ";
flag = 1;
}
}
if(flag == 1) {
tv_ConsumerSegment.setText(selected);
}
expandedConsumerSegment =true;
} else {
//display shortened representation of selected values
tv_ConsumerSegment.setText(BrandListAdapter.getSelected());
expandedConsumerSegment = false;
}
}
});
//onClickListener to initiate the dropDown list
TextView tv_customerSegment = (TextView)findViewById(R.id.tv_ConsumerSegment);
tv_customerSegment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
initiatePopUpCustomerSegment(consumerSegments,tv_ConsumerSegment);
}
});
}
PopupWindow pwConsumerSegment;
private void initiatePopUpCustomerSegment(ArrayList<String> customerSegments, TextView tv_CustomerSegment) {
LayoutInflater inflater = (LayoutInflater)S_10th_IReportMain.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//get the pop-up window i.e. drop-down layout
LinearLayout layoutCustomerSegment = (LinearLayout)inflater.inflate(R.layout.pop_up_window_customersegment, (ViewGroup)findViewById(R.id.PopUpView1));
//get the view to which drop-down layout is to be anchored
RelativeLayout layout4 = (RelativeLayout)findViewById(R.id.relativeLayout4);
pwConsumerSegment = new PopupWindow(layoutCustomerSegment, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
//Pop-up window background cannot be null if we want the pop-up to listen touch events outside its window
pwConsumerSegment.setBackgroundDrawable(new BitmapDrawable());
pwConsumerSegment.setTouchable(true);
//let pop-up be informed about touch events outside its window. This should be done before setting the content of pop-up
pwConsumerSegment.setOutsideTouchable(true);
pwConsumerSegment.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
//dismiss the pop-up i.e. drop-down when touched anywhere outside the pop-up
pwConsumerSegment.setTouchInterceptor(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
pwConsumerSegment.dismiss();
return true;
}
return false;
}
});
//provide the source layout for drop-down
pwConsumerSegment.setContentView(layoutCustomerSegment);
//anchor the drop-down to bottom-left corner of 'layout1'
pwConsumerSegment.showAsDropDown(layout4);
//populate the drop-down list
final ListView listCustomerSegment = (ListView) layoutCustomerSegment.findViewById(R.id.dropDownCustomerSegment);
ConsumerSegmentListAdapter adapter = new ConsumerSegmentListAdapter(this, customerSegments, tv_CustomerSegment);
listCustomerSegment.setAdapter(adapter);
}
public static class ConsumerSegmentListAdapter extends BaseAdapter {
private ArrayList<String> mListCustomerSegment;
private LayoutInflater mInflater;
private TextView mSelectedItems;
private static int selectedCount = 0;
private static String firstSelected = "";
private ViewHolder holder;
private static String selected = ""; //shortened selected values representation
private HashSet<String> mCheckedItems;
public static String getSelected() {
return selected;
}
public void setSelected(String selected) {
ConsumerSegmentListAdapter.selected = selected;
}
public ConsumerSegmentListAdapter(Context context, ArrayList<String> customerSegment,
TextView tv) {
mListCustomerSegment = new ArrayList<String>();
mListCustomerSegment.addAll(customerSegment);
mInflater = LayoutInflater.from(context);
mSelectedItems = tv;
}
/**
* Should be called then new data obtained from DB
*
* #param checkedItems array of strings obtained from DB
*/
public void setCheckedItems(final String[] checkedItems) {
mCheckedItems.clear();
Collections.addAll(mCheckedItems, checkedItems);
notifyDataSetChanged();
}
#Override
public int getCount() {
return mListCustomerSegment.size();
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.drop_down_customersegment, null);
holder = new ViewHolder();
holder.tv = (TextView) convertView.findViewById(R.id.SelectOptionCustomerSegment);
holder.chkbox = (CheckBox) convertView.findViewById(R.id.checkboxCustomerSegment);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final String text = mListCustomerSegment.get(position);
final boolean checked = isChecked(text);
holder.tv.setText(mListCustomerSegment.get(position));
//whenever the checkbox is clicked the selected values textview is updated with new selected values
holder.chkbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setText(position, checked, text);
}
});
if(checked) {
holder.chkbox.setChecked(true);
} else {
holder.chkbox.setChecked(false);
}
return convertView;
}
/*
* Function which updates the selected values display and information(checkSelectedConsumerSegment[])
* */
private void setText(int position, boolean checked, String text){
if (!checked) {
mCheckedItems.add(text);
selectedCount++;
} else {
mCheckedItems.remove(text);
selectedCount--;
}
if (selectedCount == 0) {
mSelectedItems.setText(R.string.select_consumersegment);
} else if (selectedCount == 1) {
firstSelected = mCheckedItems.iterator().next();
mSelectedItems.setText(firstSelected);
setSelected(firstSelected);
} else if (selectedCount > 1) {
firstSelected = mCheckedItems.iterator().next();
mSelectedItems.setText(firstSelected + " & "+ (selectedCount - 1) + " more");
setSelected(firstSelected + " & "+ (selectedCount - 1) + " more");
}
}
/**
* #param segment to be checked
*
* #return true if the segment is checked
*/
public boolean isChecked(final String segment) {
return mCheckedItems.contains(segment);
}
private class ViewHolder {
TextView tv;
CheckBox chkbox;
}
}
}
So, then You obtain new data from database which should be checked You can just call mAdapter.setCheckedItems().
I already make it. By this:
for (int j=0; j<brands.size(); j++)
{
for(String chosenElement : Brands)
{
int index = brands.indexOf(chosenElement);
checkSelected[index] = true;
}
}
What I did is i look for the index of my chosen arraylist to my spinner's adapter and set the the checkbox index into true. That simple. Anyway thanks for the idea.