I can't send data to sqlite to database [duplicate] - android

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
I am trying to add data to the SQLite database but when I add the data it gives me null pointer exception.
This is the error in the logcat
java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.File android.content.Context.getDatabasePath(java.lang.String)' on a null object reference
enter code here
package com.llmago.autism;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Objects;
public class StartFragment extends Fragment {
private EditText edtName, edtAge, edtScore;
private Button save, load;
Db db = new Db(getActivity());
public StartFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_start, container, false);
initUI(view);
// Inflate the layout for this fragment
return view;
}
public void initUI(View view) {
edtName = view.findViewById(R.id.name);
edtAge = view.findViewById(R.id.age);
edtScore = view.findViewById(R.id.result);
save = view.findViewById(R.id.save);
save.setOnClickListener(v -> btnSaveAction(view));
}
public void btnSaveAction(View view) {
String name = edtName.getText().toString();
String age = edtAge.getText().toString();
String score = edtScore.getText().toString();
boolean result = db.insertData(name, age, score);
if (result == true) {
Toast.makeText(getActivity(), "Done", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getActivity(), "Error", Toast.LENGTH_LONG).show();
}
}
}
package com.llmago.autism;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
public class Db extends SQLiteOpenHelper {
public static final String databaseName = "autism.db";
public Db(#Nullable Context context) {
super(context, databaseName, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table autism(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age TEXT, score TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS autiusm");
onCreate(db);
}
public boolean insertData(String name, String age, String score){
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("age", age);
contentValues.put("score", score);
long result = sqLiteDatabase.insert("autism", null, contentValues);
if (result == -1)
return false;
else
return true;
}
}

Declare the mContext inside FragmentClass
Context mContext;
Change constructor from
public StartFragment(Context context) {
mContext = context;
db = new Db(mContext);
}
Also replace the db() constructor
public Db(#Nullable Context context) {
super(context, databaseName, null, 1);
this.getWritableDatabase();
}
Note: When you creating fragment instance you have to pass Activity Reference

Related

Why my database deletion code did not works

My Database program works so far with submit and show data function. But deletion and modify database function is not working. I have attached the code for EventsDB.java and EventDetail.java and their resource layout file. Basically there is no problem with submit and show data part. i haven done the modify part and deletion part just din work.Please help.
package com.cinrafood.teopeishen.databasedemo;
import android.content.Intent;
import android.database.SQLException;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
EditText etEvent,etEventDetail,etDate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
etEvent=(EditText)findViewById(R.id.etEvent);
etEventDetail= (EditText)findViewById(R.id.etEventDetail);
etDate=(EditText)findViewById(R.id.etDate);
}
public void btnSubmit (View view)
{
try{
String event = etEvent.getText().toString();
String eventDetail = etEventDetail.getText().toString();
String date= etDate.getText().toString();
EventsDB db = new EventsDB(this);
db.open();
db.createEntry(event,eventDetail,date);
db.close();
Toast.makeText(MainActivity.this,"Successfully saved!!",Toast.LENGTH_LONG).show();
etDate.setText("");
etEventDetail.setText("");
etEvent.setText("");
}catch (SQLException e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}catch (Exception e)
{
Toast.makeText(this,"Please fill up all field",Toast.LENGTH_LONG).show();
}
}
public void btnShowEvents (View view)
{
startActivity(new Intent(this,EventData.class));
}
}
package com.cinrafood.teopeishen.databasedemo;
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 java.util.ArrayList;
public class EventsDB
{
public static final String KEY_ROWID ="_id";
public static final String KEY_EVENT="event_name";
public static final String KEY_EVENT_DESCRIPTIOM="event_description";
public static final String KEY_DATE="event_date";
private final String DATABASE_NAME="EventsDB";
private final String DATABASE_TABLE="EventsTable";
private final int DATABASE_VERSION=1;
private DBHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private ArrayList<Event> events;
public EventsDB(Context context)
{
ourContext= context;
}
private class DBHelper extends SQLiteOpenHelper
{
public DBHelper (Context context)
{
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+DATABASE_TABLE);
onCreate(db);
}
#Override
public void onCreate(SQLiteDatabase db) {
/*
CREATE TABLE EventsTable (_id INTEGER PRIMARY KEY AUTOINCREMENT,
event_name TEXT NOT NULL,event_description TEXT NOT NULL,
event_date DATE NOT NULL);
*/
String sqlCode="CREATE TABLE "+DATABASE_TABLE+" ("+
KEY_ROWID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+
KEY_EVENT+" TEXT NOT NULL, "+
KEY_EVENT_DESCRIPTIOM+" TEXT NOT NULL, "+
KEY_DATE+" TEXT NOT NULL);";
db.execSQL(sqlCode);
}
}
public EventsDB open() throws SQLException
{
ourHelper = new DBHelper(ourContext);
ourDatabase=ourHelper.getWritableDatabase();
events= new ArrayList<Event>();
return this;
}
public void close()
{
ourHelper.close();
}
public long createEntry(String event_name, String event_description, String event_date)
{
ContentValues cv = new ContentValues();
cv.put(KEY_EVENT,event_name);
cv.put(KEY_EVENT_DESCRIPTIOM,event_description);
cv.put(KEY_DATE,event_date);
return ourDatabase.insert(DATABASE_TABLE,null,cv);
}
public ArrayList<Event> getData()
{
String [] columns = new String[]{KEY_ROWID,KEY_EVENT,KEY_EVENT_DESCRIPTIOM,KEY_DATE};
Cursor c = ourDatabase.query(DATABASE_TABLE,columns,null,null,null,null,null);
int iRowID = c.getColumnIndex(KEY_ROWID);
int iEvent = c.getColumnIndex(KEY_EVENT);
int iEventDescription = c.getColumnIndex(KEY_EVENT_DESCRIPTIOM);
int iDate = c.getColumnIndex(KEY_DATE);
for(c.moveToFirst();!c.isAfterLast();c.moveToNext())
{
Event event = new Event(c.getInt(iRowID),c.getString(iEvent),c.getString(iEventDescription),c.getString(iDate));
events.add(event);
}
return events;
}
public long deleteEntry (String rowID){
return ourDatabase.delete(DATABASE_TABLE,KEY_ROWID+"=?",new String[]{rowID});
}
public long updateEntry(String rowID, String event_name, String event_description, String event_date)
{
ContentValues cv = new ContentValues();
cv.put(KEY_EVENT,event_name);
cv.put(KEY_EVENT_DESCRIPTIOM,event_description);
cv.put(KEY_DATE,event_date);
return ourDatabase.update(DATABASE_TABLE,cv,KEY_ROWID+"=?",new String[]{rowID});
}
}
package com.cinrafood.teopeishen.databasedemo;
import android.content.Intent;
import android.database.SQLException;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
public class EventData extends AppCompatActivity {
ListView lvEvents;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_data);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
try{
EventsDB db = new EventsDB(this);
db.open();
lvEvents= (ListView)findViewById(R.id.lvEvents);
lvEvents.setAdapter(new CustomAdapter(db.getData(),getApplicationContext()));
db.close();
}catch (SQLException e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}catch(Exception e){
Toast.makeText(this, e.getMessage(),Toast.LENGTH_LONG).show();
}
AdapterView.OnItemLongClickListener click = new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(EventData.this,EventDetail.class);
intent.putExtra("Location",position);
startActivity(intent);
return true;
}
};
lvEvents.setOnItemLongClickListener(click);
}
}
package com.cinrafood.teopeishen.databasedemo;
import android.database.SQLException;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import java.util.ArrayList;
public class EventDetail extends AppCompatActivity {
EditText etTitlePage,etEventDetailPage,etDatePage;
Button btnDeleteEvent;
int location;
ArrayList<Event> events;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_detail);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
etTitlePage=(EditText) findViewById(R.id.etTitlePage);
etEventDetailPage=(EditText) findViewById(R.id.etEventDetailPage);
etDatePage=(EditText) findViewById(R.id.etDatePage);
btnDeleteEvent=(Button)findViewById(R.id.btnDeleteEvent);
try{
EventsDB db = new EventsDB(this);
db.open();
events=db.getData();
location = getIntent().getIntExtra("Location",0);
etTitlePage.setText(events.get(location).getEvent_name());
etEventDetailPage.setText(events.get(location).getEvent_description());
etDatePage.setText(events.get(location).getEvent_date());
db.close();
}catch (SQLException e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}catch(Exception e){
Toast.makeText(this, e.getMessage(),Toast.LENGTH_LONG).show();
}
btnDeleteEvent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
EventsDB db = new EventsDB(getApplicationContext());
db.open();
db.deleteEntry((location+1)+"");
db.close();
Toast.makeText(getApplicationContext(),"Successfully deleted!!",Toast.LENGTH_LONG).show();
}catch (SQLException e)
{
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}catch(Exception e){
Toast.makeText(getApplicationContext(), e.getMessage(),Toast.LENGTH_LONG).show();
}
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
public Integer deleteContacts (Integer id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("contacts",
"id = ? ",
new String[] { Integer.toString(id) });
}
Actually you have passed position of the item in ListView to delete that item from database which is not correct. You have to pass the rowId of database primary key to complete the delete operation.
AdapterView.OnItemLongClickListener click = new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//Retrieve Event from adapter
Event event = lvEvents.getAdapter().getItem(position);
Intent intent = new Intent(EventData.this,EventDetail.class);
intent.putExtra("Location", event.getRowId()); // get rowId from event.
startActivity(intent);
return true;
}
};
And execute delete operation using that rowId
db.deleteEntry(location + "");

Unfortunately this app has stopped working (SQLiteDatabase) [duplicate]

This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 7 years ago.
I have this problem: I wrote an app, but the SQLiteDatabase isn't working.
My database class code:
package com.example.frauprinzssapp;
import android.content.ContentValues;
import android.content.Context;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class database extends SQLiteOpenHelper{
public static final String DB_NAME = "users.db";
public static final String DB_TABLENAME = "users_table";
public static final String COL_1 = "id";
public static final String COL_2 = "name";
public static final String COl_3 = "class";
public static final String COL_4 = "right";
public database(Context context) {
super(context, DB_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table "+DB_TABLENAME+"(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, class TEXT, right INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXIST "+DB_TABLENAME);
onCreate(db);
}
public boolean insertdata(String name, String clas){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COL_2, name);
cv.put(COl_3, clas);
cv.put(COL_4, 0);
long result = db.insert(DB_TABLENAME, null, cv);
if (result == -1){
return false;
}else{
return true;
}
}
}
The main code is:
package com.example.frauprinzssapp;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class Main extends Activity {
List<String> addusers = new ArrayList<String>();
database myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myDb = new database(this);
}
//-----change view voids-----
public void main(View view){
setContentView(R.layout.main);
}
public void adduser(View view){
setContentView(R.layout.adduser);
}
public void removeuser(View view){
setContentView(R.layout.removeuser);
}
//------actions------
public void add(){
EditText name = (EditText) findViewById(R.id.aun);
EditText clas = (EditText) findViewById(R.id.auc);
if (name.toString() == null || clas.toString() == null){
Toast.makeText(Main.this, "please fill in all textfields!", Toast.LENGTH_LONG);
return;
}
try{
myDb.insertdata(name.toString(), clas.toString());
Toast.makeText(Main.this, "added user "+name.toString()+"!", Toast.LENGTH_LONG);
}catch(Exception e){
Toast.makeText(Main.this, "[ERROR] Could not create user maybe its already created!", Toast.LENGTH_LONG);
}
}
public void remove(){
}
public void show(){
}
}
I used the
android:onClick="add"
to make so that the add() void runs
please now it just puts random stuff into the sqlite pleaseeeee help
try it....
//------actions------
public void add(){
EditText name = (EditText) findViewById(R.id.aun);
EditText clas = (EditText) findViewById(R.id.auc);
String name1 = name.getText().toString();
String clas1 = clas.getText().toString();
if (name1.equals("") || clas1.equals("")){
Toast.makeText(Main.this, "please fill in all textfields!", Toast.LENGTH_LONG);
return;
}
try{
myDb.insertdata(name1, clas1);
Toast.makeText(Main.this, "added user "+name1+"!", Toast.LENGTH_LONG);
}catch(Exception e){
Toast.makeText(Main.this, "[ERROR] Could not create user maybe its already created!", Toast.LENGTH_LONG);
}
}

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