Here is my code
Databasehandler.java
package com.example.mybucky.myapplication;
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.prefs.Preferences;
/**
* Created by Satyajeet Sen on 20/12/2016.
*/
public class DatabaseHandler extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "Register.db" ;
private static final int DATABASE_VERSION = 1 ;
private static final String TABLE_REGISTER = "REGISTER";
private static final String COL_ID = "id";
private static final String COL_NAME = "name";
private static final String COL_USERNAME = "username";
private static final String COL_PASSWORD = "password";
private static final String COL_AGE = "age";
SQLiteDatabase db;
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
//3rd argument to be passed is CursorFactory instance
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_REGISTER_TABLE = "CREATE TABLE " + TABLE_REGISTER + "("
+ COL_ID + " INTEGER PRIMARY KEY ," + COL_NAME + " TEXT ,"
+ COL_USERNAME + " TEXT ," + COL_PASSWORD + " TEXT ," + COL_AGE + " INTEGER "+")";
db.execSQL(CREATE_REGISTER_TABLE);
this.db=db;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_REGISTER);
// Create tables again
this.onCreate(db);
}
public void insertDetails(LoginRegisterBean l){
db=this.getWritableDatabase();
ContentValues values = new ContentValues();
String query ="SELECT * FROM "+TABLE_REGISTER;
Cursor cursor =db.rawQuery(query,null);
int count=cursor.getCount();
values.put(COL_ID,count);
// Contact Name
values.put(COL_NAME, l.getName());
values.put(COL_USERNAME, l.getUsername());
values.put(COL_PASSWORD, l.getPassword());
values.put(COL_AGE, l.getAge());
db.insert(TABLE_REGISTER,null,values);
db.close();
}
public String searchPass(String uname,String pass){
uname=COL_USERNAME;
pass=COL_PASSWORD;
db=this.getReadableDatabase();
String query=("SELECT " +uname+ "," +pass+ " from " + TABLE_REGISTER +"");
Cursor cursor = db.rawQuery(query,null);
String a,b ;
b="not found";
if(cursor.moveToFirst()){
do{
a=cursor.getString(0);
b=cursor.getString(1);
if(a.equals(COL_USERNAME)){
b=cursor.getString(1);
break;
}
}
while(cursor.moveToNext());
}
return b;
}
public String searchUser(String uname,String pass){
uname=COL_USERNAME;
pass=COL_PASSWORD;
db=this.getReadableDatabase();
String query=("SELECT " +uname+ "," +pass+ " from " + TABLE_REGISTER +"");
Cursor cursor = db.rawQuery(query,null);
String a,b ;
a="not found";
if(cursor.moveToFirst()){
do{
a=cursor.getString(0);
b=cursor.getString(1);
if(a.equals(COL_USERNAME)){
b=cursor.getString(1);
break;
}
}
while(cursor.moveToNext());
}
return a;
}
LoginRegisterBean getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_REGISTER, new String[] { COL_ID,
COL_USERNAME,COL_AGE }, COL_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
LoginRegisterBean retrievecontact = new LoginRegisterBean(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), Integer.parseInt(cursor.getString(2)));
// return contact
return retrievecontact;
}
}
UserAreaActivity.java 2edit texts one for age and other for username. Aim:-to display values of age nd username from database to edittext
package com.example.mybucky.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.EditText;
import android.widget.TextView;
import com.example.mybucky.myapplication.R;
import java.util.ArrayList;
import java.util.List;
public class UserAreaActivity extends AppCompatActivity {
DatabaseHandler helper = new DatabaseHandler(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_area);
final EditText etUsername = (EditText) findViewById(R.id.username);
final EditText etAge = (EditText) findViewById(R.id.age);
final TextView tvwelcome = (TextView) findViewById(R.id.tvwelcome);
public void retrievefromdb(LoginRegisterBean l){
List<LoginRegisterBean> lst =new ArrayList<LoginRegisterBean>();
for(int i=0;i<3;i++){
lst.add( helper.getContact(i));
}
}
}
}
I have a method returning a single contact in Databasehandler class but i dont need password to be displayed. Display fields only age and username in activity UserAreaActivity.
Welcome user!Your age is
age
---edit field------
username
---edit field-----
Related
I am new in developing android app, I want to display the username from my Table in SQLite Database after successfully login into layout activity_main.xml with activity name HomeActivity. The code for my textview in my activity_main.xml layout's
<TextView
android:id="#+id/NamaProfile"
android:layout_width="120dp"
android:layout_height="20dp"
android:layout_marginStart="160dp"
android:layout_marginTop="30dp"
android:text="TextView" />
And here's the code :
DBHelper
package com.demo.androidgudang;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/**
* Created by Administrator on 5/5/2016.
*/
public class DbHelper extends SQLiteOpenHelper {
public static final String TAG = DbHelper.class.getSimpleName();
public static final String DB_NAME = "myapp.db";
public static final int DB_VERSION = 1;
public static final String USER_TABLE = "users";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_USERNAME = "username";
public static final String COLUMN_EMAIL = "email";
public static final String COLUMN_PASS = "password";
/*
create table users(
id integer primary key autoincrement,
email text,
password text);
*/
public static final String CREATE_TABLE_USERS = "CREATE TABLE " + USER_TABLE + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_USERNAME + " TEXT,"
+ COLUMN_EMAIL + " TEXT,"
+ COLUMN_PASS + " TEXT);";
public DbHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_USERS);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + USER_TABLE);
onCreate(db);
}
/**
* Storing user details in database
* */
public void addUser(String username,String email,String password) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_USERNAME, username);
values.put(COLUMN_EMAIL, email);
values.put(COLUMN_PASS, password);
long id = db.insert(USER_TABLE, null, values);
db.close();
Log.d(TAG, "user inserted" + id);
}
public boolean getUser(String username, String email, String pass){
//HashMap<String, String> user = new HashMap<String, String>();
String selectQuery = "select * from " + USER_TABLE + " where " +
COLUMN_USERNAME + " = " + "'"+username+"'" + " and " + COLUMN_PASS + " = " + "'"+pass+"'";
if(email != null)
selectQuery += "and " + COLUMN_EMAIL + " = " + "'"+email+"'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if (cursor.getCount() > 0) {
return true;
}
cursor.close();
db.close();
return false;
}
}
HomeActivity
package com.demo.androidgudang;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class HomeActivity extends AppCompatActivity {
TextView txt_profile_name;
SharedPreferences sharedpreferences;
Intent intent;
private Button btnLogout;
private Session session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
session = new Session(this);
if(!session.loggedin()){
logout();
}
btnLogout = (Button)findViewById(R.id.btnLogout);
btnLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
logout();
}
});
}
private void logout(){
session.setLoggedin(false);
finish();
startActivity(new Intent(HomeActivity.this,LoginActivity.class));
}
}
Session.java
package com.demo.androidgudang;
import android.content.Context;
import android.content.SharedPreferences;
/**
* Created by Administrator on 5/5/2016.
*/
public class Session {
SharedPreferences prefs;
SharedPreferences.Editor editor;
Context ctx;
public Session(Context ctx){
this.ctx = ctx;
prefs = ctx.getSharedPreferences("myapp", Context.MODE_PRIVATE);
editor = prefs.edit();
}
public void setLoggedin(boolean logggedin){
editor.putBoolean("loggedInmode",logggedin);
editor.commit();
}
public boolean loggedin(){
return prefs.getBoolean("loggedInmode", false);
}
}
LoginActivity.java
package com.demo.androidgudang;
import android.content.Intent;
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.TextView;
import android.widget.Toast;
public class LoginActivity extends AppCompatActivity implements View.OnClickListener{
private Button login;
private EditText etUsername, etPass;
private DbHelper db;
private Session session;
TextView RegisterDisini;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
db = new DbHelper(this);
session = new Session(this);
login = (Button)findViewById(R.id.btnLogin);
etUsername = (EditText)findViewById(R.id.etUsername);
etPass = (EditText)findViewById(R.id.etPass);
login.setOnClickListener(this);
RegisterDisini = (TextView) findViewById(R.id.RegisterDisini);
RegisterDisini.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent registerHere = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(registerHere);
}
});
if(session.loggedin()){
startActivity(new Intent(LoginActivity.this,HomeActivity.class));
finish();
}
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btnLogin:
login();
break;
default:
}
}
private void login(){
String username = etUsername.getText().toString();
String pass = etPass.getText().toString();
if(db.getUser(username,null,pass)){
session.setLoggedin(true);
startActivity(new Intent(LoginActivity.this, HomeActivity.class));
finish();
}else{
Toast.makeText(getApplicationContext(), "Wrong username/password",Toast.LENGTH_SHORT).show();
}
}
}
Simply create a class for holding userName and loginSession
1.
public class UserInfo {
String name;
boolean isLogin;
public UserInfo(String name, boolean isLogin) {
this.name = name;
this.isLogin = isLogin;
}
}
Modify getUser()
public UserInfo getUser(String username, String email, String pass){
//HashMap<String, String> user = new HashMap<String, String>();
//UserInfo userinfo;
String selectQuery = "select * from " + USER_TABLE + " where " +
COLUMN_USERNAME + " = " + "'"+username+"'" + " and " + COLUMN_PASS + " = " + "'"+pass+"'";
if(email != null)
selectQuery += "and " + COLUMN_EMAIL + " = " + "'"+email+"'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if (cursor.getCount() > 0) {
return new UserInfo (cursor.getString(cursor.getColumnIndex(COLUMN_USERNAME)),true);
}
cursor.close();
db.close();
return new UserInfo(null,false);
}
Modify login()
{
UserInfo userinfo=db.getUser(username,null,pass)
if(userinfo.isLogin){
session.setLoggedin(true);
//you can store username
startActivity(new Intent(LoginActivity.this, HomeActivity.class)).putExtra("userName",userinfo.name);
finish();
}else{
Toast.makeText(getApplicationContext(), "Wrong username/password",Toast.LENGTH_SHORT).show();
}
}
In HomeActivity get value from intent and set it.
When the user presses Register button, the details he input will be saved into the database but it doesnt show anything.
Is there something wrong with my code? Why can't i see the data i inserted into the database? It doesnt crashes or something.
DBAdapter
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;
import android.util.Log;
public class DBAdapter
{
public static final String KEY_ROWID = "_id";
public static final String KEY_FNAME = "fname";
public static final String KEY_LNAME = "lname";
public static final String KEY_MNAME = "mname";
public static final String KEY_CONTACTNUM = "contactNum";
public static final String KEY_LICENSE = "license";
public static final String KEY_USER = "username";
public static final String KEY_PASS = "password";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "sampleForFinals";
private static final String DATABASE_TABLE = "drivers";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE =
"create table drivers (_id integer primary key autoincrement, "
+ "fname text not null, lname text not null, "
+ "mname text not null, contactNum text not null," +
"license text not null, username text not null, password text not null);";
private final Context context;
private DatabaseHelper DBHelper;
private 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)
{
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion
+ " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS drivers");
onCreate(db);
}
}
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
//---insert a driver's information into the database---
public long insertDriver(String fname, String lname, String mname, String contactNum, String license, String user, String pass)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_FNAME, fname);
initialValues.put(KEY_LNAME, lname);
initialValues.put(KEY_MNAME, mname);
initialValues.put(KEY_CONTACTNUM, contactNum);
initialValues.put(KEY_LICENSE, license);
initialValues.put(KEY_USER, user);
initialValues.put(KEY_PASS, pass);
return db.insert(DATABASE_TABLE, null, initialValues);
}
}
Register
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.ftlibrary.Fit;
public class Register extends Activity {
EditText firstname,lastname, middlename, contactNum, license, username, password;
Button register;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Fit.FitSetClientKey("SZIERAINE1527");
Fit.FitSetAppName("sampleForFinals");
firstname = (EditText) findViewById(R.id.et_firstname);
lastname = (EditText) findViewById(R.id.et_lastname);
middlename = (EditText) findViewById(R.id.et_middlename);
contactNum = (EditText) findViewById(R.id.et_contactNumber);
license = (EditText) findViewById(R.id.et_license);
username = (EditText) findViewById(R.id.et_username);
password = (EditText) findViewById(R.id.et_password);
register = (Button) findViewById(R.id.btn_register);
register.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
DBAdapter db = new DBAdapter(Register.this);
String fname = firstname.getText().toString();
String lname = lastname.getText().toString();
String mname = middlename.getText().toString();
String contact = contactNum.getText().toString();
String plate = license.getText().toString();
String user = username.getText().toString();
String pass = password.getText().toString();
db.open();
long id = db.insertDriver(fname, lname, mname, contact, plate, user, pass);
db.close();
}
});
}
}
Why can't i see any record in the database? TT TT
I've built a database class in Android using SQLite, so far it just creates a database and inputs data, however the only log report I see is that the data has been input, but the log never shows for the database creation.
I have also seen people have a .db file in their assets folder, mine is not created.
so:
1) How come it's not showing the log error for building the database, and also is there meant to be a .db file created through SQLite? It's my first time using it.
2) If it is creating, how can I call the List from the getData() method and output it in MainActivity? I've tried using intents but once I realised I wasn't getting the log report from the database creation so I need that sorted before anything.
MainActivity.java
public class MainActivity extends Activity {
Intent appIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DB db = new DB(this);
db.insertStudent("T", "T", 5, "T", "T", "T");
List<tableStudents> outputList = db.getData();
}
DB.java
package com.example.project;
import java.util.ArrayList;
import java.util.List;
import com.example.project.tableStudents.tableColumns;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.view.View;
public class DB extends SQLiteOpenHelper {
public static final int db_version = 1;
public static final String Table = "Students";
public static final String Student_ID = "Student_ID";
public static final String Student_Name = "Student_Name";
public static final String Student_Password = "Student_Password";
public static final String Student_Gender = "gender";
public static final String Student_Age = "age";
public static final String Student_Course = "course";
public static final String Modules = "modules";
public DB(Context context) {
super(context, tableColumns.Database, null, db_version);
}
#Override
public void onCreate(SQLiteDatabase db) {
//Create Table
db.execSQL("CREATE TABLE " + Table + "(" +
Student_ID + " INTEGER PRIMARY KEY, " +
Student_Name + " TEXT, " +
Student_Password + " TEXT, " +
Student_Gender + " TEXT, " +
Student_Age + " INTEGER, " +
Student_Course + " TEXT, " +
Modules + "TEXT");
Log.d("DB", "DB Created");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + Table);
onCreate(db);
}
public List<tableStudents> getData() {
List<tableStudents> studentList = new ArrayList<tableStudents>();
// Select All Query
String selectQuery = "SELECT * FROM " + Table;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
tableStudents student = new tableStudents();
student.name = cursor.getString(0);
student.gender = cursor.getString(1);
student.age = Integer.parseInt(cursor.getString(2));
student.password = cursor.getString(3);
student.course = cursor.getString(4);
student.modules = cursor.getString(5);
studentList.add(student);
} while (cursor.moveToNext());
}
// return contact list
return studentList;
}
public boolean insertStudent(String name, String gender, int age, String password, String course, String modules) {
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(Student_Name, name);
contentValues.put(Student_Gender, gender);
contentValues.put(Student_Age, age);
contentValues.put(Student_Password, password);
contentValues.put(Student_Course, course);
contentValues.put(Modules, modules);
//Log for admin insert
Log.d("DB", "Inserted Successfully");
return true;
}
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Matt Murphy please go through this link for each detail for your project
http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/.
I don't know why this error is appearing, can somebody help me please? to continue my project? thanks
//BancoDeDados class
package kabashima.materiaisdeconstrucaoconcept.bancodedados;
import android.content.ContentValue`import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import kabashima.materiaisdeconstrucaoconcept.Contact;
public class BancoDeDados extends SQLiteOpenHelper {
// private static final int DATABASE_VERSION = 1;
//private static final String DATABASE_NAME = "contacts.db";
private static final String TABLE_NAME = "contacts";
private static final String COLUMN_ID = "id";
private static final String COLUMN_NOME = "nome";
private static final String COLUMN_EMAIL = "email";
private static final String COLUMN_SENHA = "senha";
SQLiteDatabase db;
private static final String TABLE_CREATE = "create table contacts(id integer primary key not null ," +
"nome text not null, email text not null, senha text not null);";
public BancoDeDados(Context context){
//super(context, DATABASE_NAME, null, DATABASE_VERSION);
super(context, "contacts.db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABLE_CREATE);
db.execSQL( ScriptSQL.getCreateEstoqueProdutos());
this.db=db;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String query = "DROP TABLE IF EXISTS" + TABLE_NAME;
db.execSQL(query);
this.onCreate(db);
}
public void insertContact(Contact c) {
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
String query = "select * from contacts";
Cursor cursor = db.rawQuery(query, null);
int count = cursor.getCount();
values.put(COLUMN_ID, count);
values.put(COLUMN_NOME, c.getNome());
values.put(COLUMN_EMAIL, c.getEmail());
values.put(COLUMN_SENHA, c.getSenha());
db.insert(TABLE_NAME, null, values);
db.close();
}
public String searchPass(String nome){
db = this.getReadableDatabase();
String query = "select nome, senha from " + TABLE_NAME;
Cursor cursor = db.rawQuery(query, null);
String a,b;
b = "not found";
if(cursor.moveToFirst()){
do{
a = cursor.getString(0);
if(a.equals(nome))
{
b = cursor.getString(1);
break;
}
}while (cursor.moveToNext());
}
return b;
}
}
//AND THE SCRIPTSQL
package kabashima.materiaisdeconstrucaoconcept.bancodedados;
public static String getCreateEstoqueProdutos()
{
StringBuilder sqlBuilder = new StringBuilder();
sqlBuilder.append(" CREATE TABLE IF NOT EXISTS ESTOQUEPRODUTOS ( ");
sqlBuilder.append("_id INTEGER NOT NULL ");
sqlBuilder.append("PRIMARY KEY AUTOINCREMENT, ");
sqlBuilder.append("NOME VARCHAR (200), ");
sqlBuilder.append("MARCA VARCHAR (200), ");
sqlBuilder.append("LOJA VARCHAR (200), ");
sqlBuilder.append("ESTOQUE VARCHAR (10), ");
sqlBuilder.append("VALOR VARCHAR (30), ");
sqlBuilder.append(");");
return sqlBuilder.toString();
}
}
//RepositorioEstoque class
package kabashima.materiaisdeconstrucaoconcept.bancodedados.dominio;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.widget.ArrayAdapter;
public class RepositorioEstoque {
private SQLiteDatabase conn;
public RepositorioEstoque(SQLiteDatabase conn) {
this.conn = conn;
}
public void TesteInserirProdutos() {
for (int i = 0; i < 10; i++) {
ContentValues values = new ContentValues();
values.put("NOME", "JR");
conn.insertOrThrow("ESTOQUEPRODUTOS", null, values);
}
}
public ArrayAdapter<String> buscaEstoque(Context context)
{
ArrayAdapter<String> adpEstoque = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1);
Cursor cursor = conn.query("ESTOQUEPRODUTOS",null,null,null,null,null,null);
if (cursor.getCount() > 0)
{
do {
cursor.moveToFirst();
String nome = cursor.getString(1);
adpEstoque.add(nome);
} while (cursor.moveToNext());
}
return adpEstoque;
}
}
the error says it on console : 2938- 2938/kabashima.materiaisdeconstrucaoconcept E/SQLiteLog﹕ (1) no such table: ESTOQUEPRODUTOS
Hy!
I'm trying to create an application that looks for gps data that was stored in SQlite database.
But I'm facing a problem:
I built an DbAdapter class that creates my database and now I'm trying from another class to get an cursor over my all data,using this function:
public Cursor fetchAllData() {
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_LONGITUDE,KEY_LATITUDE,KEY_COUNTRY,KEY_TOWN,KEY_STREET}, null, null, null, null, null);
}
Now,I'm creating an instance of DbAdapter in my new class,but I get forceclose when I insert this line:Cursor c=db.fetchAllData();
The class that creates my database looks like this:
package test.android;
import java.util.ArrayList;
import java.util.List;
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;
import android.util.Log;
public class CoordonateDbAdapter {
public static final String KEY_ROWID = "_id";
public static final String KEY_LONGITUDE= "longitude";
public static final String KEY_LATITUDE = "latitude";
public static final String KEY_COUNTRY= "country";
public static final String KEY_TOWN= "town";
public static final String KEY_STREET = "street";
private static final String TAG = "CoordonateDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_CREATE =
"create table car1 (_id integer primary key autoincrement, "
+ "longitude text not null, latitude text not null," +
"country text not null,town text not null,street text not null);";
private static final String DATABASE_NAME = "gps";
private static final String DATABASE_TABLE = "masini";
private static final int DATABASE_VERSION = 1;
private final Context mCtx;
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) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS notes");
onCreate(db);
}
}
public CoordonateDbAdapter(Context ctx) {
this.mCtx = ctx;
}
public CoordonateDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
public long insertData(String longitude, String latitude, String country, String town, String street) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_LONGITUDE, longitude);
initialValues.put(KEY_LATITUDE, latitude);
initialValues.put(KEY_COUNTRY, country);
initialValues.put(KEY_TOWN, town);
initialValues.put(KEY_STREET, street);
return mDb.insert(DATABASE_TABLE, null, initialValues);
}
public boolean deleteData(long rowId) {
return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
public Cursor fetchAllData() {
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_LONGITUDE,KEY_LATITUDE,KEY_COUNTRY,KEY_TOWN,KEY_STREET}, null, null, null, null, null);
}
public Cursor fetchData(long rowId) throws SQLException {
Cursor mCursor = mDb.query(true, DATABASE_TABLE, new String[]
{KEY_ROWID, KEY_LONGITUDE,KEY_LATITUDE,KEY_COUNTRY,KEY_TOWN,KEY_STREET},
KEY_ROWID + "=" + rowId, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public boolean updateNote(long rowId, String longitude, String latitude,String country, String town,String street) {
ContentValues args = new ContentValues();
args.put(KEY_LONGITUDE, longitude);
args.put(KEY_LATITUDE, latitude);
args.put(KEY_COUNTRY, country);
args.put(KEY_TOWN, town);
args.put(KEY_STREET, street);
return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
}
public List<String> selectAll() {
List<String> list = new ArrayList<String>();
Cursor cursor = this.mDb.query(DATABASE_TABLE, new String[] { "longitude"},
null, null, null, null, "name desc");
if (cursor.moveToFirst()) {
do {
list.add(cursor.getString(0));
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return list;
}
}
And the class that retrieves the gps data is like this:
package test.android;
import java.util.List;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.Toast;
public class screen_database extends Activity{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen_database);
CoordonateDbAdapter db = new CoordonateDbAdapter(this);
db.open();
long id;
// id= db.insertData("-36.2", "125","Romania","Cluj","Zorilor");
// db.insertData("44", "55","Romania","Iasi","Alexandru Ioan Cuza");
// List<String> names = db.selectAll();
Cursor c=db.fetchAllData();
/* if (c.moveToFirst())
{
do {
// DisplayTitle(c);
} while (c.moveToNext());
}*/
// c.close();
}
/* public void DisplayTitle(Cursor c)
{
Toast.makeText(this,
"longitude: " + c.getString(0) + "\n" +
"latitude: " + c.getString(1) + "\n" +
"country: " + c.getString(2) + "\n" +
"town: " + c.getString(3),
Toast.LENGTH_LONG).show();
}*/
}
//}
You can see lots of lines that are comments because I get force close when I'm asking for a Cursor,so I tried to keep it as simple.
Do I need any permissions to work with cursors,becuase I looked on the internet and all the line code looks like mine?!
Another problem is that my application is quite big,and I'm accesing this classes from other classes....a long row of classes until I get to query from the Sqlite.
I would really apreciate if you would help me,it might be something simple but I can't figure it out what it is.Thank you!!!
first try to access directly by copying
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_LONGITUDE,KEY_LATITUDE,KEY_COUNTRY,KEY_TOWN,KEY_STREET}, null, null, null, null, null);
instead of calling it by method.
If that works, check if curser is available in the method.
If it is, try to reduce the SQLQuery like
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_LONGITUDE}, null, null, null, null, null);
and add more columns step by step.