I'm not able to display the database in ListView.
I would like to pass the 3 EditText information from DataInput.Java to Database.java in ListView.
Right now I'm able to save the detail form in DataInput.java and it will direct me to Database.java but the details are not shown in Database.java ListView.
I'm new to this so any help would be greatly appreciated!
DataInput.java code (Details Form):
import android.content.Intent;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class DataInput extends AppCompatActivity {
EditText event, date, descrip;
Button saveBtn;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data_input);
event = (EditText)findViewById(R.id.event_text);
date = (EditText)findViewById(R.id.date_text);
descrip = (EditText)findViewById(R.id.descrip_text);
saveBtn = (Button)findViewById(R.id.save_btn);
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String title_ = event.getText().toString()+"\n";
String date_ = date.getText().toString();
String description_ = descrip.getText().toString();
Helper dbHandler = new Helper(DataInput.this);
dbHandler.insertUserDetails(title_, date_, description_);
intent = new Intent(DataInput.this,Database.class);
startActivity(intent);
Toast.makeText(getApplicationContext(), "Details Inserted Successfully",Toast.LENGTH_SHORT).show();
}
});
}
Database.java code:
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import java.util.ArrayList;
import java.util.HashMap;
public class Database extends AppCompatActivity {
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_database);
Helper db = new Helper(this);
ArrayList<HashMap<String, String>> userList = db.GetUsers();
ListView lv = (ListView) findViewById(R.id.list_view);
ListAdapter adapter = new SimpleAdapter(Database.this,
userList, R.layout.row, new String[]{"event","description","date"}, new int[]
{R.id.event_text, R.id.date_text, R.id.descrip_text});
lv.setAdapter(adapter);
Button back = (Button)findViewById(R.id.btnBack);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
intent = new Intent(Database.this, MainActivity.class);
startActivity(intent);
}
});
}
}
Helper.java code:
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.HashMap;
public class Helper extends SQLiteOpenHelper {
private static final int DB_VERSION = 1;
private static final String DB_NAME = "usersdb";
private static final String TABLE_Users = "userdetails";
public static final String KEY_ID = "_id";
public static final String KEY_EVENT = "event";
public static final String KEY_DATE = "date";
public static final String KEY_DESC = "description";
public Helper(Context context){
super(context,DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db){
String CREATE_TABLE = "CREATE TABLE " + TABLE_Users + "("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_EVENT + " TEXT,"
+ KEY_DATE + " TEXT,"
+ KEY_DESC + " TEXT"+ ")";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
// Drop older table if exist
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Users);
// Create tables again
onCreate(db);
}
// **** CRUD (Create, Read, Update, Delete) Operations ***** //
// Adding new User Details
void insertUserDetails(String event, String date, String description){
//Get the Data Repository in write mode
SQLiteDatabase db = this.getWritableDatabase();
//Create a new map of values, where column names are the keys
ContentValues cValues = new ContentValues();
cValues.put(KEY_EVENT, event);
cValues.put(KEY_DATE, date);
cValues.put(KEY_DESC, description);
// Insert the new row, returning the primary key value of the new row
long newRowId = db.insert(TABLE_Users,null, cValues);
db.close();
}
// Get User Details
public ArrayList<HashMap<String, String>> GetUsers(){
SQLiteDatabase db = this.getWritableDatabase();
ArrayList<HashMap<String, String>> userList = new ArrayList<>();
String query = "SELECT event, date, description FROM "+ TABLE_Users;
Cursor cursor = db.rawQuery(query,null);
while (cursor.moveToNext()){
HashMap<String,String> user = new HashMap<>();
user.put("event",cursor.getString(cursor.getColumnIndex(KEY_EVENT)));
user.put("description",cursor.getString(cursor.getColumnIndex(KEY_DESC)));
user.put("date",cursor.getString(cursor.getColumnIndex(KEY_DATE)));
userList.add(user);
}
return userList;
}
// Get User Details based on userid
public ArrayList<HashMap<String, String>> GetUserByUserId(int userid){
SQLiteDatabase db = this.getWritableDatabase();
ArrayList<HashMap<String, String>> userList = new ArrayList<>();
String query = "SELECT event, date, description FROM "+ TABLE_Users;
Cursor cursor = db.query(TABLE_Users, new String[]{KEY_EVENT, KEY_DATE, KEY_DESC}, KEY_ID+ "=?",new String[]{String.valueOf(userid)},null, null, null, null);
if (cursor.moveToNext()){
HashMap<String,String> user = new HashMap<>();
user.put("event",cursor.getString(cursor.getColumnIndex(KEY_EVENT)));
user.put("description",cursor.getString(cursor.getColumnIndex(KEY_DESC)));
user.put("date",cursor.getString(cursor.getColumnIndex(KEY_DATE)));
userList.add(user);
}
return userList;
}
// Delete User Details
public void DeleteUser(int userid){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_Users, KEY_ID+" = ?",new String[]{String.valueOf(userid)});
db.close();
}
// Update User Details
public int UpdateUserDetails(String date, String description, int id){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cVals = new ContentValues();
cVals.put(KEY_DATE, date);
cVals.put(KEY_DESC, description);
int count = db.update(TABLE_Users, cVals, KEY_ID+" = ?",new String[]{String.valueOf(id)});
return count;
}
}
row.xml code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="#+id/event"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"/>
<TextView
android:id="#+id/date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"/>
<TextView
android:id="#+id/description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"/>
</LinearLayout>
</LinearLayout>
Related
So basically I am stuck as to why I cannot add any data. I have basically followed along with a youtube tutorial from scratch but for some reason, one particular error is quite persistent. (It does not allow me to add data, as such I cannot make any use of it.)
Below is the code I have been running and any help would be appreciated :) of course, point me in the right direction if this has been asked previously...I did try searching first. I can see it says theres no column named name in user_table, but what i dont understand is there was no such step in the youtube video and it worked fine?
Forgot to add error
E/SQLiteLog: (1) table Users_Table has no column named NAME
E/SQLiteDatabase: Error inserting NAME=Kono
android.database.sqlite.SQLiteException: table Users_Table has no column named NAME (code 1 SQLITE_ERROR): , while compiling: INSERT INTO Users_Table(NAME) VALUES (?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:986)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:593)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:590)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:61)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:33)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1597)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1468)
at com.example.sqldb.dbHelper.insertData(dbHelper.java:46)
at com.example.sqldb.MainActivity$2.onClick(MainActivity.java:55)
at android.view.View.performClick(View.java:7125)
at android.view.View.performClickInternal(View.java:7102)
at android.view.View.access$3500(View.java:801)
at android.view.View$PerformClick.run(View.java:27336)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
XML Layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center_horizontal"
tools:context=".MainActivity">
<ListView
android:id="#+id/usersList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/add_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="Name"/>
<Button
android:id="#+id/add_data"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add"/>
</LinearLayout>
</LinearLayout>
Main Java Code
package com.example.sqldb;
import androidx.appcompat.app.AppCompatActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
dbHelper db;
Button add_data;
EditText add_name;
ListView usersList;
ArrayList<String> listItem;
ArrayAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new dbHelper(this);
listItem = new ArrayList<>();
add_data = findViewById(R.id.add_data);
add_name = findViewById(R.id.add_name);
usersList = findViewById(R.id.usersList);
viewData();
usersList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String text = usersList.getItemAtPosition(1).toString();
Toast.makeText(MainActivity.this, "" + text, Toast.LENGTH_SHORT).show();
}
});
add_data.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name = add_name.getText().toString();
if(!name.equals("") && db.insertData(name)) {
Toast.makeText(MainActivity.this, "Data Added", Toast.LENGTH_SHORT).show();
add_name.setText("");
}else {
Toast.makeText(MainActivity.this, "Error: Data has not been added!", Toast.LENGTH_SHORT).show();
}
}
});
}
private void viewData() {
Cursor cursor = db.viewData();
if(cursor.getCount() == 0){
Toast.makeText(this, "No data to show", Toast.LENGTH_SHORT).show();
}else{
while (cursor.moveToNext()){
listItem.add(cursor.getString(1));
}
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listItem);
usersList.setAdapter(adapter);
}
}
}
Database Helper Class
package com.example.sqldb;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class dbHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "Users.db";
private static final String DB_TABLE = "Users_Table";
//Columns
private static final String ID = "ID";
private static final String NAME = "NAME";
private static final String CREATE_TABLE = "CREATE TABLE " + DB_TABLE + "(" +
ID + "INTEGER PRIMARY KEY AUTOINCREMENT," +
NAME + " TEXT " + ")";
public dbHelper(Context context){
super(context, DB_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);
onCreate(db);
}
//Method to insert data
public boolean insertData(String name){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(NAME, name);
long result = db.insert(DB_TABLE, null, contentValues);
return result != -1;// if result = -1 data will not be inserted
}
//Method to create view for data
public Cursor viewData(){
SQLiteDatabase db = this.getReadableDatabase();
String query = "Select * from " + DB_TABLE;
Cursor cursor = db.rawQuery(query, null);
return cursor;
}
}
Can you please replace below code snippet any try again to insert:
public static final String CREATE_TABLE =
"CREATE TABLE IF NOT EXISTS " + DB_TABLE + "("
+ ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ NAME + " TEXT"
+ ")";
Hope this may help you.
In Helper Class leave space frond of Integer
In Main Activity
if(!name.equals("")){ db.insertData(name);
Toast.makeText(MainActivity.this, "Data Added", Toast.LENGTH_SHORT).show();
add_name.setText("");
}else {
Toast.makeText(MainActivity.this, "Error: Data has not been added!",
Toast.LENGTH_SHORT).show();
}
Hey guys I have been trying this for 2 days now and I cant seem to get it to work. I have tried every tutorial! I am new to android studio and have been trying to make a simple app where I can register and login. I was able to create the database and insert a new row(user) to the database.[Register user]. And also I was able to log the user in.
What I am trying to do now, is retrieve a column or column from the row and display it in a text view.
For example, once I login with a user, I want to display their information from the columns, such as phone number, address, etc.
When the app is first launched, there is a registration activity. you can either register or proceed to the login activity. Once you are logged in from the login activity, there is a new activity where I want to display the information of that logged in user.
databasehelper.java
package easy.eightfivehundred.easy;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper{
public static final String DATABASE_NAME="register.db";
public static final String TABLE_NAME="register";
public static final String COL_1="ID";
public static final String COL_2="FirstName";
public static final String COL_3="LastName";
public static final String COL_4="HomeAddress";
public static final String COL_5="Phone";
public static final String COL_6="Email";
public static final String COL_7="Password";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, FirstName TEXT, LastName TEXT, HomeAddress TEXT, Phone TEXT, Email TEXT, Password TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
mainactivity
package easy.eightfivehundred.easy;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
SQLiteOpenHelper openHelper;
SQLiteDatabase db;
Button Registerbutton, Loginbutton;
EditText Firstnametxt, Lastnametxt, Homeaddresstxt, Phonenumbertxt, Emailtext, Passwordtext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
openHelper = new DatabaseHelper(this);
Registerbutton =(Button)findViewById(R.id.RegisterButton);
Loginbutton = (Button)findViewById(R.id.LogInButton);
Firstnametxt =(EditText)findViewById(R.id.FirstNameText);
Lastnametxt =(EditText)findViewById(R.id.LastNameText);
Homeaddresstxt =(EditText)findViewById(R.id.HomeAddressText);
Phonenumbertxt =(EditText)findViewById(R.id.PhoneText);
Emailtext =(EditText)findViewById(R.id.EmailText);
Passwordtext =(EditText)findViewById(R.id.PasswordText);
Registerbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
db = openHelper.getWritableDatabase();
String first = Firstnametxt.getText().toString();
String last = Lastnametxt.getText().toString();
String address = Homeaddresstxt.getText().toString();
String phone = Phonenumbertxt.getText().toString();
String email = Emailtext.getText().toString();
String password = Passwordtext.getText().toString();
insertData(first, last, address, phone, email, password);
Toast.makeText(getApplicationContext(), "You Registered Successfully!", Toast.LENGTH_LONG).show();
}
});
Loginbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, login.class);
startActivity(intent);
}
});
}
public void insertData(String first, String last, String address, String phone, String email, String password) {
ContentValues contentValues = new ContentValues();
contentValues.put(DatabaseHelper.COL_2, first);
contentValues.put(DatabaseHelper.COL_3, last);
contentValues.put(DatabaseHelper.COL_4, address);
contentValues.put(DatabaseHelper.COL_5, phone);
contentValues.put(DatabaseHelper.COL_6, email);
contentValues.put(DatabaseHelper.COL_7, password);
long id = db.insert(DatabaseHelper.TABLE_NAME, null, contentValues);
}
}
login
package easy.eightfivehundred.easy;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class login extends AppCompatActivity {
SQLiteDatabase db;
SQLiteOpenHelper openHelper;
Button Loginbutton;
EditText Emailtext, Passwordtext;
Cursor cursor;
public static final String EXTRA_MESSAGE = " ";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
openHelper = new DatabaseHelper(this);
db = openHelper.getReadableDatabase();
Loginbutton = (Button)findViewById(R.id.loginbutton);
Emailtext = (EditText)findViewById(R.id.emaillogintext);
Passwordtext = (EditText)findViewById(R.id.passwordlogintext);
Loginbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = Emailtext.getText().toString();
String password = Passwordtext.getText().toString();
cursor = db.rawQuery("SELECT * FROM " + DatabaseHelper.TABLE_NAME + " WHERE " + DatabaseHelper.COL_6 + "=? AND " + DatabaseHelper.COL_7 + "=? ", new String[]{email, password});
if(cursor != null){
if(cursor.getCount() > 0){
cursor.moveToNext();
Toast.makeText(getApplicationContext(), "Login Successful", Toast.LENGTH_LONG).show();
Intent intent = new Intent(login.this, UserHome.class);
intent.putExtra(EXTRA_MESSAGE, email);
startActivity(intent);
}
else{
Toast.makeText(getApplicationContext(), "Error!", Toast.LENGTH_LONG).show();
}
}
}
});
}
}
userhome
package easy.eightfivehundred.easy;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import static easy.eightfivehundred.easy.DatabaseHelper.TABLE_NAME;
public class UserHome extends AppCompatActivity {
SQLiteDatabase db;
SQLiteOpenHelper openHelper;
Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_home);
Intent intent = getIntent();
String email = intent.getStringExtra(login.EXTRA_MESSAGE);
}
}
In the userhome.java file is where I'm having trouble at. I simply want to display the columns from the logged in user on this page.
This should get you on your way:-
Step 1.
Amend the layout to include the TextViews with id's that will be used to show the extracted data e.g. :-
<TextView
android:id="#+id/firstname"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/lastname"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/homaddress"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/phone"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/email"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/password"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Step 2.
Add a method (added to DatabAseHelper.java although could be elsewhere like your InsertData method in MainActivity.java) to get the data as a Cursor.
e.g. :-
public Cursor getUserInfo(String email) {
SQLiteDatabase db = this.getWritableDatabase();
String whereclause = COL_6 + "=?"; //<<<< select according to email
String[] whereargs = new String[]{email};
return db.query(
TABLE_NAME,
null,
whereclause,
whereargs,
null,null,null
);
}
The above will equate to
SELECT * FROM register WHERE Email = '??????'
where ?????? will the string as passed to the method.
Step 3.
In Userhome.java declare the class variables for the TextViews, an instance of YOUR DatabaseHelper (not SQLiteOpenHelper) and the Cursor (you already have this).
e.g. :-
TextView mFirstName, mLastName, mHomeAddress, mPhone, mEmail, mPassword;
DatabaseHelper mDBHlpr;
Cursor cursor;
Step 4.
Again in UserHome.java as the onCreate method use :-
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //<<<< USE YOUR LAYOUT
Intent intent = getIntent();
String email = intent.getStringExtra(login.EXTRA_MESSAGE);
//<<<<<<<<<< NEW CODE >>>>>>>>>>
mFirstName = (TextView) this.findViewById(R.id.firstname);
mLastName = (TextView) this.findViewById(R.id.lastname);
mHomeAddress = (TextView) this.findViewById(R.id.homaddress);
mPhone = (TextView) this.findViewById(R.id.phone);
mEmail = (TextView) this.findViewById(R.id.email);
mPassword = (TextView) this.findViewById(R.id.password);
mDBHlpr = new DatabaseHelper(this); //<<<< get Instance of DatbaseHelper
cursor = mDBHlpr.getUserInfo(email); //<<< get the Cursor according to email
if (cursor.moveToFirst()) {
mFirstName.setText(cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_2)));
mLastName.setText(cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_3)));
mHomeAddress.setText(cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_4)));
mPhone.setText(cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_5)));
mEmail.setText(cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_6)));
mPassword.setText(cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_7)));
} else {
// HANDLE NO DATA THAT MATCHES WHERE CLAUSE
mFirstName.setText("Sorry No User found that has email as :- " + email);
}
cursor.close(); //<<<< DONE WITH THE CURSOR SO CLOSE IT
}
A Cursor when returned will be positioned at a position before the first row (position -1). To get to the data you need to move to a row.
The move????? methods return true or false. The former if the move could be made (so moveToFirst, if there are no rows will return false, or true if there is at least one row). Hence how you can use if (cursor.moveToFirst()){.....}.
So if there is data (a row or more, one is assumed as there should probably not be users with the same email) the TextView's are populated (otherwise i.e. else, the firstname TextView indicates user not found (shouldn't happen though)).
Data is extracted from the Cursor using get????? (getString in this case, there are other methods such as getInt, getLong ......).
The get???? methods take an integer, the column offset (first column ID is offset 0, the 2nd firstname is offset 1 ......). However, using hard coded offsets can easily result in issues, so it's recommended to use the Cursor getColumnIndex, which returns the column offset according to the column name (more flexible).
Note how the column names are retrieved from the DatabaseHelper, using this way reduces the chance for typing errors.
You could consider changing your onCreate method in the DatabaseHelper to also utilise this single source for column names by using (replaced code commented out).
:-
#Override
public void onCreate(SQLiteDatabase db) {
String crt_sql = "CREATE TABLE " + TABLE_NAME + "(" +
// Note AUTOINCREMENT is very likely not needed
// refer to https://sqlite.org/autoinc.html
COL_1 + " INTEGER PRIMARY KEY, " +
COL_2 + " TEXT, " +
COL_3 + " TEXT, " +
COL_4 + " TEXT, " +
COL_5 + " TEXT, " +
COL_6 + " TEXT, " +
COL_7 + " TEXT " +
")";
db.execSQL(crt_sql);
/*
db.execSQL("CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
"FirstName TEXT, LastName TEXT, HomeAddress TEXT, Phone TEXT, Email TEXT, Password TEXT)");
*/
}
You may wish to have a look at SQLite Autoincrement in regads to the exclusion of the AUTOINCREMENT keyword.
You may also wish to have a look at Cursor for the numerous Cursor methods (e.g. get???? and move?????)
Testing
the above was tested by adding a user who's first name was Fred, lastname FlitStone ... using this snippet of code :-
mDBHlpr.insertUser("Fred",
"Flintsone",
"1 The Caves, Bedrock",
"01 2345 6789",
email_for_testing,
"fredflintsone"
);
resulting in :-
Is there a way to grab a column from the database created, and store the
values found in the column into an array?
My main goal, is to get values in from a column, and store them into a spinner.
Look below for code!
PatientDbHelper.java
package tanav.sharma;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Tanav on 11/4/2016.
*/
public class PatientDbHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "PATIENTINFO.db";
private static final int DATABASE_VERSION = 1;
private static final String CREATE_QUERY = "CREATE TABLE "
+ PatientInfo.NewPatientInfo.TABLE_NAME + " ("
+ PatientInfo.NewPatientInfo.PATIENT_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ PatientInfo.NewPatientInfo.PATIENT_FNAME+ " TEXT,"
+ PatientInfo.NewPatientInfo.PATIENT_LNAME+" TEXT,"
+ PatientInfo.NewPatientInfo.PATIENT_DEPARTMENT+" TEXT);";
private static final String CREATE_QUERY_TEST =
"CREATE TABLE "
+ TestInfo.NewTestInfo.TABLE_TEST_NAME + " ("
+ TestInfo.NewTestInfo.TEST_BlOOD_PRESSURE + " TEXT,"
+ TestInfo.NewTestInfo.TEST_BLOOD_OXYGEN_LEVEL + " TEXT,"
+ TestInfo.NewTestInfo.TEST_RESPITORY_RATE +" TEXT,"
+ TestInfo.NewTestInfo.TEST_HEART_RATE +" TEXT);";
public PatientDbHelper(Context context){
super(context,DATABASE_NAME,null,DATABASE_VERSION);
Log.e("DATABASE OPERATIONS","Database created / opened ...");
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_QUERY);
db.execSQL(CREATE_QUERY_TEST);
Log.e("DATABASE OPERATIONS","Table created...");
}
public void addInformations(int id, String fname, String lname, String department, SQLiteDatabase db){
ContentValues contentValues = new ContentValues();
if ( id != 0 ){ contentValues.put(PatientInfo.NewPatientInfo.PATIENT_ID, id); }
contentValues.put(PatientInfo.NewPatientInfo.PATIENT_FNAME,fname);
contentValues.put(PatientInfo.NewPatientInfo.PATIENT_LNAME,lname);
contentValues.put(PatientInfo.NewPatientInfo.PATIENT_DEPARTMENT,department);
db.insert(PatientInfo.NewPatientInfo.TABLE_NAME, null,contentValues);
Log.e("DATABASE OPERATIONS","One in row inserted...");
}
public void addTestInformation(/*String BP*/ int BL, int RR, int HR, SQLiteDatabase db){
ContentValues contentTestValues = new ContentValues();
//contentTestValues.put(TestInfo.NewTestInfo.TEST_BlOOD_PRESSURE, BP);
contentTestValues.put(TestInfo.NewTestInfo.TEST_BLOOD_OXYGEN_LEVEL,BL);
contentTestValues.put(TestInfo.NewTestInfo.TEST_RESPITORY_RATE, RR);
contentTestValues.put(TestInfo.NewTestInfo.TEST_HEART_RATE, HR);
db.insert(TestInfo.NewTestInfo.TABLE_TEST_NAME, null, contentTestValues);
Log.e("DATABASE OPERATIONS", "One in row inserted...");
}
/* public Cursor getPatientDepartment(String departments, SQLiteDatabase sqLiteDatabase){
String[] projections = {PatientInfo.NewPatientInfo.PATIENT_FNAME, PatientInfo.NewPatientInfo.PATIENT_LNAME, PatientInfo.NewPatientInfo.PATIENT_DEPARTMENT};
String selection = PatientInfo.NewPatientInfo.PATIENT_DEPARTMENT+ " LIKE ?";
String[] selection_args = {departments};
Cursor cursor = sqLiteDatabase.query(PatientInfo.NewPatientInfo.TABLE_NAME,projections,selection,selection_args,null,null,null);
return cursor;
}*/
public Cursor getPatientsId(int patient_id,SQLiteDatabase sqLiteDatabase){
String[] projections = {PatientInfo.NewPatientInfo.PATIENT_ID, PatientInfo.NewPatientInfo.PATIENT_FNAME, PatientInfo.NewPatientInfo.PATIENT_DEPARTMENT};
String selection = PatientInfo.NewPatientInfo.PATIENT_ID+ " LIKE ?";
String convert = String.valueOf(patient_id);
String[] selection_args = {convert};
Cursor cursor = sqLiteDatabase.query(PatientInfo.NewPatientInfo.TABLE_NAME,projections,selection,selection_args,null,null,null);
return cursor;
}
public Cursor getInformations(SQLiteDatabase db){
Cursor cursor;
String[] projections = {PatientInfo.NewPatientInfo.PATIENT_FNAME, PatientInfo.NewPatientInfo.PATIENT_LNAME, PatientInfo.NewPatientInfo.PATIENT_DEPARTMENT};
cursor = db.query(PatientInfo.NewPatientInfo.TABLE_NAME,projections,null,null,null,null,null);
return cursor;
}
public Cursor getTestInformation(SQLiteDatabase db){
Cursor cursorTest;
String[] testProjections = {TestInfo.NewTestInfo.TEST_HEART_RATE, TestInfo.NewTestInfo.TEST_RESPITORY_RATE, TestInfo.NewTestInfo.TEST_BLOOD_OXYGEN_LEVEL, TestInfo.NewTestInfo.TEST_BlOOD_PRESSURE};
cursorTest = db.query(TestInfo.NewTestInfo.TABLE_TEST_NAME,testProjections,null,null,null,null,null);
return cursorTest;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
Above is my Database handler class, I want to grab the column PATIENT_FNAME and store all those values into an Array. Then Later on, in my AddTest.java file, i want to display these values into an spinner.
Below is my AddTest.java
package tanav.sharma;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class AddTest extends AppCompatActivity {
private RadioGroup radioGroup;
private RadioButton radioButton;
EditText etBL, etRR, etHBR;
Spinner patients;
Context context;
PatientDbHelper patientDbHelper;
SQLiteDatabase sqLiteDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_test);
getSupportActionBar().setTitle(R.string.add_test);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
etBL = (EditText) findViewById(R.id.etBOL);
etRR = (EditText) findViewById(R.id.etRR);
etHBR = (EditText) findViewById(R.id.etHBR);
patients = (Spinner) findViewById(R.id.spinner);
}
public void addTest(View view){
radioGroup = (RadioGroup) findViewById(R.id.radio);
Button addTest = (Button) findViewById(R.id.addTest);
addTest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int selectedId = radioGroup.getCheckedRadioButtonId();
RadioButton radioButton = (RadioButton) findViewById(selectedId);
}
});
//String BP = radioButton.getText().toString();
int BL = Integer.parseInt(etBL.getText().toString());
int RR = Integer.parseInt(etRR.getText().toString());
int HR = Integer.parseInt(etHBR.getText().toString());
patientDbHelper = new PatientDbHelper(this);
sqLiteDatabase = patientDbHelper.getWritableDatabase();
patientDbHelper.addTestInformation(BL,RR,HR,sqLiteDatabase);
Toast.makeText(getBaseContext(),"Data Saved",Toast.LENGTH_LONG).show();
patientDbHelper.close();
}
}
You can do something like
List<String> names = new ArrayList<>();
Cursor cursor = patientDbHelper.getInformations(sqLiteDatabase);
if (cursor != null){
while(cursor.moveToNext()){
names.add(cursor.getString(cursor.getColumnIndex(PatientInfo.NewPatientInfo.PATIENT_FNAME)));
}
cursor.close();
}
I'm working on a simple application that contains short stories and I'm trying to use a database but I got an error:
Caused by: android.database.sqlite.SQLiteException: no such column: TITLE (code 1): , while compiling: SELECT TITLE, STORY FROM MY_TABLE
SQLiteActivity.java
package com.scriptos.testsqlit;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class SQLiteActivity {
private static String DBNAME = "Sqlite_simple.db";
private static String TABLE = "MY_TABLE";
private static String COLUMN_1 = "TITLE";
private static String COLUMN_2 = "STORY";
private SQLiteDatabase database;
private SQLiteOpenHelper helper_database;
private Context context;
public SQLiteActivity(Context c){
context = c;
}
public SQLiteActivity Read() throws android.database.SQLException {
helper_database = new SQLiteHelper(context, DBNAME, null, 1);
database = helper_database.getReadableDatabase();
return this;
}
public SQLiteActivity Write() throws android.database.SQLException {
helper_database = new SQLiteHelper(context, DBNAME, null, 1);
database = helper_database.getWritableDatabase();
return this;
}
public void close(){
helper_database.close();
}
public long insert(String title, String story){
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_1, title);
contentValues.put(COLUMN_2, story);
return database.insert(TABLE, null, contentValues);
}
public int deleteAll(){
return database.delete(TABLE, null, null);
}
public String[] getAll(){
String[] columns = new String[]{COLUMN_1,COLUMN_2};
Cursor cursor = database.query(TABLE, columns,
null, null, null, null, null);
String [] result = new String[cursor.getCount()];
int title = cursor.getColumnIndex(COLUMN_1);
int story = cursor.getColumnIndex(COLUMN_2);
int a = 0;
for(cursor.moveToFirst(); !(cursor.isAfterLast()); cursor.moveToNext()){
result [a] =
cursor.getString(title) + " " +
cursor.getString(story) ;
a++;
}
return result;
}
public class SQLiteHelper extends SQLiteOpenHelper {
public SQLiteHelper(Context context, String name,
SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE + " (ID INTEGER KEY, "+COLUMN_1+ "TEXT, "+COLUMN_2 +"TEXT);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
}
MainActivity.java
package com.scriptos.testsqlit;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends Activity {
ListView listView;
SQLiteActivity db;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
listView = (ListView) findViewById(R.id.list);
String[] adapter = new String[] { "a", "b", "c",};
ArrayAdapter<String> i = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, adapter);
listView.setAdapter(i);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (position == 0) {
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("http://andrody.com/"));
startActivity(i);
}
if (position == 1) {
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("https://m.facebook.com/andrody2015"));
startActivity(i);
}
if (position == 2) {
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("https://m.youtube.com/channel/UCAGUgnnL47fU3TMRhKhkQwQ"));
startActivity(i);
}
}
});
db = new SQLiteActivity(this);
db.Write();
db.deleteAll();
db.insert("title1", "story1");
db.insert("title2","story2");
db.insert("title3","story3");
db.close();
SHOW();
}
public void SHOW() {
db.Read();
String [] x = db.getAll();
db.close();
}
}
content_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#fff5ffcf">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
</ScrollView>
</LinearLayout>
What should I do to correct this?
Your create table line;
db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE +
" (ID INTEGER KEY, "+COLUMN_1+ "TEXT, "+COLUMN_2 +"TEXT);");
...generates the SQL...
CREATE TABLE IF NOT EXISTS MY_TABLE (ID INTEGER KEY, TITLETEXT, STORYTEXT);
...which, due to missing spaces is not valid SQL and won't create the table.
Add the missing spaces to your create table, and it should work better.
db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE +
" (ID INTEGER KEY, "+COLUMN_1+ " TEXT, "+COLUMN_2 +" TEXT);");
CREATE TABLE IF NOT EXISTS MY_TABLE (ID INTEGER KEY, TITLE TEXT, STORY TEXT);
i think no space is there in your table creation
CREATE TABLE IF NOT EXISTS " + TABLE + " (ID INTEGER KEY, "+COLUMN_1+"
TEXT, "+COLUMN_2 +" TEXT);");
it may be better
I have just started to learn programming and I try to build a simple database for my exercise and I try to show all the content of the table in my database into a list in another layout but I don't know why the content isn't showing up in the list.. please help me ..
here is my apps sample
here is my activity for putting all the content in the list:
package com.DennisTA;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
public class DaftarIstilah extends Activity{
private DataKamus dbhelper;
private SQLiteDatabase db = null;
private ListView listContent = null;
private Cursor kamusCursor = null;
CustomCursorAdapter adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dbhelper = new DataKamus(this);
setContentView(R.layout.daftaristilah);
listContent = (ListView) findViewById(R.id.list1);
isDataListView();
}
private void isDataListView() {
try {
db = dbhelper.getWritableDatabase();
kamusCursor = db.query("kamus", new String[] { "_id", "inggris",
"arti", "penjelasan" }, "_id>0", null, null, null, null);
// startManagingCursor( jasaCursor);
/*
* Create an array to specify the fields we want to display in the
* list (only the 'inggris,arti,penjelasan' column in this case)
*/
String[] from = new String[] { "inggris", "arti", "penjelasan" };
/*
* and an array of the fields we want to bind those fieiplds to (in
* this case just the textView 'inggris,arti,penjelasan' from our new row.xml
* layout above)
*/
int[] to = new int[] { R.id.inggris, R.id.arti, R.id.penjelasan };
/* Now create a simple cursor adapter.. */
adapter = new CustomCursorAdapter(this, R.layout.baris, kamusCursor,
from, to);
// listView.setAdapter(adapter);
listContent.setAdapter(adapter);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (db != null && db.isOpen()) {
db.close();
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
try {
kamusCursor.close();
} catch (Exception e) {
}
}
protected class CustomCursorAdapter extends SimpleCursorAdapter {
private int layout;
private LayoutInflater inflater;
private Context context;
public CustomCursorAdapter(Context context, int layout, Cursor c,
String[] from, int[] to) {
super (context, layout, c, from, to);
this.layout = layout;
this.context = context;
inflater = LayoutInflater.from(context);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
Log.d("NewView", "*****xxx");
View v = inflater.inflate(R.layout.baris, parent, false);
return v;
}
#Override
public void bindView(View v, Context context, Cursor c) {
// 1 is the column where you're getting your data from
String inggris = c.getString(1);
String penjelasan = c.getString(3);
String arti = c.getString(2);
/**
* Next set the name of the entry.
*/
TextView name_text = (TextView) v.findViewById(R.id.inggris);
TextView des_text = (TextView) v.findViewById(R.id.penjelasan);
TextView id_text = (TextView) v.findViewById(R.id.arti);
des_text.setText(penjelasan);
id_text.setText(arti);
if (name_text != null) {
name_text.setText(inggris);
}
}
}
}
here is my baris.xml sample :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:paddingBottom="5sp"
android:paddingTop="5sp" >
<TextView
android:id="#+id/inggris"
android:layout_width="100sp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true" />
<TextView
android:id="#+id/arti"
android:layout_width="100sp"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/inggris" />
<TextView
android:id="#+id/penjelasan"
android:layout_width="100sp"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/arti" />
</RelativeLayout>
here is my daftar istilah.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="100sp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text = "Inggris"
android:textSize="20sp" />
<TextView
android:id="#+id/textView2"
android:layout_width="100sp"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/textView1"
android:text = "Arti"
android:textSize="20sp" />
<TextView
android:id="#+id/textView3"
android:layout_width="100sp"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/textView2"
android:text = "Penjelasan"
android:textSize="20sp" />
<ListView android:id="#+id/list1" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_weight = "1"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"/>
</RelativeLayout>
here is my class that contain the database:
package com.DennisTA;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DataKamus extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "dbkamus";
public static final String INGGRIS= "inggris";
public static final String ARTI = "arti";
public static final String PENJELASAN = "penjelasan";
//Constructor DataKamus untuk initiate database
public DataKamus(Context context) {
super(context, DATABASE_NAME, null, 1);
}
//method createTable untuk membuat table kamus
public void createTable(SQLiteDatabase db){
db.execSQL("DROP TABLE IF EXISTS kamus");
db.execSQL("CREATE TABLE if not exists kamus (_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"inggris TEXT, arti TEXT, penjelasan TEXT);");
}
//method generateData untuk mengisikan data ke kamus.
public void generateData(SQLiteDatabase db){
ContentValues cv=new ContentValues();
cv.put(INGGRIS, "run");
cv.put(ARTI, "lari");
cv.put(PENJELASAN, "laufen");
db.insert("kamus", INGGRIS, cv);
cv.put(INGGRIS, "walk");
cv.put(ARTI, "jalan");
cv.put(PENJELASAN, "gehen");
db.insert("kamus", INGGRIS, cv);
cv.put(INGGRIS, "read");
cv.put(ARTI, "membaca");
cv.put(PENJELASAN, "lesen");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
createTable(db);
generateData(db);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
//Toast.makeText(getBaseContext(), "Oncreate", Toast.LENGTH_SHORT).show();
createTable(db);
generateData(db);
}
}
here is my main activity :
package com.DennisTA;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private SQLiteDatabase db = null;
private Cursor kamusCursor = null;
private EditText txtInggris;
private EditText txtArti;
private EditText txtPenjelasan;
private DataKamus datakamus = null;
public static final String INGGRIS = "inggris";
public static final String ARTI = "arti";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
datakamus = new DataKamus(this);
db = datakamus.getWritableDatabase();
setContentView(R.layout.activity_main);
txtInggris = (EditText) findViewById(R.id.txtInggris);
txtArti = (EditText) findViewById(R.id.txtArti);
txtPenjelasan = (EditText) findViewById(R.id.txtPenjelasan);
}
public void getTerjemahan(View view) {
String bhsindonesia = "";
String bhsjerman="";
String englishword = txtInggris.getText().toString();
kamusCursor = db.rawQuery("SELECT _ID, INGGRIS, INDONESIA, JERMAN " + "FROM kamus where INGGRIS='" + englishword + "' ORDER BY INGGRIS", null);
if (kamusCursor.moveToFirst()) {
for (; !kamusCursor.isAfterLast();
kamusCursor.moveToNext()) {
bhsindonesia = kamusCursor.getString(2);
bhsjerman = kamusCursor.getString(3);
}
}else{
Toast.makeText(getBaseContext(), "Terjemahan Tidak ditemukan", Toast.LENGTH_SHORT).show();
}
txtArti.setText(bhsindonesia);
txtPenjelasan.setText(bhsjerman);
}
#Override
public void onDestroy() {
super.onDestroy();
try {
kamusCursor.close();
db.close();
}catch (Exception e){
}
}
}
Retrieving from database as follows:
String selectQuery = "SELECT * FROM " + Variables.TABLE_ORDER
+ " WHERE " + Variables.TABLE_ORDER_CATEGORY ;
SQLiteDatabase database = dbHelper.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
map.put("Food_Id", cursor.getString(0));
cart_Array_List.add(map);
} while (cursor.moveToNext());
}
cursor.close();
database.close();
}
Try extending a BaseAdapter and ovverride the following method:
#Override
public int getCount() {
return arraylist.size();
}