Logcat error while getting data from Sqlitedatabase to listview - android

and my XML file is
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</RelativeLayout>
in these database i am getting values from database and displaying them in a listview.
my main activity is
package com.example.kern;
import android.os.Bundle;
import android.provider.Contacts.People;
import android.app.Activity;
import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.Menu;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class Second extends ListActivity {
DatabaseAdapter helper;
SQLiteDatabase db;
private CursorAdapter dataSource;
private static final String fields[] = { "Name", "Numb"};
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
helper=new DatabaseAdapter(this);
helper.open();
lv=(ListView)findViewById(android.R.id.list);
Cursor data = db.query("Mycon", fields,null, null, null, null, null);
dataSource = new SimpleCursorAdapter(this,
R.layout.activity_second, data, fields,
new int[] { R.id.name, R.id.number });
lv.setAdapter(dataSource);
}
}
and mydatabase adapter class is
package com.example.kern;
import android.content.ContentValues;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.example.kern.DatabaseAdapter;
import com.example.kern.DatabaseAdapter.DatabaseHelper;
public class DatabaseAdapter {
DatabaseHelper helper;
SQLiteDatabase db;
static final int VERSION=2;
static final String DATA_NAME="Mycontsc";
private static final String query = "create table Mycon(id Integer primary
key,Name text,Numb text)"; //the query has been changed
private final Context mCtx;
public DatabaseAdapter(Context ctx) {
this.mCtx = ctx;
}
//DatabaseHelper has become a subclass
public class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context) {
super(context, DATA_NAME, null, VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase arg0) {
// TODO Auto-generated method stub
arg0.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
public DatabaseAdapter open() throws SQLException {
helper = new DatabaseHelper(mCtx);
db=helper.getWritableDatabase();
db=helper.getReadableDatabase();
return this;
}
public void close() {
helper.close();
}
public long AddDetail(String name,String num)
{
ContentValues vals=new ContentValues();
vals.put("Name",name);
vals.put("Numb", num);
long a=db.insert("Mycon", null, vals);
return a;
}
}
it is showing null pointer exception in logcat
09-18 10:32:02.631: E/AndroidRuntime(2286): FATAL EXCEPTION: main
09-18 10:32:02.631: E/AndroidRuntime(2286): java.lang.RuntimeException: Unable to
start activity ComponentInfo{com.example.kern/com.example.kern.Second}:
java.lang.NullPointerException
09-18 10:32:02.631: E/AndroidRuntime(2286): Caused by: java.lang.NullPointerException
09-18 10:32:02.631: E/AndroidRuntime(2286): at
com.example.kern.Second.onCreate(Second.java:29)
please check the program and give me the solution,it is showing exception,alerady there is values in the database and i am retriving them..

Cursor data = db.query("Mycon", fields,null, null, null, null, null);
You haven't initialized your db object.
Looks like you already have the initialization code i.e. SQLiteOpenHelper subclass and so on in DatabaseAdapter. Call getReadableDatabase() on the helper to get an SQLiteDatabase object you can run query() on.

Related

Creating and inserting into a database [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 6 years ago.
I'm trying to create a basic database and insert three users, but it doesn't work.
This is a class that creates the database
package com.example.matadoor.db1;
import android.content.Context;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by matadoor on 06/08/2016.
*/
public class dbcreat extends SQLiteOpenHelper {
public final String tbname="t1";
public final String cid="id";
public static String cid2="test";
public final String user="username";
public final String creat="CREATE TABLE "+cid2+"("+cid+"INTEGER primery key AUTO_INCREMENT , "+user+" TEXT); ";
public dbcreat(Context context) {
super(context,cid2,null, 1);
}
public dbcreat(Context context, String name, SQLiteDatabase.CursorFactory factory, int version, DatabaseErrorHandler errorHandler) {
super(context, name, factory, version, errorHandler);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(creat);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
And it's the other class which handles the database - opens it, closes it, and inserts into it
package com.example.matadoor.db1;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
/**
* Created by matadoor on 08/08/2016.
*/
public class dbhandler {
private dbcreat dbc;
private SQLiteDatabase sdb;
public dbhandler(Context context)
{
dbc=new dbcreat(context);
}
public void open()
{
sdb=dbc.getWritableDatabase();
}
public void close(){
dbc.close();
}
public String display(int row)
{
Cursor cu=sdb.query(dbc.tbname,null,null,null,null,null,null);
cu.moveToPosition(row);
String user=cu.getString(1);
return user;
}
public void insert(String user)
{
ContentValues cn=new ContentValues();
cn.put(dbc.user,user);
}
}
And the main class which has one Button for inserting a user into the db
package com.example.matadoor.db1;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Main extends AppCompatActivity {
Button btn;
dbhandler db;
dbcreat dbc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn=(Button)findViewById(R.id.ins);
// dbc.getWritableDatabase();
db.open();
db=new dbhandler(this);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String [] user={"ali","reza","ahmed"};
for(int i=0;i<user.length;i++)
{
db.insert(user[i]);
}
}
});
}
}
So this seems to be a error. You need to switch those two lines.
db.open(); // NullPointer here
db=new dbhandler(this);
Assuming there are no other errors with the code, this method is doing nothing to the database.
public void insert(String user)
{
ContentValues cn=new ContentValues();
cn.put(dbc.user,user);
}
You have to call sdb.insert with that cn variable.

error while retriving data from the database SQLite in android

my database helper class is
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DataHandlerDairy {
public static final String DATE = "date";
public static final String DAIRY = "dairy";
private static final String DATA_BASE_NAME = "mydairy";
private static final String TABLE_NAME = "table_dairy";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_CREATE="create table table_dairy (date text primary key," + "dairy text not null);";
DataBaseHelper1 dbhelper1;
Context ct;
SQLiteDatabase db;
public DataHandlerDairy(Context ct)
{
this.ct=ct;
dbhelper1 = new DataBaseHelper1(ct);
}
private static class DataBaseHelper1 extends SQLiteOpenHelper
{
public DataBaseHelper1(Context ct)
{
super(ct,DATA_BASE_NAME,null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
try
{
db.execSQL(TABLE_CREATE);
}
catch(SQLException e)
{
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS table_dairy ");
onCreate(db);
}
}
public DataHandlerDairy open()
{
db = dbhelper1.getWritableDatabase();
return this;
}
public void close()
{
dbhelper1.close();
}
public long insertData(String date,String dairy)
{
ContentValues content = new ContentValues();
content.put(DATE, date);
content.put(DAIRY, dairy);
return db.insertOrThrow(TABLE_NAME, null, content);
}
public Cursor returnData(String date1) throws SQLException
{
Cursor c = db.query(true, TABLE_NAME, new String[] { DATE, DAIRY}, DATE + "=" + date1, null, null, null, null, null);
if(c!=null)
{
c.moveToFirst();
}
return c;
}
}
when i try to retrive the data from the database I am getting an error.
I have used the database helper class in the following code.
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Typeface;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
public class Read_Dairy extends Activity {
String date1;
TextView tv1,tv2;
ImageButton imgb1;
Button bt1;
DataHandlerDairy handler3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read__dairy);
tv1=(TextView) findViewById(R.id.readme);
imgb1=(ImageButton) findViewById(R.id.tick);
bt1=(Button) findViewById(R.id.ready);
tv2=(TextView) findViewById(R.id.love);
Bundle bundle = getIntent().getExtras();
date1 = bundle.getString("kanna");
bt1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String getdata=" ";
tv2.setText(date1);
String abcd=tv2.getText().toString();
handler3 = new DataHandlerDairy(getBaseContext());
handler3.open();
Cursor c = handler3.returnData(abcd);
if(c.moveToFirst())
{
do
{
getdata=c.getString(1);
}while(c.moveToNext());
}
handler3.close();
if(getdata==null)
{
tv1.setText("no data exists for this date");
}
else
{
tv1.setText(getdata);
}
}
});
imgb1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent ks = new Intent(Read_Dairy.this,PickYourDate.class);
startActivity(ks);
}
});
Typeface font = Typeface.createFromAsset(getAssets(), "Strato-linked.ttf");
tv1.setTypeface(font);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_read__dairy, menu);
return true;
}
}
I am getting an error while using this and my StackTrace is
FATAL EXCEPTION: main
Process: simple.smile.my_dairy, PID: 4423
android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
at android.database.AbstractCursor.checkPosition(AbstractCursor.java:426)
at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
at simple.smile.my_dairy.Read_Dairy$1.onClick(Read_Dairy.java:71)
at android.view.View.performClick(View.java:4832)
at android.view.View$PerformClick.run(View.java:19839)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:211)
at android.app.ActivityThread.main(ActivityThread.java:5315)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:941)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:736)
Please tell me where the error is and how to rectify it.
getdata=c.getString(1) is not a good way. Instead use getdata=c.getString(c.getColumnIndex(DataHandlerDairy.DAIRY))

java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase

I designed an app and on click in image view and show image in new activity if back app force close.
I add list view code and database code if need new activity code say.
list view code:
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class sharedlist extends ListActivity{
private String[] items;
private database db;
private Typeface nazanin;
private Typeface homa;
private SharedPreferences sp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sharedlist);
db=new database(this);
db.open();
items=new String[db.count("content")];
nazanin=Typeface.createFromAsset(getAssets(), "Font/nazanin.ttf");
homa=Typeface.createFromAsset(getAssets(), "Font/homa.ttf");
sp=getApplicationContext().getSharedPreferences("setting", 0);
setListAdapter(new AAD());
}
class AAD extends ArrayAdapter{
public AAD() {
super(sharedlist.this,R.layout.row,items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater in=getLayoutInflater();
View row=in.inflate(R.layout.row,parent,false);
final String li=db.Display_shared(position,0);
TextView username=(TextView) row.findViewById(R.id.row_username);
TextView maintext=(TextView) row.findViewById(R.id.row_maintext);
username.setText(db.Display_shared(position, 1).toString());
maintext.setText(db.Display_shared(position, 2).toString());
ImageView image=(ImageView) row.findViewById(R.id.row_image);
image.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
//new imageview("link",li).execute();
Intent ed=new Intent(sharedlist.this,showImage.class);
//new imageview("link",li).execute();
ed.putExtra("postid",li);
startActivity(ed);
}
});
if(sp.getString("font", "homa").equals("nazanin")){
maintext.setTypeface(nazanin);
}else if(sp.getString("font", "homa").equals("homa")){
maintext.setTypeface(homa);
}
if(sp.getString("size", "k").equals("k")){
maintext.setTextSize(18);
}else if(sp.getString("size", "k").equals("b")){
maintext.setTextSize(25);
}
return (row);
}
}
#Override
protected void onPause() {
super.onPause();
db.close();
}
}
and database :
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
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.widget.Toast;
public class database extends SQLiteOpenHelper {
public final String path="data/data/packagename/databases/";
public final String Name="database";
public SQLiteDatabase mydb;
private final Context mycontext;
public database(Context context) {
super(context, "database", null, 1);
mycontext=context;
}
#Override
public void onCreate(SQLiteDatabase arg0) {
}
#Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
}
public void useable(){
boolean checkdb=checkdb();
if(checkdb){
}else{
this.getReadableDatabase();
try{
copydatabase();
}catch(IOException e){
}
}
}
public void open(){
mydb=SQLiteDatabase.openDatabase(path+Name, null, SQLiteDatabase.OPEN_READWRITE);
}
public void close(){
mydb.close();
}
public boolean checkdb(){
SQLiteDatabase db=null;
try{
db=SQLiteDatabase.openDatabase(path+Name, null, SQLiteDatabase.OPEN_READONLY);
}
catch(SQLException e)
{
}
return db !=null ? true:false ;
}
public void copydatabase() throws IOException{
OutputStream myOutput = new FileOutputStream(path+Name);
byte[] buffer = new byte[1024];
int length;
InputStream myInput = mycontext.getAssets().open(Name);
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myInput.close();
myOutput.flush();
myOutput.close();
}
public String Display(int row,int fild){
Cursor cu= mydb.query("content", null, null, null, null, null, null);
cu.moveToPosition(row);
String name=cu.getString(fild);
return name;
}
public Integer count(String table){
Cursor cu= mydb.query(table, null, null, null, null, null, null);
int s=cu.getCount();
return s;
}
public void insert(String id,String user,String matn){
ContentValues cv=new ContentValues();
cv.put("ID", id);
cv.put("username", user);
cv.put("matn", matn);
mydb.insert("content", "ID", cv);
}
public String Display_shared(int row,int fild){
Cursor cu= mydb.rawQuery("select * from content order by ID DESC",null);
cu.moveToPosition(row);
String name=cu.getString(fild);
return name;
}
}
log chat :
java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase: data/data/package name/databases/database
http://i.stack.imgur.com/iQOUp.png
Here:
final String li=db.Display_shared(position,0);
line causing issue because database open method called in onCreate method before setting Adapter for ListView and open method called again in getView method without closing previous connection which is opened in onCreate method.
if you are getting data from database according to position then open/close connection in getView method instead of onCreate method
or you can also get all data from table using one query and store in any data-container like ArrayList, Map,... instead of querying database many times.

How display field values in new activity when particular listview is clicked?

I have a table on my database.
one of the field from that table is displayed as a listview in the main activity.
i have implemented the setOnItemClickListener to open the new activity to display other field values of that selected list item.
new activiy is successfully opened.
but i have trouble in displaying field values....
i have browsed many sites....
but nothing helped.....
i have displayed department names in listview...
in the new activity i need get the value of DEPT_LIST_COLUMN_ID and DEPT_LIST_COLUMN_NAME
MainActivity.java
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
public class MainActivity extends Activity {
private MyDBHelper mydb;
private SimpleCursorAdapter adapter;
public static final String Row_ID = "row_id";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//********************************//
//Begin of Database-Table1_Dept_List
//********************************//
ListView dplist=(ListView)findViewById(R.id.list_view);
//Instantiate table1_dept_list
mydb =new MyDBHelper(this, null, null,4);
SQLiteDatabase db =mydb.getReadableDatabase();
//Removing duplicate values from table1_dept_list
mydb.delete_dep_list();
//Inserting into table1_dept_list
mydb.add_dept_list("DLBIOCHEM","BioChemistry");
mydb.add_dept_list("DLBIOTECH","BioTechnology");
mydb.add_dept_list("DLBOT", "Botany");
mydb.add_dept_list("DLCHEM","Chemistry");
mydb.add_dept_list("DLCOM","Commerce");
mydb.add_dept_list("DLCS","Computer Science");
mydb.add_dept_list("DLECO","Economics");
mydb.add_dept_list("DLEDU","Education");
mydb.add_dept_list("DLENG","English");
mydb.add_dept_list("DLEVS","Environmental Science");
mydb.add_dept_list("DLFSN","Food Science and Nutrition");
mydb.add_dept_list("DLGEO","Geology");
mydb.add_dept_list("DLJMC", "Journalism and Massmedia Communication");
mydb.add_dept_list("DLLIS","Library and Information Science");
mydb.add_dept_list("DLMATH","Mathematics");
mydb.add_dept_list("DLMICRO","Microbiology");
mydb.add_dept_list("DLPE","Physical Education");
mydb.add_dept_list("DLPHY","Physics");
mydb.add_dept_list("DLPRIMS","Periyar Institute of Management Studies");
mydb.add_dept_list("DLPSY","Psychology");
mydb.add_dept_list("DLSOC","Sociology");
mydb.add_dept_list("DLTAM", "Tamil");
mydb.add_dept_list("DLTAD","Textile and Apparel Design");
mydb.add_dept_list("DLZOO","Zoology");
//list view
Cursor AllDeptList = mydb.get_dept_list();
String[] from=new String[] {
MyDBHelper.DEPT_LIST_COLUMN_NAME
};
int[] to=new int[] {R.id.dis_text};
adapter = new SimpleCursorAdapter(this,R.layout.disp_text,AllDeptList,from,to,0 );
dplist.setAdapter(adapter);
//********************************//
//end of Database-Table1_Dept_List//
//********************************//
dplist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
Cursor cursor = mydb.get_dept_list();
cursor.moveToPosition(position);
Intent intent_dp_list = new Intent(MainActivity.this,DepartmentDesignation.class);
intent_dp_list.putExtra(Row_ID,arg3);
startActivity(intent_dp_list);
}
});
}
#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;
}
}
DepartmentDesignation.java
package com.example.contact;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.widget.TextView;
public class DepartmentDesignation extends Activity {
private SimpleCursorAdapter adapter;
public static String d_id;
public static String d_name;
private String Row_id;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.disp_dept_desig);
TextView tx_id = (TextView)findViewById(R.id.id);
Intent extras = getIntent();
tx_id.setText(extras.getStringExtra(Row_id));
TextView tx_name=(TextView)findViewById(R.id.name);
tx_name.setText(d_name);
}
}
MyDBHelper.java
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 MyDBHelper extends SQLiteOpenHelper{
public static final String DEPT_LIST_TABLE1_NAME="tbl_dep_list";
public static final String DEPT_LIST_ROW_ID = "_id";
public static final String DEPT_LIST_COLUMN_ID = "fld_tb1_id";
public static final String DEPT_LIST_COLUMN_NAME="fld_tb1_list";
public MyDBHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, "contact_book.db", factory, 11);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase database) {
// TODO Auto-generated method stub
database.execSQL(" CREATE TABLE " + DEPT_LIST_TABLE1_NAME + "(" + DEPT_LIST_ROW_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + DEPT_LIST_COLUMN_ID + " TEXT, " + DEPT_LIST_COLUMN_NAME + " TEXT ) " );
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DEPT_LIST_TABLE1_NAME);
onCreate(db);
}
public void add_dept_list(String dl_id, String dep_list) {
// TODO Auto-generated method stub
ContentValues values = new ContentValues(2);
values.put(MyDBHelper.DEPT_LIST_COLUMN_ID , dl_id);
values.put(MyDBHelper.DEPT_LIST_COLUMN_NAME,dep_list);
getWritableDatabase().insert(MyDBHelper.DEPT_LIST_TABLE1_NAME,null,values);
}
public int delete_dep_list(){
try{
SQLiteDatabase db =this.getWritableDatabase();
return db.delete(DEPT_LIST_TABLE1_NAME, null, null);
}
catch(Exception e){
e.printStackTrace();
}
return 0;
}
public Cursor get_dept_list(){
String[] from = new String[] {MyDBHelper.DEPT_LIST_ROW_ID,MyDBHelper.DEPT_LIST_COLUMN_ID,MyDBHelper.DEPT_LIST_COLUMN_NAME};
Cursor cursor = getReadableDatabase().query(MyDBHelper.DEPT_LIST_TABLE1_NAME, from,null,null,null, null, null);
if(cursor != null){
cursor.moveToFirst();
}
return cursor;
}
}
On your onItemClick method, pass the values you need in an intent to open the activity.
Intent intent = new Intent("blah blah");
intent.putExtra(DEPT_LIST_COLUMN_ID, "value");
intent.putExtra(DEPT_LIST_COLUMN_NAME, "value");
Then on the opened activity, do:
extras.getStringExtra(DEPT_LIST_COLUMN_ID)

android null pointer while using SQLITE

i am trying to implement an app in which text entered in edittext is saved to the DB and then is displayed in a text field. But the app is crashing when i try to do this and i get a null pointer exception. This is my code
package com.example.dbex;
import java.sql.SQLOutput;
import java.sql.SQLPermission;
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 {
public static final int DATABASE_VERSION=1;
public static final String DATABASE_NAME="contactsmanager";
public static final String TABLE_CONTACTS="contacts";
public static final String KEY_ID="id";
public static final String KEY_NAME="name";
public static final String KEY_NUMBER="number";
public DBHandler(Context context) {
super(context,DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String CREATE_TABLE_CONTACTS="CREATE TABLE "+TABLE_CONTACTS+"("+KEY_ID+" INTEGER PRIMARY KEY,"+KEY_NAME+" TEXT,"+KEY_NUMBER+" TEXT"+")";
db.execSQL(CREATE_TABLE_CONTACTS);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS "+TABLE_CONTACTS);
onCreate(db);
}
public void addContact(Contacts contacts)
{
SQLiteDatabase db=this.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(KEY_NAME, contacts.getname());
values.put(KEY_NUMBER, contacts.getnumber());
db.insert(TABLE_CONTACTS,null,values);
db.close();
}
public Contacts getContact(int id)
{
SQLiteDatabase db=this.getReadableDatabase();
Cursor c=db.query(TABLE_CONTACTS, new String[]{KEY_ID,KEY_NAME,KEY_NUMBER},KEY_ID+" =?",new String[]{String.valueOf(id)}, null, null, null, null);
Contacts contacts=null;
if(c!=null&&c.moveToFirst())
{
contacts=new Contacts(Integer.parseInt(c.getString(0)),c.getString(1),c.getString(2));
}
return contacts;
}
public void deleteContact(Contacts contacts)
{
SQLiteDatabase db=this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID+" =?", new String[]{String.valueOf(contacts.getID())});
db.close();
}
}
and the main activity is
package com.example.dbex;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b1=(Button)findViewById(R.id.button1);
EditText et1=(EditText)findViewById(R.id.editText1);
EditText et2=(EditText)findViewById(R.id.editText2);
final TextView tv1=(TextView)findViewById(R.id.textView1);
final String _name=et1.getText().toString();
final String _phone=et2.getText().toString();
final DBHandler dbh=new DBHandler(getBaseContext());
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dbh.addContact(new Contacts(_name, _phone));
String contact1=(dbh.getContact(0)).getname();
tv1.setText(contact1);
}
});
}
#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;
}
}
i am getting the null pointer exception in the line
String contact1=(dbh.getContact(0)).getname();
where is my mistake?
thanks
Since you are telling you are able to insert the value, I assume your DB creation is correct You have hardcoded the id being queried to 0. You may not be having any value here. See this post to understand that even when you delete existing rows the auto increment ID could be continuing from the last used value instead of 0. So you could be returning a null value in this part of your code:
Contacts contacts=null;
if(c!=null&&c.moveToFirst())
{
contacts=new Contacts(Integer.parseInt(c.getString(0)),c.getString(1),c.getString(2));
}
return contacts;

Categories

Resources