I'd like to save SparseBooleanArray using either SharedPreferences, or anything else, that's more preferred.
I've tried using https://stackoverflow.com/a/16711258/2530836, but everytime the activity is created, bundle is re-initialized, and bundle.getParcelable() returns null. I'm sure there is a workaround for this, but I haven't arrived at it despite a few hours of brainstorming.
Also, if there isn't, could I use something like SharedPreferences?
Here's the code:
public class ContactActivity extends Activity implements AdapterView.OnItemClickListener {
List<String> name1 = new ArrayList<String>();
List<String> phno1 = new ArrayList<String>();
ArrayList<String> exceptions = new ArrayList<String>();
MyAdapter adapter;
Button select;
Bundle bundle = new Bundle();
Context contactActivityContext;
SharedPreferences prefs;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contacts_layout);
getAllContacts(this.getContentResolver());
ListView list= (ListView) findViewById(R.id.lv);
adapter = new MyAdapter();
list.setAdapter(adapter);
list.setOnItemClickListener(this);
list.setItemsCanFocus(false);
list.setTextFilterEnabled(true);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
select = (Button) findViewById(R.id.button1);
select.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StringBuilder checkedcontacts = new StringBuilder();
for (int i = 0; i < name1.size(); i++)
{
if (adapter.isChecked(i)) {
checkedcontacts.append(name1.get(i).toString());
exceptions.add(name1.get(i).toString());
checkedcontacts.append(", ");
}
}
checkedcontacts.deleteCharAt(checkedcontacts.length() - 2);
checkedcontacts.append("selected");
editor = prefs.edit();
editor.putInt("Status_size", exceptions.size()); /* sKey is an array */
for(int i=0;i<exceptions.size();i++)
{
editor.remove("Status_" + i);
editor.putString("Status_" + i, exceptions.get(i));
}
editor.commit();
Toast.makeText(ContactActivity.this, checkedcontacts, Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
adapter.toggle(arg2);
}
private void setContext(Context contactActivityContext){
this.contactActivityContext = contactActivityContext;
}
protected Context getContext(){
return contactActivityContext;
}
public void getAllContacts(ContentResolver cr) {
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC" );
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
name1.add(name);
phno1.add(phoneNumber);
}
phones.close();
}
class MyAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener
{ SparseBooleanArray mCheckStates;
ContactActivity mContactActivity = new ContactActivity();
LayoutInflater mInflater;
TextView tv1,tv;
CheckBox cb;
int mPos;
MyAdapter()
{
mCheckStates = new SparseBooleanArray(name1.size());
mCheckStates = (SparseBooleanArray) bundle.getParcelable("myBooleanArray");
mInflater = (LayoutInflater) ContactActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return name1.size();
}
public void setPosition(int p){
mPos = p;
}
public int getPosition(){
return mPos;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi=convertView;
if(convertView==null)
vi = mInflater.inflate(R.layout.row, null);
tv= (TextView) vi.findViewById(R.id.textView1);
tv1= (TextView) vi.findViewById(R.id.textView2);
cb = (CheckBox) vi.findViewById(R.id.checkBox1);
tv.setText("Name :"+ name1.get(position));
tv1.setText("Phone No :"+ phno1.get(position));
cb.setTag(position);
cb.setChecked(mCheckStates.get(position, false));
setPosition(position);
cb.setOnCheckedChangeListener(this);
return vi;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
#Override
public void onDestroy(){
bundle.putParcelable("myBooleanArray", new SparseBooleanArrayParcelable(adapter.mCheckStates));
super.onDestroy();
}
}
You can store it in SharedPreferances
The thing about sparsebooleanarrays is: it maps integers to boolean values, hence you can save it as a string, eliminate the braces,spaces and = signs, and all you have is an int value (for index value) and the corresponding boolean value, separated by a comma, now use the string accordingly. Hope it helps :)
Bundle is created by you in the class and it is not used by activity to store the value.
If You're using the bundle of application, still you can't get the instance once you killed the application.
For you're problem better go with shared preference but in shared preference you can't store objects.
If you want to use shared preference then there are 2 solutions.
Convert object to string and store in shared preference and retrieve back and reform the Object from String. (use Gson or Jackson or you're preferred way )
Use Complex Preferences third party one, Where you can store objects and retrieve directly.
If you're more interested using bundle only then Check this discussion on stackoverflow.
save-bundle-to-sharedpreferences
how-to-serialize-a-bundle
Hope this will help you.
Related
I have tried for hours looking through examples and other people's code but I still don't quite understand it.
I have my own method, which half works.
public class List_of_recipes extends ActionBarActivity {
//original
public List<List_view_class> list_view_class;
ArrayAdapter<List_view_class> adapter;
// not the original
public List<List_view_class> another_list_class;
public ListView list;
public EditText edit_text;
//ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_of_recipes);
// actionBar = getActionBar();
//actionBar.setDisplayHomeAsUpEnabled(true);
//actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#A02727")));
list = (ListView) findViewById(R.id.listView1);
edit_text = (EditText) findViewById(R.id.editText1);
list_view_class = new ArrayList<List_view_class>();
another_list_class = new ArrayList<List_view_class>();
adapter = new MyListAdapter(list_view_class);
list_view_class.add(new List_view_class(R.drawable.chicken, "Chicken salad", "15 min", "Easy", "4 serves"));
list_view_class.add(new List_view_class(R.drawable.mexican, "Mexican egg soup", "20 min", "Easy", "2 serves"));
list_view_class.add(new List_view_class(R.drawable.oyster, "Oysters with pancetta", "10 min", "Super Easy", "2 serves"));
//list_view_class.add(new List_view_class(R.drawable.wild_mushroom,"Wild mushroom crostini","5 min", "Easy","6 serves"));
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View viewclicked, int position, long id) {
// TODO Auto-generated method stub
if (position == 0) {
Intent i = new Intent(List_of_recipes.this, Chicken_salad.class);
startActivity(i);
finish();
}
if (position == 1) {
Intent i = new Intent(List_of_recipes.this, Mexican_egg.class);
startActivity(i);
finish();
}
if (position == 2) {
Intent i = new Intent(List_of_recipes.this, Oyster.class);
startActivity(i);
finish();
}
}
});
edit_text.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
String searchString = edit_text.getText().toString();
another_list_class.clear();
int textLength = edit_text.length();
for (int i = 0; i < list_view_class.size(); i++) {
String name = list_view_class.get(i).gettitle().toString();
if (textLength <= name.length()) {
if (searchString.equalsIgnoreCase(name.substring(0, textLength))) {
another_list_class.add(list_view_class.get(i));
}
}
}
adapter.notifyDataSetChanged();
adapter = new MyListAdapter(another_list_class);
list.setAdapter(adapter);
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
});
}
public class MyListAdapter extends ArrayAdapter<List_view_class> {
public MyListAdapter(List<List_view_class> object_class) {
super(List_of_recipes.this, R.layout.activity_list_class_view, object_class);
}
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = (LayoutInflater) List_of_recipes.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.activity_list_class_view, null, true);
}
List_view_class listclass = list_view_class.get(position);
ImageView image = (ImageView) rowView.findViewById(R.id.imageView1);
image.setImageResource(listclass.getrecipe_icon());
TextView date = (TextView) rowView.findViewById(R.id.textView1);
date.setText(listclass.gettitle());
TextView cook = (TextView) rowView.findViewById(R.id.cooktime);
cook.setText(listclass.getcook_time());
TextView diff = (TextView) rowView.findViewById(R.id.difficultylvl);
diff.setText(listclass.getdifficulty());
TextView serve = (TextView) rowView.findViewById(R.id.serving);
serve.setText(listclass.getmakes());
return rowView;
}
}
}
It gives no errors, but all I am getting is the first list view item no matter what I type.
I am not sure what else to add or what I am doing wrong here. Any help will be appreciated, thank you !
there is no need to create another adapter again and again on edit text change.you can refresh list view by just calling notifyDataSetChanged on adapter.
String searchString = s.toString();
another_list_class.clear();
for(int i =0; i< list_view_class.size(); i++){
String name = list_view_class.get(i).gettitle().toString();
if(name.contains(searchString))
{
another_list_class.add(list_view_class.get(i));
}
}
adapter.notifyDataSetChanged();
equalsIgnoreCase returns true if and only if two strings are exactly equal(Ignoring case sensitive);
You can also use startWith in place of contains
One more thing set your adpater with another_list_class arraylist initially.
because in this example we are changing search result in another_list_class .
It is better to put code in afterTextChanged.
Try to move code to afterTextChanged
int textLength=edit_text.getText()!=null?edit_text.getText().toString().length():0;
for(int i =0; i< list_view_class.size(); i++)
{
String name = list_view_class.get(i).gettitle().toString();
if(textLength <= name.length()){
if(searchString.equalsIgnoreCase(name.substring(0,textLength)))
{
another_list_class.add(list_view_class.get(i));
}
}
}
I have an listview in my application and when I add search to my listview it dosen't work at all.
when I add those code to my project, getfilter doesn't resolve.
enter code here
public class MyActivity extends Activity {
InputStream in;
BufferedReader reader;
String line = "1";
public ListView listView;
VehicleAdapter adapter;
ArrayList<String> dataItems = new ArrayList<String>();
public int star = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
G.currentActivity = this;
setContentView(R.layout.main);
// Adad.setTestMode(true);
ReadText();
// String[] dataArray = dataItems.toArray(new String[0]);
//String[] dataArray = getResources().getStringArray(R.array.listdata);
//List<String> dataTemp = Arrays.asList(dataArray);
// dataItems.addAll(dataTemp);
listView = (ListView) findViewById(R.id.mainList);
EditText ed = (EditText) findViewById(R.id.editText1);
ArrayList<Bitmap> arr_bitmaps = new ArrayList<Bitmap>(4);
adapter = new VehicleAdapter(MyActivity.this, arr_bitmaps, dataItems);
listView.setAdapter(adapter);
listView.setTextFilterEnabled(true);
ed.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// vaghti kar bar harfi vared kard josteju mikone :
MyActivity.this.adapter.getFilter().filter(arg0);
}
});
}
public class VehicleAdapter extends BaseAdapter {
ArrayList<String> arr_calllog_name = new ArrayList<String>();
public Activity context;
ArrayList<Bitmap> imageId;
public LayoutInflater inflater;
public VehicleAdapter(Activity context, ArrayList<Bitmap> arr_bitmaps, ArrayList<String> arr_calllog_name) {
super();
this.imageId = arr_bitmaps;
this.context = context;
this.arr_calllog_name = arr_calllog_name;
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return arr_calllog_name.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;
}
public class ViewHolder {
TextView txtName;
ImageButton btn;
}
#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 = inflater.inflate(R.layout.child_listview, null);
holder.txtName = (TextView) convertView.findViewById(R.id.childTextView);
holder.btn = (ImageButton) convertView.findViewById(R.id.childButton);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.txtName.setText(PersianReshape.reshape(arr_calllog_name.get(position)));
Typeface custom_font = Typeface.createFromAsset(getAssets(), "fonts/B Morvarid_YasDL.com.ttf");
//holder.txtName.setTypeface(G.defaultFont);
holder.txtName.setTypeface(custom_font);
holder.btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = arr_calllog_name.get(position);
sharingIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject Here");
sharingIntent.putExtra(Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
});
return convertView;
}
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem menuItem) {
if (menuItem.getItemId() == R.id.contact) {
Intent intent = new Intent(MyActivity.this, ContactUs.class);
startActivity(intent);
}
return super.onOptionsItemSelected(menuItem);
}
private void ReadText() {
try {
in = this.getAssets().open("text.txt");
reader = new BufferedReader(new InputStreamReader(in));
while (line != null) {
line = reader.readLine();
if (line != null)
dataItems.add(line);
else
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
my broblem is this code.
enter code here
MyActivity.this.adapter.getFilter().filter(arg0);
why getFilter() doesn't resolve?
Is it releted to my adaptor?
please help
why getFilter() doesn't resolve?
Because Filterable interface is not implemented in VehicleAdapter class.
To call adapter.getFilter().filter for Activity usng Adapter object need to implement Filterable interface in Adapter class and override getFilter.
See following example how to make Adapter Filterable:
Android Filter Custom ListView (BaseAdapter)
In custom adapter it would not work. this code for search will work in SimpleAdapter. For your adapter you have to write custom code for search.
Follow this link it would do as per your need (search filter in custom adapetr)
Custom Listview Adapter with filter Android
When I had problems trying to fix the position of my listView items to the desired intent when filtered, and got info I could override the problem using a custom adapter, I have done that but I do not know how to assign the clicks to each items, please check below code:
public class IndexPageActivity extends Activity {
ListView listView;
EditText editTextB;
#Override
protected void onCreate(Bundle savfedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.indexpage);
listView = (ListView) findViewById(R.id.pageList);
editTextB = (EditText) findViewById(R.id.searchB);
listView.setAdapter(new PagesAdapter(this));
listView.setOnItemClickListener((OnItemClickListener) this);
}
}
class SingleRow {
String pagedata;
SingleRow(String pagedata){
this.pagedata=pagedata;
}
}
class PagesAdapter extends BaseAdapter implements OnItemClickListener{
ArrayList<SingleRow> pagelist;
Context context;
PagesAdapter(Context c){
context=c;
pagelist = new ArrayList<SingleRow>();
Resources res = c.getResources();
String [] pagedatas = res.getStringArray(R.array.pages_data);
for (int i=0;i<463;i++){
pagelist.add(new SingleRow(pagedatas[i]));
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return pagelist.size();
}
#Override
public Object getItem(int i) {
// TODO Auto-generated method stub
return pagelist.get(i);
}
#Override
public long getItemId(int i) {
// TODO Auto-generated method stub
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewG) {
// TODO Auto-generated method stub
LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row=inflater.inflate(R.layout.single_row,viewG,false);
TextView pagetitle = (TextView) row.findViewById(R.id.textViewRow);
SingleRow temp=pagelist.get(i);
pagetitle.setText(temp.pagedata);
return row;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int i, long arg3) {
// TODO Auto-generated method stub
}
}
I will appreciate any help given. Thank Yhu!
EDIT
Will this work?
if (index == 0) {
Intent i = new Intent(this, WebViewActivity.class);
i.putExtra("keyHTML", "file:///android_asset/page1.html");
startActivity(i);
} else if (index == 1) {
Intent i = new Intent(this, WebViewActivity.class);
i.putExtra("keyHTML", "file:///android_asset/page2.html");
startActivity(i);
Edited ALL
I just got what you need, I added a filter to your baseAdapter and then on text change within the editText You filter the listView and then you go to the activity needed.
here is the full code but you need to bare in mind that I have changed the following:
I changed the pageList to ArrayList instead of
There is a bug in filtering that when I erase what I wrote in the EditText it doesnt update the ListView, you need to figure out why.
I changed the returned value of the function getItem(int i) from Object to String
Within the onItemClick you have to search for the name instead of the position.
here is the code:
public class IndexPageActivity extends Activity implements OnItemClickListener{
ListView listView;
EditText editTextB;
PagesAdapter adapter1;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.pageList);
editTextB = (EditText) findViewById(R.id.searchB);
adapter1 = new PagesAdapter(this);
listView.setAdapter(adapter1);
adapter1.notifyDataSetChanged();
listView.setOnItemClickListener(this);
editTextB.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2,
int arg3) {
// When user changed the Text
IndexPageActivity.this.adapter1.getFilter().filter(cs.toString());
adapter1.notifyDataSetChanged();
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
// TODO Auto-generated method stub
Intent i;
String name = adapter1.getItem(position);
Log.d("id", name);
if (name.equals("Item1"))
{
i = new Intent(this, anActivity.class);
startActivity(i);
}
else if (name.equals("Item2"))
{
i = new Intent(this, anActivity2.class);
startActivity(i);
}
}
}
class SingleRow {
String pagedata;
SingleRow(String pagedata){
this.pagedata=pagedata;
}
}
class PagesAdapter extends BaseAdapter implements Filterable{
ArrayList<String> pagelist;
List<String> arrayList;
Context context;
String [] pagedatas;
PagesAdapter(Context c){
context=c;
pagelist = new ArrayList<String>();
Resources res = c.getResources();
pagedatas = res.getStringArray(R.array.pages_data);
for (int i=0;i<463;i++){
pagelist.add(pagedatas[i]);
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return pagelist.size();
}
#Override
public String getItem(int i) {
// TODO Auto-generated method stub
return pagelist.get(i);
}
#Override
public long getItemId(int i) {
// TODO Auto-generated method stub
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewG) {
// TODO Auto-generated method stub
LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row=inflater.inflate(R.layout.single_row,viewG,false);
TextView pagetitle = (TextView) row.findViewById(R.id.textViewRow);
String temp=pagelist.get(i);
pagetitle.setText(temp);
return row;
}
public class filter_here extends Filter{
#Override
protected FilterResults performFiltering(CharSequence constraint) {
// TODO Auto-generated method stub
FilterResults Result = new FilterResults();
// if constraint is empty return the original names
if(constraint.length() == 0 ){
Result.values = pagelist;
Result.count = pagelist.size();
return Result;
}
ArrayList<String> Filtered_Names = new ArrayList<String>();
String filterString = constraint.toString().toLowerCase();
String filterableString;
for(int i = 0; i<pagelist.size(); i++){
filterableString = pagelist.get(i);
if(filterableString.toLowerCase().contains(filterString)){
Filtered_Names.add(filterableString);
}
}
Result.values = Filtered_Names;
Result.count = Filtered_Names.size();
return Result;
}
#Override
protected void publishResults(CharSequence constraint,FilterResults results) {
// TODO Auto-generated method stub
pagelist = (ArrayList<String>) results.values;
notifyDataSetChanged();
}
}
#Override
public Filter getFilter() {
// TODO Auto-generated method stub
return new filter_here();
}
}
Two different ways for it:
1) If you want to use something like this at onCreate of your activity;
listView.setOnItemClickListener((OnItemClickListener) this);
You should implement OnItemClickListener to your activity:
IndexPageActivity extends Activity implements OnItemClickListener
and implement its onItemClick method at your activity. (also remove OnItemClickListener interface from your custom adapter)
2) You can simply use below without implementing OnItemClickListener to any class:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO: handle row clicks here
}
I suggest 2nd option. That is easier.
Edit: This not relevant to your problem but you should reuse your views/rows at listView. Change your getView method to:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.single_row, parent, false);
} else {
view = convertView;
}
TextView pagetitle = (TextView) view.findViewById(R.id.textViewRow);
SingleRow temp=pagelist.get(i);
pagetitle.setText(temp.pagedata);
return view;
}
Set your setOnItemClickListenerlike this:
#Override
protected void onCreate(Bundle savfedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.indexpage);
listView = (ListView) findViewById(R.id.pageList);
editTextB = (EditText) findViewById(R.id.searchB);
listView.setAdapter(new PagesAdapter(this));
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//Your code here
//int position is the index of the list item you clicked
//use it to manipulate the item for each click
}
});
}
I am struggling with trying to implement an OnLongClick feature - I can't understand where to add a listener and to define the resulting method.
The implementation i have used uses an adapter - and does not have an onClickListener, but works jsut fine. can anyone suggest where/how to implement OnLongClick listener
I don't need every item in the list to perform different actions - just for anywere on the screen to pick up the long press
public class CombChange extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ListEdit(this, symbols));
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
String selectedValue = (String) getListAdapter().getItem(position);
if (lastPressed.equals(selectedValue) ){
count++;}
}
public class ListEdit extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
public ListEdit(Context context, String[] values) {
super(context, R.layout.activity_comb_change, values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.activity_comb_change, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.label);
ImageView imageView = (ImageView) rowView.findViewById(R.id.logo);
textView.setText(values[position]);
// Change icon based on name
String s = values[position];
if (s.equals("a")) {
imageView.setImageResource(R.drawable.a);
return rowView;
}
}
Try this:
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
v.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
String selectedValue = (String) getListAdapter().getItem(position);
if (lastPressed.equals(selectedValue) ){
count++;}
return false;
}
});
}
It is unfortunate that a ListActivity does not have a protected onListItemLongClick() method similar to the onListItemClick() function.
Instead, you can add setOnLongClickListener() to the top-level layout item (or any View) in your adapter's getView() function.
Example:
myView.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// Do something here.
return true;
}
});
Warning, the OnLongClickListener you put onto your list item may hide exposure to the onListItemClick() function you already have working for the list. If this is the case, you will also have to add setOnClickListener() to getView() and use it instead.
in your getView you can say
rowview.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View arg0) {
//Do your stuff here
return false;
}
});
I'm testing code copied from a Java Android examples site. I'm trying to modify it to start a new activity when a user clicks into a row of the current activity. So I'm using the Intent method but I'm not able to figure out how to reference the current View instance argument to the Intent method.
I've tried dozens of combinations, and spent 2 days researching. This must seem basic to many of you I know, but my apologies, this is week #2 for me learning Java, Eclipse and the Android SDK (target= API 8)
public class CustomListViewDemo extends ListActivity {
private EfficientAdapter adap;
private static String[] data = new String[] { "0", "1" };
private static String[] TitleString = new String[] { "Title1", "Title2" };
private static String[] DetailString = new String[] { "Detail1", "Detail2" };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
adap = new EfficientAdapter(this);
setListAdapter(adap);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
Toast.makeText(this, "Click-" + String.valueOf(position),
Toast.LENGTH_SHORT).show();
}
public static class EfficientAdapter extends BaseAdapter implements
Filterable {
private LayoutInflater mInflater;
private Bitmap mIcon1;
private Context context;
public EfficientAdapter(Context context) {
// Cache the LayoutInflate to avoid asking for a new one each time.
mInflater = LayoutInflater.from(context);
this.context = context;
}
/**
* Make a view to hold each row.
*
*/
public View getView(final int position, View convertView,
ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.adaptor_content, null);
holder = new ViewHolder();
holder.textLine = (TextView) convertView
.findViewById(R.id.textLine);
holder.buttonLine = (Button) convertView
.findViewById(R.id.buttonLine);
holder.DbuttonLine = (Button) convertView
.findViewById(R.id.DbuttonLine);
holder.textLine2 = (TextView) convertView
.findViewById(R.id.textLine2);
convertView.setOnClickListener(new OnClickListener() {
private int pos = position;
#Override
public void onClick(View v) {
// Toast.makeText(context, "Click-" +
// String.valueOf(pos),
// Toast.LENGTH_SHORT).show();
// ******************** ERROR IS LINE BELOW *********
// "No enclosing instance of the type CustomListViewDemo is accessible in scope"
Intent i = new Intent(CustomListViewDemo.this, IntentA.class);
startActivity(i);
}
});
holder.buttonLine.setOnClickListener(new OnClickListener() {
private int pos = position;
#Override
public void onClick(View v) {
Toast.makeText(context,
"Delete-" + String.valueOf(pos),
Toast.LENGTH_SHORT).show();
}
});
holder.DbuttonLine.setOnClickListener(new OnClickListener() {
private int pos = position;
#Override
public void onClick(View v) {
Toast.makeText(context,
"Details-" + String.valueOf(pos),
Toast.LENGTH_SHORT).show();
}
});
convertView.setTag(holder);
} else {
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
holder = (ViewHolder) convertView.getTag();
}
holder.textLine.setText(TitleString[position]
+ String.valueOf(position));
holder.textLine2.setText(DetailString[position]
+ String.valueOf(position));
return convertView;
}
static class ViewHolder {
TextView textLine;
TextView textLine2;
Button buttonLine;
Button DbuttonLine;
}
#Override
public Filter getFilter() {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return data[position];
}
}
}
I have seen many examples about how to refer to outer members of nested classes but not found a good example on find the view instance of an outer class for use as a method argument. Can anyone point me in the right direction?
If you look at the docs, the constructor you're invoking (new Intent(CustomListViewDemo.this, IntentA.class)), is this one:
public Intent (Context packageContext, Class<?> cls)
Since you're already storing a Context, you can fix your problem by using new Intent(this.context, IntentA.class) instead.
CustomListViewDemo.this
For this to work, you need an instance.
In a static nested class, there is no outer instance.
You have to either make the class "non-static", or explicitly pass a reference to a CustomListViewDemo instance around that you want to use here.
EfficientAdapter is a static class so you don't necessarily have an instance of CustomListViewDemo that you can use yet. Static implies that the class can be used without an instance, hence your error
"No enclosing instance of the type CustomListViewDemo is accessible in scope"
You have two options here.
1) Go with dmon's suggestion and use the context you have stored:
Intent i = new Intent(context, IntentA.class);
2) Do not make EfficientAdapter a static class (what is the reason for having it static?)