I'm new, I am doing some debugging. I am having some difficulty that I am having some difficulty conveying.
I am trying to read from a SQLite database I have created in another activity.
My current problem appears to be:
SQLiteDatabase db = myOpenHelper.getReadableDatabase();
which should point to my database helper class.
public class SecondActivity extends ListActivity {
CustomOpenHelper myOpenHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
displayDataInTable();
}
void displayDataInTable() {
List<String> values = queryTable();
if (values != null) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(SecondActivity.this, android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
}
}
List<String> queryTable() {
List<String> player = new ArrayList<String>();
SQLiteDatabase db = myOpenHelper.getReadableDatabase();
Cursor cursor = db.query(true, CustomOpenHelper.TABLE_NAME, new String[]{"_id, name, score"}, null, null, null, null, null, null, null);
while (cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndex("_id"));
String name = cursor.getString(cursor.getColumnIndex("name"));
int score = cursor.getInt(cursor.getColumnIndex("score"));
player.add(id + " --> the player " + name + " has got a score of " + score + "s");
}
return player;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_second, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
The LogCat error (extract):
09-28 20:41:57.039 1271-1285/system_process W/ActivityManager﹕ Launch timeout has expired, giving up wake lock!
09-28 20:42:23.468 3642-3642/com.example.eagle.sqlite2activitytest D/AndroidRuntime﹕ Shutting down VM
09-28 20:42:23.486 3642-3642/com.example.eagle.sqlite2activitytest E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.eagle.sqlite2activitytest, PID: 3642
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.eagle.sqlite2activitytest/com.example.eagle.sqlite2activitytest.SecondActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase com.example.eagle.sqlite2activitytest.CustomOpenHelper.getReadableDatabase()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase com.example.eagle.sqlite2activitytest.CustomOpenHelper.getReadableDatabase()' on a null object reference
at com.example.eagle.sqlite2activitytest.SecondActivity.queryTable(SecondActivity.java:43)
at com.example.eagle.sqlite2activitytest.SecondActivity.displayDataInTable(SecondActivity.java:29)
at com.example.eagle.sqlite2activitytest.SecondActivity.onCreate(SecondActivity.java:24)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
09-28 20:42:23.493 1271-1721/system_process W/ActivityManager﹕ Force finishing activity com.example.eagle.sqlite2activitytest/.SecondActivity
What do you think?
try this you can create proper object like this.
CustomOpenHelper myOpenHelper = new CustomOpenHelper(this);
and then write following statement,
SQLiteDatabase db = myOpenHelper.getReadableDatabase();
instead of having to call:
SQLiteDatabase db = myOpenHelper.getReadableDatabase();
where the error is just use this instead so you dont need a sqlitedatabase object:
Cursor cursor = getActivity().getContentResolver().query(Uri,
projection,selection,selectionArgs,sortOrder);
Related
I have one database but I want to make 2 tables for separate classes. One for saving new user data and one for saving user's sessions. The one I am trying to get to work is the table consisted of the Session Title, Time, Active. The table for User Username, First, Last works but the one for the session doesn't. Ultimately, I want to put 2 tables in one database/java class which is the "ListBaseHelper". Where did I go wrong?
Here is the Java Class with the database and tables:
public class ListBaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "listBase.db";
private static final int DATABASE_VERSION = 2;
//Define a query for creating table so you don't get lost
private static final String CREATE_QUERY =
"CREATE TABLE " + ListTable.TABLE_NAME + "(" + ListDbSchema.ListTable.USERNAME + " TEXT," +
ListDbSchema.ListTable.FIRST + " TEXT," + ListDbSchema.ListTable.LAST + " TEXT);";
private static final String CREATE_QUERY2 =
"CREATE TABLE " + ListTable.TABLE_NAME2 + "(" + ListDbSchema.ListTable.TITLE + " TEXT," +
ListDbSchema.ListTable.TIME + " TEXT," + ListDbSchema.ListTable.ACTIVE + " TEXT);";
public ListBaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
//Log message
Log.e("DATABASE OPERATIONS", "Database created /opened...");
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_QUERY);
Log.e("DATABASE OPERATIONS", "Table created...");
db.execSQL(CREATE_QUERY2);
Log.e("DATABASE OPERATIONS", "Table created...");
}
public void addInformations(String username, String first, String last, SQLiteDatabase db) {
ContentValues contentValues = new ContentValues();
contentValues.put(ListTable.USERNAME, username);
contentValues.put(ListTable.FIRST, first);
contentValues.put(ListTable.LAST, last);
db.insert(ListDbSchema.ListTable.TABLE_NAME, null, contentValues);
Log.e("DATABASE OPERATIONS", "One row inserted...");
}
public void addSessionInfo(String title, String time, String active, SQLiteDatabase db) {
ContentValues contentValues = new ContentValues();
contentValues.put(ListTable.TITLE, title);
contentValues.put(ListTable.TIME, time);
contentValues.put(ListTable.ACTIVE, active);
db.insert(ListDbSchema.ListTable.TABLE_NAME2, null, contentValues);
Log.e("DATABASE OPERATIONS", "One row inserted...");
}
public Cursor getInformations(SQLiteDatabase db) {
Cursor cursor;
String[] projections = {ListTable.USERNAME, ListTable.FIRST, ListTable.LAST};
cursor = db.query(ListDbSchema.ListTable.TABLE_NAME, projections, null, null, null, null, null);
return cursor;
}
public Cursor SessionInformations(SQLiteDatabase db) {
Cursor cursor2;
String[] projections = {ListTable.TITLE, ListTable.TIME, ListTable.ACTIVE};
cursor2 = db.query(ListDbSchema.ListTable.TABLE_NAME2, projections, null, null, null, null, null);
return cursor2;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
}
When this java class runs, it will ask user for input.
public class NewSessionActivity extends AppCompatActivity {
EditText SessionTitle, SessionTime, SessionActive;
Context context = this;
ListBaseHelper sessionbasehelper;
SQLiteDatabase sqliteDatabase;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_options_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.logoff_menu_item) {
super.onOptionsItemSelected(item);
Toast.makeText(this, "Logging You Off...", Toast.LENGTH_LONG).show();
startActivity(new Intent(NewSessionActivity.this, LaunchActivity.class));
}
return true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_session);
SessionTitle = (EditText) findViewById(R.id.title);
SessionTime = (EditText) findViewById(R.id.time);
SessionActive = (EditText) findViewById(R.id.active);
}
public void btn_submit(View view) {
{
context = this;
String title = SessionTitle.getText().toString();
String time = SessionTime.getText().toString();
String active = SessionActive.getText().toString();
sessionbasehelper= new ListBaseHelper(context);
sqliteDatabase = sessionbasehelper.getWritableDatabase();
sessionbasehelper.addSessionInfo(title,time,active,sqliteDatabase);
Toast.makeText(getBaseContext(), "New Session Saved!", Toast.LENGTH_LONG).show();
Intent intent = new Intent(NewSessionActivity.this, ViewAllSessionsActivity.class);
startActivity(intent);
sessionbasehelper.close();
}
}
}
When java class runs, it's supposed to show the data the user entered from NewSessionActivity above.
public class ViewAllSessionsActivity extends AppCompatActivity{
//Create instance of database
ListBaseHelper myDb;
Button btn_logout;
ListView sessionlistView;
SQLiteDatabase sqLiteDatabase;
ListBaseHelper listbaseDbHelper;
Cursor cursor2;
SessionDataAdapter sessionDataAdapter;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_options_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.logoff_menu_item) {
super.onOptionsItemSelected(item);
Toast.makeText(this, "Logging You Off...", Toast.LENGTH_LONG).show();
startActivity(new Intent(ViewAllSessionsActivity.this, LaunchActivity.class));
}
return true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_all_sessions);
sessionlistView = (ListView) findViewById(R.id.listViewSession);
sessionDataAdapter = new SessionDataAdapter(getApplicationContext(),R.layout.all_session_layout);
sessionlistView.setAdapter(sessionDataAdapter);
listbaseDbHelper = new ListBaseHelper(getApplicationContext());
sqLiteDatabase = listbaseDbHelper.getReadableDatabase();
cursor2 = listbaseDbHelper.SessionInformations(sqLiteDatabase);
if(cursor2.moveToFirst())
{
do {
String title, time, active;
title = cursor2.getString(0);
time = cursor2.getString(1);
active = cursor2.getString(2);
SessionList sessionlist = new SessionList(title, time, active);
sessionDataAdapter.add(sessionlist);
}while (cursor2.moveToNext());
}
btn_logout = (Button)findViewById(R.id.complete_button);
btn_logout.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
//Use the name of this class, and the name class where you want to be taken when the button is clicked.
Intent intent = new Intent(ViewAllSessionsActivity.this, PaymentActivity.class);
startActivity(intent);
}
});
}
}
This is the LogCat when I run my app:
09-26 10:54:06.071 2712-2712/com.bignerdranch.android.assignment2 E/DATABASE OPERATIONS: Database created /opened...
09-26 10:54:24.365 2712-2712/com.bignerdranch.android.assignment2 E/DATABASE OPERATIONS: Database created /opened...
09-26 10:54:24.368 2712-2712/com.bignerdranch.android.assignment2 E/SQLiteLog: (1) no such table: table_name2
09-26 10:54:24.369 2712-2712/com.bignerdranch.android.assignment2 E/SQLiteDatabase: Error inserting title=Hi time=10:22 active=yes
android.database.sqlite.SQLiteException: no such table: table_name2 (code 1): , while compiling: INSERT INTO table_name2(title,time,active) VALUES (?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1469)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
at com.bignerdranch.android.assignment2.database.ListBaseHelper.addSessionInfo(ListBaseHelper.java:65)
at com.bignerdranch.android.assignment2.NewSessionActivity.btn_submit(NewSessionActivity.java:62)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
09-26 10:54:24.370 2712-2712/com.bignerdranch.android.assignment2 E/DATABASE OPERATIONS: One row inserted...
09-26 10:54:24.919 2712-2712/com.bignerdranch.android.assignment2 E/DATABASE OPERATIONS: Database created /opened...
09-26 10:54:24.941 2712-2712/com.bignerdranch.android.assignment2 E/SQLiteLog: (1) no such table: table_name2
09-26 10:54:24.951 2712-2712/com.bignerdranch.android.assignment2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.bignerdranch.android.assignment2, PID: 2712
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.bignerdranch.android.assignment2/com.bignerdranch.android.assignment2.ViewAllSessionsActivity}: android.database.sqlite.SQLiteException: no such table: table_name2 (code 1): , while compiling: SELECT title, time, active FROM table_name2
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: android.database.sqlite.SQLiteException: no such table: table_name2 (code 1): , while compiling: SELECT title, time, active FROM table_name2
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1316)
at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1163)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1034)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1202)
at com.bignerdranch.android.assignment2.database.ListBaseHelper.SessionInformations(ListBaseHelper.java:82)
at com.bignerdranch.android.assignment2.ViewAllSessionsActivity.onCreate(ViewAllSessionsActivity.java:60)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
09-26 10:54:38.877 3535-3535/com.bignerdranch.android.assignment2 E/DATABASE OPERATIONS: Database created /opened...
09-26 10:54:38.892 3535-3535/com.bignerdranch.android.assignment2 E/SQLiteLog: (1) no such table: table_name2
09-26 10:54:38.893 3535-3535/com.bignerdranch.android.assignment2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.bignerdranch.android.assignment2, PID: 3535
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.bignerdranch.android.assignment2/com.bignerdranch.android.assignment2.ViewAllSessionsActivity}: android.database.sqlite.SQLiteException: no such table: table_name2 (code 1): , while compiling: SELECT title, time, active FROM table_name2
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: android.database.sqlite.SQLiteException: no such table: table_name2 (code 1): , while compiling: SELECT title, time, active FROM table_name2
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1316)
at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1163)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1034)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1202)
at com.bignerdranch.android.assignment2.database.ListBaseHelper.SessionInformations(ListBaseHelper.java:82)
at com.bignerdranch.android.assignment2.ViewAllSessionsActivity.onCreate(ViewAllSessionsActivity.java:60)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
I am a complete beginner to android/Java development and I massively appreciate any pointers anyone is able to give me on the issue I'm having. Here is the MainActivity.java.
package com.example.harris.enterappman;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
EditText enterName;
TextView usersName;
String str = enterName.getText().toString();
public void getName(View view){
enterName = (EditText) findViewById(R.id.enterName);
usersName = (TextView) findViewById(R.id.helloNameView);
usersName.setText(str);
}
public void printUsersName(){
}
}
Everytime I try and run the program, it fails with the error:
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.harris.enterappman/com.example.harris.enterappman.Main Activity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2121)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
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:5021)
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:827)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:643)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.harris.enterappman.MainActivity.<init>(MainActivity.java:48)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1208)
at android.app.Instrumentation.newActivity(Instrumentation.java:1064)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2112)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
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:5021)
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:827)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:643)
at dalvik.system.NativeStart.main(Native Method)
From others posts online I have come to the conclusion that the problem is related to abstract methods? I was unable to work out how my code was wrong.
Cheers,
Harris
String str = enterName.getText().toString();
enterName is null at this point, as you are not setting it ever. You are welcome to declare String str; as a field, but you cannot initialize it until after you set a value on enterName.
You have code to initialize enterName in a somewhat strange getName() method, but you do not appear to be calling that ever.
you have not initialised entername properly
either use:
....
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
enterName = (EditText) findViewById(R.id.enterName);
usersName = (TextView) findViewById(R.id.helloNameView);
usersName.setText(str);
}
...
or use it like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getName();
}
public void getName(){
enterName = (EditText) findViewById(R.id.enterName);
usersName = (TextView) findViewById(R.id.helloNameView);
usersName.setText(str);
}
You call enterName.getText() when enterName is null, which leads to NullPointerException.
Few things I suggest:
If you want to own references to the layout components, call these in the onCreate method:
enterName = (EditText) findViewById(R.id.enterName);
usersName = (TextView) findViewById(R.id.helloNameView);
Don't call methods in the class itself (except some constructors), call them in a method (I refer to the str variable).
how possible you are setting your str using enterName, as enterName is not initialized and hence it is null causing Null pointer exception
you must have to initilize enterName before using it, as you are doing initialization in your getName() method, and then use it to get its text
your code must be like this and you have to call this method from onCreate()
public void getName(View view){
enterName = (EditText) findViewById(R.id.enterName);
usersName = (TextView) findViewById(R.id.helloNameView);
usersName.setText(enterName.getText().toString());
}
I was able to run my app successfully through the emulator. but suddenly a bunch of errors appeared so now I am not able to launch it. There is a Fatal error. Here is LogCat output:
08-26 12:14:27.937 2112-2112/com.joudi.myapplication D/AndroidRuntime﹕ Shutting down VM
08-26 12:14:27.938 2112-2112/com.joudi.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.joudi.myapplication, PID: 2112
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.joudi.myapplication/com.joudi.myapplication.MainActivity}: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at com.joudi.myapplication.MainActivity.onCreate(MainActivity.java:29)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
I do not know ow to fix the "IndexOutOfBoundsException: Invalid index 0, size is 0" error. Here is my MainActicity.java file code:
import android.graphics.Canvas;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import com.joudi.myapplication.data.NoteItem;
import com.joudi.myapplication.data.NotesDataSource;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private NotesDataSource datasource;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
datasource = new NotesDataSource(this);
List<NoteItem> notes= datasource.findAll();
NoteItem note = notes.get(0);
note.setText("Updated!");
datasource.update(note);
notes= datasource.findAll();
note= notes.get(0);
Log.i("NOTES", note.getKey());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Looks looks datasource.findAll();returns an empty list.
notes.get(0); throws the exception.
You should check if the size of the list is greater then 0.
if (notes.size() >0){
NoteItem note = notes.get(0);
note.setText("Updated!");
datasource.update(note);
}
You need to check the size of notes before trying to access its element:
List<NoteItem> notes= datasource.findAll();
// Check the value of notes to avoid IndexOutOfBoundsException
if (null!=notes || notes.size()>0){
note = notes.get(0);
}
I am trying to connect to an azure application, using android, but I am getting this error. Here is my code and my logs.
I have checked everything and it seen to be right, but the problem I think is with getApplicationContext(). I am unable to debug.
can someone help me please?
public class login extends Activity {
UserServicesImpl usv;
private EditText txtemail;
private EditText txtpassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
txtemail = (EditText) findViewById(R.id.txtemail);
txtpassword = (EditText) findViewById(R.id.txtpassword);
}
public void LoginKarrega(View view){
usv = new UserServicesImpl();
AlertDialog alertDialog = new AlertDialog.Builder(login.this).create();
alertDialog.setTitle("Alert");
if(usv.exist(txtemail.getText().toString(), txtpassword.getText().toString()) == true) {
alertDialog.setMessage("Sucessful login");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
}
else {
alertDialog.setMessage("wrong login");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
}
alertDialog.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_login, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Logcat:
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:4007)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4002)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:105)
at com.microsoft.windowsazure.mobileservices.notifications.MobileServicePush.<init>(MobileServicePush.java:134)
at com.microsoft.windowsazure.mobileservices.MobileServiceClient.initialize(MobileServiceClient.java:1473)
at com.microsoft.windowsazure.mobileservices.MobileServiceClient.<init>(MobileServiceClient.java:182)
at com.microsoft.windowsazure.mobileservices.MobileServiceClient.<init>(MobileServiceClient.java:158)
at ao.co.karrega.services.customers.UserServicesImpl.<init>(UserServicesImpl.java:39)
at ao.co.karrega.login.LoginKarrega(login.java:32)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4002)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Use below code to solve this error. Currently you are using this instead of getApplicationContext().
try {
mClient = new MobileServiceClient(
"https://newvbdemo.azure-mobile.net/",
"SUFYiOYEAlbEoKfsDgfWNIywaPSMhC29",
getApplicationContext()
);
mTable = mClient.getTable("Users",Users.class);
}catch (MalformedURLException e) {
e.printStackTrace();
}
Your class UserServicesImpl extends Activity but it does not seem to be an Activity.
In particular, activities usually don't have an explicit constructor, and you cannot use an Activity as a Context before its onCreate() lifecycle method. Construction phase <init> in your stacktrace is too early.
The stacktrace also shows that you're trying to instantiate an activity with new in LoginKarrega. Never instantiate an activity with new yourself.
Looks like you should be removing the extends Activity and pass a Context as an argument instead.
Im just starting out with Java Development and i am fiddling around with the Android Media recorder. However I am getting a NullPointerException which I click the record button using the following source code:
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
//import android.net.Uri;
import android.view.Menu;
import android.view.MenuItem;
import android.os.Environment;
import android.view.View;
import java.io.File;
import java.io.IOException;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import java.lang.String;
public class MainActivity extends ActionBarActivity {
String outputFile = "test.3gp";
private MediaRecorder myAudioRecorder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MediaRecorder myAudioRecorder = new MediaRecorder();
myAudioRecorder = new MediaRecorder();
// Uri target = Uri.parse(outputFile.getAbsolutePath());
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myAudioRecorder.setOutputFile(outputFile);
}
public void Start_Record(View v)
{
try {
myAudioRecorder.prepare();
myAudioRecorder.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
myAudioRecorder.stop();
myAudioRecorder.release();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I realise that this probably due to the fill pointer being set to NULL, however I am struggling to see how to initialize the file reference for this to vanish. I am getting th exception on mediaRecorderPrepare()
Here is the Exception thrown:
03-09 22:53:56.548 31836-31836/uk.co.spectralgear.spectralboost E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:4007)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4002)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaRecorder.prepare()' on a null object reference
at uk.co..MainActivity.Start_Record(MainActivity.java:38)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4002)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Any help would be greatly appreciated:)
PROBLEM:
Your class variable "myAudioRecord" is null when "Start_Record()" tries to use it:
Caused by: java.lang.NullPointerException:
Attempt to invoke virtual method 'void Android.media.MediaRecorder.prepare()' on a null object reference
SOLUTION: Delete this line from your "onCreate()" method:
public class MainActivity extends ActionBarActivity {
String outputFile = "test.3gp";
private MediaRecorder myAudioRecorder; // Your class variable: OK...
#Override
protected void onCreate(Bundle savedInstanceState) {
...
// MediaRecorder myAudioRecorder = new MediaRecorder(); // DELETE THIS LINE!!!
myAudioRecorder = new MediaRecorder(); // OK...
...
The declaration of "myAudioRecorder" inside onCreate() HIDES the outer declaration. So the outer (class-level) "myAudioRecorder" never gets initialized ... and your program dies with an NPE when "Start_Record()" tries to access it.
PS:
Please consider changing the method name to "start_Record()". Or better, "startRecord()". This is more consistent with Java naming conventions.
I think you are using stop() function while it was already stopped. Check your code and logic.