SearchView does not perform its function, how to filter this custom adapter? - android-arrayadapter

I have created a custom adapter that extends ArrayAdapter containing Listview with two TextView in a single row. I have SearchView on the ActionBar.In onQueryTextChange(String s) i have tried some methods which i have found, works but result is not correct, in the end i have only first row from ListView. How to make SearchView to work correctly?
Everything else working fine. This app is for minSdkVersion="9" and above. Any suggestion will be OK. Regards.
import android.app.SearchManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.SearchView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.ListView;
import android.widget.TextView;
public class A extends ActionBarActivity{
ListView list;
String[] titl;
String[] opis;
SearchView searchView;
VjuAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
ActionBar aB = getSupportActionBar();
aB.setDisplayHomeAsUpEnabled(true);
Resources res=getResources();
titl=res.getStringArray(R.array.naslov);
opis=res.getStringArray(R.array.podnaslov);
list=(ListView) findViewById(R.id.listView);
VjuAdapter adapter=new VjuAdapter(this, titl, opis);
adapter.getFilter().filter(null);
list.setAdapter(adapter);
list.setTextFilterEnabled(true);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
MenuInflater men = getMenuInflater();
men.inflate(R.menu.main, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
MenuItem searchItem = menu.findItem(R.id.trazi);
ComponentName cn = new ComponentName(this, A.class);
searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setSearchableInfo(searchManager.getSearchableInfo(cn));
//searchView.setOnQueryTextListener(this);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String arg0) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onQueryTextChange(String s) {
// Here i have tried some methods which i have found
// this works but result is not correct, in the end i have
// only first row from ListView
/*if (TextUtils.isEmpty(s)) {
((LayoutInflater) list.getAdapter()).getFilter().filter(s);
} else {
adapter.getFilter().filter(s.toString());
}
return true;
}
});*/
//s.toLowerCase(Locale.getDefault());
VjuAdapter vd = (VjuAdapter)list.getAdapter();
Ll.m("POCETAK VD "+ vd);
Filter filter = vd.getFilter();
Ll.m("SRED VD.GET "+ vd.getFilter());
filter.filter(s);
Ll.m("KRAJ FILTER "+ filter);
/*if (TextUtils.isEmpty(s)) {
list.clearTextFilter();
} else {
//adapter.setSelectionAfterHeaderView();
adapter.getFilter().filter(s.toString());
}*/
return true;
}
});
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
int id = item.getItemId();
/*if (id == R.id.trazi){
onSearchRequested();
}*/
if (id == android.R.id.home){
onBackPressed();
}
if (id == R.id.about){
Intent i = new Intent("com.kanna.sanjarica.ABOUT");
startActivity(i);
}
if (id == R.id.oceni_apl){
Uri uri = Uri.parse("market://details?id=" + getApplicationContext().getPackageName());
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
startActivity(goToMarket);
}
if (id == R.id.kontakt){
String mailTo="kanjah77#gmail.com";
Intent email_intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto",mailTo, null));
email_intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");
email_intent.putExtra(android.content.Intent.EXTRA_TEXT,"");
startActivity(Intent.createChooser(email_intent, "PoĊĦalji email..."));
}
return true;
}
}
class VjuAdapter extends ArrayAdapter<String>{
Context context;
String [] titlArray;
String [] opisArray;
public VjuAdapter(Context c, String[] naslov, String[] podnaslov ) {
super(c,R.layout.single_row,R.id.textView1,naslov);
this.context=c;
this.titlArray=naslov;
this.opisArray=podnaslov;
}
class MyViewHolder{
TextView textVel;
TextView textMal;
MyViewHolder(View v){
textVel=(TextView) v.findViewById(R.id.textView1);
textMal=(TextView) v.findViewById(R.id.textView2);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row=convertView;
MyViewHolder holder=null;
if(row==null){
LayoutInflater inf=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row=inf.inflate(R.layout.single_row, parent, false);
holder=new MyViewHolder(row);
row.setTag(holder);
}else{
holder=(MyViewHolder) row.getTag();
}
holder.textVel.setText(titlArray[position]);
holder.textMal.setText(opisArray[position]);
return row;
}
}

This is from http://developer.android.com/:
A concrete BaseAdapter that is backed by an array of arbitrary
objects. By default this class expects that the provided resource id
references a single TextView. If you want to use a more complex
layout, use the constructors that also takes a field id. That field id
should reference a TextView in the larger layout resource.
You have 2 TextView, and constructor class is this:
ArrayAdapter(Context context, int resource, int textViewResourceId)

Related

AutoCompleteTextView doesn't show full address (new Places SDK)

I migrated from the old Places SDK to the new Places SDK (including writing a new adapter), and now when typing an address into my AutoCompleteTextView it shows only the Place Names in the drop-down list (i.e. addresses but without city, state, country), but I need it to show the full address.
Here is my adapter:
import android.content.Context;
import android.graphics.Typeface;
import android.text.style.CharacterStyle;
import android.text.style.StyleSpan;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import androidx.annotation.NonNull;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.libraries.places.api.model.AutocompletePrediction;
import com.google.android.libraries.places.api.model.AutocompleteSessionToken;
import com.google.android.libraries.places.api.model.RectangularBounds;
import com.google.android.libraries.places.api.model.TypeFilter;
import com.google.android.libraries.places.api.net.FindAutocompletePredictionsRequest;
import com.google.android.libraries.places.api.net.FindAutocompletePredictionsResponse;
import com.google.android.libraries.places.api.net.PlacesClient;
import java.util.List;
public class PlaceAutocompleteAdapterNew extends ArrayAdapter<AutocompletePrediction> implements Filterable
{
PlacesClient placesClient;
AutocompleteSessionToken token;
private static final CharacterStyle STYLE_BOLD = new StyleSpan(Typeface.BOLD);
private List<AutocompletePrediction> mResultList;
private List<AutocompletePrediction> tempResult;
Context context;
private String TAG="PlaceAutoCompleteAdapter";
public PlaceAutocompleteAdapterNew(Context context,PlacesClient placesClient,AutocompleteSessionToken token) {
super(context,android.R.layout.simple_expandable_list_item_1,android.R.id.text1);
this.context=context;
this.placesClient=placesClient;
this.token=token;
}
public View getView(int position, View convertView, ViewGroup parent) {
View row = super.getView(position, convertView, parent);
AutocompletePrediction item = getItem(position);
TextView textView1 = (TextView) row.findViewById(android.R.id.text1);
textView1.setText(item.getPrimaryText(STYLE_BOLD));
return row;
}
#Override
public int getCount() {
return mResultList.size();
}
#Override
public AutocompletePrediction getItem(int position) {
return mResultList.get(position);
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
// Skip the autocomplete query if no constraints are given.
if (constraint != null) {
// Query the autocomplete API for the (constraint) search string.
mResultList = getAutoComplete(constraint);
if (mResultList != null) {
// The API successfully returned results.
results.values = mResultList;
results.count = mResultList.size();
}
}
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
// The API returned at least one result, update the data.
notifyDataSetChanged();
} else {
// The API did not return any results, invalidate the data set.
notifyDataSetInvalidated();
}
}
#Override
public CharSequence convertResultToString(Object resultValue) {
// Override this method to display a readable result in the AutocompleteTextView
// when clicked.
if (resultValue instanceof AutocompletePrediction) {
return ((AutocompletePrediction) resultValue).getFullText(null);
} else {
return super.convertResultToString(resultValue);
}
}
};
}
private List<AutocompletePrediction> getAutoComplete(CharSequence constraint){
// Create a new token for the autocomplete session. Pass this to FindAutocompletePredictionsRequest,
// and once again when the user makes a selection (for example when calling fetchPlace()).
AutocompleteSessionToken token = AutocompleteSessionToken.newInstance();
// Create a RectangularBounds object.
// Use the builder to create a FindAutocompletePredictionsRequest.
FindAutocompletePredictionsRequest request = FindAutocompletePredictionsRequest.builder()
// Call either setLocationBias() OR setLocationRestriction().
//.setLocationBias(bounds)
//.setLocationRestriction(bounds)
.setTypeFilter(TypeFilter.ADDRESS)
.setSessionToken(token)
.setQuery(constraint.toString())
.build();
placesClient.findAutocompletePredictions(request).addOnSuccessListener(new OnSuccessListener<FindAutocompletePredictionsResponse>() {
#Override
public void onSuccess(FindAutocompletePredictionsResponse response) {
for (AutocompletePrediction prediction : response.getAutocompletePredictions()) {
Log.i(TAG, prediction.getPrimaryText(null).toString());
}
tempResult=response.getAutocompletePredictions();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
if (exception instanceof ApiException) {
ApiException apiException = (ApiException) exception;
Log.e(TAG, "Place not found: " + apiException.getStatusCode());
}
}
});
return tempResult;
}
}
How can I show the full addresses in the drop-down list?
getAutoComplete is returning tempResult. This is a List that contains fullText (the full address), primaryText (just the address without city, state, country), and other items. So the fullText is what I want, which is being returned, but the primaryText is what is being displayed in the AutoCompleteTextView. How can I fix this?
I changed this line:
textView1.setText(item.getPrimaryText(STYLE_BOLD));
to this:
textView1.setText(item.getFullText(STYLE_BOLD));

Recyclerview Filter not working.its not searching the elements

when i filter recyclerview it shows Not found .My Searchview not working.when i run the code its result in Not Found i think there is problem in onQueryTextChange
myfilter function also did not work
#Override
public boolean onQueryTextSubmit(String query) {
Toast.makeText(SecondActivity1.this, "Name is : " + query, Toast.LENGTH_SHORT).show();
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
final List<DatabaseModel> filteredModelList = filter(dbList, newText);
if (filteredModelList.size() > 0) {
// Toast.makeText(SecondActivity1.this, "Found", Toast.LENGTH_SHORT).show();
recyclerAdapter.setFilter(filteredModelList);
return true;
} else {
Toast.makeText(SecondActivity1.this, "Not Found", Toast.LENGTH_SHORT).show();
return false;
}
private List filter(List models, String query) {
query = query.toLowerCase();
recyclerAdapter.notifyDataSetChanged();
final List<DatabaseModel> filteredModelList = new ArrayList<>();
// mRecyclerView.setLayoutManager(new LinearLayoutManager(SecondActivity1.this));
// mRecyclerView.setAdapter(RecyclerAdapter);
for (DatabaseModel model : models) {
final String text = model.getName().toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
//
}
here is filter method which recieve parameter(dblist,newtext) filter method recieves these method when i use toast its show that it takes newText But didnot filter this.i checked many sites but this is same in many sites points.when i enter name toast shows name which i enter but it did not filter
RecyclerAdapter.java
package com.example.prabhu.databasedemo;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/**
* Created by user_adnig on 11/14/15.
*/
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
List<DatabaseModel> dbList;
static Context context;
RecyclerAdapter(Context context, List<DatabaseModel> dbList ){
this.dbList = new ArrayList<>();
this.context = context;
this.dbList = (ArrayList<DatabaseModel>) dbList;
}
#Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(
R.layout.item_row, null);
// create ViewHolder
ViewHolder viewHolder = new ViewHolder(itemLayoutView);
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerAdapter.ViewHolder holder, int position) {
holder.name.setText(dbList.get(position).getName());
holder.email.setText(dbList.get(position).getEmail());
}
#Override
public int getItemCount() {
return dbList.size();
}
public void setFilter(List<DatabaseModel> countryModels) {
// Toast.makeText(RecyclerAdapter.this,"Method is called", Toast.LENGTH_SHORT).show();
dbList = new ArrayList<>();
dbList.addAll(countryModels);
notifyDataSetChanged();
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView name,email;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
name = (TextView) itemLayoutView
.findViewById(R.id.rvname);
email = (TextView)itemLayoutView.findViewById(R.id.rvemail);
itemLayoutView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent intent = new Intent(context,DetailsActivity.class);
Bundle extras = new Bundle();
extras.putInt("position",getAdapterPosition());
intent.putExtras(extras);
/*
int i=getAdapterPosition();
intent.putExtra("position", getAdapterPosition());*/
context.startActivity(intent);
Toast.makeText(RecyclerAdapter.context, "you have clicked Row " + getAdapterPosition(), Toast.LENGTH_LONG).show();
}
}
}
this is my recyclerAdapterCode.i also used Recycleradapter.setFilter(filterModeList) method but it did not work for me.i think in my set filter method error which i did not solve yet.
. But when I clear the search widget I don't get the full list instead I get the empty RecyclerView.

Android Studio, Parse.com, custom adapter, cannot resolve symbol

I am new in creating apps. I am learning by doing courses on Udemy. So right now I am learning how to create a simple app where your can register, login and post a message, and I am doing all of this using Parse.com. Everything worked perfectly until today, when it was time to create a custom adapter that shows these posts.
The error is: cannot resolve symbol mStatus in the HomepageActivity class, though in the Udemy video, everything works perfectly.
Another strange error is in the line
ParseQuery<ParseObject> query = new ParseQuery <ParseObject> ("Status");
the second <ParseObject> is greyed out and it says Explicit type argument can be replaced with <>, though in the video its white(working).
The only explanation I thought of is that the video is old and something changed in the syntax, but I am not that great of a programmer to understand what to do. Or maybe im doing something wrong? Please help.
P.S . when I am trying to run the app, I am getting this message:
Note:C:\Users\User\AndroidStudioProjects\LiveUpdate\app\src\main\java\com\mycompany\liveupdate\StatusAdapter.java uses unchecked or unsafe operations.
Here is the adapter code:
package com.mycompany.liveupdate;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.parse.ParseObject;
import java.util.List;
/**
* Created by User on 2015-01-18.
*/
public class StatusAdapter extends ArrayAdapter {
protected Context mContext;
protected List<ParseObject> mStatus;
public StatusAdapter(Context context, List status) {
super(context, R.layout.homepagecustomlayout, status);
mContext = context;
mStatus = status;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(
R.layout.homepagecustomlayout, null);
holder = new ViewHolder();
holder.usernameHomepage = (TextView) convertView
.findViewById(R.id.usernameHP);
holder.statusHomepage = (TextView) convertView
.findViewById(R.id.statusHP);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
ParseObject statusObject = mStatus.get(position);
// title
String username = statusObject.getString("user");
holder.usernameHomepage.setText(username);
// content
String status = statusObject.getString("newStatus");
holder.statusHomepage.setText(status);
return convertView;
}
public static class ViewHolder {
TextView usernameHomepage;
TextView statusHomepage;
}
}
Here is the code, where im trying to call this adapter:
package com.mycompany.liveupdate;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import com.parse.FindCallback;
import com.parse.Parse;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import java.util.List;
public class HomepageActivity extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homepage);
Parse.initialize(this, "uinXCHcfbdm8zrbUT9y8Vu4R2qU5D22FZwkHs5HZ", "v1PL4oDu3ebtSidJFhjWRkkBQVAD8sefIB1WDFeq");
ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser != null) {
// show user the homepage
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Status");
query.orderByDescending("createdAt");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> status, ParseException e) {
if(e == null){
//success
mStatus = status;
StatusAdapter adapter = new StatusAdapter(getListView().getContext(), status);
setListAdapter(adapter);
}else {
//there was a problem
}
}
});
} else {
// show the signup or login screen
Intent takeUserToLogin = new Intent(HomepageActivity.this, LogInActivity.class);
startActivity(takeUserToLogin);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_homepage, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
switch (id){
case R.id.updateStatus:
//take user to updatestatus activity
Intent intent = new Intent(this, UpdateStatusActivity.class );
startActivity(intent);
break;
case R.id.logoutUser:
// log out user
ParseUser.logOut();
// take the user back to logout screen
Intent takeUserToLogin = new Intent(this, LogInActivity.class);
startActivity(takeUserToLogin);
break;
}
return super.onOptionsItemSelected(item);
}
}

Parse search a specific user

I have found this code for searching for a specific user, using Parse. But when i run the code, it crashes.
What is wrong with the code???
The following is the link to the codes https://teamtreehouse.com/forum/tutorial-adding-search-to-ribbit-app
Here is the code
package com.twaa9l.isnap;
import java.util.List;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseQuery;
import com.parse.ParseRelation;
import com.parse.ParseUser;
import com.parse.SaveCallback;
public class EditFriendsActivity extends ListActivity {
public static final String TAG = EditFriendsActivity.class.getSimpleName();
protected List<ParseUser> mUsers;
protected ParseRelation<ParseUser> mFriendsRelation;
protected ParseUser mCurrentUser;
protected EditText sUsername;
protected Button mSearchButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_edit_friends);
// Show the Up button in the action bar.
setupActionBar();
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
#Override
protected void onResume() {
super.onResume();
mCurrentUser = ParseUser.getCurrentUser();
mFriendsRelation = mCurrentUser.getRelation(ParseConstants.KEY_FRIENDS_RELATION);
sUsername = (EditText)findViewById(R.id.searchFriend);
mSearchButton = (Button)findViewById(R.id.searchButton);
///////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////The New Code for Search Users by Username///////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////
mSearchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Get text from each field in register
String username = sUsername.getText().toString();
//String password = mPassword.getText().toString();
///Remove white spaces from any field
/// and make sure they are not empty
username = username.trim();
//password = password.trim();
//Check if fields not empty
if(username.isEmpty()){
AlertDialog.Builder builder = new AlertDialog.Builder(EditFriendsActivity.this);
builder.setMessage(R.string.login_error_message)
.setTitle(R.string.login_error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
else{
//Login User
setProgressBarIndeterminateVisibility(true);
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereEqualTo("username", username);
query.orderByAscending(ParseConstants.KEY_USERNAME);
query.setLimit(200);
query.findInBackground(new FindCallback<ParseUser>() {
#Override
public void done(List<ParseUser> users, ParseException e) {
setProgressBarIndeterminateVisibility(false);
if(e == null){
//Success we have Users to display
//Get users match us
mUsers = users;
//store users in array
String[] usernames = new String[mUsers.size()];
//Loop Users
int i = 0;
for(ParseUser user : mUsers){
usernames[i] = user.getUsername();
i++;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
EditFriendsActivity.this,
android.R.layout.simple_list_item_checked,
usernames
);
setListAdapter(adapter);
addFriendCheckmarks();
}
else{
//No Users to Display
Log.e(TAG, e.getMessage());
AlertDialog.Builder builder = new AlertDialog.Builder(EditFriendsActivity.this);
builder.setMessage(e.getMessage())
.setTitle(R.string.error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
}
}
});
}
/**
* Set up the {#link android.app.ActionBar}.
*/
private void setupActionBar() {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
if(getListView().isItemChecked(position)){
//Add Friends
mFriendsRelation.add(mUsers.get(position));
}
else{
//Remove Friend
mFriendsRelation.remove(mUsers.get(position));
}
mCurrentUser.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if(e != null){
Log.e(TAG, e.getMessage());
}
}
});
}
private void addFriendCheckmarks(){
mFriendsRelation.getQuery().findInBackground(new FindCallback<ParseUser>() {
#Override
public void done(List<ParseUser> friends, ParseException e) {
if(e == null){
//List Returned - look for a match
for(int i = 0; i < mUsers.size(); i++){
ParseUser user = mUsers.get(i);
for(ParseUser friend : friends){
if(friend.getObjectId().equals(user.getObjectId())){
//we have a match
getListView().setItemChecked(i, true);
}
}
}
}
else{
Log.e(TAG, e.getMessage());
}
}
});
}
}

How to fix checkboxes auto random selection by scrolling listview, and also shows java.lang.IndexOutOfBoundsException: Invalid index 10, size is 10

Hi i'm new to android and doing custom listview with checkbox, in that i'm facing random selection of another list item checkbox while scrolling. I have gone through some threads but didn't solve my problem. Pls help me out from this. Here is my custom adapter
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ViewRecord extends Activity {
DataBaseHelper db;
ListView listView;
Button delAll, more, setTime;
ListAdapter list;
CheckBox check;
boolean checks = false;
ArrayList<Contacts> arrayContacts = new ArrayList<Contacts>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.records);
listView = (ListView) findViewById(R.id.listview);
delAll = (Button) findViewById(R.id.delete);
more = (Button) findViewById(R.id.addMore);
setTime = (Button) findViewById(R.id.btnTime);
check = (CheckBox) findViewById(R.id.checkBox1);
loadlist();
// For adding more contacts to BlockList
more.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(ViewRecord.this, ContactList.class);
startActivity(intent);
}
});
// For selecting the whole Records to delete.....
check.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
list = new ListAdapter(getBaseContext());
checks = !checks;
for (int count =0; count<arrayContacts.size(); count++){
listView.setAdapter(list);
list.mCheckStates.put(count, checks);
list.notifyDataSetChanged();
}
// check.toggle();
}
});
}
private void loadlist() {
// TODO Auto-generated method stub
list = new ListAdapter(this);
listView.setAdapter(list);
//listView.setOnItemClickListener(this);
listView.setItemsCanFocus(false);
listView.setTextFilterEnabled(true);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
arrayContacts.clear();
// Reading DataBase Contacts.
db = new DataBaseHelper(getApplicationContext());
db.getWritableDatabase();
ArrayList<Contacts> arrayStor = db.getContacts();
for (int i = 0; i < arrayStor.size(); i++) {
String Id = arrayStor.get(i).getContactId();
String Name = arrayStor.get(i).getContactName();
String Number = arrayStor.get(i).getContactNumber();
Contacts contacts = new Contacts();
contacts.setContactId(Id);
contacts.setContactName(Name);
contacts.setContactNumber(Number);
arrayContacts.add(contacts);
}
// listView.setAdapter(new ListAdapter(this));
db.close();
}
private class ListAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener {
private SparseBooleanArray mCheckStates;
LayoutInflater inflater;
ViewHolder viewHolder;
CheckBox cb;
public ListAdapter(Context context) {
mCheckStates = new SparseBooleanArray(arrayContacts.size());
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return arrayContacts.size();
}
#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 position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if (convertView == null) {
convertView = inflater.inflate(R.layout.listview_row, null);
cb = (CheckBox) convertView.findViewById(R.id.checkox);
cb.setTag(position);
cb.setChecked(mCheckStates.get(position, false));
cb.setOnCheckedChangeListener(this);
viewHolder = new ViewHolder();
viewHolder.txtName = (TextView) convertView.findViewById(R.id.txtdisplaypname);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.txtName.setText(arrayContacts.get(position).getContactName().trim());
delAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
AlertDialog.Builder alertbox = new AlertDialog.Builder(
ViewRecord.this);
alertbox.setCancelable(true);
alertbox.setMessage("Are you sure you want to delete ?");
alertbox.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0,
int arg1) {
if(check.isChecked()==true){
db.emptyRecords();
check.toggle();
ViewRecord.this.onResume();
}else
{
for(int i = 0; i < arrayContacts.size(); i++){
{
if(mCheckStates.get(i)==true)
{
db.RemoveRecord(arrayContacts.get(i).getContactId().trim(), "", "");
System.out.println("The contact name and id is :" + arrayContacts.get(i).getContactId() + arrayContacts.get(i).getContactName());
ViewRecord.this.onResume();
}
}
}
Toast.makeText(getApplicationContext()," Records Deleted...",Toast.LENGTH_SHORT).show();
db.close();
}
}
});
alertbox.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0,
int arg1) {
}
});
alertbox.show();
db.close();
}
});
setTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
ArrayList<String> contactName = new ArrayList<String>();
ArrayList<String> contactNumber = new ArrayList<String>();
for(int i = 0; i < arrayContacts.size(); i++)
{
if(mCheckStates.get(i)==true)
{
// For sending contact names to schedule
contactName.add(arrayContacts.get(i).getContactName());
contactNumber.add(arrayContacts.get(i).getContactNumber()) ;
}
}
Intent sendIntent = new Intent (getApplicationContext(), Time_Settings.class);
sendIntent.putExtra("contactName", contactName);
sendIntent.putExtra("contactNumber", contactNumber);
// Toast.makeText(getApplicationContext(), contactName + contactNumber, 0).show();
startActivity(sendIntent);
}
});
return convertView;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, checks);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
notifyDataSetChanged();
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
private class ViewHolder {
TextView txtName;
}
}
}
Here i did a view reusing thats why it does auto checking checkboxes, just remove the braces and else part from getView this solved my problem

Resources