This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 7 years ago.
I have a problem when I want to start a new activity wchich contains a reference to object extending SQLiteOpenHelper.
This is how I sart my activity:
// Listener for button
class LoginButtonListener implements View.OnClickListener {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), MasterUserActivity.class);
v.getContext().startActivity(intent);
}
}
My new activity:
// I will be implementing ListView in here
public class MasterUserActivity extends ListActivity {
private DBHandler dbHandler = new DBHandler(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.master_user);
Toast toast = Toast.makeText(MasterUserActivity.this, "It works :)", Toast.LENGTH_LONG);
toast.show();
}
}
And my DBHandler class:
public class DBHandler extends SQLiteOpenHelper {
public DBHandler(Context contex) {
super(contex, "bankapplication.db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase database) {
String query = "CREATE TABLE users ( login TEXT, password TEXT, name TEXT, "
+ "phone TEXT, country TEXT, balance TEXT)";
database.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
String query = "DROP TABLE IF EXISTS users";
database.execSQL(query);
onCreate(database);
}
}
It works fine when I comment out private DBHandler dbHandler = new DBHandler(this);
What is wrong in here ?
This line is causing the error :
private DBHandler dbHandler = new DBHandler(this);
You can not call new while declaring variable, instead initialize inside onCreate method of your activity.
Related
I am making a "Note" program to practice and learn - my first "freestyle" project after reading a book on the subject. The way i figured i would do this is to store the title and content of the note in a SQLite table, and insert and remove from the table as needed.
The first activity consists of a ListView which gets all the notes(rows) from the DB. The user is supposed to press a button at the first activity, which says "New note", which then leads to another activity where you can enter the title and the content of the note, press the "Save" button, and then with an intent, return to the activity with the ListView where the newly added note plus all earlier created notes are displayed in the ListView.
My problem is that when the intent starts the activity with the ListView from the NewNote activity, the newly added note wont show in the ListView at once. If i then add a new note again, it returns to the first activity, but then the note i added first is displayed. And so it goes on. In other words the list on the first activity is always "one note behind", as it only adds the note i added the last time and not the one i recently added. Maybe its a bad explanation, but i think thats as clear as it gets. I spent alot of time today logging and trying to find the problem but i cant seem to figure this out on my own.
Here is my code.
Starting with my database class:
public class DatabaseHandler extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "DB";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NOTES = "Notes";
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_CONTENT = "content";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_PERSON_TABLE = "CREATE TABLE " + TABLE_NOTES + "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_TITLE + " TEXT," + KEY_CONTENT + " INTEGER" + ")";
db.execSQL(CREATE_PERSON_TABLE);
}
public void dropTable() {
SQLiteDatabase db = this.getReadableDatabase();
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NOTES);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NOTES);
onCreate(db);
}
public void newNote(String title, String content) {
SQLiteDatabase db = this.getReadableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TITLE, title);
values.put(KEY_CONTENT, content);
db.insert(TABLE_NOTES, null, values);
db.close();
}
public void deleteNote(String id) {
SQLiteDatabase db = getReadableDatabase();
db.delete(TABLE_NOTES, KEY_ID + "=" + id, null);
}
public ArrayList<Note> getNotes() {
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<Note> notes = new ArrayList<>();
Cursor cursor = db.query(TABLE_NOTES, new String[]{KEY_ID, KEY_TITLE, KEY_CONTENT}, null, null, null, null, KEY_ID + " DESC", null);
if (cursor != null) {
cursor.moveToFirst();
}
while(cursor.moveToNext()) {
Note note = new Note(cursor.getString(0), cursor.getString(1), cursor.getString(2));
notes.add(note);
}
db.close();
return notes;
}
public void deleteAll() {
SQLiteDatabase db = this.getReadableDatabase();
db.execSQL("delete from " + TABLE_NOTES);
db.close();
}
}
My Main activity, ListActivity:
public class ListActivity extends AppCompatActivity {
private DatabaseHandler dbh;
private ListView list;
private ArrayAdapter<Note> listAdapter;
private Button newBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
dbh = new DatabaseHandler(this);
Intent intent = getIntent();
String id = intent.getStringExtra("Id");
String title = intent.getStringExtra("Title");
String content = intent.getStringExtra("Content");
//If save button is pressed at NewNote
if (title != null && content != null) {
dbh.newNote(title, content);
Log.d("note", title + " added");
}
//If delete button is pressed at NewNote
if (id != null) {
dbh.deleteNote(id);
}
initWidgets();
}
public void initWidgets() {
list = findViewById(R.id.list);
newBtn = findViewById(R.id.newButton);
newBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent newButtonIntent = new Intent(ListActivity.this, NewNote.class);
startActivity(newButtonIntent);
}
});
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Note note = listAdapter.getItem(i);
Intent editIntent = new Intent(ListActivity.this, EditNote.class);
editIntent.putExtra("Title", note.getTitle());
editIntent.putExtra("Content", note.getContent());
editIntent.putExtra("Id", note.getId());
startActivity(editIntent);
}
});
refreshList();
}
public void refreshList() {
listAdapter = new ArrayAdapter(this, R.layout.list_item, dbh.getNotes());
list.setAdapter(listAdapter);
Log.d("note", "View updated");
}
}
My NewNote class:
public class NewNote extends AppCompatActivity {
private EditText title;
private EditText content;
private Button btnSave;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_note);
initWidgets();
}
public void initWidgets() {
title = findViewById(R.id.title);
content = findViewById(R.id.content);
btnSave = findViewById(R.id.saveButton);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(NewNote.this, ListActivity.class);
i.putExtra("Title", title.getText().toString());
i.putExtra("Content", content.getText().toString());
startActivity(i);
}
});
}
}
Not really relevant as i have not implemented it fully, if you are just reading through the code you can 100% just ignore this class - my EditNote class:
public class EditNote extends AppCompatActivity {
private EditText title;
private EditText content;
private Button saveBtn;
private Button deleteBtn;
private String noteId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_note);
initWidgets();
Intent intent = getIntent();
title.setText(intent.getStringExtra("Title"));
content.setText(intent.getStringExtra("Content"));
noteId = intent.getStringExtra("Id");
}
public void initWidgets() {
title = findViewById(R.id.titleEdit);
content = findViewById(R.id.contentEdit);
deleteBtn = findViewById(R.id.deleteButton);
deleteBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
Intent i = new Intent(EditNote.this, ListActivity.class);
i.putExtra("Id", noteId);
startActivity(i);
}
});
}
}
Also there are my XML files, and a Note class which only consists of member variables and setters/getters, either of them i consider relevant. I think the problem is somewhere in the DB class, ListActivity class, or NewNote class.
Maybe this is alot to read for you and maybe its messy or im doing something wrong with the posting but i would be grateful for help on how to resolve this issue. Also if you see other things i can do better please point them out!
Thanks!
I am trying to create a database, but nothing happening with my code. I know this question is very basic but I am a new learner so I could not solve my problem so kindly help me.
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME="employeedb";
private static final String TABLE_NAME="EMPLOYEETABLE";
private static final int DATABASE_VERSION=1;
private static final String EID="_id";
private static final String NAME="Name";
private static final String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+" ("+EID+" INTEGER PRIMARY AUTOINCREMENT, "+NAME+" VARCHAR(255))";
private static final String DROP_TABLE="DROP TABLE "+TABLE_NAME+"IF EXISTS";
private Context context;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
Message.message(context, "Constructor called.");
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
Message.message(context, "onCreate called.");
db.execSQL(CREATE_TABLE);
}
catch (Exception e)
{
Message.message(context, ""+e);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
Message.message(context, "onUpgrade called.");
db.execSQL(DROP_TABLE);
onCreate(db);
} catch (SQLException e) {
Message.message(context, ""+e);
}
}
}
Here is Message Class that only one method
public class Message {
public static void message(Context context, String message){
Toast.makeText(context,message,Toast.LENGTH_SHORT);
}
}
Here is MainActivity Code where i call the getWritabeDatase Method.
public class MainActivity extends Activity implements MyDialog.Communicator {
LinearLayout layout;
TextView txt;
TextView date;
DatabaseHelper dbhelper;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
layout = (LinearLayout) findViewById(R.id.layoutbottom);
date = (TextView) findViewById(R.id.date);
txt =(TextView) findViewById(R.id.title);
GeneralMethods generalmethods = new GeneralMethods(this,this);
dbhelper = new DatabaseHelper(this);
SQLiteDatabase sqLiteDatabase = dbhelper.getWritableDatabase();
}
public void showDialog(View v){
FragmentManager manager = getFragmentManager();
MyDialog myDialog = new MyDialog();
myDialog.show(manager,"MyDialog");
}
#Override
public void onDialogueMessage(String message) {
date.setText(message);
}
}
You onCreate will get called when you first access the database using the helper.
Any call to either
getReadableDatabase() or getWritableDatabase()
will cause the onCreate to get triggered and only then. Your onUpgrade will trigger when you change the database version of an already existing schema.
Also as per SQLite documentation, an integer primary key will automatically get incremented to the max+1 value on it's own.
Adding an Auto increment causes unnecessary explicit overhead and changes the rowid selection algorithm and they do not recommend it.
You have forgotten the show() for the toast in your Message class
Toast.makeText(context,message,Toast.LENGTH_SHORT).show();
Basically without the show(), the Toast will not get shown, it will just get created. Now since onCreate gets called only once, to check if it's working , uninstall and reinstall the app or clear it's data before testing
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I have watched so many solution and applied all but still getting null pointer exception in my code. Here is my code kindly have a look and reply as fast as anyone can. Thanks in advance.
DBHandler.java Class code
public class DBHandler extends SQLiteOpenHelper {
//Database Version
private static final int DATABASE_VERSION=1;
// Database Name
private static final String DATABASE_NAME="Patient.db";
//Table Name
private static final String TABLE_NAME="patientDetail";
//Table Columns Names
private static final String ID="id";
private static final String NAME="name";
private static final String ADDRESS="address";
private static final String PHONE_NUMBER="phone_number";
//Constructor
public DBHandler(Context context)
{
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
//Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_PATIENT_DETAIL_TABLE="CREATE TABLE "+TABLE_NAME+"("
+ ID+" INTEGER PRIMARY KEY AUTOINCREMENT,"
+NAME+" TEXT,"
+ADDRESS +" TEXT,"
+PHONE_NUMBER + " TEXT )" ;
db.execSQL(CREATE_PATIENT_DETAIL_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//Drop older tables if exist
db.execSQL("DROP TABLE IF EXIST "+TABLE_NAME);
/// Create Table again
onCreate(db);
}
public boolean insertData(String name,String address, String ph_no)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values= new ContentValues();
values.put(NAME,name);
values.put(ADDRESS,address);
values.put(PHONE_NUMBER,ph_no);
long result = db.insert(TABLE_NAME,null,values);
if(result == -1)
return false;
else
return true;
}
}
//insertPatient.java Class Code
public class insertPatient extends Fragment {
DBHandler mydb=null;
EditText editname,editaddress,editph_no;
Button btn_adddata;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.insert_patient, container, false);
mydb = new DBHandler(getActivity());
editname=(EditText) rootView.findViewById(R.id.insert_name);
editname=(EditText) rootView.findViewById(R.id.insert_address);
editname=(EditText) rootView.findViewById(R.id.insert_ph_no);
btn_adddata=(Button) rootView.findViewById(R.id.insert_button);
btn_adddata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
adddata();
}
});
return rootView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mydb = new DBHandler(getActivity());
}
public void adddata()
{
mydb = new DBHandler(getActivity());
Toast.makeText(getActivity(), "working button", Toast.LENGTH_LONG).show();
try {
boolean isinserted = mydb.insertData(editname.getText().toString(), editaddress.getText().toString(), editph_no.getText().toString());
if (isinserted) {
Toast.makeText(getActivity(), "data saved", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getActivity(), "data Not saved", Toast.LENGTH_LONG).show();
}
}
catch (Exception e) {
Toast.makeText(getActivity(), String.valueOf(e), Toast.LENGTH_LONG).show();
}
}
}
I have appllied so many solutions like either button is initialized or not, getactivity(), getcontext() and getbasecontext() for initializtion of dbhandler object, also made many changes in my db handler with different solutions but still got the same error. I did not checked my solution for activity only as i am using fragment classes so i tried it only in it.
Your problem is all your editText you are getting ids are assigned to editname instead of the ones you need, and you are using their getText method.
In your insertPatient class:
editname=(EditText) rootView.findViewById(R.id.insert_name);
editname=(EditText) rootView.findViewById(R.id.insert_address);
editname=(EditText) rootView.findViewById(R.id.insert_ph_no);
to:
editname=(EditText) rootView.findViewById(R.id.insert_name);
editaddress=(EditText) rootView.findViewById(R.id.insert_address);
editph_no=(EditText) rootView.findViewById(R.id.insert_ph_no);
you have not initialize editaddress and editph_no. you are only initializing editname for three times with diff ids.
see below line in your code
editname=(EditText) rootView.findViewById(R.id.insert_name);
editname=(EditText) rootView.findViewById(R.id.insert_address);
editname=(EditText) rootView.findViewById(R.id.insert_ph_no);
your are getting value from editaddress and editph_no and it throws exception
boolean isinserted = mydb.insertData(editname.getText().toString(), editaddress.getText().toString(), editph_no.getText().toString());
edit that lines to
editname=(EditText) rootView.findViewById(R.id.insert_name);
editaddress =(EditText) rootView.findViewById(R.id.insert_address);
editph_no =(EditText) rootView.findViewById(R.id.insert_ph_no);
I am new on Android programming. So that, I'll use wrong technical words, sorry for that ;)
i ve an app. in this app, onCreate, im checking if my db is created ( this check is for first time use ), if my db isn't created yet I'm routing user to a second layout( or activty. i couldnt be sure whch one is right word ). in this activity, when i try to create a SQLiteDatabase parameter im having a null pointer exception.
Here is a part of MainActivity.java
public class MainActivity extends Activity
{
VeriTabani veritabani; // vertiabani means database in turkish
#Override
protected void onCreate(Bundle savedInstanceState)
{
if(db_flag==0)
{
Intent intent = new Intent(MainActivity.this, SecondClass.class);
startActivity(intent);
//...
}
}
}
Here is my VeriTabani.java;
public class VeriTabani extends SQLiteOpenHelper
{
static final String VeriTabani="DATABASENAME";
static final int version=1;
public VeriTabani(Context context) {
super(context, VeriTabani, null, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE TABLENAME ( id INTEGER PRIMARY KEY AUTOINCREMENT, xxx STRING,yyy STRING );");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXIST TABLENAME");
onCreate(db);
}
}
And, here is my SecondClass.java;
public class SecondClass extends Activity
{
VeriTabani veritabani;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
SQLiteDatabase db=veritabani.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put("xxx", another_parameter);
//...
}
//...
}
}
}
im having error on this line;
SQLiteDatabase db=veritabani.getWritableDatabase();
I'm using same VeriTabani class to insert records to DB in MainActivity and it works perfectly. i couldnt undertand what is wrong when i use same code block in another activity.
i guess solve is simple but i couldnt get it.
Thanks for your help.
you have just declared your variable
VeriTabani veritabani;
you haven't initialized that variable. you need to initialize it on onCreate() method.
veritabani = new VeriTabani(YourActivityName.this);
im having error on this line;
SQLiteDatabase db=veritabani.getWritableDatabase();
Looks like you didn't initialize your veritabani variable.
Add the following to that activity's onCreate():
veritabani = new VeriTabani(this);
Hi i am going to create a SQLite database and insert records. but my database does not create.
following is the code. Cant understand why. trying this for a long time
If someone can help its a great help
public class DatabaseHelper extends SQLiteOpenHelper{
static final String dbName="MyDatabase";
public DatabaseHelper(Context context) {
super(context, dbName, null,33);
}
#Override
public void onCreate(SQLiteDatabase db) {
String qry = "CREATE TABLE DEPT(dept_id INTEGER PRIMARY KEY, deptName TEXT)";
db.execSQL(qry);
}
}
I am calling the constructor like this
public class MainActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DatabaseHelper dp = new DatabaseHelper(this);
Toast.makeText(this, "Finish Execution", Toast.LENGTH_LONG).show();
}
}
create your database by using this sample
http://marakana.com/forums/android/examples/55.html