Unable to bind data by query from DB to spinner - android

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}

Related

how to display sqllite inserting data using recyclerview in android studio

I am new to android.
When I insert data it works properly. but while I click the button for displaying the inserted data using recyclerview it makes following error message: Sqlite Insert and View has stopped.
Error message is like:
at
com.example.sqliteinsertandview.MainActivity.ShowData(MainActivity.java:56)
at java.lang.reflect.Method.invoke(Native Method) 
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:397) 
at android.view.View.performClick(View.java:6256) 
at android.view.View$PerformClick.run(View.java:24701) 
at android.os.Handler.handleCallback(Handler.java:789) 
at android.os.Handler.dispatchMessage(Handler.java:98) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6541) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
MainActivity code:
public class MainActivity extends AppCompatActivity {
private EditText nameEt, ageEt;
private Button insertBtn;
String name, age;
DatabaseHelper helper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
insertData();
}
private void insertData() {
insertBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = nameEt.getText().toString();
age = ageEt.getText().toString();
long id = helper.insertData(name, age);
Toast.makeText(MainActivity.this, "Your id" + id, Toast.LENGTH_SHORT).show();
}
});
}
private void init() {
nameEt = findViewById(R.id.nameEt);
ageEt = findViewById(R.id.ageEt);
insertBtn = findViewById(R.id.insertBtn);
helper = new DatabaseHelper(this);
}
public void ShowData(View view) {
startActivity(new Intent(this, ShowActivity.class));
}
}
ShowActivity Code:
public class ShowActivity extends AppCompatActivity {
RecyclerView recyclerView;
UserAdapter adapter;
List<User> users;
DatabaseHelper helper;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show);
init();
getData();
}
private void getData(){
Cursor cursor = helper.showData();
while (cursor.moveToNext()){
int id = cursor.getInt(cursor.getColumnIndex(helper.COL_ID));
String name = cursor.getString(cursor.getColumnIndex(helper.COL_NAME));
String age = cursor.getString(cursor.getColumnIndex(helper.COL_AGE));
users.add(new User(id,name,age));
adapter.notifyDataSetChanged();
}
}
private void init(){
recyclerView = findViewById(R.id.userRecyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
users = new ArrayList<>();
helper = new DatabaseHelper(this);
adapter = new UserAdapter(users);
recyclerView.setAdapter(adapter);
}
DatabaseHelper code:
public class DatabaseHelper extends SQLiteOpenHelper {
private static String DATABASE_NAME = "User.db";
private static String TABLE_NAME = "User";
public static String COL_ID = "Id";
public static String COL_NAME = "Name";
public static String COL_AGE = "Age";
private static int VERSION = 1;
private static String createTable = "create table "+TABLE_NAME+"(Id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT, Age TEXT)";
public DatabaseHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
long insertData(String name, String age){
ContentValues contentValues = new ContentValues();
contentValues.put(COL_NAME,name);
contentValues.put(COL_AGE,age);
SQLiteDatabase sqLiteDatabase = getWritableDatabase();
long id = sqLiteDatabase.insert(TABLE_NAME,null,contentValues);
sqLiteDatabase.close();
return id;
}
public Cursor showData(){
String show_all = " select* From "+TABLE_NAME;
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
Cursor cursor = sqLiteDatabase.rawQuery(show_all,null);
return cursor;
}
}
You didn't add ShowActivity class in AndroidManifest.xml file. Add this inside application tag
<activity android:name=".ShowActivity"/>

Populating Listview from Database Only Works Once

I'm trying to update a listview with user entries into two text inputs. Once the save button is clicked, the user's entry should appear. Based on my code, the listview updates the first time I fill out the two text inputs and I hit save, but the second time I hit save, the listview does not update. Here's my code:
Home.java
public class Home extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
EditText inputOne;
EditText inputTwo;
MyDBHandler dbHandler;
Button saveButton;
MyCursorAdapter cursorAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
inputOne = (EditText) findViewById(R.id.inputOne);
inputTwo = (EditText) findViewById(R.id.inputTwo);
dbHandler = new MyDBHandler(this, null, null, 1);
saveButton = (Button) findViewById(R.id.saveButton);
MyDBHandler myDBHandler = new MyDBHandler(this);
Cursor c = myDBHandler.getCursor();
cursorAdapter = new MyCursorAdapter(this,c,1);
ListView notes = (ListView) findViewById(R.id.notes);
notes.setAdapter(cursorAdapter);
public void saveClicked(View view) {
Test test = new Test( inputOne.getText().toString(), inputTwo.getText().toString() );
dbHandler.addTest(test);
inputOne.setText("");
inputTwo.setText("");
cursorAdapter.notifyDataSetChanged();
}
MyDBHandler.java
public class MyDBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "Database.db";
public static final String TABLE_TEST = "test";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_ONE = "one";
public static final String COLUMN_TWO = "two";
public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_TEST + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
COLUMN_ONE + " TEXT," +
COLUMN_TWO + " TEXT" + ");";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TEST);
onCreate(db);
}
public void addTest(Test test){
ContentValues values = new ContentValues();
values.put(COLUMN_ONE, test.get_one());
values.put(COLUMN_TWO, test.get_two());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_TEST, null, values);
db.close();
}
public Cursor getCursor(){
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_ACTIVITIES + " WHERE 1";
Cursor c = db.rawQuery(query, null);
return c;
}
}
MyCursorAdapter.java
public class MyCursorAdapter extends CursorAdapter {
public MyCursorAdapter(Context context, Cursor c, int flags) {
super(context, c, 1);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.custom_row, parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView one = (TextView) view.findViewById(R.id.one);
TextView two = (TextView) view.findViewById(R.id.two);
String one_string = cursor.getString(cursor.getColumnIndexOrThrow(MyDBHandler.COLUMN_ONE));
one.setText(one_string);
String two_string = cursor.getString(cursor.getColumnIndexOrThrow(MyDBHandler.COLUMN_TWO));
two.setText(two_string);
}
}
Test.java
public class Test {
private int _id;
private String _one;
private String _two;
public Test(){
}
public Test(int id){
this._id = id;
}
public Test(String one, String two){
this._one = one;
this._two = two;
}
public int get_id() {
return _id;
}
public void set_id(int _id) {
this._id = _id;
}
public String get_one() {
return _one;
}
public void set_one(String _one) {
this._one = _one;
}
public String get_two() {
return _two;
}
public void set_two(String _two) {
this._two = _two;
}
The correct way to refresh a ListView backed by a Cursor is to call cursorAdapter.notifyDatasetChanged(), without needing to recreate and reset the adapter.
So in your saveClicked method you just update the db and let the Adapter know there has been a change.
To do this, you'll need to keep a reference to the adapter as an instance field instead of declaring it as a local variable.
Turns out my ListView was populating, but I made the mistake of putting a ListView inside of a ScrollView - so I wasn't able to see the addition of entries. It worked once I used the solution from this: Android - ListView's height just fits 1 ListView item

android: SQLite Db error

hello i am building a SQLite Db for my android application . this is the code :
package com.example.pap_e;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class FeedsDbAdapter {
private final Context mCtx;
private static final String DEBUG_TAG = "RSSDatabase";
private static final int DB_VERSION = 1;
private static final String DB_NAME = "rss_data";
public static String TABLE = "list";
public static final String ID = "_id";
public static final String RSS = "_rss";
public static final String TITLE = "_title";
public static final String PUBDATE = "_pubdate";
public static final String DESCRIPTION = "_description";
public static final String LINK = "_link";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static class DatabaseHelper extends SQLiteOpenHelper{
DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE_TABLE"+TABLE+"("+ID+ "integer PRIMARY KEY AUTOINCREMENT,"+RSS+"text NOT NULL,"
+TITLE+"text NOT NULL,"+PUBDATE+"text NOT NULL,"+DESCRIPTION+"text NOT NULL,"+LINK+"text NOT NULL"+")");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE);
onCreate(db);}
}
public FeedsDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
public boolean updateAnakoinosi(long rowId, String rss, String title,
String pubdate, String description, String link) {
ContentValues args = new ContentValues();
args.put(RSS, rss);
args.put(TITLE, title);
args.put(PUBDATE, pubdate);
args.put(DESCRIPTION, description);
args.put(LINK, link);
return mDb.update(TABLE, args, ID + "=" + rowId, null) > 0;}
public Cursor fetchAllAnakoinoseis() {
return mDb.query(TABLE, new String[] { ID, RSS, TITLE, PUBDATE,
DESCRIPTION,LINK }, null, null, null, null, null); }
}
The thing is that i get an error at public class FeedsDbAdapter that says:"The blank final field mCtx may not have been initialized" but i had it initialized using private final Context mCtx; Am i missing something here ? Thanks a lot in advance!
You didn't initialize the context yet. You have to initialize it inside FeedsDbAdapter constructor like :
public FeedsDbAdapter (Context context){
mCtx = context;
}
first declare FeedsDbAdapter constructor, because you use FeedsDbAdapter class through its constructor in other classes ans the other activity context will assign to this current context.
Change your code to :
private static class DatabaseHelper extends SQLiteOpenHelper{
DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
mCtx = context;
}
This question of yours relates to java. This line private final Context mCtx; is just a declaration of field mCtx of type context. And as this field has been declared as final, It has to be iniliazed inside the constructor mCtx = context;. Even if mCtx is not declared as final, it has still to be initialized before being used.
Thats because your class is static... Remove static from your class and change your code to
DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
mCtx = context;
}

Sqlite:The constructor is undefined

I have created DBAdapter class which is responsible for making a connection to a Database and does any query and finally close the connection.
I have another class which it is not inherited from Activity class(ReminderBeep), but i have to use my DBAdapter in this class.
Actually i don't know how can i manipulate the DBAdapter constructor to make the connection.*
The error is: The constructor DBAdapter(ReminderBeep) is undefined
DBAdapter is:
public class DBAdapter {
static final String DATABASE_NAME = "MyDB";
static final int DATABASE_VERSION = 2;
final Context context;
DatabaseHelper DBHelper;
SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
}
#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 void insert(String sql)
{
db.execSQL(sql);
}
}
BeepReminder is:
public class ReminderBeep
{
public void DeleteDailyActivities()
{
DBAdapter db=new DBAdapter(this);
db.open();
String sql="delete from DailyWorks";
db.insert(sql);
db.close();
}
}
ReminderBeep is not extendig Activity. But DBAdapter want a Context as paramter,
DBAdapter db=new DBAdapter(this);
this refers to ReminderBeep

sqlite. Table not creating

I'm trying to create table in the sqlite, but it is showing error that table cannot be created. I have a same code but the database and table name are different. the fields are same. Also one doubt. Can't i create the different table in the same database containing the same fields.
DbAdapter.java
the code is as below.
public class DbAdapter {
private static final String DATABASE_NAME="bible1";
private static final String DATABASE_TABLE="test1";
private static final int DATABASE_VERSION=1;
public static final String KEY_ID="_id";
public static final String UNITS="units";
public static final String CHAPTERS="chapters";
private static final String CREATE_DATABASE="create table test1 (_id integer primary key autoincrement, units text not null, chapters text not null);";
private SQLiteHelper sqLiteHelper;
private static SQLiteDatabase sqLiteDatabase;
private Context context;
//constructor
public DbAdapter(Context c){
context = c;
}
private static class SQLiteHelper extends SQLiteOpenHelper{
public SQLiteHelper(Context context){
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(CREATE_DATABASE);
MakeUnits();
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
public DbAdapter open() throws SQLException{
try{
sqLiteHelper = new SQLiteHelper(context);
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
}catch(NullPointerException ne){
Log.e("error in creating the table", "bye");
}
return this;
}
public void close(){
sqLiteHelper.close();
}
public static long MakeUnits()
{
ContentValues insert1 = new ContentValues();
insert1.put(UNITS, "Unit1");
insert1.put(CHAPTERS, "CHAPTER1");
return sqLiteDatabase.insert(DATABASE_TABLE,null,insert1);
}
public Cursor fetchAllNotes(){
return sqLiteDatabase.query(DATABASE_TABLE, new String[]{KEY_ID,UNITS,CHAPTERS}, null, null, null, null, null);
}
}
MainActivity.java
public class MainActivity extends ListActivity {
private DbAdapter Database;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listContent = (ListView) findViewById(android.R.id.list);
Database= new DbAdapter(this);
Database.open();
Cursor c = Database.fetchAllNotes();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
It is giving error when the open() method is called. Couldn't figure it out.
in the logcat the error in the tag is that "error in creating the table"
You're trying to call sqLiteDatabase.insert inside MakeUnits, but this sqLiteDatabase variable is null until after you call getWritableDatabase. You should pass db to MakeUnits and call insert on db, not on sqLiteDatabase.
database will be created only when you make a call to
getWritableDatabase()/getReadableDatabase()
If you do not have permissions for a writable db, you will get a readable
db.
public SQLiteDatabase getWritableDB() {
try {
return helper.getWritableDatabase();
} catch (Exception e) {
return getReadableDB();
}
}
public SQLiteDatabase getReadableDB() {
return helper.getReadableDatabase();
}

Categories

Resources