How to pass list-view data to SQLite database? - java

I'm building message app and my message and number are showing in list-view but I'm not sure how to pass the list-view data to SQLite database? This is my list view code looks like but not sure how to pass the data to database.
package com.example.sunny.messager;
import java.util.ArrayList;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.database.Cursor;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class ListActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
ListView lv=(ListView)findViewById(R.id.SmsList);
if(fetchInbox()!=null){
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,fetchInbox());
lv.setAdapter(adapter);
}
}
public ArrayList<String> fetchInbox(){
ArrayList<String> sms=new ArrayList<String>();
Uri uriSms=Uri.parse("content://sms/");
Cursor cursor=getContentResolver().query(uriSms, new String[]{"_id","address","date","body"}, null, null, null);
cursor.moveToFirst();
while(cursor.moveToNext()){
String address=cursor.getString(1);
String body=cursor.getString(3);
sms.add("Number: " +address+"\n Message: " +body);
}
return sms;
}
}

You need to use these classes SQLiteDatabase and and SQLiteOpenHelper.
SQLiteDatabase is the class for us to perform CRUD function.
SQLiteOpenHelper is a helper class to manage database creation and version management.
Now let’s start code on table structure portion first – create table in Android. We will create a file name SMSData.java , and the code in this file will look like this
package com.example.sqlitedb;
public class SMSData {
// Labels table name
public static final String TABLE = "SMSData";
// Labels Table Columns names
public static final String KEY_ID = "id";
public static final String KEY_number = "number";
public static final String KEY_message= "message";
// property help us to keep data
public int SMSData_ID;
public int number;
public String message;
}
We’ll create a class and name it DBHelper.java and code in this file will look like this, to ease on understand code line by line i put comment in code.
package com.example.sqlitedb;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHelper extends SQLiteOpenHelper {
//version number to upgrade database version
//each time if you Add, Edit table, you need to change the
//version number.
private static final int DATABASE_VERSION = 4;
// Database Name
private static final String DATABASE_NAME = "crud.db";
public DBHelper(Context context ) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
//All necessary tables you like to create will create here
String CREATE_TABLE_SMSDATA= "CREATE TABLE " + SMSData.TABLE + "("
+ SMSData.KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT ,"
+ SMSData.KEY_number+ " INTEGER, "
+ SMSData.KEY_message+ " TEXT )";
db.execSQL(CREATE_TABLE_SMSDATA);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed, all data will be gone!!!
db.execSQL("DROP TABLE IF EXISTS " + SMSData.TABLE);
// Create tables again
onCreate(db);
}
}
With above 2 steps, SMSData table will be created when app get started and now we could code the CRUD functions! Create SMSDataRepo.java, the purpose of this class is to perform CRUD on the SMSData table. The code in this file will look like this.
package com.example.sqlitedb;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.HashMap;
public class SMSDataRepo {
private DBHelper dbHelper;
public SMSDataRepo(Context context) {
dbHelper = new DBHelper(context);
}
public int insert(SMSData sMSData) {
//Open connection to write data
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(SMSData.KEY_number, sMSData.number);
values.put(SMSData.KEY_message,sMSData.message);
// Inserting Row
long SMSData_Id = db.insert(SMSData.TABLE, null, values);
db.close(); // Closing database connection
return (int) SMSData_Id;
}
public void delete(int SMSData_Id) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
// It's a good practice to use parameter ?, instead of concatenate string
db.delete(SMSData.TABLE, SMSData.KEY_ID + "= ?", new String[] { String.valueOf(SMSData_Id) });
db.close(); // Closing database connection
}
public void update(SMSData sMSData) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(SMSData.KEY_number, sMSData.number);
values.put(SMSData.KEY_message,sMSData.message);
// It's a good practice to use parameter ?, instead of concatenate string
db.update(SMSData.TABLE, values, SMSData.KEY_ID + "= ?", new String[] { String.valueOf(SMSData.SMSData_ID) });
db.close(); // Closing database connection
}
public ArrayList<HashMap<String, String>> getSMSDataList() {
//Open connection to read only
SQLiteDatabase db = dbHelper.getReadableDatabase();
String selectQuery = "SELECT " +
SMSData.KEY_ID + "," +
SMSData.KEY_number+
SMSData.KEY_message+ "," +
" FROM " + SMSData.TABLE;
//SMSData sMSData= new SMSData();
ArrayList<HashMap<String, String>> sMSDataList = new ArrayList<HashMap<String, String>>();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
HashMap<String, String> sMSData= new HashMap<String, String>();
sMSData.put("number", cursor.getString(cursor.getColumnIndex(SMSData.KEY_number)));
sMSData.put("message", cursor.getString(cursor.getColumnIndex(SMSData.KEY_message)));
sMSDataList.add(sMSData);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return sMSDataList;
}
public SMSData getSMSDataById(int Id){
SQLiteDatabase db = dbHelper.getReadableDatabase();
String selectQuery = "SELECT " +
SMSData.KEY_ID + "," +
SMSData.KEY_number + "," +
SMSData.KEY_message +
" FROM " + SMSData.TABLE
+ " WHERE " +
SMSData.KEY_ID + "=?";// It's a good practice to use parameter ?, instead of concatenate string
int iCount =0;
SMSData sMSData= new SMSData();
Cursor cursor = db.rawQuery(selectQuery, new String[] { String.valueOf(Id) } );
if (cursor.moveToFirst()) {
do {
sMSData.SMSData_ID =cursor.getInt(cursor.getColumnIndex(SMSData.KEY_ID));
sMSData.number=cursor.getInt(cursor.getColumnIndex(SMSData.KEY_number));
sMSData.message=cursor.getString(cursor.getColumnIndex(SMSData.KEY_message));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return sMSData;
}
}

Related

I have an ArrayList coming from SQL Server stored procedure and I want to insert all the data to a SQLite database. Please look at my code below

I was able to get data from SQL Server, but I don't know what to do after, Please help me or any idea how can I insert the data from my ArrayList to SQLite Database and insert it into a Custom ListView.
.................................................................................................
ConnectionHelper.java
package com.example.storedprocedures;
import android.annotation.SuppressLint;
import android.os.StrictMode;
import android.util.Log;
import java.sql.Connection;
import java.sql.DriverManager;
public class ConnectionHelper {
Connection con;
String ip = "***.***.*.***";
String port = "*****";
String classes = "net.sourceforge.jtds.jdbc.Driver";
String database = "CentralizedDB";
String username = "******";
String password = "********";
String url = "jdbc:jtds:sqlserver://"+ip+":"+port+"/"+database;
#SuppressLint("NewApi")
public Connection conclass(){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection connection = null;
try{
Class.forName(classes);
connection = DriverManager.getConnection(url, username, password);
}catch(Exception exception){
Log.e("Error:", exception.getMessage());
}
return connection;
}
}
MainActivity.java
package com.example.storedprocedures;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
TextView lblheader;
Button btnviewall,btnview;
ListView lstTaggedList;
EditText edtid;
Connection connect;
ResultSet rs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lblheader = (TextView) findViewById(R.id.lblheader);
lstTaggedList = (ListView) findViewById(R.id.lstTaggedList);
btnviewall = (Button) findViewById(R.id.btnviewall);
btnview = (Button) findViewById(R.id.btnview);
edtid = (EditText) findViewById(R.id.edtid);
ConnectionHelper connectionHelper = new ConnectionHelper();
connect = connectionHelper.conclass();
btnviewall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
PreparedStatement statement = connect.prepareStatement("EXEC SP_TaggedList");
final ArrayList list = new ArrayList();
rs = statement.executeQuery();
while (rs.next()) {
list.add(rs.getString("mrCode"));
list.add(rs.getString("docId_branch"));
list.add(rs.getString("brchName"));
list.add(rs.getString("industry_type"));
list.add(rs.getString("specialization_id"));
list.add(rs.getString("uName"));
list.add(rs.getString("class_id"));
list.add(rs.getString("max_visit"));
}
ArrayAdapter adapter = new ArrayAdapter(MainActivity.this,
android.R.layout.simple_list_item_1, list);
} catch (SQLException e) {
Toast.makeText(MainActivity.this, e.getMessage().toString(),
Toast.LENGTH_LONG).show();
}
}
});
btnview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
PreparedStatement statement = connect.prepareStatement("EXEC SP_TaggedList '"+edtid.getText().toString()+"'");
final ArrayList list = new ArrayList();
rs = statement.executeQuery();
while (rs.next()) {
list.add(rs.getString("mrCode"));
list.add(rs.getString("docId_branch"));
list.add(rs.getString("brchName"));
list.add(rs.getString("industry_type"));
list.add(rs.getString("specialization_id"));
list.add(rs.getString("uName"));
list.add(rs.getString("class_id"));
list.add(rs.getString("max_visit"));
}
ArrayAdapter adapter = new ArrayAdapter(MainActivity.this,
android.R.layout.simple_list_item_1, list);
} catch (SQLException e) {
Toast.makeText(MainActivity.this, e.getMessage().toString(),
Toast.LENGTH_LONG).show();
}
}
});
lstTaggedList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
String item = lstTaggedList.getItemAtPosition(position).toString();
Toast.makeText(MainActivity.this, item + " selected", Toast.LENGTH_LONG).show();
}
});
}
}
With SQLite on android, the typically way to use an SQLite database is to have a class that extends SQLiteOpenHelper.
SQLiteOpenHelper will if the database does not exist call the onCreate method passing an empty SQLiteDatabase to the method (not totally empty as sqlite_master and android_metadata tables will exist, but empty as far as user tables will be concerned). You can then create the tables using the execSQL method for each table (or other components such as indexes, view triggers).
You can also include other methods that cater for CRUD operations to access the data.
Here's a Simple Demo of a database that drives a ListView.
First DatabaseHelper i.e. the class that extends SQLiteOpenHelper :-
class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "the_database.db";
public static final int DATABASE_VERSION = 1;
private static volatile DatabaseHelper INSTANCE; /* singleton instance of DatabaseHelper */
private SQLiteDatabase db;
/* Constructor (not publicly available) */
private DatabaseHelper(Context context) {
super(context,DATABASE_NAME,null,DATABASE_VERSION);
db = this.getWritableDatabase();
}
/* Get singleton instance of DatabaseHelper */
public static DatabaseHelper getInstance(Context context) {
if (INSTANCE==null) {
INSTANCE = new DatabaseHelper(context);
}
return INSTANCE;
}
public static final String TABLE_NAME = "the_table";
public static final String COLUMN_MRCODE = BaseColumns._ID; /* Cursor Adapter must have _id column */
public static final String COLUMN_DOCID_BRANCH = "docid_branch";
public static final String COLUMN_BRCHNAME = "brchname";
public static final String COLUMN_INDUSTRY_TYPE = "industry_type";
public static final String COLUMN_SPECIALIZATION_ID = "specilization_id";
public static final String COLUMN_UNAME = "uname";
public static final String COLUMN_CLASS_ID = "class_id";
public static final String COLUMN_MAX_VISIT = "max_visit";
private static final String CRTSQL_THE_TABLE =
"CREATE TABLE IF NOT EXISTS " + TABLE_NAME + "(" +
COLUMN_MRCODE + " INTEGER PRIMARY KEY" +
"," + COLUMN_DOCID_BRANCH + " INTEGER " +
"," + COLUMN_BRCHNAME + " TEXT " +
"," + COLUMN_INDUSTRY_TYPE + " TEXT " +
"," + COLUMN_SPECIALIZATION_ID + " INTEGER " +
"," + COLUMN_UNAME + " TEXT " +
"," + COLUMN_CLASS_ID + " INTEGER " +
"," + COLUMN_MAX_VISIT + " INTEGER " +
")";
private static final String CRTSQL_DOCID_BRANCH_INDEX =
"CREATE INDEX IF NOT EXISTS " + COLUMN_DOCID_BRANCH + "_" + TABLE_NAME + "_idx001 " +
" ON " + TABLE_NAME + "(" +
COLUMN_DOCID_BRANCH +
")";
/* MUST be overridden (not much use if not used) */
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CRTSQL_THE_TABLE);
db.execSQL(CRTSQL_DOCID_BRANCH_INDEX);
}
/* MUST be overridden but doesn't necessarily have to do anything*/
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
/* CRUD */
public long insert(Long mrcode, long docid_branch, String brchname, String industry_type, String uname, long class_id, long max_visit ) {
ContentValues cv = new ContentValues();
if (mrcode != null) {
cv.put(COLUMN_MRCODE,mrcode);
}
cv.put(COLUMN_DOCID_BRANCH,docid_branch);
if (brchname != null) {
cv.put(COLUMN_BRCHNAME,brchname);
}
if (industry_type != null) {
cv.put(COLUMN_INDUSTRY_TYPE,industry_type);
}
if (uname != null) {
cv.put(COLUMN_UNAME,uname);
}
cv.put(COLUMN_CLASS_ID,class_id);
cv.put(COLUMN_MAX_VISIT,max_visit);
return db.insert(TABLE_NAME,null,cv);
}
public Cursor getAllTheTableRows() {
return db.query(TABLE_NAME,null,null,null,null,null,null);
}
#SuppressLint("Range")
public long getNumberOfRowsInTheTable() {
long rv=0;
String output_column = "row_count";
Cursor csr = db.query(TABLE_NAME,new String[]{"count(*) AS " + output_column},null,null,null,null,null);
if (csr.moveToFirst()) {
rv = csr.getLong(csr.getColumnIndex(output_column));
}
csr.close(); /* should always close cursors when done with them */
return rv;
}
}
as can be seen the database will
have 1 table named the_table
have an index on the docid_branch column
all the component names are defined based upon a single hard coded name.
have columns along the lines of what can be seen from your code.
a singleton approach has been used
some basic CRUD methods have been included to allow data to be inserted and extracted.
To demonstrate use of the DatabaseHelper and a means of driving a ListView (via a CursorAdapter) then MainActivity :-
public class MainActivity extends AppCompatActivity {
DatabaseHelper dbHelper;
ListView lv;
SimpleCursorAdapter sca;
Cursor csr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHelper = DatabaseHelper.getInstance(this);
lv = this.findViewById(R.id.lv);
if (dbHelper.getNumberOfRowsInTheTable() < 1) {
addSomeTestData();
}
setOrRefreshListView();
}
/*
Whenever the ListView is to be changed (including initially)
this can be called.
*/
private void setOrRefreshListView() {
csr = dbHelper.getAllTheTableRows(); /* gets the latest data from the database */
if (sca == null) {
sca = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_2,
csr,
new String[]{DatabaseHelper.COLUMN_UNAME,DatabaseHelper.COLUMN_INDUSTRY_TYPE}, /* The column names in the Cursor */
new int[]{android.R.id.text1,android.R.id.text2},0); /* The respective id's in the ListView's layout */
lv.setAdapter(sca);
} else {
sca.swapCursor(csr);
}
}
private void addSomeTestData() {
dbHelper.insert(001L,111,"Branch001","MINING","FRED",1,10);
dbHelper.insert(null,222,"Branch002","HOSPITALITY","MARY",6,1);
dbHelper.insert(null,333,"Branch003","REFINING","JANE",5,5);
}
}
Note that for brevity a predefined/stock layout has been used
Results
When run then :-
Using App Inspection then :-
as can bee seen the specialization_id is NULL this is because the insert method in the DatabaseHelper class omitted consideration of the column.
Again using App Inspection but with a custom query then :-
android_metadata table can be seen to exist (contains the locale and is android specific)
the docid_branch_the_table_idx001 index has been created.
how can I insert the data from my ArrayList to SQLite Database
So with the above you just need to get an Instance of the the DatabaseHelper and then invoke the insert method whilst looping through your ArrayList.
This isn't the best solution as each insert is done in it's own transaction.

Android crashes to previous screen debug in the post

I was adding a list view to my database when in the end the database list view windows opens and crashes
Do you have any idea what this crash code mean? I can add code later if you need it
(Edit still no luck finding anything that could throw this command)
Can you check with a command any way?
Database form:
package com.example.laivumusis;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
import com.example.laivumusis.KlausimuContracts.*;
import java.util.ArrayList;
import java.util.List;
public class KlausimynoDatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "Klausimynas.db";
private static final int DATABASE_VERSION = 1;
private SQLiteDatabase db;
public KlausimynoDatabaseHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
this.db = db;
final String SQL_CREATE_QUESTIONS_TABLE = "CREATE TABLE " +
KlausimuLentele.TABLE_NAME + " ( " +
KlausimuLentele._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KlausimuLentele.COLUMN_QUESTION + " TEXT, " +
KlausimuLentele.COLLUMN_OPTION1 + " TEXT, " +
KlausimuLentele.COLLUMN_OPTION2 + " TEXT, " +
KlausimuLentele.COLLUMN_OPTION3 + " TEXT, " +
KlausimuLentele.COLLUMN_ANSWER_NR + " INTEGER" +
")";
db.execSQL(SQL_CREATE_QUESTIONS_TABLE);
fillKlausimuLentele();
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + KlausimuLentele.TABLE_NAME);
onCreate(db);
}
public boolean addData (String pasirinkimas1){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KlausimuLentele.COLLUMN_OPTION1, pasirinkimas1);
long result = db.insert(KlausimuLentele.TABLE_NAME, null, contentValues);
if (result == -1){
return false;
}else{
return true;
}
}
public Cursor getListContents() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("SELECT * FROM " + KlausimuLentele.TABLE_NAME,null );
return data;
}
private void fillKlausimuLentele() {
Klausimai q1 = new Klausimai("Kelintais metais buvo išleista java proogramavimo kalba?", "1991", "1995", "1989", 1);
addQuestion(q1);
Klausimai q2 = new Klausimai("Ar destytojas pasigailės mūsų?", "Priklauso nuo darbo", "Priklauso nuo pingų", "Prklauso nuo nuotaikos", 1);
addQuestion(q2);
Klausimai q3 = new Klausimai("Kai sunervina žaidimas koks geriausias būdas iš jo išeiti?", "Alt+F4", "Quit To desktop", "Ištraukti maitinimo laida",1);
addQuestion(q3);
Klausimai q4 = new Klausimai("A is correct again", "A", "B", "C", 1);
addQuestion(q4);
Klausimai q5 = new Klausimai("B is correct agian", "A", "B", "C", 2);
addQuestion(q5);
}
private void addQuestion(Klausimai klausimai) {
ContentValues cv = new ContentValues();
cv.put(KlausimuLentele.COLUMN_QUESTION, klausimai.getKlausimas());
cv.put(KlausimuLentele.COLLUMN_OPTION1, klausimai.getPasirinkimas1());
cv.put(KlausimuLentele.COLLUMN_OPTION2, klausimai.getPasirinkimas2());
cv.put(KlausimuLentele.COLLUMN_OPTION3, klausimai.getPasirinkimas3());
cv.put(KlausimuLentele.COLLUMN_ANSWER_NR, klausimai.getAtsakymoNr());
db.insert(KlausimuLentele.TABLE_NAME, null, cv);
}
public List<Klausimai> getAllQuestions() {
List<Klausimai> klausimuSarasas = new ArrayList<>();
db = getReadableDatabase();
Cursor c = db.rawQuery("SELECT * FROM " + KlausimuLentele.TABLE_NAME, null);
if (c.moveToFirst()) {
do {
Klausimai klausimai = new Klausimai();
klausimai.setKlausimas(c.getString(c.getColumnIndex(KlausimuLentele.COLUMN_QUESTION)));
klausimai.setPasirinkimas1(c.getString(c.getColumnIndex(KlausimuLentele.COLLUMN_OPTION1)));
klausimai.setPasirinkimas2(c.getString(c.getColumnIndex(KlausimuLentele.COLLUMN_OPTION2)));
klausimai.setPasirinkimas3(c.getString(c.getColumnIndex(KlausimuLentele.COLLUMN_OPTION3)));
klausimai.setAtsakymoNr(c.getInt(c.getColumnIndex(KlausimuLentele.COLLUMN_ANSWER_NR)));
klausimuSarasas.add(klausimai);
} while (c.moveToNext());
}
c.close();
return klausimuSarasas;
}
}
But i think the problem is in here because this is the form which crashes:
package com.example.laivumusis;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
public class ViewListData extends AppCompatActivity {
KlausimynoDatabaseHelper myDB;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.editlistview_layout);
ListView listView = (ListView) findViewById(R.id.listView);
myDB = new KlausimynoDatabaseHelper(this);
ArrayList<String> theList = new ArrayList<>();
Cursor data = myDB.getListContents();
if (data.getCount() == 0) {
Toast.makeText(ViewListData.this,"Database tuščias!",Toast.LENGTH_LONG).show();
}else{
while (data.moveToNext()){
theList.add(data.getString(1));
ListAdapter listAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,theList);
listView.setAdapter(listAdapter);
}
}
}
}
Debug:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.laivumusis, PID: 3859
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
Your object seems to be null while converting to string. use the following to check if null:
if (obj !=null){
//store in database
}

Building Database and outputting data in Android

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/.

Android SQLite problems, how to display data

Hi guys I'm currently creating an Android Application on Eclipse through various online tutorials. I have got as far as creating a SQLite database and being able to manually input information - although I'm not quite sure how to delete the information yet. What I would like is for the user to click a button and then it will display the information that they have inputted on a profile page - at the moment it is only two fields. I have spent hours going through various tutorials and research and just can not seem to get it to work. If anybody has the time to have a look through my code and tell me how I should call the methods to add new data via a button then it would be greatly appreciated. I think I am loosing my mind. I also understand I may not have gone around the correct way of setting things up but I am still learning.
Here is my DatabaseHandler.java file
package com.example.myapp;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "contactsManager";
// Contacts table name
private static final String TABLE_CONTACTS = "contacts";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_EMAIL = "email";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_EMAIL + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new contact
void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_EMAIL, contact.getEmail()); // Contact Phone
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
// Getting single contact
Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_EMAIL }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
// return contact
return contact;
}
// Getting All Contacts
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setEmail(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
// Updating single contact
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_EMAIL, contact.getEmail());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}
// Deleting single contact
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
}
// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
And below is my page that so far just sends forced information to the database as you will see.
package com.example.myapp;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class Addrecord extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
DatabaseHandler db = new DatabaseHandler(this);
/**
* CRUD Operations
* */
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
db.addContact(new Contact("Dan", "dljbrown#icloud.com"));
db.addContact(new Contact("Pash", "pashj#hotmail.com"));
db.addContact(new Contact("Nigel", "Dancinboyforever#hotmail.com"));
db.addContact(new Contact("Jit", "Jit#hotmail.com"));
// Log.d("Delete: ", "Deleting..");
// db.deleteContact(new Contact("Dan", "dljbrown#icloud.com"));
// db.deleteContact(new Contact("Pash", "pashj#hotmail.com"));
// db.deleteContact(new Contact("Nigel",
// "Dancinboyforever#hotmail.com"));
// db.deleteContact(new Contact("Jit", "dljbrown#icloud.com"));
// Reading all contacts
Log.d("Reading: ", "Reading all contacts..");
List<Contact> contacts = db.getAllContacts();
for (Contact cn : contacts) {
String log = "Id: " + cn.getID() + " ,Name: " + cn.getName()
+ " ,Email: " + cn.getEmail();
// Writing Contacts to log
Log.d("Name: ", log);
}
}
}
So instead of the information being passed straight to the database and displayed in the log like below I would like the user to of pressed a button from a previous page and I will display their information.
Thanks if anybody gets round to replying!!
Here is the activity that I currently link to the "Addrecord" activity, once "Page1" in the list view has been clicked then I would like it to display the users information (Sample info at the moment)
package com.example.myapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class Home extends Activity {
Button button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
populateListView();
registerClickCallback();
}
public void populateListView() {
String[] homelist = { "Page1", "Page2", "Page3", "Page4", "Page5" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.list_home, homelist);
ListView list = (ListView) findViewById(R.id.testhomelist);
list.setAdapter(adapter);
}
public void registerClickCallback() {
ListView list = (ListView) findViewById(R.id.testhomelist);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
// NOW COPY AND PASTE FOR ALL THE OTHERS
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked,
int position, long id) {
if (position == 0) {
Intent myintent = new Intent(getApplicationContext(),
Addrecord.class);
startActivity(myintent);
}
if (position == 1) {
Intent myintent2 = new Intent(getApplicationContext(),
Pagetwo.class);
startActivity(myintent2);
}
if (position == 2) {
Intent myintent3 = new Intent(getApplicationContext(),
Pagethree.class);
startActivity(myintent3);
}
if (position == 3) {
Intent myintent4 = new Intent(getApplicationContext(),
Pagefour.class);
startActivity(myintent4);
}
if (position == 4) {
Intent myintent5 = new Intent(getApplicationContext(),
Pagefive.class);
startActivity(myintent5);
}
if (position == 5) {
Intent myintent6 = new Intent(getApplicationContext(),
Pagesix.class);
startActivity(myintent6);
}
}
});
}

Simple Android App SQLite login [duplicate]

This question already has an answer here:
SQL Lite android app login
(1 answer)
Closed 9 years ago.
I have an on going issue with my SQLite login for my app. I have a simple DBHandler class that has created a database, inside the database I have stored a single user: Username: test Password: 1234
I also have a LogInScreen class that handles the view of the login and also will hold the methods to authenticate the login.
I want the user to enter their login details into the text fields and when they press the login button to verify this against my database. As you can see in the attached image.
I already have the username stored and this is my code
The code does work but as you can see in the LogInScreen class it is not checking against my database but the actual text fields. Unfortunately I am completely new to SQLite and programming so I just can not figure it out. Any help will be highly appreciated :)
package com.C05025.noughtsandcrosses;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "userDB.db";
private static final String TABLE_USERS = "users";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_PASSWORD = "password";
public DBHandler(Context context, String name, CursorFactory factory,
int version) {
//super(context, name, factory, version);
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String CREATE_USER_TABLE = "CREATE TABLE " + TABLE_USERS + "("
+ " INTEGER PRIMARY KEY," + COLUMN_NAME + " TEXT,"
+ COLUMN_PASSWORD + " INTEGER" + ")";
db.execSQL(CREATE_USER_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
}
public void addUser(LogIn user) {
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, user.getName());
values.put(COLUMN_PASSWORD, user.getPassword());
SQLiteDatabase db = this.getWritableDatabase();
db.insert(TABLE_USERS, null, values);
db.close();
}
public LogIn findUser(String Username) {
String query = "Select * FROM " + TABLE_USERS + " WHERE " + COLUMN_NAME + " = \"" +
Username + "\"";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
LogIn User = new LogIn();
if (cursor.moveToFirst()) {
cursor.moveToFirst();
User.setName(cursor.getString(1));
User.setPassword(Integer.parseInt(cursor.getString(2)));
cursor.close();
} else {
User = null;
}
db.close();
return User;
}
}
LoginScreen Class:
package com.C05025.noughtsandcrosses;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class LogInScreen extends Activity {
EditText txtUsername;
EditText txtPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loginscreen);
txtUsername = (EditText) findViewById(R.id.EditUsername);
txtPassword = (EditText) findViewById(R.id.EditPassword);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void newLogIn(View view) {
if(txtUsername.getText().toString().equals("test") &&
txtPassword.getText().toString().equals("1234")){
Intent i = new Intent(LogInScreen.this, MainMenu.class);
startActivity(i);
LogInScreen.this.finish();
}
else{
Toast.makeText(getApplicationContext(), "Wrong Credentials",
Toast.LENGTH_SHORT).show();
}
}
}
Even though I don't really understand the problem and I'd love to see the stacktrace, this is a wonderful guide you can use on how to add login and registration to your application using SQLite, MySQL and PHP.

Categories

Resources