cursorloader selection query using like - android

I am doing search functionality using CursorLoader class.
i want to check search word present in first name or in second name.
loader fragment
public class FriendsListCursorAdapter extends CursorAdapter {
private Cursor cursor;
final VROPreferenceManager preferenceManager = new VROPreferenceManager();
Context con;
public FriendsListCursorAdapter(Context context, Cursor c, boolean b) {
super(context,c,true);
cursor = c;
con=context;
}
public void addItems(Cursor newItems) {
if (0 == newItems.getCount()) {
return;
}
notifyDataSetChanged();
}
public int getCount() {
// TODO Auto-generated method stub
return cursor.getCount();
}
cursorLoADER FRAGMENT
public class FindPeopleFragment extends BaseFragment implements LoaderCallbacks<Cursor> {
public FindPeopleFragment() {
}
private TextView advancedSearchOption;
private TextView saerchButton;
private EndlessListView listUsers;
private EditText searchWord;
private EditText searchFirstName;
private EditText searchLastName;
private EditText searchEmail;
private EditText searchCountry;
private EditText searchState;
private int offset = 0;
private final int limit = 30;
private boolean mHaveMoreDataToLoad = true;
private VROAccountManager manager;
private ArrayList<VROUser> postsList = new ArrayList<>();
private View advanced;
private Cursor FriendsCursor;
// Cursor c;
private TextView description;
long friend_name;
FriendsListCursorAdapter FRIEND_ADAPTER;
DatabaseHelper dh;
FriendinfoService friendinfoService;
String searchValue;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
title = "My Friends";
// setSelection(0);
}
private View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
friendinfoService = new FriendinfoService();
if (rootView != null) {
((ViewGroup) rootView.getParent()).removeView(rootView);
return rootView;
}
rootView = inflater.inflate(R.layout.fragment_find_people, null);
getLoaderManager().initLoader(1, null, this);
progressBar = rootView.findViewById(R.id.progressBar);
saerchButton = (TextView) rootView.findViewById(R.id.button_search);
listUsers = (EndlessListView) rootView.findViewById(R.id.user_list);
searchWord = (EditText) rootView
.findViewById(R.id.editText_search_word);
searchFirstName = (EditText) rootView
.findViewById(R.id.editText_search_first_name);
searchLastName = (EditText) rootView
.findViewById(R.id.editText_search_last_name);
searchEmail = (EditText) rootView
.findViewById(R.id.editText_search_email);
searchCountry = (EditText) rootView
.findViewById(R.id.editText_search_country);
searchState = (EditText) rootView
.findViewById(R.id.editText_search_state);
advancedSearchOption = (TextView) rootView
.findViewById(R.id.advancedSearch);
advancedSearchOption.setVisibility(View.GONE);
manager = new VROAccountManager(getActivity());
advanced = rootView.findViewById(R.id.layout_advanced_search);
description = (TextView) rootView.findViewById(R.id.description);
description
.setText("You are friends with the following users. To find new friends or to view friends request sent or received use the menu on right");
saerchButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
searchValue=searchWord.getText().toString();
getLoaderManager().initLoader(2, null, FindPeopleFragment.this);
}
});
listUsers.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Cursor mycursor = (Cursor) listUsers.getItemAtPosition(position);
VROUser user = VROUser.parse(mycursor);
Intent intent = new Intent(getActivity(), ProfileViewActivity.class);
intent.putExtra("userId", user.getUserID());
getActivity().startActivity(intent);
}
});
return rootView;
}
private final EndlessListView.OnLoadMoreListener loadMoreListener = new EndlessListView.OnLoadMoreListener() {
#Override
public boolean onLoadMore() {
if (true == mHaveMoreDataToLoad) {
//loadMoreData();
getLoaderManager().initLoader(1, null, FindPeopleFragment.this);
} else {
Toast.makeText(getActivity(), "No more data to load",
Toast.LENGTH_SHORT).show();
}
return mHaveMoreDataToLoad;
}
#Override
public void onReachedTop(boolean isTop) {
// TODO Auto-generated method stub
}
};
private final Handler handler = new Handler();
private View progressBar;
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
CursorLoader cursorLoader=null;
if(id==1) {
cursorLoader = new CursorLoader(getActivity(),
FriendinfoTable.CONTENT_URI, null, null, null, null);
}
FriendinfoTable.Cols.FRIENDSHIP_STATUS, FriendinfoTable.Cols.QUICKBLOX_ID};
if (id==2) {
FriendinfoTable.CONTENT_URI, null, selectQuery, null, null);
cursorLoader = new CursorLoader(getActivity(),
FriendinfoTable.CONTENT_URI, null, FriendinfoTable.Cols.FIRST_NAME+" like '%"+searchValue+"%' or "+FriendinfoTable.Cols.LAST_NAME+" like '%"+searchValue+"%'",null, null);
}
return cursorLoader;
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
System.out.println("Value returningggggggggggggggg" + data.getCount());
FriendsCursor = data;
try {
if (FRIEND_ADAPTER == null) {
FRIEND_ADAPTER = new FriendsListCursorAdapter(getActivity(),
FriendsCursor, true);
listUsers.setAdapter(FRIEND_ADAPTER);
} else {
FRIEND_ADAPTER.swapCursor(FriendsCursor);
}
}
catch (Exception E)
{
Log.i("ERROR",E.getMessage());
}
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
}
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.vro_contact_view, null);
bindView(view, context, cursor);
return view;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView txtID = (TextView) view.findViewById(R.id.text_fname_lname);
txtID.setText(cursor.getString(cursor.getColumnIndex("first_name")));
TextView txtCode = (TextView) view.findViewById(R.id.text_email);
txtCode.setText(cursor.getString(cursor.getColumnIndex("email")));
ImageView profilePic = (ImageView) view.findViewById(R.id.user_image);
VROUser pic = VROUser.parse(cursor);
ImageLoader.getInstance().displayImage(
preferenceManager.getResourceSertver()
+ pic.getProfilePICURL(), profilePic,
Consts.UIL_USER_AVATAR_DISPLAY_OPTIONS);
}
}
FriendInfoTable is a class where table and fields are created look like
public class FriendinfoTable {
public static final String TABLE_NAME = "friendinfotable";
public static class Cols {
public static final String ID = "_id";
public static final String FIRST_NAME = "first_name";
public static final String LAST_NAME = "last_name";
public static final String USER_NAME = "user_name";
public static final String EMAIL="email";
public static final String USER_PROFILE_PIC="user_profile_pic";
public static final String USER_TIMELINE_PIC="user_timeline_pic";
public static final String COUNTRY="country";
public static final String STATE="state";
public static final String CITY="city";
public static final String ABOUT="about";
public static final String GENDER="gender";
public static final String DATEOFBIRTH="dob";
public static final String FRIENDSHIP_STATUS="friendship_status";
public static final String QUICKBLOX_ID="quickblox_id";
}
}
this is complete code..Listview is success before search function.
please help me

For this you can use like for check a work in first and last name.
cursorLoader = new CursorLoader(getActivity(),
FriendinfoTable.CONTENT_URI, null, FIRST_NAME+" like '%"+search_work+"%' or "+SECOND_NAME+" like '%"+search_work+"%'", null, null);

Related

Delete ListiView and SQLite row in Android

I'm developing an application in Android Studio using this library: com.daimajia.swipelayout:library:1.2.0#aar. My app user a SQLite database with the following classes:
BDSQLiteHelper.java
public class BDSQLiteHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "ExtraOficial";
private static final String TABELA_VAZAMENTOS = "VazamentosToSQL";
private static final String vazID = "VazID";
private static final String nomeServico = "nomeServico";
private static final String[] VAZ_COLUNAS = {vazID, nomeServico};
public BDSQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_VAZAMENTOTABLE = "CREATE TABLE VazamentosToSQL ("+
"vazID INTEGER PRIMARY KEY AUTOINCREMENT,"+
"nomeServico)";
db.execSQL(CREATE_VAZAMENTOTABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS VazamentosToSQL");
this.onCreate(db);
}
public void addVazamentos(VazamentosToSQL VazamentosToSQL) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(nomeServico, VazamentosToSQL.getNomeServico());
db.insert(TABELA_VAZAMENTOS, null, values);
db.close();
}
public VazamentosToSQL getVazamentos (int vazID) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABELA_VAZAMENTOS,
VAZ_COLUNAS,
" vazID = ?",
new String[] {String.valueOf(vazID)},
null,
null,
null,
null);
if (cursor == null) {
return null;
} else {
cursor.moveToFirst();
VazamentosToSQL VazamentosToSQL = cursorTovazamentos(cursor);
return VazamentosToSQL;
}
}
private VazamentosToSQL cursorTovazamentos(Cursor cursor) {
VazamentosToSQL VazamentosToSQL = new VazamentosToSQL();
VazamentosToSQL.setVazID(Integer.parseInt(cursor.getString(0)));
VazamentosToSQL.setNomeServico(cursor.getString(1));
return VazamentosToSQL;
}
public ArrayList<VazamentosToSQL> getAllVazamentos() {
ArrayList<VazamentosToSQL> listaVazamentos = new ArrayList<VazamentosToSQL>();
String query = "SELECT * FROM " + TABELA_VAZAMENTOS + " ORDER BY "+ vazID + " DESC";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
do {
VazamentosToSQL VazamentosToSQL = cursorTovazamentos(cursor);
listaVazamentos.add(VazamentosToSQL);
} while (cursor.moveToNext());
}
return listaVazamentos;
}
[...]
public int deleteVazamentos(VazamentosToSQL VazamentosToSQL) {
SQLiteDatabase db = this.getWritableDatabase();
int i = db.delete(TABELA_VAZAMENTOS,
vazID+" =?",
new String[] { String.valueOf(VazamentosToSQL.getVazID())});
db.close();
return i;
}
VazamentosToSQL.java
public class VazamentosToSQL {
private int vazID;
private String nomeServico;
public int getVazID() { return vazID; }
public void setVazID(int vazID) {
this.vazID = vazID;
}
public String getNomeServico() { return nomeServico; }
public void setNomeServico(String nomeServico) { this.nomeServico = nomeServico; }
}
ListViewActivity.java:
[...]
//variables
private BDSQLiteHelper bd;
ArrayList<VazamentosToSQL> listaVazamentos;
SwipeLayout swipeLayout;
private final static String TAG = ListViewActivity.class.getSimpleName();
vazamentosAdapter adapter;
ListView lista;
[...]
#Override
protected void onCreate(Bundle savedInstanceState)
{super.onCreate(savedInstanceState);
[...]
bd = new BDSQLiteHelper(this);
lista = (ListView) findViewById(R.id.lvdenuncias);
listaVazamentos = bd.getAllVazamentos();
setListViewHeader();
setListViewAdapter();
lista.setOnItemClickListener(new AdapterView.OnItemClickListener() { //aqui é o vazamentosAdapter
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(ExibeVazamentosActivity.this, DetalhesVazamentosActivity.class);
intent.putExtra("vazID", listaVazamentos.get(position).getVazID());
startActivity(intent);
}
});
#Override
protected void onStart() {
super.onStart();
updateAdapter(); //Refresh ListView items
}
private void setListViewHeader() {
LayoutInflater inflater = getLayoutInflater();
View header = inflater.inflate(R.layout.header_listview, lista, false);
totalClassmates = (TextView) header.findViewById(R.id.total);
swipeLayout = (SwipeLayout)header.findViewById(R.id.swipe_layout);
setSwipeViewFeatures();
//UNNECESSARY for me: lista.addHeaderView(header);
}
private void setSwipeViewFeatures() {
swipeLayout.setShowMode(SwipeLayout.ShowMode.PullOut);
//add drag edge.(If the BottomView has 'layout_gravity' attribute, this line is unnecessary)
swipeLayout.addDrag(SwipeLayout.DragEdge.Left, findViewById(R.id.bottom_wrapper));
swipeLayout.addSwipeListener(new SwipeLayout.SwipeListener() {
#Override
public void onClose(SwipeLayout layout) {
Log.i(TAG, "onClose");
}
#Override
public void onUpdate(SwipeLayout layout, int leftOffset, int topOffset) {
Log.i(TAG, "on swiping");
}
#Override
public void onStartOpen(SwipeLayout layout) {
Log.i(TAG, "on start open");
}
#Override
public void onOpen(SwipeLayout layout) {
Log.i(TAG, "the BottomView totally show");
}
#Override
public void onStartClose(SwipeLayout layout) {
Log.i(TAG, "the BottomView totally close");
}
#Override
public void onHandRelease(SwipeLayout layout, float xvel, float yvel) {
//when user's hand released.
}
});
}
private void setListViewAdapter() {
adapter = new vazamentosAdapter(this, listaVazamentos);
lista.setAdapter(adapter);
}
public void updateAdapter() {
listaVazamentos.clear();
listaVazamentos.addAll(bd.getAllVazamentos());
adapter.notifyDataSetChanged(); //update adapter
lista.invalidateViews();
lista.refreshDrawableState();
}
}
vazamentosAdapter.java:
public class vazamentosAdapter extends ArrayAdapter<VazamentosToSQL> {
private final Context context;
private final ArrayList<VazamentosToSQL> elementos;
File imgFile;
private Bitmap bitmap;
private ExifInterface exifObject;
private ExibeVazamentosActivity activity;
int vazID;
private SQLiteDatabase bd;
public vazamentosAdapter(Context context, ArrayList<VazamentosToSQL> elementos) {
super(context, R.layout.linha, elementos);
this.context = context;
this.elementos = elementos;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
// inflate UI from XML file
convertView = inflater.inflate(R.layout.linha, parent, false);
// get all UI view
holder = new ViewHolder(convertView);
// set tag for holder
convertView.setTag(holder);
}else {
// if holder created, get tag from view
holder = (ViewHolder) convertView.getTag();
}
[...]
editText.setText(elementos.get(position).getVaznomeServico());
holder.btnEdit.setOnClickListener(onEditListener(position, holder));
holder.btnDelete.setOnClickListener(onDeleteListener(position, holder));
return convertView;
}
private View.OnClickListener onDeleteListener(final int position, final ViewHolder holder) {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
/**--------------Tried it, not working =( ---------------*/
elementos.get(position).getVazID();
//listaVazamentos.remove(position);
//activity.listaVazamentos.remove(position);
//bd = context.openOrCreateDatabase("DesoExtraOficial", Activity.MODE_PRIVATE, null);
//bd.execSQL("DELETE from VazamentosToSQL where vazID = '" + elementos.get(position).getVazID() + "'");
//bd.close();
//elementos.remove(position);
Toast.makeText(context, "ID: "+elementos.get(position).getVazID(),Toast.LENGTH_LONG).show();
bd.deleteVazamentos(VazamentosToSQL);
holder.swipeLayout.close();
// activity.updateAdapter(); //Executa o método "updateAdapter()" na Activity "ExibeVazamentos"
/**--------------Tried it, not working =( ---------------*/
}
};
}
private class ViewHolder {
private TextView name;
private View btnDelete;
private View btnEdit;
private SwipeLayout swipeLayout;
private ListView listv;
public ViewHolder(View v) {
swipeLayout = (SwipeLayout)v.findViewById(R.id.swipe_layout);
btnDelete = v.findViewById(R.id.delete);
btnEdit = v.findViewById(R.id.edit_query);
listv = (ListView) v.findViewById(R.id.lvdenuncias);
swipeLayout.setShowMode(SwipeLayout.ShowMode.PullOut);
}
}
The mentioned library is working great. But i'm trying to delete database row when user click in a button according to the listview selected line. With this code: elementos.get(position).getVazID() I get the database index. But I can't delete from database. Someone can help me with the code to delete row from database and line from listview?
Try changing this:
public int deleteVazamentos(VazamentosToSQL VazamentosToSQL) {
SQLiteDatabase db = this.getWritableDatabase();
int i = db.delete(TABELA_VAZAMENTOS, vazID+" =?", new String[] { String.valueOf(VazamentosToSQL.getVazID())});
db.close();
return i;
}
To this:
public void deleteVazamentos(int vazID) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABELA_VAZAMENTOS, "vazID=" + vazID, null);
}
Then if you want to delete a row, you can call:
(Inside onDeleteListener)
bd.deleteVazamentos(elementos.get(position).getVazID());

listview shows first Item of cursor on every row

I have listView in my fragment i use a cursorAdapter to fill the list view but problem is Adapter shows first row data on every item if there are 3 items in cursor listview show three items but all are same i search a lot but i found nothing usefull
fragment:
public class ListPatientFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
private PatientAdapter mPatientAdapter;
private ListView mListView;
private Button mAddButton;
private int mPosition = ListView.INVALID_POSITION;
private static final String SELECTED_KEY = "selected_position";
public ListPatientFragment() {
}
public interface Callback {
/**
* DetailFragmentCallback for when an item has been selected.
*/
public void onItemSelected(Uri dateUri);
}
private static final String[] FORECAST_COLUMNS = {
MedicalContract.PropertyEntry.TABLE_NAME + "." + MedicalContract.PropertyEntry._ID,
MedicalContract.PropertyEntry.COLUMN_DATE,
MedicalContract.PropertyEntry.COLUMN_SEX,
MedicalContract.PropertyEntry.COLUMN_AGE,
MedicalContract.PropertyEntry.COLUMN_CHIEF_COMPLIMENT,
MedicalContract.PropertyEntry.COLUMN_RESIDENT_ILLNESS,
MedicalContract.PatientEntry.COLUMN_PATIENT_SETTING,
MedicalContract.PropertyEntry.COLUMN_NAME_KEY,
MedicalContract.PatientEntry.COLUMN_PATIENT_IDENTIFICATION,
MedicalContract.PatientEntry.COLUMN_PATIENT_SETTING,
MedicalContract.PatientEntry.COLUMN_FIRST_NAME,
MedicalContract.PatientEntry.COLUMN_LAST_NAME
};
static final int COL_PROPERTY_ID = 1;
static final int COL_DATE = 2;
static final int COL_SEX = 3;
// this is correct:
static final int COL_AGE = 4;
//this is correct:
static final int COL_RESIDENT_ILLNESS = 6;
//this is correct:
static final int COL_CHIEF_COMPLIMENT = 5;
static final int COL_PATIENT_IDENTIFICATION = 8;
static final int COL_PATIENT_SETTING = 9;
static final int COL_FIRST_NAME = 10;
static final int COL_LAST_NAME =11;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_list_patient, container, false);
//return inflater.inflate(R.layout.fragment_list_patient, container, false);
String sortOrder = MedicalContract.PropertyEntry.COLUMN_DATE + " DESC";
Uri allPatientUri = MedicalContract.PropertyEntry.buildAllPatientList(System.currentTimeMillis());
Cursor cur = getActivity().getContentResolver().query(allPatientUri,
null, null, null, sortOrder);
mPatientAdapter = new PatientAdapter(getActivity(), cur, 0);
mListView = (ListView) rootView.findViewById(R.id.MainListOfAllPatients);
mListView.setAdapter(mPatientAdapter);
mAddButton =(Button) rootView.findViewById(R.id.New_Patient_Button);
assert mAddButton !=null;
mAddButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent MyIntent= new Intent (getActivity(),MedicalActivity.class);
startActivity(MyIntent);
}
});
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView adapterView, View view, int position, long l) {
// CursorAdapter returns a cursor at the correct position for getItem(), or null
// if it cannot seek to that position.
Cursor cursor = (Cursor) adapterView.getItemAtPosition(position);
if (cursor != null) {
Toast.makeText(getActivity(),cursor.getString(COL_DATE),Toast.LENGTH_SHORT).show();
String PatientIdentification = cursor.getString(COL_PATIENT_IDENTIFICATION);
Long PatientDate=cursor.getLong(COL_PROPERTY_ID);
((Callback) getActivity())
.onItemSelected(MedicalContract.PropertyEntry.buildPropertyPatientWithDate(PatientIdentification,PatientDate));
}
mPosition = position;
}
});
return rootView;
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String sortOrder = MedicalContract.PropertyEntry.COLUMN_DATE + " DESC";
Uri listOfAllPatientUri = MedicalContract.PropertyEntry.buildAllPatientList(System.currentTimeMillis());
return new CursorLoader(getActivity(),
listOfAllPatientUri,
FORECAST_COLUMNS,
null,
null,
sortOrder);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
mPatientAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
}
}
adapter:
public class PatientAdapter extends CursorAdapter {
public PatientAdapter(Context context, Cursor c, int flags) {
super(context, c, flags);
}
public static class ViewHolder {
public final ImageView iconView;
public final TextView patientFirstNameView;
public final TextView patientLastNameView;
public final TextView patientAgeView;
public final TextView patientResidentIllnessView;
public ViewHolder(View view) {
iconView = (ImageView) view.findViewById(R.id.list_item_icon);
patientFirstNameView = (TextView) view.findViewById(R.id.patient_first_name);
patientLastNameView = (TextView) view.findViewById(R.id.patient_last_name);
patientAgeView = (TextView) view.findViewById(R.id.patient_age);
patientResidentIllnessView = (TextView) view.findViewById(R.id.patient_resident_illness);
}
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
int layoutId = -1;
layoutId = R.layout.detail_list_patient;
View view = LayoutInflater.from(context).inflate(layoutId, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
view.setTag(viewHolder);
return view;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder viewHolder = (ViewHolder) view.getTag();
if(cursor != null &&cursor.moveToFirst()) {
String patientSex = cursor.getString(ListPatientFragment.COL_SEX);
if (patientSex.equals("Male")) {
viewHolder.iconView.setImageResource(R.mipmap.ic_male_icon);
} else if (patientSex.equals("Female")) {
viewHolder.iconView.setImageResource(R.mipmap.ic_female_icon);
}
String patientFirstName = cursor.getString(ListPatientFragment.COL_FIRST_NAME);
viewHolder.patientFirstNameView.setText(patientFirstName);
String patientLastName = cursor.getString(ListPatientFragment.COL_LAST_NAME);
viewHolder.patientLastNameView.setText(patientLastName);
String patientAge = cursor.getString(ListPatientFragment.COL_AGE);
viewHolder.patientAgeView.setText(patientAge);
String patientIllness = cursor.getString(ListPatientFragment.COL_RESIDENT_ILLNESS);
viewHolder.patientResidentIllnessView.setText(patientIllness);
}
}
}
XML listView:
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/MainListOfAllPatients"
android:background="#color/ColorPrimaryLight"></ListView>

ViewPager.setCurrentItem shows previous item and not the selected item

ViewPager.setCurrentItem shows previous item and not the selected item. I am trying to show a list view from an sqlite database.
The data is shown properly in the listview, onitemclick it should pass the position as an intent to the the next activity which has a viewpager .
The viewpager works fine and all the data is shown ,except for ViewPager.setCurrentItem a simple task of showing the data related to the position send as intent a previous item is shown.
What need to be done to show exactly the selected item.
Here is the listactivity code
public class MainActivity extends ListActivity {
private static final String DB_NAME = "db.sqlite";
private static final String TABLE_NAME = "Posts";
private static final String FRIEND_ID = "col_2";
private static final String FRIEND_NAME = "col_3";
private SQLiteDatabase database;
private ListView listView;
private ArrayList<String> friends;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ExternalDbOpenHelper dbOpenHelper = new ExternalDbOpenHelper(this, DB_NAME);
database = dbOpenHelper.openDataBase();
fillFreinds();
setUpList();
}
private void setUpList() {
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, friends));
listView = getListView();
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position,long id) {
Toast.makeText(getApplicationContext(),
((TextView) view).getText().toString(),
Toast.LENGTH_SHORT).show();
//startActivity(new Intent(getApplicationContext(), viepagerActivity.class));
Intent i = new Intent(MainActivity.this, viepagerActivity.class);
i.putExtra("position", position);
MainActivity.this.startActivity(i);
}
});
}
private void fillFreinds() {
friends = new ArrayList<String>();
Cursor friendCursor = database.query(TABLE_NAME,
new String[]
{FRIEND_ID, FRIEND_NAME},
null, null, null, null
, FRIEND_ID);
friendCursor.moveToFirst();
if(!friendCursor.isAfterLast()) {
do {
String name = friendCursor.getString(0);
friends.add(name);
} while (friendCursor.moveToNext());
}
friendCursor.close();
}
}
and here is the Viewpager Activity
public class viepagerActivity extends Activity {
private List<String> testContactName = new ArrayList<String>();
private List<String> testContactNumber = new ArrayList<String>();
MyAdapter mAdapter;
public ViewPager mViewPager;
private ExternalDbOpenHelper databaseHelper;
private SQLiteDatabase database;
private static final String DB_NAME = "db.sqlite";
private static final String TABLE_NAME = "Posts";
private static final String FRIEND_ID = "col_2";
private static final String FRIEND_NAME = "col_3";
private ListView listView;
private ArrayList<String> friends;
WebView webView;
String mimeType = "text/html";
String encoding = "utf-8";
int index;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main1);
databaseHelper = new ExternalDbOpenHelper(this, DB_NAME);
database = databaseHelper.openDataBase();
mViewPager = (ViewPager) findViewById(R.id.pager);
mAdapter = new MyAdapter();
if (mViewPager.getAdapter() != null)
mViewPager.setAdapter(null);
mViewPager.setAdapter(mAdapter);
Bundle b = getIntent().getExtras();
index = b.getInt("position");
mViewPager.postDelayed(new Runnable() {
#Override
public void run() {
mViewPager.setCurrentItem(index);
}
}, 10);
try {
getAllContacts();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void getAllContacts() {
//SQLiteDatabase db = databaseHelper.database;
Cursor cursor = database.query(TABLE_NAME,
new String[]
{FRIEND_ID, FRIEND_NAME},
null, null, null, null
, null);
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex(cursor
.getColumnName(0)));
String phoneNumber = cursor.getString(cursor.getColumnIndex(cursor
.getColumnName(1)));
testContactName.add(name);
mAdapter.notifyDataSetChanged();
testContactNumber.add(phoneNumber);
mAdapter.notifyDataSetChanged();
}
cursor.close();
}
private class MyAdapter extends PagerAdapter {
public MyAdapter() {
super();
}
#Override
public int getCount() {
return testContactName.size();
}
#Override
public boolean isViewFromObject(View collection, Object object) {
return collection == ((View) object);
}
#Override
public Object instantiateItem(View collection, final int position) {
Bundle b = getIntent().getExtras();
LayoutInflater inflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.viewpager_items, null);
TextView contactName = (TextView) view.findViewById(R.id.labelText);
// TextView contactNumber = (TextView) view
// .findViewById(R.id.answerText);
webView = (WebView)findViewById(R.id.webview);
try {
//contactName.setText(testContactName.get(position));
contactName.setText("Details");
//contactNumber.setText(testContactNumber.get(position));
String pish = "<html><head><style type=\"text/css\">#font-face {font-family: MyFont;src: url(\"file:///assets/DroidHindi.ttf\")}body {font-family: MyFont;font-size: medium;text-align: justify;}</style></head><body>";
String pas = "</body></html>";
String myHtmlString = pish + testContactNumber.get(position) + pas;
//webView.loadData(myHtmlString, mimeType, encoding);
webView.loadDataWithBaseURL("", testContactNumber.get(position), "text/html", "UTF-8", null);
}
catch(Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
((ViewPager)collection).addView(view, 0);
return view;
}
#Override
public void destroyItem(View collection, int position, Object view) {
((ViewPager) collection).removeView((View) view);
mAdapter.notifyDataSetChanged();
}
}
}

Search functionality in Android Custom ListView from database using CursorLoader and CursorAdapter

I have CursorAdapter to show data from database usin CursorLoader. Now, I want add search functionality to custom listview. So, I tried with this. but, this is not working.
public class FindPeopleFragment extends BaseFragment implements LoaderCallbacks<Cursor> {
public FindPeopleFragment() {
}
private TextView advancedSearchOption;
private TextView saerchButton;
private EndlessListView listUsers;
private EditText searchWord;
private EditText searchFirstName;
private EditText searchLastName;
private EditText searchEmail;
private EditText searchCountry;
private EditText searchState;
private int offset = 0;
private final int limit = 30;
private boolean mHaveMoreDataToLoad = true;
private VROAccountManager manager;
private ArrayList<VROUser> postsList = new ArrayList<>();
private View advanced;
private Cursor FriendsCursor;
private Cursor FriendsCursorTemp;
// Cursor c;
private TextView description;
long friend_name;
FriendsListCursorAdapter FRIEND_ADAPTER;
DatabaseHelper dh;
FriendinfoService friendinfoService;
String searchValue;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
title = "My Friends";
}
private View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
friendinfoService = new FriendinfoService();
if (rootView != null) {
((ViewGroup) rootView.getParent()).removeView(rootView);
return rootView;
}
rootView = inflater.inflate(R.layout.fragment_find_people, null);
getLoaderManager().initLoader(1, null, this);
saerchButton = (TextView) rootView.findViewById(R.id.button_search);
listUsers = (EndlessListView) rootView.findViewById(R.id.user_list);
searchWord = (EditText) rootView
.findViewById(R.id.editText_search_word);
searchFirstName = (EditText) rootView
.findViewById(R.id.editText_search_first_name);
searchLastName = (EditText) rootView
.findViewById(R.id.editText_search_last_name);
searchEmail = (EditText) rootView
.findViewById(R.id.editText_search_email);
searchCountry = (EditText) rootView
.findViewById(R.id.editText_search_country);
searchState = (EditText) rootView
.findViewById(R.id.editText_search_state);
advancedSearchOption = (TextView) rootView
.findViewById(R.id.advancedSearch);
advancedSearchOption.setVisibility(View.GONE);
manager = new VROAccountManager(getActivity());
advanced = rootView.findViewById(R.id.layout_advanced_search);
description = (TextView) rootView.findViewById(R.id.description);
description
.setText("You are friends with the following users. To find new friends or to view friends request sent or received use the menu on right");
searchOption.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int start, int before, int count) {
AbstractActivity.this.cursorAdapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
listUsers.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Cursor mycursor = (Cursor) listUsers.getItemAtPosition(position);
VROUser user = VROUser.parse(mycursor);
Intent intent = new Intent(getActivity(), ProfileViewActivity.class);
intent.putExtra("userId", user.getUserID());
getActivity().startActivity(intent);
//Toast.makeText(getActivity(), " " + FriendsCursor.getColumnIndex("user_profile_pic"), Toast.LENGTH_SHORT).show();
}
});
return rootView;
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
CursorLoader cursorLoader=null;
if(id==1) {
cursorLoader = new CursorLoader(getActivity(),
FriendinfoTable.CONTENT_URI, null, null, null, null);
}
if (id==2) {
cursorLoader = new CursorLoader(getActivity(),
FriendinfoTable.CONTENT_URI, null,
FriendinfoTable.Cols.FIRST_NAME+" like '%"+searchValue+"%' or "+FriendinfoTable.Cols.LAST_NAME+" like '%"+searchValue+"%'",
null, null);
}
return cursorLoader;
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
System.out.println("Value returningnnnnnnnnnnnnnnnnnnnnnnnnnnn " + data.getCount());
FriendsCursor = data;
if (FRIEND_ADAPTER == null) {
FRIEND_ADAPTER = new FriendsListCursorAdapter(getActivity(),
FriendsCursor, true);
listUsers.setAdapter(FRIEND_ADAPTER);
FRIEND_ADAPTER = null;
} else {
FRIEND_ADAPTER.swapCursor(FriendsCursor);
}
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
}
}
and adapter class code
public class FriendsListCursorAdapter extends CursorAdapter {
private Cursor cursor;
final VROPreferenceManager preferenceManager = new VROPreferenceManager();
Context con;
public FriendsListCursorAdapter(Context context, Cursor c, boolean b) {
super(context,c,true);
cursor = c;
con=context;
}
public void addItems(Cursor newItems) {
if (0 == newItems.getCount()) {
return;
}
notifyDataSetChanged();
}
public int getCount() {
// TODO Auto-generated method stub
return cursor.getCount();
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.vro_contact_view, null);
bindView(view, context, cursor);
return view;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView txtID = (TextView) view.findViewById(R.id.text_fname_lname);
txtID.setText(cursor.getString(cursor.getColumnIndex("first_name")));
TextView txtCode = (TextView) view.findViewById(R.id.text_email);
txtCode.setText(cursor.getString(cursor.getColumnIndex("email")));
ImageView profilePic = (ImageView) view.findViewById(R.id.user_image);
VROUser pic = VROUser.parse(cursor);
ImageLoader.getInstance().displayImage(
preferenceManager.getResourceSertver()
+ pic.getProfilePICURL(), profilePic,
Consts.UIL_USER_AVATAR_DISPLAY_OPTIONS);
}
}
I will be glad if you guys help to find out what's the problem in my code or how can i add search functionality to a custom listview.
Implement the interface Filter in your adapter and override the getfilter() method.
below is the short example.
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
//your logic
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
//final updated arraylist
}
};
return filter;
}

filtering of android listview using CursorAdapter not working

I have created a list view in android and I want to add edit text above the list and when the user enter text the list will be filtered according to user input.listview in fragmentcode like below:
public class FindPeopleFragment extends BaseFragment implements LoaderCallbacks<Cursor> {
public FindPeopleFragment() {
}
private TextView advancedSearchOption;
private TextView saerchButton;
private EndlessListView listUsers;
private EditText searchWord;
private EditText searchFirstName;
private EditText searchLastName;
private EditText searchEmail;
private EditText searchCountry;
private EditText searchState;
private int offset = 0;
private final int limit = 30;
private boolean mHaveMoreDataToLoad = true;
private VROAccountManager manager;
private ArrayList<VROUser> postsList = new ArrayList<>();
private View advanced;
private Cursor FriendsCursor;
private Cursor FriendsCursorTemp;
// Cursor c;
private TextView description;
long friend_name;
FriendsListCursorAdapter FRIEND_ADAPTER;
DatabaseHelper dh;
FriendinfoService friendinfoService;
String searchValue;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
title = "My Friends";
// setSelection(0);
}
private View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
friendinfoService = new FriendinfoService();
if (rootView != null) {
((ViewGroup) rootView.getParent()).removeView(rootView);
return rootView;
}
rootView = inflater.inflate(R.layout.fragment_find_people, null);
getLoaderManager().initLoader(1, null, this);
// progressBar = rootView.findViewById(R.id.progressBar);
saerchButton = (TextView) rootView.findViewById(R.id.button_search);
listUsers = (EndlessListView) rootView.findViewById(R.id.user_list);
searchWord = (EditText) rootView
.findViewById(R.id.editText_search_word);
searchFirstName = (EditText) rootView
.findViewById(R.id.editText_search_first_name);
searchLastName = (EditText) rootView
.findViewById(R.id.editText_search_last_name);
searchEmail = (EditText) rootView
.findViewById(R.id.editText_search_email);
searchCountry = (EditText) rootView
.findViewById(R.id.editText_search_country);
searchState = (EditText) rootView
.findViewById(R.id.editText_search_state);
advancedSearchOption = (TextView) rootView
.findViewById(R.id.advancedSearch);
advancedSearchOption.setVisibility(View.GONE);
manager = new VROAccountManager(getActivity());
advanced = rootView.findViewById(R.id.layout_advanced_search);
description = (TextView) rootView.findViewById(R.id.description);
dh=new DatabaseHelper(getActivity());
description
.setText("You are friends with the following users. To find new friends or to view friends request sent or received use the menu on right");
searchWord.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
FindPeopleFragment.this.FRIEND_ADAPTER.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
#Override
public void afterTextChanged(Editable arg0) {
}
});
listUsers.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Cursor mycursor = (Cursor) listUsers.getItemAtPosition(position);
VROUser user = VROUser.parse(mycursor);
Intent intent = new Intent(getActivity(), ProfileViewActivity.class);
intent.putExtra("userId", user.getUserID());
getActivity().startActivity(intent);
}
});
return rootView;
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
CursorLoader cursorLoader=null;
if(id==1) {
cursorLoader = new CursorLoader(getActivity(),
FriendinfoTable.CONTENT_URI, null, null, null, null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
System.out.println("Value returningnnnnnnnnnnnnnnnnnnnnnnnnnnn " + data.getCount());
FriendsCursor = data;
if (FRIEND_ADAPTER == null) {
FRIEND_ADAPTER = new FriendsListCursorAdapter(getActivity(),
FriendsCursor, true);
listUsers.setAdapter(FRIEND_ADAPTER);
FRIEND_ADAPTER = null;
} else {
FRIEND_ADAPTER.swapCursor(FriendsCursor);
}
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
}
}
and CursorAdapter is coded as
public class FriendsListCursorAdapter extends CursorAdapter implements Filterable {
private Cursor cursor;
final VROPreferenceManager preferenceManager = new VROPreferenceManager();
Context con;
String cString;
List<String> arrayListNames;
public FriendsListCursorAdapter(Context context, Cursor c, boolean b) {
super(context,c,true);
cursor = c;
con=context;
}
public void addItems(Cursor newItems) {
if (0 == newItems.getCount()) {
return;
}
notifyDataSetChanged();
}
public int getCount() {
// TODO Auto-generated method stub
return cursor.getCount();
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.vro_contact_view, null);
bindView(view, context, cursor);
return view;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView txtID = (TextView) view.findViewById(R.id.text_fname_lname);
txtID.setText(cursor.getString(cursor.getColumnIndex("first_name")));
TextView txtCode = (TextView) view.findViewById(R.id.text_email);
txtCode.setText(cursor.getString(cursor.getColumnIndex("email")));
ImageView profilePic = (ImageView) view.findViewById(R.id.user_image);
VROUser pic = VROUser.parse(cursor);
ImageLoader.getInstance().displayImage(
preferenceManager.getResourceSertver()
+ pic.getProfilePICURL(), profilePic,
Consts.UIL_USER_AVATAR_DISPLAY_OPTIONS);
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
FilterResults results = new FilterResults();
ArrayList<String> FilteredArrayNames = new ArrayList<String>();
// perform your search here using the searchConstraint String.
cString = charSequence.toString().toLowerCase();
for (int i = 0; i < cursor.getCount(); i++) {
String dataNames = cursor.getString(i);
if (dataNames.toLowerCase().startsWith(cString.toString())) {
FilteredArrayNames.add(dataNames);
}
}
results.count = FilteredArrayNames.size();
results.values = FilteredArrayNames;
// Log.e("VALUES", results.values.toString());
return results;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
arrayListNames = (List<String>) filterResults.values;
notifyDataSetChanged();
}
};
return filter;
}
}
but i got an error like
java.lang.NullPointerException: Attempt to invoke virtual method 'android.widget.Filter vro.nagainfo.vromain.ui.adaptors.FriendsListCursorAdapter.getFilter()' on a null object reference at line
FindPeopleFragment.this.FRIEND_ADAPTER.getFilter().filter(cs);
please help me to find the solution.

Categories

Resources