I am trying to update position value by overriding getItemPosition() but it is not working. Please help..
Code here -
#Override
public int getItemPosition(Object object) {
super.getItemPosition(object);
SharedPreferences pos = ctx.getSharedPreferences("forposition", MODE_PRIVATE);
int tom = pos.getInt("pos",0);
Log.d("posTom","value : "+tom );
return tom;
}
This is instantiateItem() method :
public Object instantiateItem(#NonNull ViewGroup container, int position) {
inflater = (LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.swipe,container,false);
ImageView imageView = (ImageView) v.findViewById(R.id.imageview);
SharedPreferences sp = ctx.getSharedPreferences("your_shared_pref_name", MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
if((sp.getString("array", null)) == null) {
String temp = Arrays.toString(count);
editor.putString("array", temp);
editor.commit();
}
String fetch = sp.getString("array", null);
Log.d("positionlist ","value : "+fetch);
fetch = fetch.substring(1, fetch.length()-1);
String strarray[] =fetch.split(", ") ;
/* SharedPreferences spt= ctx.getSharedPreferences("your_shared_pref_name", MODE_PRIVATE);
int post = spt.getInt("pos",1);*/
Log.d("position","value : "+position );
Log.d("posvalue","value : "+strarray[position] );
Log.d("poscondition","value : "+(Integer.parseInt(strarray[position]) == 0) );
if (Integer.parseInt(strarray[position]) == 0) {
BackgroundTask task = new BackgroundTask(this);
task.execute();
imageView.setImageResource(img[position]);
container.addView(v);
strarray = setValue(position, strarray);
String temp1 = Arrays.toString(strarray);
editor.putString("array", temp1);
editor.commit();
} else {
imageView.setImageResource(img[position]);
container.addView(v);
}
SharedPreferences pos = ctx.getSharedPreferences("forposition", MODE_PRIVATE);
SharedPreferences.Editor poseditor = pos.edit();
poseditor.putInt("pos", position);
poseditor.commit();
return v;
}
Please give solution how to update position from instantiateItem() method.
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 a listview with custom adapter and its working fine. But it takes more than 15 sec to load data to listview.and use 60mb of ram memory. Please tell me what is the issue and why its taking too much time? please help me with some code or edit my code .Here is my code. Thanks in advance!
custom adapter
public class Listadapter extends BaseAdapter {
CheckBox checkBox;
boolean index[];
boolean[] itemChecked;
ApplicationInfo entry;
String[] itempkg;
private Context mContext;
private List<ApplicationInfo> mListAppInfo;
private PackageManager mPackManager;
private ArrayList<Boolean> checkList = new ArrayList<Boolean>();
public Listadapter(Context applicationContext, List<ApplicationInfo> 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)
{
// get the selected entry
final ViewHolder holder;
// LayoutInflater inflater = (LayoutInflater) mContext.getLayoutInflater();
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);
// holder.ck1.setTag(packageList.get(position));
} 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.packageName);
holder.checkBox.setChecked(false);
if (itemChecked[position])
holder.checkBox.setChecked(true);
else
holder.checkBox.setChecked(false);
holder.checkBox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (holder.checkBox.isChecked()) {
itemChecked[position] = true;
// SharedPreferences preferences = mContext.getSharedPreferences("YOUR_APP_NAME", Context.MODE_PRIVATE);
// SharedPreferences.Editor edit = preferences.edit();
// edit.putBoolean("checkbox_" + position, true);
// edit.commit();
// editor.putBoolean("CheckBoxState" + position, true);
} else {
itemChecked[position] = false;
// editor.putBoolean("CheckBoxState" + position, false);
// SharedPreferences preferences = mContext.getSharedPreferences("YOUR_APP_NAME", Context.MODE_PRIVATE);
// SharedPreferences.Editor edit = preferences.edit();
// edit.putBoolean("checkbox_" + position, false);
// edit.commit();
}
}
});
return convertView;
}
public void setItemChecked5(boolean[] items5) {
itemChecked = items5;
}
private class ViewHolder
{
ImageView ivAppIcon;
TextView tvAppName;
TextView tvPkgName;
CheckBox checkBox;
}
}
here is activity code
public class Profile5Activity extends Activity implements AdapterView.OnItemClickListener {
ListView apps5;
PackageManager packageManager5;
ArrayList<String> checkedValue5;
Button bt5;
ApplicationInfo pi5 = new ApplicationInfo();
Context context = this;
static String currentApp5 = "NULL";
CheckBox cb5;
Listadapter Adapter5 = null;
boolean[] itemChecked5;
//static String currentApp5;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile5);
itemChecked5 = new boolean[AllApps.getInstalledApplication(this).size()];
//needPermissionForBlocking(MainActivity.mainContext);
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>();
}
// bt1 = (Button) findViewById(R.id.button1);
apps5 = (ListView) findViewById(R.id.listViewm);
apps5.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
packageManager5 = getPackageManager();
List<String> list = 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, View v, int position, long arg3)
{
// TODO Auto-generated method stub
cb5 = (CheckBox) v.findViewById(R.id.checkBox1);
TextView tv5 = (TextView) v.findViewById(R.id.textView);
pi5 = (ApplicationInfo) arg0.getItemAtPosition(position);
cb5.performClick();
if (cb5.isChecked()) {
checkedValue5.add(tv5.getText().toString());
itemChecked5[position] = true;
String pname = (tv5.getText().toString());
// Toast.makeText(MainActivity.this, "all" + position, Toast.LENGTH_LONG).show();
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 = (tv5.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();
}
}
I am able to save Strings in my saved preferences but having difficulty saving my spinner.
public class Diet extends Activity {
private SharedPreferences sharedPreferences;
Spinner spnCalorieRange;
Here is my onCreate:
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String strAge = Integer.toString(age);
String strHeight = Integer.toString(height);
String strWeight = Integer.toString(weight);
name = loadSavedPreference("name");
strAge = loadSavedPreference("strAge");
strHeight = loadSavedPreference("strHeight");
strWeight = loadSavedPreference("strWeight");
etName.setText(name);
etAge.setText(strAge);
etHeight.setText(strHeight);
etWeight.setText(strWeight);
This is my Spinner in my onCreate:
spinner = (Spinner)findViewById(R.id.spnCalorieRange);
adapter = ArrayAdapter.createFromResource(this, R.array.Calorie_Range, android.R.layout.simple_spinner_dropdown_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
long item = parent.getItemIdAtPosition(position);
String pos =spinner.getSelectedItem().toString();
//sharedPreferences.edit().putInt("PREF_SPINNER", position).commit();
if (item == 0){
deficitPercentage = .05;
}
else if (item ==1)
{
deficitPercentage = .1;
}
else if (item ==2)
{
deficitPercentage = .15;
}
else if (item ==3)
{
deficitPercentage = .2;
}
else if (item ==4)
{
deficitPercentage = .25;
}
else
{
deficitPercentage = .3;
}
//editor.putString("pos", pos);
//editor.commit();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
This is in my onCLick behind a button, where I'm saving the strings and spinner
age = (int) Double.parseDouble(etAge.getText().toString());
height = (int) Double.parseDouble(etHeight.getText().toString());
weight = (int) Double.parseDouble(etWeight.getText().toString());
//Save Preferences
String strAge = Integer.toString(age);
String strHeight = Integer.toString(height);
String strWeight = Integer.toString(weight);
name = etName.getText().toString();
savePreference("name",name);
strAge = etAge.getText().toString();
savePreference("strAge",strAge);
strHeight = etHeight.getText().toString();
savePreference("strHeight",strHeight);
strWeight = etWeight.getText().toString();
savePreference("strWeight",strWeight);:
You can't save the actual spinner object to shared prefs, but you can save all of the values that make the spinner work its magic and next time you create the spinner, just apply those values
In your onItemSelected place:
int spinnerPosition = spinner.getSelectedItemPosition();
saveSpinnerPosition(spinnerPosition);
Save method
public void saveSpinnerPosition(int position){
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
prefEditor.putInt("spnCalorieRange",position);
prefEditor.apply();
}
Load method
public void loadSpinnerPosition{
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
int position= sharedPreferences .getInt"spnCalorieRange",-1);
if(spinnerValue > -1)
// set the value of the spinner
spinner.setSelection(position);
}
To put spinners back to position, call loadSpinnerPosition in your onCreate
------------------------------------------------------------------------------------------------------------------------------------
Edit:
because I noticed this post is also your question, u can also do everything at once:
At the top of your activity:
int spinnerPosition;
In your onItemSelected place:
spinnerPosition = spinner.getSelectedItemPosition();
Save method
public void saveMethod(){
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("Gender", radioSexButton.isChecked());
editor.putBoolean("Male", rdoMale.isChecked());
prefEditor.putInt("spnCalorieRange",spinnerPosition);
prefEditor.apply();
}
Load method
public void loadMethod(){
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
int position= sharedPreferences .getInt"spnCalorieRange",-1);
radioSexButton.setChecked(sharedPreferences.getBoolean("Gender", false));
rdoMale.setChecked(sharedPreferences.getBoolean("Male", false));
if(spinnerValue > -1)
// set the value of the spinner
spinner.setSelection(position);
}
Then call saveMethod() when u want to save all your states, and call loadMethod() when u wanna load all your states
Should help u out
i´m using Gson and Json to save objects that are used to show posts containing images and texts. Problem is that the saved posts will not show up in the listView. I have succeeded in saving the posts but not loading them.
in PlaceViewFragment - is supposed to show posts
#Override
public void onStop() {
super.onStop();
SharedPreferences prefs = activity.getSharedPreferences(desination, 0);
SharedPreferences.Editor prefsEditor = prefs.edit();
Gson gson = new Gson();
String json = gson.toJson(contentList);
prefsEditor.putString(desination, json);
prefsEditor.commit();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_place_view, container, false);
activity = this.getActivity();
desination = getArguments().getString("destination");
/**
*Load contentItems using Json.
**/
SharedPreferences prefs = activity.getSharedPreferences(desination, 0);
/*
SharedPreferences.Editor prefsEditor = prefs.edit();
prefsEditor.clear();
prefsEditor.commit();
*/
Gson gson = new Gson();
String json = prefs.getString(desination, null);
Map<String, ?> keys = prefs.getAll();
for (Map.Entry<String, ?> entry : keys.entrySet()) {
Log.d("map values", entry.getKey() + ": " +
entry.getValue().toString());
}
Type type = new TypeToken<ArrayList<ContentItem>>() {
}.getType();
contentList = gson.fromJson(json, type);
// Log.d("Contentlist 1", contentList.get(0).getImages().get(0).toString());
if (contentList == null) {
contentList = new ArrayList<ContentItem>();
}
listView = (ListView) view.findViewById(R.id.listView2);
// get data from the table by the ListAdapter
listView.setAdapter(myAdapter);
myAdapter = new MyAdapter(this.getActivity(), R.layout.view_layout, contentList);
MyAdapter
#Override
public int getCount() {
return items.size();
}
#Override
public ContentItem getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder holder;
if (v == null) {
v = mInflater.inflate(R.layout.view_layout, parent, false);
holder = new ViewHolder();
holder.date = (TextView) v.findViewById(R.id.dateview);
holder.cap = (TextView) v.findViewById(R.id.caption);
holder.tt1 = (TextView) v.findViewById(R.id.textview1);
holder.tt2 = (TextView) v.findViewById(R.id.textview2);
holder.tt3 = (TextView) v.findViewById(R.id.textview3);
holder.im1 = (ImageView) v.findViewById(R.id.image1);
holder.im2 = (ImageView) v.findViewById(R.id.image2);
holder.im3 = (ImageView) v.findViewById(R.id.image3);
v.setTag(holder);
} else {
v = convertView;
holder = (ViewHolder) v.getTag();
}
ContentItem p = getItem(position);
holder.date.setText(p.getDate());
holder.cap.setText(p.getCaption());
if (p.getTexts().size() > 0) {
holder.tt1.setText(p.getTexts().get(0));
holder.tt1.setVisibility(View.VISIBLE);
holder.tt2.setText(p.getTexts().get(1));
holder.tt2.setVisibility(View.VISIBLE);
holder.tt3.setText(p.getTexts().get(2));
holder.tt3.setVisibility(View.VISIBLE);
}
if (p.getImages().size() > 0) {
holder.im1.setImageBitmap(loadImageFromStorage(p.getImages().get(0)));
holder.im1.setVisibility(View.VISIBLE);
holder.im2.setImageBitmap(loadImageFromStorage(p.getImages().get(1)));
holder.im2.setVisibility(View.VISIBLE);
holder.im3.setImageBitmap(loadImageFromStorage(p.getImages().get(2)));
holder.im3.setVisibility(View.VISIBLE);
}
return v;
}
private class ViewHolder {
public ImageView im1, im2, im3;
public TextView date, cap, tt1, tt2, tt3;
}
private Bitmap loadImageFromStorage(String path) {
Bitmap b = null;
try {
File f = new File(path, "image.jpg");
b = BitmapFactory.decodeStream(new FileInputStream(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return b;
}
}
I think it is in this code something goes wrong.
You inverted the method call, you have
listView.setAdapter(myAdapter);
myAdapter = new MyAdapter(this.getActivity(), R.layout.view_layout, contentList);
it should be
myAdapter = new MyAdapter(this.getActivity(), R.layout.view_layout, contentList);
listView.setAdapter(myAdapter);
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.