I am Creating SqLite Application ... the application is launched perfectly but when I fill all EditText Fields And Click On The Add Button.. The Application has stopped.. this message popups..
MainActivity.java
package com.example.database;
import android.support.v7.app.ActionBarActivity;
import android.text.Editable;
import android.app.Activity;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity{
EditText first,last,age,classc;
Button add,view;
String FirstName;
String LastName;
String Class;
String Age;
sqLit myDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDB = new sqLit(this);
Link();
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
xmlToVar();
Integer flag=myDB.insertValue(FirstName, LastName, Class, Age);
if (flag==1)
{
Context context=MainActivity.this;
Toast toast = Toast.makeText(context, "Record Added" , Toast.LENGTH_LONG);
toast.show();
}
else
{
Context context=MainActivity.this;
Toast toast = Toast.makeText(context, "Error Occured" , Toast.LENGTH_LONG);
toast.show();
}
}
});
}
public void Link()
{
first=(EditText) findViewById(R.id.editFirst);
last=(EditText) findViewById(R.id.editLast);
classc=(EditText) findViewById(R.id.editClass);
age=(EditText) findViewById(R.id.editAge);
add=(Button) findViewById(R.id.Add);
view=(Button) findViewById(R.id.ViewAll);
}
public void xmlToVar()
{
FirstName = first.getText().toString();
LastName = last.getText().toString();
Class = classc.getText().toString();
try
{
Age = age.getText().toString();
}
catch(NumberFormatException e)
{
e.printStackTrace();
}
}
}
sqLit.java
package com.example.database;
import org.w3c.dom.Text;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.text.Editable;
public class sqLit extends SQLiteOpenHelper
{
public static final String DB_NAME="student12.db";
public static final String TABLE_NAME="class1";
public static final String COL_1="ROLLNO";
public static final String COL_2="FirstName";
public static final String COL_3="LastName";
public static final String COL_4="Class";
public static final String COL_5="Age";
public sqLit(Context context) {
super(context, DB_NAME, null, 1);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + TABLE_NAME + "(" +COL_1 + " INTEGER AUTOINCREMENT PRIMARY KEY,"+COL_2 + " TEXT,"+COL_3 + " TEXT,"+COL_4 + " TEXT,"+COL_5 + " TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("Drop Table If Exist" + TABLE_NAME );
onCreate(db);
}
public Integer insertValue(String firstName, String lastName, String Class, String Age)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentV = new ContentValues();
contentV.put(COL_2, firstName);
contentV.put(COL_3, lastName);
contentV.put(COL_4, Class);
contentV.put(COL_5, Age);
long isInserted = db.insert(TABLE_NAME, null, contentV);
if (isInserted == -1){
return 0;
}
else
{
return 1;
}
}
}
Logcat
06-11 20:28:40.925: W/dalvikvm(25232): threadid=1: thread exiting with uncaught exception (group=0xb3f2b288)
06-11 20:28:40.925: E/AndroidRuntime(25232): FATAL EXCEPTION: main
06-11 20:28:40.925: E/AndroidRuntime(25232): android.database.sqlite.SQLiteException: near "AUTOINCREMENT": syntax error (code 1): , while compiling: CREATE TABLE class1(ROLLNO INTEGER AUTOINCREMENT PRIMARY KEY,FirstName TEXT,LastName TEXT,Class TEXT,Age TEXT)
06-11 20:28:40.925: E/AndroidRuntime(25232): at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
06-11 20:28:40.925: E/AndroidRuntime(25232): at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:882)
06-11 20:28:40.925: E/AndroidRuntime(25232): at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:493)
06-11 20:28:40.925: E/AndroidRuntime(25232): at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
06-11 20:28:40.925: E/AndroidRuntime(25232): at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
06-11 20:28:40.925: E/AndroidRuntime(25232): at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
06-11 20:28:40.925: E/AndroidRuntime(25232): at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1663)
06-11 20:28:40.925: E/AndroidRuntime(25232): at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1594)
06-11 20:28:40.925: E/AndroidRuntime(25232): at com.example.database.sqLit.onCreate(sqLit.java:35)
06-11 20:28:40.925: E/AndroidRuntime(25232): at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:252)
06-11 20:28:40.925: E/AndroidRuntime(25232): at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
06-11 20:28:40.925: E/AndroidRuntime(25232): at com.example.database.sqLit.insertValue(sqLit.java:48)
06-11 20:28:40.925: E/AndroidRuntime(25232): at com.example.database.MainActivity$1.onClick(MainActivity.java:44)
06-11 20:28:40.925: E/AndroidRuntime(25232): at android.view.View.performClick(View.java:4084)
06-11 20:28:40.925: E/AndroidRuntime(25232): at android.view.View$PerformClick.run(View.java:16966)
06-11 20:28:40.925: E/AndroidRuntime(25232): at android.os.Handler.handleCallback(Handler.java:615)
06-11 20:28:40.925: E/AndroidRuntime(25232): at android.os.Handler.dispatchMessage(Handler.java:92)
06-11 20:28:40.925: E/AndroidRuntime(25232): at android.os.Looper.loop(Looper.java:137)
06-11 20:28:40.925: E/AndroidRuntime(25232): at android.app.ActivityThread.main(ActivityThread.java:4745)
06-11 20:28:40.925: E/AndroidRuntime(25232): at java.lang.reflect.Method.invokeNative(Native Method)
06-11 20:28:40.925: E/AndroidRuntime(25232): at java.lang.reflect.Method.invoke(Method.java:511)
06-11 20:28:40.925: E/AndroidRuntime(25232): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
06-11 20:28:40.925: E/AndroidRuntime(25232): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
06-11 20:28:40.925: E/AndroidRuntime(25232): at dalvik.system.NativeStart.main(Native Method)
06-11 20:28:40.944: D/dalvikvm(25232): GC_CONCURRENT freed 203K, 5% free 6173K/6471K, paused 13ms+0ms, total 16ms
Thanks Guys.. :)
Can you try to re-shuffle the SQL autoincrement location?
db.execSQL("CREATE TABLE " + TABLE_NAME + "(" +COL_1 + " INTEGER PRIMARY KEY AUTOINCREMENT,"+COL_2 + " TEXT,"+COL_3 + " TEXT,"+COL_4 + " TEXT,"+COL_5 + " TEXT)");
Edit:
Actually, I may have been over complicating. It appears (according to the SQL Lite documentation at http://www.sqlite.org/faq.html#q1) that:
"If you declare a column of a table to be INTEGER PRIMARY KEY, then
whenever you insert a NULL into that column of the table, the NULL is
automatically converted into an integer which is one greater than the
largest value of that column over all other rows in the table, or 1 if
the table is empty."
So you may be okay to leave out AUTOINCREMENT altogether as long as you insert nulls in there later on.
Related
I am new on android and working on my android app's login activity for which em using php mysql with volley library. But every time I run my app on emulator it shows the message Unfortunately, app has stopped. Here the login activity code is:
package com.example.u.locationtracker;
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.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private EditText pass1, email1;
private Button login;
private TextView link_reg;
private ProgressBar loading;
private String URL_LOGIN= "http://192.168.1.1/register.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
email1= (EditText) findViewById(R.id.etemail1);
pass1= (EditText) findViewById(R.id.etpassl);
loading= (ProgressBar) findViewById(R.id.loading1);
link_reg= (TextView) findViewById(R.id.signup);
login= (Button) findViewById(R.id.btnlogin);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mEmail= email1.getText().toString().trim();
String mpass= pass1.getText().toString().trim();
if(!mEmail.isEmpty() || !mpass.isEmpty()){
Login(mEmail, mpass);
}else{
email1.setError("Please Enter Email...!");
pass1.setError("Please Enter Password...!");
}
}
});
link_reg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent it= new Intent(MainActivity.this, Register.class);
startActivity(it);
}
});
}
private void Login(final String email, final String pass) {
loading.setVisibility(View.VISIBLE);
login.setVisibility(View.GONE);
StringRequest stringRequest= new StringRequest(Request.Method.POST, URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
JSONObject jsonObject= new JSONObject(response);
String success= jsonObject.getString("Success");
JSONArray jsonArray= jsonObject.getJSONArray("Login");
if(success.equals("1")){
for (int i= 0; i < jsonArray.length(); i++){
JSONObject object= jsonArray.getJSONObject(i);
Toast t= Toast.makeText(MainActivity.this,
"Login Successful", Toast.LENGTH_LONG);
t.show();
loading.setVisibility(View.GONE);
}
}
}catch (JSONException e) {
e.printStackTrace();
loading.setVisibility(View.GONE);
login.setVisibility(View.VISIBLE);
Toast t1= Toast.makeText(MainActivity.this,
"Error" + e.toString(),
Toast.LENGTH_LONG);
t1.show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loading.setVisibility(View.GONE);
login.setVisibility(View.VISIBLE);
Toast t2= Toast.makeText(MainActivity.this,
"Error" + error.toString(),
Toast.LENGTH_LONG);
t2.show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params= new HashMap<>();
params.put("Email", email);
params.put("Password", pass);
return params;
}
};
RequestQueue requestQueue= Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
According to logcat the problem is:
at com.example.u.locationtracker.MainActivity.onCreate(MainActivity.java:39)
here the php code:
<?php
if ($_SERVER['REQUEST_METHOD']=='POST') {
$email= $_POST['email1'];
$pass= $_POST['pass1'];
require_once 'connect.php';
$select= "SELECT * FROM user_table WHERE Email= '$email' ";
$r= mysqli_query($conn, $select);
$result= array();
$result['login']= array();
if (mysqli_num_rows($r)=== 1) {
$row= mysqli_fetch_assoc($r);
if ( password_verify($pass, $row['Pass']) ) {
$index['Name']= $row['Name'];
$index['Email']= $row['Email'];
array_push($result['login'], $index);
$result['success']= "1";
$result['message']= "Success";
echo json_encode($result);
mysql_close($conn);
}else{
$result['success']= "0";
$result['message']= "Error";
echo json_encode($result);
mysql_close($conn);
}
}
}
?>
Here is the Logcat:
02-03 21:03:21.626 2006-2012/? E/jdwp: Failed writing handshake bytes: Broken pipe (-1 of 14)
02-03 21:03:21.806 2006-2006/? E/dalvikvm: Could not find class 'android.support.v4.view.ViewCompat$OnUnhandledKeyEventListenerWrapper', referenced from method android.support.v4.view.ViewCompat.addOnUnhandledKeyEventListener
02-03 21:03:21.806 2006-2006/? E/dalvikvm: Could not find class 'android.view.WindowInsets', referenced from method android.support.v4.view.ViewCompat.dispatchApplyWindowInsets
02-03 21:03:21.826 2006-2006/? E/dalvikvm: Could not find class 'android.view.WindowInsets', referenced from method android.support.v4.view.ViewCompat.onApplyWindowInsets
02-03 21:03:21.826 2006-2006/? E/dalvikvm: Could not find class 'android.view.View$OnUnhandledKeyEventListener', referenced from method android.support.v4.view.ViewCompat.removeOnUnhandledKeyEventListener
02-03 21:03:21.836 2006-2006/? E/dalvikvm: Could not find class 'android.support.v4.view.ViewCompat$1', referenced from method android.support.v4.view.ViewCompat.setOnApplyWindowInsetsListener
02-03 21:03:22.756 2006-2006/com.example.u.locationtracker E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method android.support.v7.widget.AppCompatImageHelper.hasOverlappingRendering
02-03 21:03:27.786 2006-2006/com.example.u.locationtracker E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.u.locationtracker, PID: 2006
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.u.locationtracker/com.example.u.locationtracker.MainActivity}: android.view.InflateException: Binary XML file line #45: Error inflating class ImageView
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2193)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2243)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5019)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #45: Error inflating class ImageView
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:713)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at android.support.v7.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at com.example.u.locationtracker.MainActivity.onCreate(MainActivity.java:39)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2157)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2243)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5019)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.content.res.Resources$NotFoundException: Resource is not a Drawable (color or path): TypedValue{t=0x1/d=0x7f07005d a=-1 r=0x7f07005d}
at android.content.res.Resources.loadDrawable(Resources.java:2068)
at android.content.res.TypedArray.getDrawable(TypedArray.java:602)
at android.widget.ImageView.<init>(ImageView.java:129)
at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:72)
at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:68)
at android.support.v7.app.AppCompatViewInflater.createImageView(AppCompatViewInflater.java:182)
at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:106)
at android.support.v7.app.AppCompatDelegateImpl.createView(AppCompatDelegateImpl.java:1266)
at android.support.v7.app.AppCompatDelegateImpl.onCreateView(AppCompatDelegateImpl.java:1316)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:684)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at android.support.v7.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at com.example.u.locationtracker.MainActivity.onCreate(MainActivity.java:39)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2157)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2243)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5019)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
The problem seems to lie in this line:
setContentView(R.layout.activity_main);
Are you sure, the layout exists and doesn't have compile errors?
A full stacktrace would be more helpful
All files under my SQLite package are giving errors. As these are predefined classes and don't require or allow editing, I'm having a hard time making my project.
The codes are too long to be posted here.
For instance, these imports in SQLiteDatabase.java are appearing in red:
import android.database.sqlite.SQLiteDebug.DbStats;
import dalvik.system.CloseGuard;
and my logcat shows the following errors:
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: FATAL EXCEPTION: main
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: android.database.sqlite.SQLiteException: no such table: user (code 1): , while compiling: select * from user
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1314)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1253)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at com.example.abcd.helloworld.DatabaseHelper.insertUser(DatabaseHelper.java:40)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at com.example.abcd.helloworld.SignUp$1.onClick(SignUp.java:52)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at android.view.View.performClick(View.java:4240)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at android.view.View$PerformClick.run(View.java:17721)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at android.os.Handler.handleCallback(Handler.java:730)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:92)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at android.os.Looper.loop(Looper.java:137)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5103)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at java.lang.reflect.Method.invokeNative(Native Method)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:525)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at dalvik.system.NativeStart.main(Native Method)
All coding done by me seems to be correct.
The code for table creation is:
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "user.db";
private static final String TABLE_NAME = "user";
private static final String COLUMN_ID = "id";
private static final String COLUMN_NAME = "name";
private static final String COLUMN_EMAIL = "email";
private static final String COLUMN_UNAME = "uname";
private static final String COLUMN_PASS = "pass";
SQLiteDatabase db;
private static final String TABLE_CREATE = "create table user (id integer primary key autoincrement," +
"name text, email text, uname text, pass text);";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABLE_CREATE);
this.db = db;
}
public void insertUser(User u) {
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
String query = "select * from user";
Cursor cursor = db.rawQuery(query, null);
int count = cursor.getCount();
values.put(COLUMN_ID, count);
values.put(COLUMN_NAME, u.getName());
values.put(COLUMN_EMAIL, u.getEmail());
values.put(COLUMN_UNAME, u.getUname());
values.put(COLUMN_PASS, u.getPass());
db.insert(TABLE_NAME, null, values);
}
public String searchPass(String uname) {
db = this.getReadableDatabase();
String query = "select uname, pass 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(uname)) {
b = cursor.getString(1);
break;
}
}
while (cursor.moveToNext());
}
db.close();
return b;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String query = "DROP TABLE IF EXISTS" + TABLE_NAME;
db.execSQL(query);
this.OnCreate(db);
}
private void OnCreate(SQLiteDatabase db) {
db.execSQL(TABLE_CREATE);
this.db = db;
}
}
You are using onCreate method twice in your code. Remove duplication.
Try below code:
public class DBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "user.db";
public DBHandler(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "create table user(" +
"id integer primary key autoincrement, " +
"name text, "+
"email text, "+
"uname text, "+
"pass text"+
");";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String query = "drop table if exists user";
db.execSQL(query);
onCreate(db);
}
/*
Remaining code
Please do not add onCreate and onUpgrade method anymore.
*/
}
Your code seems to be ok, try to debug the SQLite code. Execute the statement outside the android code. Open your terminal and execute the sql statement, and after that execute .tables, this command will show you the existed tables in your db.
More info, you can find here,
http://www.tutorialspoint.com/sqlite/sqlite_create_table.htm
Trying to retrieve the data from sqLite and show it in Alert Dialog Builder.
But not Showing the data at all. When I click on the View Button nothing happens.
MainActivity.java
package com.example.database;
import android.support.v7.app.ActionBarActivity;
import android.text.Editable;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity{
EditText first,last,age,classc;
Button add,view;
String FirstName;
String LastName;
String Class;
Integer Age;
sqLit myDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDB = new sqLit(this);
Link();
addButtonClicked();
viewButtonClicked();
}
public void addButtonClicked()
{
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
xmlToVar();
Integer flag=myDB.insertValue(FirstName, LastName, Class, Age);
if (flag==1)
{
Context context=MainActivity.this;
Toast toast = Toast.makeText(context, "Record Added" , Toast.LENGTH_LONG);
toast.show();
}
else
{
Context context=MainActivity.this;
Toast toast = Toast.makeText(context, "Error Occured" , Toast.LENGTH_LONG);
toast.show();
}
}
});
}
public void viewButtonClicked()
{
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Cursor res = myDB.getData();
if (res.getCount()==0)
{
showMessage("Error" , "No Data Found");
return;
}
StringBuffer buffer = new StringBuffer();
while (res.moveToNext())
{
buffer.append("ID : " + res.getString(0) + "\n");
buffer.append("FirstName : " + res.getString(1) + "\n");
buffer.append("LastName : " + res.getString(2) + "\n");
buffer.append("Class : " + res.getString(3) + "\n");
buffer.append("Age : " + res.getString(4) + "\n");
showMessage("Here is your Data",buffer.toString() );
}
}
});
}
public void showMessage(String title, String message)
{
AlertDialog.Builder Builder = new AlertDialog.Builder(this);
Builder.setCancelable(true);
Builder.setTitle(title);
Builder.setMessage(message);
}
public void Link()
{
first=(EditText) findViewById(R.id.editFirst);
last=(EditText) findViewById(R.id.editLast);
classc=(EditText) findViewById(R.id.editClass);
age=(EditText) findViewById(R.id.editAge);
add=(Button) findViewById(R.id.Add);
view=(Button) findViewById(R.id.ViewAll);
}
public void xmlToVar()
{
FirstName = first.getText().toString();
LastName = last.getText().toString();
Class = classc.getText().toString();
Age = Integer.parseInt(age.getText().toString());
}
}
sqLit.java
package com.example.database;
import org.w3c.dom.Text;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.text.Editable;
public class sqLit extends SQLiteOpenHelper
{
public static final String DB_NAME="student12.db";
public static final String TABLE_NAME="class1";
public static final String COL_1="ROLLNO";
public static final String COL_2="FirstName";
public static final String COL_3="LastName";
public static final String COL_4="Class";
public static final String COL_5="Age";
public sqLit(Context context) {
super(context, DB_NAME, null, 1);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + TABLE_NAME + "(" +COL_1 + " INTEGER PRIMARY KEY AUTOINCREMENT,"+COL_2 + " TEXT,"+COL_3 + " TEXT,"+COL_4 + " TEXT,"+COL_5 + " INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("Drop Table If Exist" + TABLE_NAME );
onCreate(db);
}
public Integer insertValue(String firstName, String lastName, String Class, Integer Age)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentV = new ContentValues();
contentV.put(COL_2, firstName);
contentV.put(COL_3, lastName);
contentV.put(COL_4, Class);
contentV.put(COL_5, Age);
long isInserted = db.insert(TABLE_NAME, null, contentV);
if (isInserted == -1){
return 0;
}
else
{
return 1;
}
}
public Cursor getData()
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("Select * From "+TABLE_NAME, null);
return res;
}
}
LogCat
06-11 22:02:40.728: D/dalvikvm(1576): Not late-enabling CheckJNI (already on)
06-11 22:02:40.737: E/Trace(1576): error opening trace file: No such file or directory (2)
06-11 22:02:40.817: D/gralloc_goldfish(1576): Emulator without GPU emulation detected.
06-11 22:05:14.779: D/dalvikvm(1576): GC_CONCURRENT freed 197K, 5% free 6176K/6471K, paused 15ms+0ms, total 19ms
06-11 22:08:27.242: E/Trace(2066): error opening trace file: No such file or directory (2)
06-11 22:08:27.322: D/gralloc_goldfish(2066): Emulator without GPU emulation detected.
06-11 22:08:31.472: D/dalvikvm(2066): GC_CONCURRENT freed 225K, 5% free 6148K/6471K, paused 17ms+1ms, total 19ms
06-11 22:10:36.644: D/dalvikvm(2290): GC_CONCURRENT freed 225K, 5% free 6148K/6471K, paused 16ms+0ms, total 19ms
06-11 22:10:52.355: D/AndroidRuntime(2290): Shutting down VM
06-11 22:10:52.355: W/dalvikvm(2290): threadid=1: thread exiting with uncaught exception (group=0xb3f1c288)
06-11 22:10:52.355: E/AndroidRuntime(2290): FATAL EXCEPTION: main
06-11 22:10:52.355: E/AndroidRuntime(2290): java.lang.NumberFormatException: Invalid int: ""
06-11 22:10:52.355: E/AndroidRuntime(2290): at java.lang.Integer.invalidInt(Integer.java:138)
06-11 22:10:52.355: E/AndroidRuntime(2290): at java.lang.Integer.parseInt(Integer.java:359)
06-11 22:10:52.355: E/AndroidRuntime(2290): at java.lang.Integer.parseInt(Integer.java:332)
06-11 22:10:52.355: E/AndroidRuntime(2290): at com.example.database.MainActivity.xmlToVar(MainActivity.java:115)
06-11 22:10:52.355: E/AndroidRuntime(2290): at com.example.database.MainActivity$1.onClick(MainActivity.java:46)
06-11 22:10:52.355: E/AndroidRuntime(2290): at android.view.View.performClick(View.java:4084)
06-11 22:10:52.355: E/AndroidRuntime(2290): at android.view.View$PerformClick.run(View.java:16966)
06-11 22:10:52.355: E/AndroidRuntime(2290): at android.os.Handler.handleCallback(Handler.java:615)
06-11 22:10:52.355: E/AndroidRuntime(2290): at android.os.Handler.dispatchMessage(Handler.java:92)
06-11 22:10:52.355: E/AndroidRuntime(2290): at android.os.Looper.loop(Looper.java:137)
06-11 22:10:52.355: E/AndroidRuntime(2290): at android.app.ActivityThread.main(ActivityThread.java:4745)
06-11 22:10:52.355: E/AndroidRuntime(2290): at java.lang.reflect.Method.invokeNative(Native Method)
06-11 22:10:52.355: E/AndroidRuntime(2290): at java.lang.reflect.Method.invoke(Method.java:511)
06-11 22:10:52.355: E/AndroidRuntime(2290): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
06-11 22:10:52.355: E/AndroidRuntime(2290): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
06-11 22:10:52.355: E/AndroidRuntime(2290): at dalvik.system.NativeStart.main(Native Method)
06-11 22:12:22.676: D/dalvikvm(2455): GC_CONCURRENT freed 201K, 5% free 6172K/6471K, paused 17ms+0ms, total 19ms
06-11 22:14:01.238: D/dalvikvm(2652): Not late-enabling CheckJNI (already on)
06-11 22:14:01.248: E/Trace(2652): error opening trace file: No such file or directory (2)
06-11 22:14:01.338: D/gralloc_goldfish(2652): Emulator without GPU emulation detected.
The Button isn’t working at all.
The below exception from xmlToVar method is the problem, you are calling this in addButtonClicked method
java.lang.NumberFormatException: Invalid int: ""
If the value in Age field is not entered then this error will happen if you make empty check before calling
Age = Integer.parseInt(age.getText().toString());
should solve the issue
Validate input before you use parseInt in xmlToVar():
String ageStr = age.getText().toString();
if (ageStr != "")
r.age = Integer.parseInt(ageStr);
You can also initialize Integer age, if there can be a default value.
You need to provide information about the following :
i) Did you try to debug ?
ii) If yes, does the cursor get any data ?
Now a different approach to the problem :
Create class of data [makes it easier to handle, i.e store and fetch from database]
example :
Class :
public class NoticeInformation {
private String NoticeType, NoticeHeader, NoticeLink;
private int Important, NoticeId, Read;
public NoticeInformation(int NoticeId,
String NoticeType,
String NoticeHeader,
String NoticeLink,
int Important,
int Read){
this.NoticeId = NoticeId;
this.NoticeType = NoticeType;
this.NoticeHeader = NoticeHeader;
this.NoticeLink = NoticeLink;
this.Important = Important;
this.Read = Read;
}
public int getNoticeId() {
return NoticeId;
}
public void setNoticeId(int noticeId) {
NoticeId = noticeId;
}
public String getNoticeType() {
return NoticeType;
}
public void setNoticeType(String noticeType) {
NoticeType = noticeType;
}
public String getNoticeHeader() {
return NoticeHeader;
}
public void setNoticeHeader(String noticeHeader) {
NoticeHeader = noticeHeader;
}
public String getNoticeLink() {
return NoticeLink;
}
public void setNoticeLink(String noticeLink) {
NoticeLink = noticeLink;
}
public int getImportant() {
return Important;
}
public void setImportant(int important) {
Important = important;
}
public int getRead() {
return Read;
}
public void setRead(int read) {
Read = read;
}
}
Database Read :
public List<NoticeInformation> getScheduleNotice(){
SQLiteDatabase db = this.getReadableDatabase();
List<NoticeInformation> res = new ArrayList<>();
String Query = "SELECT * FROM " + TABLE_NAME1 + " WHERE NoticeType = 'Schedule';";
Cursor cursor = db.rawQuery(Query, null);
if (cursor.moveToFirst()){
cursor.moveToFirst();
do
{
NoticeInformation obj = new NoticeInformation(cursor.getInt(0), cursor.getString(1),
cursor.getString(2), cursor.getString(3), cursor.getInt(5),
cursor.getInt(4));
res.add(obj);
}while(cursor.moveToNext());
return res;
}
return null;
}
Instead of handling cursor in the application end, just have the data in a list. It is easier to handle [in my humble opinion].
Try this approach and let me know the result.
My app closes when i insert this sample records for testing, i tried it in many ways. from activity class im sending string values to insert to the database.
My MainInvoiceActivity Class
public class MainInvoiceActivity extends Activity {
private DBHelper mydb ;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_invoice);
if ( mydb.insertsample( "one" , "two" , "3" )){ // LINE NO 67
Toast.makeText(getApplicationContext(), "Insert Success!", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), "not done", Toast.LENGTH_SHORT).show();
}
}
}
My database SQLiteOpenHelper class
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "MyDBName.db";
public static final String TABLE_SAMPLE = "sample";
public DBHelper(Context context)
{
super(context, DATABASE_NAME , null, 1);
}
public void onCreate(SQLiteDatabase db) {
String CREATE_SAMPLE_TABLE = "CREATE TABLE sample ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"one TEXT, "+
"two TEXT, "+
"three TEXT )";
db.execSQL(CREATE_SAMPLE_TABLE);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS sample");
onCreate(db);
}
public boolean insertsample (String one, String two, String three)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues myValues = new ContentValues();
myValues.put(one, one);
myValues.put(two, two);
myValues.put(three, three);
db.insert(TABLE_SAMPLE, null, myValues);
return true;
}
}
LOG message
E/AndroidRuntime(1153): FATAL EXCEPTION: main
E/AndroidRuntime(1153): Process: com.ezycode.pos, PID: 1153
E/AndroidRuntime(1153): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ezycode.pos/com.ezycode.pos.MainInvoiceActivity}: java.lang.NullPointerException
E/AndroidRuntime(1153): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
E/AndroidRuntime(1153): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
E/AndroidRuntime(1153): at android.app.ActivityThread.access$800(ActivityThread.java:135)
E/AndroidRuntime(1153): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
E/AndroidRuntime(1153): at android.os.Handler.dispatchMessage(Handler.java:102)
E/AndroidRuntime(1153): at android.os.Looper.loop(Looper.java:136)
E/AndroidRuntime(1153): at android.app.ActivityThread.main(ActivityThread.java:5017)
E/AndroidRuntime(1153): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(1153): at java.lang.reflect.Method.invoke(Method.java:515)
E/AndroidRuntime(1153): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
E/AndroidRuntime(1153): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
E/AndroidRuntime(1153): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(1153): Caused by: java.lang.NullPointerException
E/AndroidRuntime(1153): at com.ezycode.pos.MainInvoiceActivity.onCreate(MainInvoiceActivity.java:67)
E/AndroidRuntime(1153): at android.app.Activity.performCreate(Activity.java:5231)
E/AndroidRuntime(1153): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
E/AndroidRuntime(1153): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
Correct code will be like something below
public class MainInvoiceActivity extends Activity {
private DBHelper mydb ;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_invoice);
mydb = new DBHelper(this); //This is missing your code.
if ( mydb.insertsample( "one" , "two" , "3" )){ // LINE NO 67
Toast.makeText(getApplicationContext(), "Insert Success!", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "not done", Toast.LENGTH_SHORT).show();
}
}
So I am trying out a tutorial for SQLite I have seen in the internet, and after tweaking it a bit I launched it and it crashes. Before modifying the code, it works. I know that some of the functions are deprecated, but that didn't seem to be the issue because as I said it ran before I modified it. I also know that the error is on line 44 on one of my classes (I have put a comment in this line to distinguish it) but I don't see why it gives me an error. Here is my code:
AndroidSQLite.java:
package com.example.sqlite;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class AndroidSQLite extends Activity {
EditText inputContent1, inputContent2, inputContent3;
Button buttonAdd, buttonDeleteAll;
private SQLiteAdapter mySQLiteAdapter;
ListView listContent;
SimpleCursorAdapter cursorAdapter;
Cursor cursor;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
inputContent1 = (EditText)findViewById(R.id.UserID);
inputContent2 = (EditText)findViewById(R.id.Password);
inputContent3 = (EditText)findViewById(R.id.Fname);
buttonAdd = (Button)findViewById(R.id.add);
buttonDeleteAll = (Button)findViewById(R.id.deleteall);
listContent = (ListView)findViewById(R.id.contentlist);
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToWrite();
cursor = mySQLiteAdapter.queueAll();
String[] from = new String[]{SQLiteAdapter.KEY_USERS_USERID, SQLiteAdapter.KEY_USERS_PASSWORD, SQLiteAdapter.KEY_USERS_FNAME};
int[] to = new int[]{R.id.id, R.id.text1, R.id.text2};
cursorAdapter = new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
listContent.setAdapter(cursorAdapter);
buttonAdd.setOnClickListener(buttonAddOnClickListener);
buttonDeleteAll.setOnClickListener(buttonDeleteAllOnClickListener);
}
Button.OnClickListener buttonAddOnClickListener = new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String data1 = inputContent1.getText().toString();
String data2 = inputContent2.getText().toString();
String data3 = inputContent3.getText().toString();
mySQLiteAdapter.insert(data1, data2, data3);
updateList();
}
};
Button.OnClickListener buttonDeleteAllOnClickListener = new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
mySQLiteAdapter.deleteAll();
updateList();
}
};
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mySQLiteAdapter.close();
}
#SuppressWarnings("deprecation")
private void updateList(){
cursor.requery();
}
}
SQLiteAdapter.java
package com.example.sqlite;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
public class SQLiteAdapter {
public static final String DB_NAME = "adserve";
public static final String DB_TABLE_USERS = "users";
public static final int DB_VERSION = 1;
public static final String KEY_USERS_USERID = "_id";
public static final String KEY_USERS_PASSWORD = "Password";
public static final String KEY_USERS_FNAME = "Fname";
//create table MY_DATABASE (ID integer primary key, Content text not null);
private static final String SCRIPT_CREATE_DATABASE =
"create table " + DB_TABLE_USERS + " ("
+ KEY_USERS_USERID + " integer primary key, "
+ KEY_USERS_PASSWORD + " text not null, "
+ KEY_USERS_FNAME + " text not null);";
private SQLiteHelper sqLiteHelper;
private SQLiteDatabase sqLiteDatabase;
private Context context;
public SQLiteAdapter(Context c){
context = c;
}
public SQLiteAdapter openToRead() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, DB_NAME, null, DB_VERSION);
sqLiteDatabase = sqLiteHelper.getReadableDatabase();
return this;
}
public SQLiteAdapter openToWrite() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, DB_NAME, null, DB_VERSION);
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
return this;
}
public void close(){
sqLiteHelper.close();
}
public long insert(String UserID, String Password, String Fname){
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_USERS_USERID, UserID);
contentValues.put(KEY_USERS_PASSWORD, Password);
contentValues.put(KEY_USERS_FNAME, Fname);
return sqLiteDatabase.insert(DB_TABLE_USERS, null, contentValues);
}
public int deleteAll(){
return sqLiteDatabase.delete(DB_TABLE_USERS, null, null);
}
public Cursor queueAll(){
String[] columns = new String[]{KEY_USERS_USERID, KEY_USERS_PASSWORD, KEY_USERS_FNAME};
Cursor cursor = sqLiteDatabase.query(DB_TABLE_USERS, columns, null, null, null, null, null);
return cursor;
}
public class SQLiteHelper extends SQLiteOpenHelper {
public SQLiteHelper(Context context, String name, CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(SCRIPT_CREATE_DATABASE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
}
And my logcat:
02-20 10:04:53.811: E/AndroidRuntime(1940): FATAL EXCEPTION: main
02-20 10:04:53.811: E/AndroidRuntime(1940): Process: com.example.sqlite, PID: 1940
02-20 10:04:53.811: E/AndroidRuntime(1940): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sqlite/com.example.sqlite.AndroidSQLite}: java.lang.IllegalArgumentException: column '_id' does not exist
02-20 10:04:53.811: E/AndroidRuntime(1940): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2176)
02-20 10:04:53.811: E/AndroidRuntime(1940): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2226)
02-20 10:04:53.811: E/AndroidRuntime(1940): at android.app.ActivityThread.access$700(ActivityThread.java:135)
02-20 10:04:53.811: E/AndroidRuntime(1940): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397)
02-20 10:04:53.811: E/AndroidRuntime(1940): at android.os.Handler.dispatchMessage(Handler.java:102)
02-20 10:04:53.811: E/AndroidRuntime(1940): at android.os.Looper.loop(Looper.java:137)
02-20 10:04:53.811: E/AndroidRuntime(1940): at android.app.ActivityThread.main(ActivityThread.java:4998)
02-20 10:04:53.811: E/AndroidRuntime(1940): at java.lang.reflect.Method.invokeNative(Native Method)
02-20 10:04:53.811: E/AndroidRuntime(1940): at java.lang.reflect.Method.invoke(Method.java:515)
02-20 10:04:53.811: E/AndroidRuntime(1940): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
02-20 10:04:53.811: E/AndroidRuntime(1940): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
02-20 10:04:53.811: E/AndroidRuntime(1940): at dalvik.system.NativeStart.main(Native Method)
02-20 10:04:53.811: E/AndroidRuntime(1940): Caused by: java.lang.IllegalArgumentException: column '_id' does not exist
02-20 10:04:53.811: E/AndroidRuntime(1940): at android.database.AbstractCursor.getColumnIndexOrThrow(AbstractCursor.java:303)
02-20 10:04:53.811: E/AndroidRuntime(1940): at android.widget.CursorAdapter.init(CursorAdapter.java:172)
02-20 10:04:53.811: E/AndroidRuntime(1940): at android.widget.CursorAdapter.<init>(CursorAdapter.java:120)
02-20 10:04:53.811: E/AndroidRuntime(1940): at android.widget.ResourceCursorAdapter.<init>(ResourceCursorAdapter.java:52)
02-20 10:04:53.811: E/AndroidRuntime(1940): at android.widget.SimpleCursorAdapter.<init>(SimpleCursorAdapter.java:78)
02-20 10:04:53.811: E/AndroidRuntime(1940): at com.example.sqlite.AndroidSQLite.onCreate(AndroidSQLite.java:43)
02-20 10:04:53.811: E/AndroidRuntime(1940): at android.app.Activity.performCreate(Activity.java:5243)
02-20 10:04:53.811: E/AndroidRuntime(1940): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
02-20 10:04:53.811: E/AndroidRuntime(1940): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2140)
02-20 10:04:53.811: E/AndroidRuntime(1940): ... 11 more
Quoting the documentation for CursorAdapter:
The Cursor must include a column named "_id" or this class will not work
You do not have such a column in your Cursor, as far as I can tell.
One solution would be to switch from query() to rawQuery(), so you can add ROWID AS _id to your list of columns, to fulfil the CursorAdapter contract.
The SQLite Site says,
In SQLite, table rows normally have a 64-bit signed integer ROWID which is unique among all rows in the same table. (WITHOUT ROWID tables are the exception.)
So if you want to use a column only as an integer primary key, you can directly access the in built one using ROWID.
and the document on Cursor adapter says,
The Cursor must include a column named "_id" or this class will not work. Additionally, using MergeCursor with this class will not work if the merged Cursors have overlapping values in their "_id" columns.
which is the error you are getting.
Also if searched, you could find solution to yours on already answered SO questions like this one.