I am trying to implement search on user input. The serach results will be shown after searching the relevant option from database.
I have made this method to display the results
public Cursor getBooksBySearch(String query) {
// TODO Auto-generated method stub
String[] args={query};
return(getReadableDatabase().rawQuery("SELECT _id,chapter FROM chapters WHERE chapter LIKE '%" + query + "%", args));
}
Here the query is coming from an activity SearchResultAcitvity.java
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
ListView myListView = (ListView)findViewById(R.id.txt_query);
dbBookHelper = new BooklistHelper(this);
ourCursor = dbBookHelper.getBooksBySearch(query);
startManagingCursor(ourCursor);
adapter = new BookAdapter(ourCursor);
myListView.setAdapter(adapter);
myListView.setOnItemClickListener(onListClick);
}
I want to match this coming query string to get the results from my chapter table.
Can I just match the query string m getting in String query = intent.getStringExtra(SearchManager.QUERY) with the data in my database.
Using list view to display.
Please help me in this.
Let me know if you want more information
Thanks in Advance :)
This will return list of data search by keyword
public ArrayList<ObjectType> getSearchData(String keyword)
{
ArrayList<ObjectType> objectTypeList = new ArrayList<ObjectType>();
SQLiteDatabase db = getWritableDatabase();
String checkEntry="SELECT id,firstname,lastname FROM abc_table WHERE firstname like '%"+ keyword +"%'" +" or "+ "p.lastname like '%"+ keyword +"%'";
Cursor cursor = db.rawQuery(checkEntry, null);
try
{
//If entry exist then update
if (cursor.moveToFirst())
{
do
{
ObjectType objectType = new ObjectType();
int PID=cursor.getInt(0);
String fname = cursor.getString(1);
String LastName = cursor.getString(2);
objectType.setFirstName(fname);
objectType.setLastName(LastName);
objectTypeList.add(objectType);
}
while(cursor.moveToNext());
}
}
finally
{
if(cursor != null)
cursor.close();
}
return objectTypeList;
}
ObjectType is class
public class ObjectType {
int id;
String firstName;
String lastName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
Hope this ll help you.. :)
Related
I'm trying to pass objects from a SQLite database to a fragment, but they're getting nulled somewhere along the way.
The Log.i line in DatabaseHelper outputs as expected, but the Log.i line in CollectionsFragment does not -- it returns the correct number of values, but all of them are null.
I feel like logging collectionsList in DatabaseHelper would be useful, but I'm not sure how to do that with an ArrayList.
Snippet from DatabaseHelper:
public List<Book> getAllCollections(int authorID) {
List<Book> collectionsList = new ArrayList<>();
// Select all query
String selectQuery = "SELECT DISTINCT collection FROM " + BOOKS + " WHERE author_id = '" + authorID + "'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Book book = new Book();
book.setCollection(cursor.getString(0));
Log.i("stories", cursor.getString(0)); // returns with correct values
collectionsList.add(book);
} while (cursor.moveToNext());
}
return collectionsList;
// not sure how to log collectionsList here
}
Snippet from CollectionsFragment:
// link ListView object with XML ListView
collectionsListView = (ListView) view.findViewById(R.id.collections_list_view);
// create new instance of DatabaseHelper
DatabaseHelper db = new DatabaseHelper(getActivity());
// return view;
// create list of collections through getAllCollections method
List<Book> collectionsList = db.getAllCollections(authorID);
Log.i("testing", collectionsList.toString()); // returns [null, null]
// create new ArrayAdapter
ArrayAdapter<Book> arrayAdapter =
new ArrayAdapter<Book>(getActivity(), android.R.layout.simple_list_item_1, collectionsList);
// link ListView and ArrayAdapter
collectionsListView.setAdapter(arrayAdapter);
Book Class:
public class Book {
int id;
String title;
int author_id;
String collection;
String body;
#Override
public String toString() {
return title;
}
public Book() {
}
public Book(int id, String title, int author_id, String collection, String body) {
this.id = id;
this.title = title;
this.author_id = author_id;
this.collection = collection;
this.body = body;
}
// getters
public int getStoryID() {
return this.id;
}
public String getTitle() {
return this.title;
}
public int getAuthorID() {
return this.author_id;
}
public String getCollection() {
return this.collection;
}
public String getBody() {
return this.body;
}
// setters
public void setStoryID(int id) {
this.id = id;
}
public void setTitle(String title) {
this.title = title;
}
public void setAuthorID(int author_id) {
this.author_id = author_id;
}
public void setCollection(String collection) {
this.collection = collection;
}
public void setBody(String body) {
this.body = body;
}
}
I am making small app. It has 2 listview on MainActivity.
DB is SQLLite and has tree cloumns id(int), person(text), status(text).
Firt listview will be show informations from DB with this query
select * from DB where status=B
And next ListView will show information where status=A.
lv1.status=b | lv2.status=a
Person 1 | Person 2
Person 3 | Person 4
When i click lv2 on item, value of clicked lv2 field 'status' must change to 'b'.
But I can not write right query for db.
public void changeUser(){
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_STATUS, "B");
db.update(TABLE_ORDER, values, null, null);
db.close();
}
Thanks
Here is my code
lvB = (ListView)findViewById(R.id.lvB);
listClientB();
lvA = (ListView)findViewById(R.id.lvA);
listClientA();
lvA.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
User user = (User)adapterView.getAdapter().getItem(i);
int id = user.get_id();
if (user.getStatus().contains("A")){
dbHelper.changeUser();
}
Toast.makeText(getApplicationContext(), id + "-NUMBER id", Toast.LENGTH_LONG).show();
Log.d(String.valueOf(user.get_id()), "-NUMBER id");
listClientA();
Log.d(user.getStatus(), "Pressed");
}
});
}
private void listClientA(){
list = dbHelper.allUsersA();
klientStatusAdapter = new KlientStatusAdapter(MainActivity.this, list);
lvA.setAdapter(klientStatusAdapter);
lvA.setTextFilterEnabled(true);
}
private void listClientB(){
list = dbHelper.allUsersB();
klientStatusAdapter = new KlientStatusAdapter(MainActivity.this, list);
lvB.setAdapter(klientStatusAdapter);
lvB.setTextFilterEnabled(true);
}
Here is from DB
public List<User> allUsersA(){
db = this.getReadableDatabase();
List<User> users = new ArrayList<User>();
String s = "select * from " + TABLE_ORDER + " where status = 'A'";
Cursor cursor = db.rawQuery(s, null);
if (cursor.moveToFirst()){
do {
User user = new User();
user.set_id(Integer.parseInt(cursor.getString(0)));
user.setClientName(cursor.getString(1));
user.setCleintOrderedFood(cursor.getString(2));
user.setStatus(cursor.getString(3));
users.add(user);
}while (cursor.moveToNext());
}
db.close();
return users;
}
public List<User> allUsersB(){
db = this.getReadableDatabase();
List<User> users = new ArrayList<User>();
String s = "select * from " + TABLE_ORDER + " where status = 'B'";
Cursor cursor = db.rawQuery(s, null);
if (cursor.moveToFirst()){
do {
User user = new User();
user.set_id(Integer.parseInt(cursor.getString(0)));
user.setClientName(cursor.getString(1));
user.setCleintOrderedFood(cursor.getString(2));
user.setStatus(cursor.getString(3));
users.add(user);
}while (cursor.moveToNext());
}
db.close();
return users;
}
public void changeUser(){
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_STATUS, "B");
db.update(TABLE_ORDER, values, null, null);
db.close();
}
Here is adapter
public class ClientStatusAdapter extends BaseAdapter{
LayoutInflater inflater;
Context context;
List<User> wordsList;
DbHelper dbHelper;
public ClientStatusAdapter(Context context1, List<User> wordsList) {
this.context = context1;
this.wordsList = wordsList;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
dbHelper = new DbHelper(context);
}
#Override
public int getCount() {
return wordsList.size();
}
#Override
public Object getItem(int i) {
return wordsList.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view == null){
view = inflater.inflate(R.layout.kliyent_status_adapter, null);
}
TextView txtIsmAdapter = (TextView)view.findViewById(R.id.txtIsmAdapter);
TextView txtOvqatAdapter = (TextView)view.findViewById(R.id.txtOvqatAdapter);
final User user = wordsList.get(i);
TextView txtCliyentNames = (TextView)view.findViewById(R.id.txtCliyentNames);
txtCliyentNames.setText(user.getClientName());
TextView txtCliyentOrderedFoood = (TextView)view.findViewById(R.id.txtCliyentOrderedFoood);
txtCliyentOrderedFoood.setText(user.getCleintOrderedFood());
TextView txtStatusAdapter = (TextView)view.findViewById(R.id.txtStatusAdapter);
txtStatusAdapter.setText(user.getStatus());
notifyDataSetChanged();
ImageView imgOn = (ImageView) view.findViewById(R.id.imgOn);
return view;
}
}
Here is entity User
public class User {
private int _id;
private String clientName;
private String cleintOrderedFood;
private String status = "A";
public User() {
}
public User(int _id, String clientName, String cleintOrderedFood) {
this._id = _id;
this.clientName = clientName;
this.cleintOrderedFood = cleintOrderedFood;
}
public User(int _id, String clientName, String cleintOrderedFood, String status) {
this._id = _id;
this.clientName = clientName;
this.cleintOrderedFood = cleintOrderedFood;
this.status = status;
}
public int get_id() {
return _id;
}
public void set_id(int _id) {
this._id = _id;
}
public String getClientName() {
return clientName;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
public String getCleintOrderedFood() {
return cleintOrderedFood;
}
public void setCleintOrderedFood(String cleintOrderedFood) {
this.cleintOrderedFood = cleintOrderedFood;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
If you look closely at the SQLiteDatabase.update() method, you will see it is declared as
int update (String table,
ContentValues values,
String whereClause,
String[] whereArgs)
Note the last two parameters. These are how you select which rows to update. For example, you can specify to only update rows with a given id:
public void changeUser(int userId){
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_STATUS, "B");
String whereClause = "_id = ?";
String where = new String[] {Integer.toString(userId)};
db.update(TABLE_ORDER, values, whereClause, where);
db.close();
}
Here I am assuming you use the conventional column name _id. Of course, you can change this to suit your needs if you have a different column name.
Note that you will now need to pass a parameter to changeUser(). However, you have not shown how nor where you currently call it, so I am unable to provide any advice how to change this.
I have problem in my code
I want to send data when the user clicks
and receive data in another activity
example
I want to send position of items and on I go to second activity
I want to display form table where position = description field
my code
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(getApplicationContext(),Details.class);
i.putExtra("id",position);
startActivity(i);
}
});
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
TextView t1=(TextView)findViewById(R.id.t1);
ImageButton im=(ImageButton)findViewById(R.id.im);
Intent data=getIntent();
String des=data.getStringExtra("id");
// myDbHelper.openDataBase();
Cursor curser= DBAdapter.myDataBase.rawQuery("SELECT * FROM sweet where id = '" + des + "'", null);
curser.moveToPosition(0);
while (!curser.isAfterLast()) {
t1.append(curser.getColumnIndex(0));
curser.close();
}
Second Activity
Intent data=getIntent();
int des=data.getIntExtra("id", 1);
//String s= String.valueOf(des);
//
// Cursor sq= myDbHelper.myDataBase.rawQuery("select * from sweet where description = '"+des+"')",null);
try {
//String query = "SELECT * FROM sweet WHERE " + des + " = name";
String query = "SELECT * FROM sweet WHERE " + des + " = name";
SQLiteDatabase database = myDbHelper.getReadableDatabase();
//Cursor sq = myDbHelper.myDataBase.rawQuery("select * from sweet", null);
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
String description = cursor.getString(2);
t1.setText(description);
}
tabele
My table
id
name
description
this is 3 field
Intent data=getIntent();
int des=data.getIntExtra("id", 1);
try {
SQLite database=myDBHelper.getWritableDatabase();
Cursor cursor = database.rawQuery(SELECT * FROM sweet WHERE desccription =? ", new String[]{String.valueOf(des)}, null);
Details details=new Details();
if(cursor !=null)
{
while(cursor.moveToNext())
{
String description = cursor.getString(cursor.getColumnIndexOrThrow(myDbHelper.Description));
details.setDescription(description);
t1.setText(description);
}
}
Details
public class Info {
private int id;
private String name;
private String description;
public void setID(int id)
{
this.id=id;
}
public int getID()
{
return this.id;
}
public String setName(String name)
{
this.name=name;
}
public String getName()
{
return this.name;
}
public String setDescription(String description)
{
this.description=description;
}
public String getDescription()
{
return this.description;
}
I am trying to make simple android app where the user enter his information and then save it in the database and display the user info using listview. I have three java files: DBHelper.java, MainActivity.java and userInfo.java.
(MainActivity.java) is where the user enters his name and email.
(DBHelper.java) is where the database is created to save the user info.
(userInfo.java) is where the user info can be displayed.
in my app I successfully displayed the data from database using textview, and my question is how I can display the data from database using listview.
updated:
this is the getData() method from DBHelper.java file:
public List<Person> getData() {
// TODO Auto-generated method stub
String[] columns = new String[] { KEY_ID2, KEY_NAME, KEY_EMAIL};
Cursor c = ourDbase.query(TABLE_SCORE, columns, null, null, null, null, null + " DESC");
List<Person> people = new ArrayList<Person>();
int iRow = c.getColumnIndex(KEY_ID);
int iName = c.getColumnIndex(KEY_NAME);
int iEmail= c.getColumnIndex(KEY_EMAIL);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
Person p = new Person();
p.setEmail(c.getString(iEmail));
//set other info, like id, name
people.add(person);
}
return people;
}
here is the Person class:
public class Person {
private int ID;
private String NAME;
private String EMAIL;
public Person()
{
ID=0;
NAME="";
EMAIL="";
}
public Person(String qNAME, int qEMAIL) {
NAME = qNAME;
EMAIL= qEMAIL;
}
public int getID()
{
return ID;
}
public String getNAME() {
return NAME;
}
public int getEMAIL() {
return EMAIL;
}
public void setID(int id)
{
ID=id;
}
public void setNAME(String qNAME) {
NAME = qNAME;
}
public void setSCORE(int qEMAIL) {
EMAIL= qEMAIL;
}
}
and this is the code where I get the data from database and set it in textview from userInfo.java:
DbHelper userInfo = new DbHelper(this);
userInfo .open();
String data = userInfo .getData();
userInfo .close();
tv.setText(data);
how I can display the data from database using listview.
Since you dont provide any code about the listview and its adapter, i assume you dont know where to start.
You should create a listview, either with custom-created adapter or basic adapter (from android). After that, add the data from the database to your listview's adapter and use notifyDataSetChanged() to make sure the data is refreshed on the listview.
Simple tutorial : http://androidexample.com/Create_A_Simple_Listview_-_Android_Example/index.php?view=article_discription&aid=65&aaid=90
In-depth (recommended) tutorial : http://www.vogella.com/tutorials/AndroidListView/article.html
I tried to retrieve all data from database and put it into arraylist but i get only one record of table. here is my code :
where Birthdates is arraylist.
public ArrayList<String> read()
{
Birthdates.clear();
String selectQuery = "SELECT * FROM Birthday_Reminder";
Cursor crs=database.rawQuery(selectQuery,null);
System.out.println("In read");
if(crs.moveToFirst())
{
do {
Toast.makeText(con,"adding to arraylist", Toast.LENGTH_LONG).show();
Birthdates.add(crs.getString(crs.getColumnIndex("B_Date")));
}
while (crs.moveToNext());
}
return Birthdates;
}
i am doing this way by using getters and setters
package com.sunil.smilee;
public class DataOfUser {
int _id;
String _data;
String _date;
// Empty constructor
public DataOfUser(){
}
// constructor
// getting ID
public int getID(){
return this._id;
}
// setting id
public void setID(int id){
this._id = id;
}
// getting name
public String getD(){
return this._data;
}
// setting name
public void setD(String s){
this._data = s;
}
//
public void setDate(String string) {
// TODO Auto-generated method stub
this._date = string;
}
public String getDate(){
return this._date ;
}
}
// Add it in database class or change accordingly
// Getting All Contacts
public List<DataOfUser> getAllContacts() {
List<DataOfUser> dist = new ArrayList<DataOfUser>();
// Select All Query
String selectQuery = "SELECT * FROM " + ITEM.TABLE_DATA;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
DataOfUser contact = new DataOfUser();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setD(cursor.getString(1));
contact.setDate(cursor.getString(2));
dist.add(contact);//add data in list
} while (cursor.moveToNext());
//
}
// return contact list
return dist;
}