By using assets folder, we are reading data i.e,address details based on search keyword:
Here is my code
private SQLiteDatabase db;
private Cursor c;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_search = (EditText) findViewById(R.id.et_search);
img = (ImageView) findViewById(R.id.img_search);
list = (ListView) findViewById(R.id.list_search);
db = openOrCreateDatabase("sample", Context.MODE_PRIVATE, null);
img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
search_keyword = et_search.getText().toString();
arr_data = new ArrayList<ListItems>();
if (isValid()) {
SELECT_SQL = "SELECT ROWID AS _id,* FROM Addresses where Type LIKE '%" + search_keyword + "%'";
Log.d("daatt",SELECT_SQL);
try {
c = db.rawQuery(SELECT_SQL, null);
c.moveToFirst();
showRecords();
} catch (SQLiteException e) {
Toast.makeText(getApplicationContext(), "No Data", Toast.LENGTH_LONG).show();
}
}
}
});
}
private void showRecords() {
String ugName = c.getString(c.getColumnIndex("Name"));
String ugaddress = c.getString(c.getColumnIndex("Address"));
String ugtype = c.getString(c.getColumnIndex("Type"));
ListItems items = new ListItems();
// Finish reading one raw, now we have to pass them to the POJO
items.setName(ugName);
items.setAddress(ugaddress);
items.setType(ugtype);
// Lets pass that POJO to our ArrayList which contains undergraduates as type
arr_data.add(items);
}
ListDataAdapter adapter = new ListDataAdapter(arr_data);
list.setAdapter(adapter);
if (c != null && !c.isClosed()) {
int count = c.getCount();
c.close();
}
Log.d("ListData", "" + arr_data);
}
private boolean isValid() {
if (search_keyword.length() == 0) {
Toast.makeText(getApplicationContext(), "please enter valid key word", Toast.LENGTH_LONG).show();
return false;
}
return true;
}
For 1st build we got successful data loaded using list adapter
But after clean project, & Rebuild project showing a no such table expection
Please guide us wr we r going wrong
Advance Thanks
As far as I can see from your print, the table you're referring to is called ListOfAddress, ain't it? your SQL is:
SELECT_SQL = "SELECT ROWID AS _id,* FROM Addresses where Type LIKE '%" + search_keyword + "%'";
I might be wrong, but I would double check the query.
Related
I wrote a code in which i can retrieve the data from the database but when i run it and try to search something. The application crashes as soon as i press Submit
public class search extends AppCompatActivity {
Button SearchButton;
EditText SearchText;
TextView SearchResult;
SQLiteDatabase db;
String builder;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
SearchButton=(Button)findViewById(R.id.searchbutton);
SearchText=(EditText)findViewById(R.id.Searchtext);
SearchResult=(TextView)findViewById(R.id.SearchCourse);
db=this.openOrCreateDatabase("Courses", Context.MODE_PRIVATE,null);
SearchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int GetID = Integer.valueOf(SearchText.getText().toString());
Cursor TuplePointer = db.rawQuery("Select from Course where ID="+GetID+"",null);
TuplePointer.moveToFirst();
String Course = TuplePointer.getString(TuplePointer.getColumnIndex("Course"));
SearchResult.setText(Course);
}
});
}
}
Replace this line
Cursor TuplePointer = db.rawQuery("Select from Course where ID=" + GetID + "", null);
with
Cursor TuplePointer = db.rawQuery("Select Course from Course where ID=" + GetID + "", null);
Where Course is your column name
Write your code within try catch first. Afterthat try to catch exact exception. you will be clear what are you doing wrong.
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS + " Where " + KEY_APP_BOOKINGID + " = " + id;
Cursor cursor = db.rawQuery(selectQuery, null);
Please Try this
SQLiteDatabase db = this.getReadableDatabase();
String GetID = SearchText.getText().toString();
Cursor cursor = db.rawQuery("SELECT * FROM Course WHERE ID = ?", new String[]{String.valueOf(GetID)}, null);
if (cursor.moveToFirst()) {
do {
String Course = cursor.getString(cursor.getColumnIndex("Course"));
SearchResult.setText(Course);
} while (cursor.moveToNext());
}
Thank You everyone I figured out what i was doing wrong on the get Column index i targeted course but what i didnt realize is that there was no such field as course :)
Keep practice like below code you will debug proper
public void getFirstName(String id) {
String sql = "select first_name from basic_info WHERE contact_id="+ id;
Cursor c = fetchData(sql);
if (c != null) {
while (c.moveToNext()) {
String FirstName = c.getString(c.getColumnIndex("first_name"));
Log.e("Result =>",FirstName);
}
c.close();
}
return data;
}
public Cursor fetchData(String sql) {
SQLiteDatabase db = this.getWritableDatabase();
return db.rawQuery(sql, null);
}
I'm getting many time repeating data from Sqlite / Android database. I want to get recode without repeating in Android cursor.
Here's my query:
public Cursor getQuizQuiestion(String cat, String level, String questionNo) {
String QUERY_SELECT_QUIESTION = "SELECT * FROM " +TABLE_QUIESTION +" WHERE "+COL_CAT+ " = '" +cat+"' AND "
+COL_LEVEL+ " = " +level+" ORDER BY RANDOM() LIMIT 1";
Cursor cursor = db.rawQuery(QUERY_SELECT_QUIESTION, null);
return cursor;
}
I Have Simple Example if I Used In My Project I think MayBe IT's Help You;
public ArrayList<ModelRandomList> getRandomData(String city){
ArrayList<ModelRandomList> modelRandomListArrayListLists = new ArrayList<ModelRandomList>();
String queryRandomData ="SELECT DISTINCT * FROM "+TABLE_NAME+" WHERE "+COL_CITY + "=?"+ "Order BY RANDOM()";
Cursor cursor = db.rawQuery(queryRandomData,new String[] { String.valueOf(city) });
if(cursor.getCount() != 0){
while (cursor.moveToNext()){
/*mName =cursor.getString(0);
mCity = cursor.getString(1);
Log.d(TAG,mName +" City "+mCity );*/
ModelRandomList modelRandomList = new ModelRandomList();
modelRandomList.setUserName(cursor.getString(0));
modelRandomList.setUserCity(cursor.getString(1));
modelRandomListArrayListLists.add(modelRandomList);
}
Random random = new Random();
Collections.shuffle(modelRandomListArrayListLists,random);
}
Log.d(TAG, "Get Random Totla No of Recode Found "+cursor.getCount());
return modelRandomListArrayListLists;
}
and in Your Activity
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private SqlLiteDataBaseHelper sqlLiteDataBaseHelper;
private Button btGetRandomData;
private ArrayList<ModelRandomList> modelRandomLists;
private Button btSingleRandomData;
private int position = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
modelRandomLists = new ArrayList<ModelRandomList>();
sqlLiteDataBaseHelper = new SqlLiteDataBaseHelper(MainActivity.this);
try{
if(sqlLiteDataBaseHelper.checkDataBase()){
Log.e(TAG, "Data Base Already Exists");
}else {
sqlLiteDataBaseHelper.CopyDataBaseFromAsset();
}
sqlLiteDataBaseHelper.openDataBase();
try {
Log.e(TAG, "No Of Racode In DataBase " + sqlLiteDataBaseHelper.getDataCount());
}catch (Exception e){
e.printStackTrace();
}
}catch (Exception e){
e.printStackTrace();
}
init();
}
private void init() {
btGetRandomData = (Button)findViewById(R.id.btRandomData);
btSingleRandomData = (Button)findViewById(R.id.btSingleRandomData);
}
#Override
protected void onResume() {
super.onResume();
btGetRandomData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
modelRandomLists = sqlLiteDataBaseHelper.getRandomData("A");
for (ModelRandomList crt : modelRandomLists) {
Log.e(TAG, " " + crt.getUserName());
Log.e(TAG, " " + crt.getUserCity());
}
}
});
btSingleRandomData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try{
Log.d(TAG,modelRandomLists.get(position).getUserName());
position ++;
}catch (Exception e){
e.printStackTrace();
position =0;
}
}
});
}
}
You would have to keep a track of what questions have been seen before. What about this:
private List<Integer> seenQuestions = new ArrayList<>();
public Cursor getUseenQuizQuestion(String cat,String level,String questionNo) {
Cursor cursor = getQuizQuiestion(cat, level, questionNo);
while(cursor == null) { // This could be an infinite loop!!
cursor = getQuizQuiestion(cat, level, questionNo);
}
return cursor;
}
private Cursor getQuizQuiestion(String cat,String level,String questionNo){
String QUERY_SELECT_QUIESTION = "SELECT * FROM " +TABLE_QUIESTION +" WHERE "+COL_CAT+ " = '" +cat+"' AND "
+COL_LEVEL+ " = " +level+" ORDER BY RANDOM() LIMIT 1";
Cursor cursor = db.rawQuery(QUERY_SELECT_QUIESTION, null);
if(cursor.moveToFirst()) {
int resultId = cursor.getString(cursor.getColumnIndexOrThrow("_id"));
if(seenQuestions.contains(resultId)) {
cursor.close();
return null;
}
seenQuestions.add(resultId);
}
return cursor;
}
^ the code sample above has many flaws and could loop infinitely.
But the point is you need to keep track of what has been returned and query again if you have seen it.
Alternatively, you could allow your DB query to return all data and then use a Random value to select one of the items.
There is no way to create unique results if you are querying over and over again.
Since you are not using the questionNo parameter and return a cursor anyway: why not just remove the limit 1 and add the distinct clause to your statement?
If you do it that way, you can use your cursor to iterate over the unique questions:
String QUERY_SELECT_QUIESTION = "SELECT DISTINCT * FROM " +TABLE_QUIESTION +" WHERE "+COL_CAT+ " = '" +cat+"' AND "
+COL_LEVEL+ " = " +level+" ORDER BY RANDOM()";
Then you can iterate over the questions until you have none or whatever your conditions are:
Cursor cursor = db.rawQuery(QUERY_SELECT_QUIESTION, null);
try {
while (cursor.moveToNext()) {
//display question or copy them to a member or whatever
}
} finally {
cursor.close();
}
This is my MainActivity.
public class MainActivity extends Activity {
EditText etName, etEmail;
DatabaseHelper dbHelper;
Button save;
// declare view
ListView lvEmployees;
// declare adapter
CustomizedAdapter adapter;
// datasource
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etName = (EditText) findViewById(R.id.etName);
etEmail = (EditText) findViewById(R.id.etEmail);
save = (Button) findViewById(R.id.btnSave);
lvEmployees = (ListView) findViewById(R.id.lvEmployees);
dbHelper = new DatabaseHelper(this);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
save(v);
}
});
}
public void save(View v) {
String name = etName.getText().toString();
String email = etEmail.getText().toString();
Employee employee = new Employee(name, email);
Toast.makeText(getApplicationContext(), employee.toString(),
Toast.LENGTH_LONG).show();
long inserted = dbHelper.insertEmployee(employee);
if (inserted >= 0) {
Toast.makeText(getApplicationContext(), "Data inserted",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Data insertion failed...",
Toast.LENGTH_LONG).show();
}
ArrayList<Employee> employees = dbHelper.getAllEmployees();
if (employees != null && employees.size() > 0) {
adapter = new CustomizedAdapter(this, employees);
lvEmployees.setAdapter(adapter);
}
}
}
This is my DataBaseHelper.
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DB_NAME = "task_management";
public static final int DB_VERSION = 1;
public static final String EMPLOYEE_TABLE = "employee";
public static final String ID_FIELD = "_id";
public static final String NAME_FIELD = "name";
public static final String EMAIL_FIELD = "email";
public static final String EMPLOYEE_TABLE_SQL = "CREATE TABLE "
+ EMPLOYEE_TABLE + " (" + ID_FIELD + " INTEGER PRIMARY KEY, "
+ NAME_FIELD + " TEXT, " + EMAIL_FIELD + " DATETIME);";
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// create tables
db.execSQL(EMPLOYEE_TABLE_SQL);
Log.e("TABLE CREATE", EMPLOYEE_TABLE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// upgrade logic
}
// insert
public long insertEmployee(Employee emp) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(NAME_FIELD, emp.getName());
values.put(EMAIL_FIELD, emp.getEmail());
long inserted = db.insert(EMPLOYEE_TABLE, null, values);
db.close();
return inserted;
}
// query
public ArrayList<Employee> getAllEmployees() {
ArrayList<Employee> allEmployees = new ArrayList<Employee>();
SQLiteDatabase db = this.getReadableDatabase();
// String[] columns={NAME_FIELD, EMAIL_FIELD, PHONE_FIELD};
// SELECT * FROM EMPLOYEE;
Cursor cursor = db.query(EMPLOYEE_TABLE, null, null, null, null, null,
null);
// Cursor cursor = db.rawQuery("SELECT * FROM EMPLOYEE", null);
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
for (int i = 0; i < cursor.getCount(); i++) {
//
int id = cursor.getInt(cursor.getColumnIndex(ID_FIELD));
String name = cursor.getString(cursor
.getColumnIndex(NAME_FIELD));
String email = cursor.getString(cursor
.getColumnIndex(EMAIL_FIELD));
Employee e = new Employee(id, name, email);
allEmployees.add(e);
cursor.moveToNext();
}
}
cursor.close();
db.close();
return allEmployees;
}
}
When i put data and pressed the save button then my data is saved and show in my ListView.
But when i close the apps and open it then i don't see any data in my ListView.
After putting data and pressed save button my new and existing data show in my ListView.
So how can i show my existing data in ListView after open my apps and without press the save button.
If you want to show data each time app starts, you would need to move your list populating code in onCreate
Move this code to onCreate instead of Save button's onClick
ArrayList<Employee> employees = dbHelper.getAllEmployees();
if (employees != null && employees.size() > 0) {
adapter = new CustomizedAdapter(this, employees);
lvEmployees.setAdapter(adapter);
}
Hope it helps.
P.S: If you need to repopulate list after Save button's click, make a separate function which contains this code. And call tha function in onCreate as well as in Save button's onClick
You are setting the adapter for the list view in your save method that is called only when you actually press the save button. Here's the part where you do it.
ArrayList<Employee> employees = dbHelper.getAllEmployees();
if (employees != null && employees.size() > 0) {
adapter = new CustomizedAdapter(this, employees);
lvEmployees.setAdapter(adapter);
}
Thats why there is no data in the listview when you open the app.
You should do this in your onCreate method, and in your save you should do something like this:
1. declare the the arraylist of employees along with listview;
ArrayList<Employee> employees;
in your oncreate call this code that you should remove from the save method
employees = dbHelper.getAllEmployees();
if (employees != null && employees.size() > 0) {
adapter = new CustomizedAdapter(this, employees);
lvEmployees.setAdapter(adapter);
}
in save method just add one more item to the list, and notify adapter that there has been a change in the data it's displaying.
employees.add(employee);
adapter.notifyDataSetChanged();
I want to get a value of single column returned in the form of ArrayList<> from SQLite for retrieving data my code is :
public List<ContentDataObject> findAll() {
List<ContentDataObject> contentDataObjects = new ArrayList<ContentDataObject>();
String selectQuery = "SELECT " +
DBHelper.MOBILE_CONTENT_FULLTEXT+
" FROM " + DBHelper.MOBILE_CONTENT_TABLE_NAME;
database = dbOpenHelper.getReadableDatabase();
try {
Cursor cursor = database.rawQuery(selectQuery, null);
Log.i(TAG, "Returned " + cursor.getCount() + " rows");
if(cursor != null){
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
ContentDataObject contentDataObject = check(cursor);
contentDataObjects.add(contentDataObject);
cursor.moveToNext();
}
// Make sure to close the cursor
cursor.close();
}
} catch (Exception e) {
// TODO: handle exception
}
return contentDataObjects;
}
my check(cursor) is :
public ContentDataObject check(Cursor cursor) {
ContentDataObject contentDataObject = new ContentDataObject();
contentDataObject.setId(cursor.getLong(cursor.getColumnIndex(DBHelper.MOBILE_CONTENT_ID)));
contentDataObject.setTitle(cursor.getString(cursor.getColumnIndex(DBHelper.MOBILE_CONTENT_TITLE)));
contentDataObject.setFulltext(cursor.getString(cursor.getColumnIndex(DBHelper.MOBILE_CONTENT_FULLTEXT)));
contentDataObject.setState(cursor.getInt(cursor.getColumnIndex(DBHelper.MOBILE_CONTENT_STATE)));
contentDataObject.setNewValue(cursor.getInt(cursor.getColumnIndex(DBHelper.MOBILE_CONTENT_NEW)));
contentDataObject.setHeader(cursor.getString(cursor.getColumnIndex(DBHelper.MOBILE_CONTENT_HEADER)));
contentDataObject.setColor(cursor.getInt(cursor.getColumnIndex(DBHelper.MOBILE_CONTENT_COLOR)));
contentDataObject.setNext(cursor.getString(cursor.getColumnIndex(DBHelper.MOBILE_CONTENT_NEXT)));
contentDataObject.setPrevious(cursor.getString(cursor.getColumnIndex(DBHelper.MOBILE_CONTENT_PREVIOUS)));
return contentDataObject;
}
in MainActivity.java I'm using this code :
ContentDataObject contentDataObject;
TextView textView;
ContentsDataSource dataSource;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.myView);
dataSource = new ContentsDataSource(this);
dataSource.open();
List<ContentDataObject> contentDataObjects = dataSource.findAll();
textView.setText(""+contentDataObjects.indexOf(contentDataObject.getFulltext()));
}
but, I'm unable to get data and set to textView.
I think you don't use List<E> if you only want to get one value from SQLite so you should try this one !
change findAll() in this way :
public String findAll() {
^^^^^^
String myQuery = "SELECT " +
DBHelper.MOBILE_CONTENT_FULLTEXT+
" FROM " + DBHelper.MOBILE_CONTENT_TABLE_NAME+
" WHERE _id = 2";
Cursor cursor = database.rawQuery(myQuery, null);
String fullText = null;
^^^^^^^^^^^^^^^
if(cursor.getCount() <= 0) {
Log.w(TAG, "There is no data to display");
}
else {
fullText = "";
if(cursor.moveToFirst()) {
do {
fullText += cursor.getString(cursor.getColumnIndex(DBHelper.MOBILE_CONTENT_FULLTEXT)) + "\n";
} while(cursor.moveToNext());
}// end if
}
return fullText;
^^^^^^^^^^^^^^^^
}
And in onCreate() use this :
ContentsDataSource dataSource;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.myView);
dataSource = new ContentsDataSource(this);
dataSource.open();
parseAndIsertData();
textView.setText(dataSource.getFullText());
^^^^^^^^^^^^^^^^^^^^^^^^^
}
I hope this Will work for you!
your contentDataObject is never initialized so your calling actually.
textView.setText(""+contentDataObjects.indexOf( NULL ));
I'm trying to display the content of my SQLite table using SimpleAdapter and TableView.
It works just fine at first launch, but when i relaunch the Activity it adds the table one more time in the listView.
This happens everytime i launch the intent from my front menu.
It seems to me that the SimpleAdapter is stored from the last time, and added again when the intent is opend from the menu?
Maybe there is a way to reset the adapter everytime it is launched?
I'm new to programming and hope someone can help me:)
Some code:
static final ArrayList<HashMap<String,String>> results = new ArrayList<HashMap<String,String>>();
private String tableName = DBAdapter.tableName;
private SQLiteDatabase newDB;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
openAndQueryDatabase();
displayResultList();
}
private void displayResultList() {
ListAdapter adapter = new SimpleAdapter(
this,
results,
R.layout.liste,
new String[] {"Name","LastName","Age"},
new int[] {R.id.item_id,R.id.item_name,R.id.item_tid}
);
setListAdapter(adapter);
}
private void openAndQueryDatabase() {
try {
DBAdapter dbHelper = new DBAdapter(this.getApplicationContext());
newDB = dbHelper.getWritableDatabase();
Cursor c = newDB.rawQuery("SELECT Startnr, Navn, Tid FROM " +
tableName + " ORDER BY Startnr ASC" , null);
if (c != null ) {
if (c.moveToFirst()) {
do {
HashMap<String,String> list = new HashMap<String,String>();
String firstName = c.getString(c.getColumnIndex("Startnr"));
String lastName = c.getString(c.getColumnIndex("Navn"));
String age = c.getString(c.getColumnIndex("Tid"));
list.put("Name", "" + firstName);
list.put("LastName", "" + lastName);
list.put("Age", "" + age);
results.add(list);
}while (c.moveToNext());
}
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
if (newDB != null)
newDB.close();
}
}
Its because you have declared the "results" array list as a "static" variable.