I am trying to connect SQLite database in Android Studio through SQLiteAssetHelper, I have tried everything, but it is showing ... Unable to Open Database.
I don't know what is the problem here. I am new to android development.
I have seen other question's answers, but it couldn't help me.
This is my DB Class:
public class MyDB extends SQLiteAssetHelper {
private static final String DB_NAME="Demo.db";
private static final int DB_ver=1;
//private static MyDB myDB=null;
public MyDB(Context context) {
super(context, DB_NAME, null, DB_ver);
}
}
this is DB Access Class:
public class OpenDBHelper {
private SQLiteOpenHelper openHelper;
private SQLiteDatabase db;
private static OpenDBHelper openDBHelper ;
private OpenDBHelper(Context context)
{
this.openHelper = new MyDB(context);
}
public static OpenDBHelper getInstance(Context context)
{
if(openDBHelper==null)
{
openDBHelper=new OpenDBHelper(context.getApplicationContext()) ;
}
return openDBHelper;
}
public SQLiteDatabase openwrite()
{
this.db= openHelper.getReadableDatabase();
return db;
}
}
and this is the main activity where I am trying to load the data in listview:
public class MainActivity extends AppCompatActivity {
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv=(ListView) findViewById(R.id.lv_main);
loadStudents();
}
public void loadStudents()
{
ArrayList<HashMap<String, String>> userList = GetAllStudents();
ListAdapter adapter = new SimpleAdapter(this, userList, R.layout.lv_row,new String[]{"name","cast","phone"}, new int[]{R.id.tv_name, R.id.tv_cast, R.id.tv_phone});
lv.setAdapter(adapter);
}
//GEt All Students to listview
public ArrayList<HashMap<String, String>> GetAllStudents(){
ArrayList<HashMap<String, String>> userList = new ArrayList<>();
OpenDBHelper open= OpenDBHelper.getInstance(this);
SQLiteDatabase db=open.openwrite();
String query = "SELECT * FROM tbl_bio";
Cursor cursor = db.rawQuery(query,null);
if(cursor.getCount()>0) {
while (cursor.moveToNext()) {
HashMap<String, String> user = new HashMap<>();
user.put("name", cursor.getString(1));
user.put("cast", cursor.getString(2));
user.put("phone", cursor.getString(3));
//user.put("pass", cursor.getString(4));
userList.add(user);
}
}
return userList;
}
}
Related
I am new to app creating and for some reason my app won't open a table called "Full Book" which I was going to used in an activity to search using a "Material Search Bar". So every time I install the app on my physical device and try to open the search activity it crashes showing the following error message:
Process: uk.co.crystalclearlanguage.httpwww.dyagetmedoc, PID: 31912
java.lang.RuntimeException: Unable to start activity ComponentInfo{uk.co.crystalclearlanguage.httpwww.dyagetmedoc/uk.co.crystalclearlanguage.httpwww.dyagetmedoc.Main2Activity}: android.database.sqlite.SQLiteException: no such table: FullBook (code 1): , while compiling: SELECT Phrase FROM FullBook
#################################################################
Error Code : 1 (SQLITE_ERROR)
Caused By : SQL(query) error or missing database.
(no such table: FullBook (code 1): , while compiling: SELECT Phrase FROM FullBook)
#################################################################
the really weird thing is however, when I use another activity that looks in the same database for another table and then try to run the search function it works perfectly.
Here is my database helper for the search function:
public class Database extends SQLiteAssetHelper {
private static final String DB_NAME="DoYouGetMeDoc.db";
private static final int DB_VER=1;
public Database(Context context) {
super(context, DB_NAME, null, DB_VER);
}
public List<Items> getFullBook(){
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String[] sqliteSelect={"Phrase","Description","Example", "Chapter"};
String tableName="FullBook";
qb.setTables(tableName);
Cursor cursor = qb.query(db,sqliteSelect,null,null,null,null,null);
List<Items> results = new ArrayList<>();
if (cursor.moveToFirst()){
do {
Items items = new Items();
items.setPhrase(cursor.getString(cursor.getColumnIndex("Phrase")));
items.setDescription(cursor.getString(cursor.getColumnIndex("Description")));
items.setExample(cursor.getString(cursor.getColumnIndex("Example")));
items.setChapter(cursor.getString(cursor.getColumnIndex("Chapter")));
results.add(items);
}while (cursor.moveToNext());
}
return results;
}
public List<String> getPhrases(){
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String[] sqliteSelect={"Phrase"};
String tableName="FullBook";
qb.setTables(tableName);
Cursor cursor = qb.query(db,sqliteSelect,null,null,null,null,null);
List<String> results = new ArrayList<>();
if (cursor.moveToFirst()){
do {
results.add(cursor.getString(cursor.getColumnIndex("Phrase")));
}while (cursor.moveToNext());
}
return results;
}
public List<Items> getPhrasesbyPhrase(String phrase)
{
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String[] sqliteSelect={"Phrase","Description","Example","Chapter"};
String tableName="FullBook";
qb.setTables(tableName);
Cursor cursor = qb.query(db,sqliteSelect,"Phrase like ?",new String[]{"%"+phrase+"%"},null,null,null);
List<Items> results = new ArrayList<>();
if (cursor.moveToFirst()){
do {
Items items = new Items();
items.setPhrase(cursor.getString(cursor.getColumnIndex("Phrase")));
items.setDescription(cursor.getString(cursor.getColumnIndex("Description")));
items.setExample(cursor.getString(cursor.getColumnIndex("Example")));
items.setChapter(cursor.getString(cursor.getColumnIndex("Chapter")));
results.add(items);
}while (cursor.moveToNext());
}
return results;
}
}
Main2Activity (Search Activity):
public class Main2Activity extends AppCompatActivity{
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
SearchAdapter adapter;
MaterialSearchBar materialSearchBar;
List<String> suggestList = new ArrayList<>();
Database database;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
recyclerView= findViewById(R.id.recyler_search);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
materialSearchBar = findViewById(R.id.search_bar);
database = new Database(this);
materialSearchBar.setHint("Search");
materialSearchBar.setCardViewElevation(10);
loadSuggestionList();
materialSearchBar.addTextChangeListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
List<String> suggest = new ArrayList<>();
for (String search:suggestList)
{
if (search.toLowerCase().contains(materialSearchBar.getText().toLowerCase()))
suggest.add(search);
}
materialSearchBar.setLastSuggestions(suggest);
}
#Override
public void afterTextChanged(Editable s) {
}
});
materialSearchBar.setOnSearchActionListener(new MaterialSearchBar.OnSearchActionListener() {
#Override
public void onSearchStateChanged(boolean enabled) {
if (!enabled)
adapter = new SearchAdapter(getBaseContext(),database.getFullBook());
recyclerView.setAdapter(adapter);
}
#Override
public void onSearchConfirmed(CharSequence text) {
startSearch(text.toString());
}
#Override
public void onButtonClicked(int buttonCode) {
}
});
adapter = new SearchAdapter(this,database.getFullBook());
recyclerView.setAdapter(adapter);
}
private void startSearch(String text) {
adapter = new SearchAdapter(this,database.getPhrasesbyPhrase(text));
recyclerView.setAdapter(adapter);
}
private void loadSuggestionList() {
suggestList = database.getPhrases();
materialSearchBar.setLastSuggestions(suggestList);
}
#Override
public void onBackPressed() {
Intent i= new Intent(Main2Activity.this,MainActivity.class);
startActivity(i);
finish();
}
}
Any help/advice would be greatly appreciated
Update:
the stack definitely says that the "DoYouGetMeDoc.db" database has been opened.
If it helps here is the search adapter/viewholder:
class SearchViewHolder extends RecyclerView.ViewHolder {
public TextView phrase;
public TextView decription;
public TextView example;
public TextView chapter;
public SearchViewHolder(#NonNull View itemView) {
super(itemView);
phrase = itemView.findViewById(R.id.txt_Phrase);
decription = itemView.findViewById(R.id.txt_Description);
example = itemView.findViewById(R.id.txt_Example);
chapter = itemView.findViewById(R.id.txt_Chapter);
}
}
public class SearchAdapter extends RecyclerView.Adapter<SearchViewHolder> {
private Context context;
private List<Items> items;
public SearchAdapter(Context context, List<Items> items) {
this.context = context;
this.items = items;
}
#NonNull
#Override
public SearchViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
LayoutInflater layoutInflater = LayoutInflater.from(viewGroup.getContext());
View itemview = layoutInflater.inflate(R.layout.layout_item,viewGroup,false);
return new SearchViewHolder(itemview);
}
#Override
public void onBindViewHolder(#NonNull SearchViewHolder searchViewHolder, int i) {
searchViewHolder.phrase.setText(items.get(i).getPhrase());
searchViewHolder.decription.setText(items.get(i).getDescription());
searchViewHolder.example.setText(items.get(i).getExample());
searchViewHolder.chapter.setText(items.get(i).getChapter());
}
#Override
public int getItemCount() {
return items.size();
}
}
Once again. Any help and guidance would be very much appreciated especially since this is the last piece of the app that needs to work correctly.
I did some research and I was missing an "instance" in my SQLiteAssetHelper Class. So I added the following:
private static Database instance;
public static Database getInstance(Context context){
if (null == instance){
instance = new Database(context);
}
return instance;
}
and added the following to my MainActivity.Java in the "OnCreate" method:
Database.getInstance(this);
I have strange problem with my android app. I have some data and I saved that data in SQLite Database. And in this fragment I try to read my data from table using SimpleCursorAdapter
public class LogFragment extends Fragment{
private static SQLiteDatabase db;
private static SQLiteOpenHelper helper;
private static Context context;
private static ListView listView;
private static String senderOrReceiver;
private static SimpleCursorAdapter adapter;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getActivity();
adapter = new SimpleCursorAdapter(context, R.layout.log_message, null,
new String[]{Constants.COMMAND, Constants.VALUE, Constants.TIME_STAMP, Constants.MESSAGE_ID, Constants.SESSION_ID, Constants.PARAMS},
new int[]{R.id.command, R.id.value, R.id.time_stamp, R.id.message_id, R.id.session_id, R.id.params}, 0);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_log, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
listView = (ListView) view.findViewById(R.id.listView);
}
#Override
public void onDestroy() {
super.onDestroyView();
if(db != null){
db.close();
}
}
public static void readFromDatabase(String sender){
senderOrReceiver = sender;
new DatabaseTalker().execute();
}
private static class DatabaseTalker extends AsyncTask <Void, Void, Cursor>{
#Override
protected Cursor doInBackground(Void... params) {
helper = new Database(context);
db = helper.getReadableDatabase();
return db.query(Constants.TABLE_NAME, null, null, null, null, null, null);
}
#Override
protected void onPostExecute(Cursor cursor) {
super.onPostExecute(cursor);
adapter.changeCursor(cursor);
listView.setAdapter(adapter);
}
}
}
and here's what I got in my ListView . I have six fields (Command, Value, Time Stamp, MessageID, SessionID, Params) and as you can see only one field is filled (for example) Command: On, Value: , Time Stamp: , MessageID: , SessionID: , Params: . and so on... Why I get this result?
EDIT:
Here how I write my data to database
public void addInfo(Information info){
SQLiteDatabase db = this.getWritableDatabase();
addToTable(db, Constants.COMMAND, info.getCommand());
addToTable(db, Constants.VALUE, info.getValue());
addToTable(db, Constants.TIME_STAMP, info.getTimeStamp());
addToTable(db, Constants.MESSAGE_ID, info.getMessageID());
addToTable(db, Constants.SESSION_ID, info.getSessionID());
addToTable(db, Constants.PARAMS, info.getParams());
db.close();
}
private static void addToTable(SQLiteDatabase db, final String TAG, String value){
ContentValues values = new ContentValues();
values.put(TAG, value);
db.insert(Constants.TABLE_NAME, null, values);
}
Your each addToTable() call inserts a new row that contains just one column value.
To insert a row with all the values, add the values to the same ContentValues and call insert() once.
i have a database which i created in Sqlite database browser and using a library to use that database for populating my lists in ListActivity. now to i want to convert my ListActivity to ListFragment...
here is the code...
code for DataBaseHelper
import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;
public class DataBaseHelper extends SQLiteAssetHelper {
private static final String DATABASE_NAME = "dictionary.db";
private static final int DATABASE_VERSION = 1;
public DataBaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public Cursor getDictionary() {
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String [] sqlSelect = {"0 _id", "dream_title", "dream_meaning"};
String sqlTables = "dictionary";
qb.setTables(sqlTables);
Cursor c = qb.query(db, sqlSelect, null, null,
null, null, null);
c.moveToFirst();
return c;
}
}
code for MainActivity
public class MainActivity extends ListActivity {
private Cursor dictionary;
private DataBaseHelper db;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
db = new DataBaseHelper(this);
dictionary = db.getDictionary(); // you would not typically call this on the main thread
ListAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
dictionary,
new String[] {"dream_title"},
new int[] {android.R.id.text1});
getListView().setAdapter(adapter);
}
#Override
protected void onDestroy() {
super.onDestroy();
dictionary.close();
db.close();
}
}
Any help will be appreciable
ListFragment uses setListAdapter. I think that's all you would need to change.
well I am using my existing database, I made a list<> "mSorular" with this code:
public class TestAdapter {
private final Context mContext;
private SQLiteDatabase mDb;
private DataBaseHelper mDbHelper;
public TestAdapter(Context context) {
this.mContext = context;
mDbHelper = new DataBaseHelper(mContext);
}
public List<soru> getTestData() {
List<soru> mSorular = new LinkedList<soru>();
try {
Cursor mCur = mDb.query("Soru", null, null,
null,
null,
null,
null,
null);
if (mCur != null) {
if (mCur.moveToFirst()) {
do {
soru Soru = new soru();
Soru.setmSoru(mCur.getString(2));
Soru.setmCevap1(mCur.getString(3));
Soru.setmCevap2(mCur.getString(4));
Soru.setmCevap3(mCur.getString(5));
mSorular.add(Soru);
} while (mCur.moveToNext());
}
}
return mSorular;
} catch (SQLException mSQLException) {
Log.e(TAG, "getTestData >>" + mSQLException.toString());
throw mSQLException;
}
}
after that I want to use my mSorular list in a listfragment. When I try to
public class framelist extends ListFragment {
private static String tag = "sqllist";
TestAdapter adapter = new TestAdapter(this);
it gives this error:
The constructor TestAdapter(framelist) is undefined
without this my list will return empty. so how can I Use my list in this listfragment
ListFragment is not a Context. First change it to use the attached Activity as Context, and then move it into the onCreate() method of the Fragment because before this call there might not be an Activity attached. (actually it's after the onAttach(Activity) call)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate();
TestAdapter adapter = new TestAdapter(getActivity());
...
{
Hey guys I already have a data in my database but I want to show it into spinner I'm really new to this problem, so would you guys help me to solve this problem,or I would prefer if you write the correct code for me :) Thanks in advance.
First this is my DB class
public class DBAdapter
{
public static final String UPDATEDATE = "UpdateDate";
//Declare fields in PersonInfo
public static final String ROWID = "_id";
public static final String PT_FNAME = "Username";
public static final String PT_COLORDEF = "ColorDeficiency";
private static final String DATABASE_CREATE =
"create table PersonInfo (_id integer primary key autoincrement, "
+ "Username text not null, ColorDeficiency text);";
private static final String DATABASE_NAME = "CAS_DB";
private static final String tbPerson = "PersonInfo";
private static final int DATABASE_VERSION = 1;
private final Context databaseContext;
private final Context context;
private DatabaseHelper DBHelper;
public SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
databaseContext = ctx;
}
//start database helper
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion)
{
}
}
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
public Cursor all(Activity activity){
String[] from ={ROWID,PT_FNAME,PT_COLORDEF};
String order = PT_FNAME;
Cursor cursor =db.query(tbPerson, from, null, null, null, null, order);
activity.startManagingCursor(cursor);
return cursor;
}
In another class
private DBAdapter db;
private Spinner spinner;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.greeting);
initComponent();
db = new DBAdapter(this);
Cursor c = db.all(this);
SimpleCursorAdapter CursorAdapter = new SimpleCursorAdapter(
this,android.R.layout.simple_spinner_item,c,
new String[]{DBAdapter.PT_FNAME},new int[]{android.R.id.list});
CursorAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(CursorAdapter);
try changing
new int[]{android.R.id.list}
to
new int[]{android.R.layout.simple_spinner_item}