java.lang.NullPointerException when trying to access SQLite database - java

I am trying to create a login page which checks a SQLite database for the users details, and if they are present, they are advanced to the main page of the application. I keep getting the java.lang.NullPointerException and do not know what I am doing wrong. Please can you advise on where the issues are in the code?
Login.java:
package com.B00512756.angertwo;
public class Login extends Activity implements OnClickListener{
public static final String DATABASE_NAME = "login_database.db";
public static final String USER_INFO_TABLE = "user_information";
public static final String COLUMN_ID = "UserID";
public static final String COLUMN_RATING = "UserName";
public static final String COLUMN_NAME = "Password";
public SQLiteDatabase regDB;
public EditText txtUserName;
public EditText txtPassword;
public static Button btnLogin;
public static Button btnCancel;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loginpage);
txtUserName=(EditText)this.findViewById(R.id.txtUname);
txtPassword=(EditText)this.findViewById(R.id.txtPwd);
//btnLogin=(Button)this.findViewById(R.id.btnLogin);
Button Login = (Button) findViewById(R.id.btnLogin);
Button Register = (Button) findViewById(R.id.btnregister);
Button Cancel = (Button) findViewById(R.id.btnCancel);
Register.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), Registration.class);
startActivityForResult(myIntent, 0);
finish();
}
});
Cancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
android.os.Process.killProcess(android.os.Process.myPid());
}
});
Login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//String[] columns = new String[]{COLUMN_ID, COLUMN_RATING, COLUMN_NAME };
Cursor c = regDB.query(USER_INFO_TABLE, new String[] {
COLUMN_ID, COLUMN_RATING, COLUMN_NAME}, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(COLUMN_ID);
int iRating = c.getColumnIndex(COLUMN_RATING);
int iName = c.getColumnIndex(COLUMN_NAME);
c.moveToLast();
for (int i = c.getCount() - 1; i >= 0; i--) {
// Get the data
result = result + c.getString(iRow) + " " + c.getString(iRating) + " " + c.getString(iName) + "\n" ;
if("select * from USER_INFO_TABLE where UserName =" + "\""+ txtUserName + "\""+" and Password="+ "\""+ txtPassword != null);
{ Intent j = new Intent();
j.setClassName("com.B00512756.angertwo",
"com.B00512756.angertwo.AngerprototypetwoActivity");
startActivity(j);}
// Move the cursor
c.moveToPrevious();
//return result;
}
c.close();
}
});
}
private SQLiteDatabase getWritableDatabase() {
// TODO Auto-generated method stub
return null;
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
}
Loginpage.xml:
<?xml version="1.0" encoding="UTF-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:stretchColumns="1">
<TableRow>
<TextView
android:text="User Name: "
android:id="#+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:text=""
android:id="#+id/txtUname"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</EditText>
</TableRow>
<TableRow>
<TextView
android:text="Password: "
android:id="#+id/TextView02"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:text=""
android:id="#+id/txtPwd"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:password="true">
</EditText>
</TableRow>
<TableRow>
<Button
android:text="Login"
android:id="#+id/btnLogin"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</Button>
<Button
android:text="Register"
android:id="#+id/btnregister"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</Button>
<Button
android:text="Cancel"
android:id="#+id/btnCancel"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</Button>
</TableRow>
</TableLayout>
AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.B00512756.angertwo"
android:versionCode="1"
android:versionName="1.0" xmlns:android="http://schemas.android.com/apk/res/android">
<uses-sdk android:minSdkVersion="8" />
<application android:name=".AppState" android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".Login"
android:label="#string/main_title">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Login" android:label="#string/begin_label"
android:theme="#android:style/Theme"></activity>
<activity android:name=".Question1" android:label="#string/question_one"
android:theme="#android:style/Theme"></activity>
<activity android:name=".Question2" android:label="#string/question_two"
android:theme="#android:style/Theme"></activity>
<activity android:name=".Question3" android:label="#string/question_three"
android:theme="#android:style/Theme"></activity>
<activity android:name=".Question4" android:label="#string/question_four"
android:theme="#android:style/Theme"></activity>
<activity android:name=".Question5" android:label="#string/question_five"
android:theme="#android:style/Theme"></activity>
<!-- <activity android:name=".AngerprototypetwoActivity" android:label="#string/main_title"
android:theme="#android:style/Theme"></activity> -->
<activity android:name=".nextQ1" android:id="#+id/next_Q1_button"
android:theme="#android:style/Theme"></activity>
<activity android:name=".Strategies" android:label="#string/strategies_label"
android:theme="#android:style/Theme"></activity>
<activity android:name=".Contact" android:label="#string/begin_label"
android:theme="#android:style/Theme"></activity>
<activity android:name=".Strat_What_Is_Anger" android:label="#string/strategies_label_what_is_anger"
android:theme="#android:style/Theme"></activity>
<activity android:name=".Strat_Use_Distraction" android:label="#string/strategies_label_distraction"
android:theme="#android:style/Theme"></activity>
<activity android:name=".Registration" android:label="#string/registration"
android:theme="#android:style/Theme"></activity>
</application>
</manifest>
Logcat:
05-19 17:08:17.111: ERROR/AndroidRuntime(27481): FATAL EXCEPTION: main
05-19 17:08:17.111: ERROR/AndroidRuntime(27481): java.lang.NullPointerException
05-19 17:08:17.111: ERROR/AndroidRuntime(27481): at com.B00512756.angertwo.Login$3.onClick(Login.java:76)
05-19 17:08:17.111: ERROR/AndroidRuntime(27481): at android.view.View.performClick(View.java:2408)
05-19 17:08:17.111: ERROR/AndroidRuntime(27481): at android.view.View$PerformClick.run(View.java:8816)
05-19 17:08:17.111: ERROR/AndroidRuntime(27481): at android.os.Handler.handleCallback(Handler.java:587)
05-19 17:08:17.111: ERROR/AndroidRuntime(27481): at android.os.Handler.dispatchMessage(Handler.java:92)
05-19 17:08:17.111: ERROR/AndroidRuntime(27481): at android.os.Looper.loop(Looper.java:123)
05-19 17:08:17.111: ERROR/AndroidRuntime(27481): at android.app.ActivityThread.main(ActivityThread.java:4627)
05-19 17:08:17.111: ERROR/AndroidRuntime(27481): at java.lang.reflect.Method.invokeNative(Native Method)
05-19 17:08:17.111: ERROR/AndroidRuntime(27481): at java.lang.reflect.Method.invoke(Method.java:521)
05-19 17:08:17.111: ERROR/AndroidRuntime(27481): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
05-19 17:08:17.111: ERROR/AndroidRuntime(27481): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
05-19 17:08:17.111: ERROR/AndroidRuntime(27481): at dalvik.system.NativeStart.main(Native Method)
05-19 17:08:17.121: WARN/ActivityManager(58): Force finishing activity com.B00512756.angertwo/.Login
05-19 17:08:17.641: WARN/ActivityManager(58): Activity pause timeout for HistoryRecord{4505c768 com.B00512756.angertwo/.Login}
05-19 17:08:19.731: INFO/Process(27481): Sending signal. PID: 27481 SIG: 9
05-19 17:08:19.751: INFO/WindowManager(58): WIN DEATH: Window{4507d5b0 com.B00512756.angertwo/com.B00512756.angertwo.Login paused=false}
05-19 17:08:19.751: INFO/ActivityManager(58): Process com.B00512756.angertwo (pid 27481) has died.
05-19 17:08:19.921: WARN/InputManagerService(58): Got RemoteException sending setActive(false) notification to pid 27481 uid 10045
05-19 17:08:20.341: DEBUG/dalvikvm(117): GC_EXTERNAL_ALLOC freed 484 objects / 27832 bytes in 383ms
05-19 17:08:24.590: DEBUG/dalvikvm(197): GC_EXPLICIT freed 100 objects / 4336 bytes in 127ms
05-19 17:08:28.610: WARN/ActivityManager(58): Activity destroy timeout for HistoryRecord{4505c768 com.B00512756.angertwo/.Login}
05-19 17:08:29.650: DEBUG/dalvikvm(264): GC_EXPLICIT freed 58 objects / 2800 bytes in 140ms
05-19 17:08:33.513: DEBUG/SntpClient(58): request time failed: java.net.SocketException: Address family not supported by protocol
Additional info:
Login.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("null")
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String name = txtUserName.getText().toString();
String pwd = txtPassword.getText().toString();
SQLiteDatabase regDB = null;
//String[] columns = new String[]{COLUMN_ID, COLUMN_RATING, COLUMN_NAME };
Cursor c = regDB.query(USER_INFO_TABLE, new String[] {
COLUMN_ID, COLUMN_RATING, COLUMN_NAME}, null, null, null, null, null);
if(null!=c){
c.moveToFirst();
System.out.println("Cursor Size"+c.getCount());
}
String result = "";
int iRow = c.getColumnIndex(COLUMN_ID);
int iRating = c.getColumnIndex(COLUMN_RATING);
int iName = c.getColumnIndex(COLUMN_NAME);
c.moveToLast();
for (int i = c.getCount() - 1; i >= 0; i--) {
// Get the data
result = result + c.getString(iRow) + " " + c.getString(iRating) + " " + c.getString(iName) + "\n" ;
if("select * from USER_INFO_TABLE where UserName =" + "\""+ name + "\""+" and Password="+ "\""+ pwd != null );
{ Intent j = new Intent();
j.setClassName("com.B00512756.angertwo",
"com.B00512756.angertwo.AngerprototypetwoActivity");
startActivity(j);}
// Move the cursor
c.moveToPrevious();
//return result;
}
c.close();
}
});
Null error is thrown at this line:
Cursor c = regDB.query(USER_INFO_TABLE, new String[] {
COLUMN_ID, COLUMN_RATING, COLUMN_NAME}, null, null, null, null, null);
You help is much appreciated :)

It's here:
05-19 17:08:17.111: ERROR/AndroidRuntime(27481): at com.B00512756.angertwo.Login$3.onClick(Login.java:76)
Find the source for Login.java, go to line 76, and see what object instances are de-referenced. One of those is null.

Related

My Android application runs on emulator but not working on my android device

My application works fine on android emulator. When I'm trying to run it on my device LogCat column gives me info that there is no such columns: USERNAME.
On emulator my SQLite database is created normally and I can add new users and sign but in device there is an exception when I'm trying doing this.
Here is a Log file when i'm trying to create new user:
02-14 17:29:07.997: D/BubblePopupHelper(9620): isShowingBubblePopup : false
02-14 17:30:07.617: E/SQLiteLog(10274): (1) no such column: USERNAME
02-14 17:30:07.627: D/AndroidRuntime(10274): Shutting down VM
02-14 17:30:07.627: E/AndroidRuntime(10274): FATAL EXCEPTION: main
02-14 17:30:07.627: E/AndroidRuntime(10274): Process: com.example.naukamagisterka, PID: 10274
02-14 17:30:07.627: E/AndroidRuntime(10274): android.database.sqlite.SQLiteException: no such column: USERNAME (code 1): , while compiling: SELECT * FROM USERS WHERE USERNAME=?
02-14 17:30:07.627: E/AndroidRuntime(10274): at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
02-14 17:30:07.627: E/AndroidRuntime(10274): at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:897)
02-14 17:30:07.627: E/AndroidRuntime(10274): at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:508)
02-14 17:30:07.627: E/AndroidRuntime(10274): at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:726)
02-14 17:30:07.627: E/AndroidRuntime(10274): at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
02-14 17:30:07.627: E/AndroidRuntime(10274): at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
02-14 17:30:07.627: E/AndroidRuntime(10274): at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
02-14 17:30:07.627: E/AndroidRuntime(10274): at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1426)
02-14 17:30:07.627: E/AndroidRuntime(10274): at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1273)
02-14 17:30:07.627: E/AndroidRuntime(10274): at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1144)
02-14 17:30:07.627: E/AndroidRuntime(10274): at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1312)
02-14 17:30:07.627: E/AndroidRuntime(10274): at com.example.naukamagisterka.LoginDataBaseAdapter.getSingleEntryUsers(LoginDataBaseAdapter.java:81)
02-14 17:30:07.627: E/AndroidRuntime(10274): at com.example.naukamagisterka.SignUPActivity$1.onClick(SignUPActivity.java:44)
02-14 17:30:07.627: E/AndroidRuntime(10274): at android.view.View.performClick(View.java:4764)
02-14 17:30:07.627: E/AndroidRuntime(10274): at android.view.View$PerformClick.run(View.java:19844)
02-14 17:30:07.627: E/AndroidRuntime(10274): at android.os.Handler.handleCallback(Handler.java:739)
02-14 17:30:07.627: E/AndroidRuntime(10274): at android.os.Handler.dispatchMessage(Handler.java:95)
02-14 17:30:07.627: E/AndroidRuntime(10274): at android.os.Looper.loop(Looper.java:135)
02-14 17:30:07.627: E/AndroidRuntime(10274): at android.app.ActivityThread.main(ActivityThread.java:5376)
02-14 17:30:07.627: E/AndroidRuntime(10274): at java.lang.reflect.Method.invoke(Native Method)
02-14 17:30:07.627: E/AndroidRuntime(10274): at java.lang.reflect.Method.invoke(Method.java:372)
02-14 17:30:07.627: E/AndroidRuntime(10274): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
02-14 17:30:07.627: E/AndroidRuntime(10274): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.naukamagisterka"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="17"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".ActivityLogin"
android:label="#string/title_activity_activity_login" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".SignUPActivity"
android:label="#string/title_activity_sign_up" >
</activity>
<activity
android:name=".HomeAfterLogin"
android:label="#string/title_activity_home_after_login" >
</activity>
</application>
</manifest>
ActivityLogin.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:gravity="center_vertical|center_horizontal"
android:orientation="vertical" android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin" tools:context=".LoginActivity"
android:background="#0099CC"
android:descendantFocusability="beforeDescendants"
android:focusableInTouchMode="true">
<LinearLayout
android:id="#+id/ll1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center_vertical|center_horizontal">
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/logo" />
</LinearLayout>
<LinearLayout
android:id="#+id/ll2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center_vertical|center_horizontal">
<ProgressBar android:id="#+id/login_progress" style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:visibility="gone" />
<ScrollView android:id="#+id/login_form" android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:id="#+id/email_login_form"
android:layout_width="match_parent"
android:layout_height="254dp"
android:orientation="vertical" >
<AutoCompleteTextView android:id="#+id/email" android:layout_width="match_parent"
android:layout_height="wrap_content" android:hint="#string/prompt_email"
android:inputType="textEmailAddress" android:maxLines="1"
android:singleLine="true"
android:layout_marginBottom="10dp"
android:textColorHint="#ffffffff"
android:textColor="#ffffffff" />
<EditText android:id="#+id/password" android:layout_width="match_parent"
android:layout_height="wrap_content" android:hint="#string/prompt_password"
android:imeActionLabel="#string/action_sign_in"
android:imeOptions="actionUnspecified" android:inputType="textPassword"
android:maxLines="1" android:singleLine="true"
android:layout_marginBottom="10dp"
android:textColorHint="#ffffffff"
android:textColor="#ffffffff" />
<Button
android:id="#+id/email_sign_in_button"
style="?android:textAppearanceSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:background="#66CCFF"
android:text="#string/action_sign_in"
android:textColor="#ffffffff"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
</ScrollView>
</LinearLayout>
<LinearLayout
android:id="#+id/ll3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="bottom|center_horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/sign_up"
android:id="#+id/signUpTextView"
android:autoLink="web"
android:textColor="#ffffffff" />
</LinearLayout>
</LinearLayout>
ActivityLogin.java
package com.example.naukamagisterka;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.method.DialerKeyListener;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class ActivityLogin extends Activity {
Button btnLogin;
TextView btnSingIn;
LoginDataBaseAdapter loginDataBaseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loginDataBaseAdapter = new LoginDataBaseAdapter(this);
loginDataBaseAdapter=loginDataBaseAdapter.open();
btnLogin = (Button)findViewById(R.id.email_sign_in_button);
btnSingIn = (TextView)findViewById(R.id.signUpTextView);
final EditText editTextEmail = (EditText)findViewById(R.id.email);
final EditText editTextPassword = (EditText)findViewById(R.id.password);
btnSingIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intentSignIn = new Intent(getApplicationContext(), SignUPActivity.class);
startActivity(intentSignIn);
}
});
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//try {
final String userName = editTextEmail.getText().toString();
final String userPassword = editTextPassword.getText().toString();
String storedPassword = loginDataBaseAdapter.getSingleEntry(userName);
if (storedPassword.equals(userPassword)){
Toast.makeText(ActivityLogin.this, "Udana próba zalogowania.", Toast.LENGTH_LONG).show();
setContentView(R.layout.activity_home_after_login);
}
else{
Toast.makeText(ActivityLogin.this, "Niepoprawny e-mail lub hasło! Spróbuj ponownie.", Toast.LENGTH_LONG).show();
}
} //catch (Exception e) {
//
//}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
loginDataBaseAdapter.close();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
LoginDataBaseAdapter.java
package com.example.naukamagisterka;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.widget.Toast;
public class LoginDataBaseAdapter {
static final String DATABASE_NAME = "WylaczSwiatloDB";
static final int DATABASE_VERSION=1;
public static final int NAME_COULMN=1;
public String Email;
public String Password;
public int Points;
LoginDataBaseAdapter loginDataBaseAdapter;
static final String DATABASE_CREATE = "CREATE TABLE "+"USERS"+"(USERNAME VARCHAR, PASSWORD VARCHAR, POINTS INT)"+";"+"";
public SQLiteDatabase db;
private final Context context;
private DataBaseHelper dbHelper;
public LoginDataBaseAdapter(Context _context){
context=_context;
dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public LoginDataBaseAdapter open() throws SQLException{
db=dbHelper.getWritableDatabase();
return this;
}
public void close(){
db.close();
}
public SQLiteDatabase getDatabaseInstance(){
return db;
}
public void insertEntry(String userName, String password){
ContentValues newValues = new ContentValues();
newValues.put("USERNAME", userName);
newValues.put("PASSWORD", password);
newValues.put("POINTS", 0);
db.insert("USERS", null, newValues);
}
public int deleteEntry(String UserName){
String where = "USERNAME=?";
int numberOFEntriesDeleted = db.delete("USERS", where, new String[]{UserName});
return numberOFEntriesDeleted;
}
public String getSingleEntry(String userName){
Cursor cursor = db.query("USERS", null, "USERNAME=?", new String[]{userName},null,null,null);
if (cursor.getCount()<1) //Nie ma username
{
cursor.close();
return "NOT EXIST";
}
else{
cursor.moveToFirst();
String password = cursor.getString(cursor.getColumnIndex("PASSWORD"));
cursor.close();
return password;
}
}
public String getSingleEntryUsers(String userName){
Cursor cursor = db.query("USERS", null, " USERNAME=?", new String[]{userName},null,null,null);
if (cursor.getCount()<1) //Nie ma username
{
cursor.close();
return "NOT EXIST";
}
else{
cursor.moveToFirst();
String user = cursor.getString(cursor.getColumnIndex("USERNAME"));
cursor.close();
return user;
}
}
public void updateEntry(String userName, String password){
ContentValues updateValues = new ContentValues();
updateValues.put("USERNAME", userName);
updateValues.put("PASSWORD", password);
updateValues.put("POINTS", 0);
String where = "USERNAME=?";
db.update("USERS", updateValues, where, new String[]{userName});
//String storedUsers = loginDataBaseAdapter.getSingleEntry(userName);
}
public void displayToast(String value){
Toast.makeText(context, value, Toast.LENGTH_LONG).show();
}
}
Anyone could help?
You may have changed the DB schema without increasing DATABASE_VERSION and thus the new app is finding the old DB.
static final int DATABASE_VERSION=2;
should fix it.
Try to uninstall Application on device and rerun it.

having error when trying to catch values from database and display it in a text view. android

i am having a sqllite database. i am trying to catch values from the database and display it in a text view. i get the following error.
having error in this line
TextView result = (TextView) findViewById(R.id.textviewres);
Full error stack..
02-10 21:24:53.986: E/AndroidRuntime(27992): FATAL EXCEPTION: main
02-10 21:24:53.986: E/AndroidRuntime(27992): java.lang.RuntimeException: Unable to start activity ComponentInfo{lk.adspace.jaffnatemples/lk.adspace.jaffnatemples.Db_results}: java.lang.ClassCastException: android.widget.RelativeLayout cannot be cast to android.widget.TextView
02-10 21:24:53.986: E/AndroidRuntime(27992): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2343)
02-10 21:24:53.986: E/AndroidRuntime(27992): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)
02-10 21:24:53.986: E/AndroidRuntime(27992): at android.app.ActivityThread.access$600(ActivityThread.java:162)
02-10 21:24:53.986: E/AndroidRuntime(27992): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
02-10 21:24:53.986: E/AndroidRuntime(27992): at android.os.Handler.dispatchMessage(Handler.java:107)
02-10 21:24:53.986: E/AndroidRuntime(27992): at android.os.Looper.loop(Looper.java:194)
02-10 21:24:53.986: E/AndroidRuntime(27992): at android.app.ActivityThread.main(ActivityThread.java:5371)
02-10 21:24:53.986: E/AndroidRuntime(27992): at java.lang.reflect.Method.invokeNative(Native Method)
02-10 21:24:53.986: E/AndroidRuntime(27992): at java.lang.reflect.Method.invoke(Method.java:525)
02-10 21:24:53.986: E/AndroidRuntime(27992): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
02-10 21:24:53.986: E/AndroidRuntime(27992): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
02-10 21:24:53.986: E/AndroidRuntime(27992): at dalvik.system.NativeStart.main(Native Method)
02-10 21:24:53.986: E/AndroidRuntime(27992): Caused by: java.lang.ClassCastException: android.widget.RelativeLayout cannot be cast to android.widget.TextView
02-10 21:24:53.986: E/AndroidRuntime(27992): at lk.adspace.jaffnatemples.Db_results.onCreate(Db_results.java:52)
02-10 21:24:53.986: E/AndroidRuntime(27992): at android.app.Activity.performCreate(Activity.java:5122)
02-10 21:24:53.986: E/AndroidRuntime(27992): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
02-10 21:24:53.986: E/AndroidRuntime(27992): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2307)
02-10 21:24:53.986: E/AndroidRuntime(27992): ... 11 more
DB handler class..
package lk.adspace.jaffnatemples;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class Dbhandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "jaffnatempletest";
// Temple table name
private static final String TABLE_TEMPLE = "templ";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_TMPNAME = "temple_name";
private static final String KEY_TMPTYPE = "temple_type";
private static final String KEY_LATITUDE = "latitude";
private static final String KEY_LONGITUDE = "longitude";
private static final String KEY_IMGNAME = "image_name";
private static final String KEY_YEARBUILD = "year_build";
private static final String KEY_ADDRESS = "address";
private static final String KEY_CITY = "city";
private static final String KEY_EMAIL = "email";
private static final String KEY_WEB = "website";
private static final String KEY_TEL1 = "telephone1";
private static final String KEY_TEL2 = "telephone2";
private static final String KEY_DESCRI = "Description";
private final ArrayList<kovil> temple_list = new ArrayList<kovil>();
public Dbhandler (Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TEMPLE_TABLE = "CREATE TABLE " + TABLE_TEMPLE + "("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," + KEY_TMPNAME + " TEXT," + KEY_TMPTYPE + " TEXT," + KEY_LATITUDE + " TEXT," + KEY_LONGITUDE + " TEXT," + KEY_IMGNAME + " TEXT,"
+ KEY_YEARBUILD + " TEXT," + KEY_ADDRESS + " TEXT," + KEY_CITY + " TEXT," + KEY_EMAIL + " TEXT," + KEY_WEB + " TEXT," + KEY_TEL1 + " TEXT," + KEY_TEL2 + " TEXT,"
+ KEY_DESCRI + " TEXT" + ")";
db.execSQL(CREATE_TEMPLE_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TEMPLE);
// Create tables again
onCreate(db);
}
// Adding new temple
public void Add_Temple(kovil Kovil) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TMPNAME, Kovil.gettemplename());
values.put(KEY_TMPTYPE, Kovil.gettempletype());
values.put(KEY_LATITUDE, Kovil.getlatitude());
values.put(KEY_LONGITUDE, Kovil.getlongitude());
values.put(KEY_IMGNAME, Kovil.getimage_name());
values.put(KEY_YEARBUILD, Kovil.getyear_build());
values.put(KEY_ADDRESS, Kovil.getaddress());
values.put(KEY_CITY, Kovil.getcity());
values.put(KEY_EMAIL, Kovil.getemail());
values.put(KEY_WEB, Kovil.getwebsite());
values.put(KEY_TEL1, Kovil.gettelephone1());
values.put(KEY_TEL2, Kovil.gettelephone2());
values.put(KEY_DESCRI, Kovil.getDescription());
// Inserting Row
db.insert(TABLE_TEMPLE, null, values);
db.close(); // Closing database connection
}
// Getting single contact
kovil Get_Temple(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_TEMPLE, new String[] { KEY_ID,
KEY_TMPNAME, KEY_TMPTYPE, KEY_LATITUDE, KEY_LONGITUDE, KEY_IMGNAME, KEY_YEARBUILD, KEY_ADDRESS, KEY_CITY, KEY_EMAIL, KEY_EMAIL, KEY_WEB, KEY_TEL1, KEY_TEL2, KEY_DESCRI }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
kovil Kovil = new kovil(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5), cursor.getString(6), cursor.getString(7), cursor.getString(8), cursor.getString(9), cursor.getString(10), cursor.getString(11), cursor.getString(12), cursor.getString(13));
// return contact
cursor.close();
db.close();
return Kovil;
}
// Getting All Contacts
public ArrayList<kovil> Get_Temple() {
try {
temple_list.clear();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_TEMPLE;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
System.out.print("CALLED");
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
kovil Kovil = new kovil();
Kovil.setID(Integer.parseInt(cursor.getString(0)));
System.out.print("CALLED"+cursor.getString(0));
Kovil.settemplename(cursor.getString(1));
Kovil.settempletype(cursor.getString(2));
Kovil.setlatitude(cursor.getString(3));
Kovil.setlongitude(cursor.getString(4));
Kovil.setimage_name(cursor.getString(5));
Kovil.setyear_build(cursor.getString(6));
Kovil.setaddress(cursor.getString(7));
Kovil.setcity(cursor.getString(8));
Kovil.setemail(cursor.getString(9));
Kovil.setwebsite(cursor.getString(10));
Kovil.settelephone1(cursor.getString(11));
Kovil.settelephone2(cursor.getString(12));
Kovil.setDescription(cursor.getString(13));
// Adding contact to list
temple_list.add(Kovil);
} while (cursor.moveToNext());
}
// return contact list
cursor.close();
db.close();
return temple_list;
} catch (Exception e) {
// TODO: handle exception
Log.e("all_temples", "" + e);
}
return temple_list;
}
public String collect(){
SQLiteDatabase ourDatabase = this.getWritableDatabase();
String result="";
String []column =new String[]{KEY_ID,KEY_TMPNAME,KEY_TMPTYPE,KEY_LATITUDE,KEY_LONGITUDE,KEY_IMGNAME,KEY_YEARBUILD,KEY_ADDRESS,KEY_CITY,KEY_EMAIL,KEY_WEB,KEY_TEL1,KEY_TEL2,KEY_DESCRI};
Cursor c=ourDatabase.query("templ", column, null, null, null, null,null, null);
//Cursor c=ourDatabase.query(
c.moveToFirst();
int iKEY_ID = c.getColumnIndex(KEY_ID);
int iKEY_TMPNAME= c.getColumnIndex(KEY_TMPNAME);
int iKEY_TMPTYPE= c.getColumnIndex(KEY_TMPTYPE);
for (c.moveToFirst();!c.isAfterLast();c.moveToNext()){
//for (int x=0;x<5;x++){
result = result+c.getString(iKEY_ID)+" "+c.getString(iKEY_TMPNAME)+" \t\t\t\t"+c.getString(iKEY_TMPTYPE)+" \n";
}
return result;
}
// Getting contacts Count
public int Get_Total_Temple() {
String countQuery = "SELECT * FROM " + TABLE_TEMPLE;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
db.close();
return count;
}
}
My main display class(Db_results.java)
package lk.adspace.jaffnatemples;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.provider.ContactsContract.Data;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class Db_results<LayoutInfalter> extends Activity {
Temple_Adapter tAdapter;
ArrayList<kovil> temple_data = new ArrayList<kovil>();
ListView temple_listview;
Dbhandler dbhand = new Dbhandler(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_db_result);
temple_listview = (ListView) findViewById(R.id.list);
kovil insertData = new kovil("temple_name", "temple_type", "latitude", "longitude", "image_name", "year_build", "address",
"city", "email", "website", "telephone1", "telephone2", "Description");
Dbhandler dbhand = new Dbhandler(this);
dbhand .Add_Temple(insertData );
kovil insertData2 = new kovil("temple_name2", "temple_type2", "latitude2", "longitude2", "image_name2", "year_build2", "address2",
"city2", "email2", "website2", "telephone12", "telephone22", "Description2");
dbhand .Add_Temple(insertData2 );
// int count =dbhand .Get_Total_Temple();
// TextView textView = (TextView) findViewById(R.id.count);
TextView result = (TextView) findViewById(R.id.textviewres);
//String c=collect();
result.setText(dbhand.collect());
// i want to display all the values in a list over here.
System.out.print("CALLING View_all_temples");
//View_all_temples();
}
public void View_all_temples(){
System.out.print("iNTO View_all_temples STAGE 1");
//temple_data.clear();
ArrayList<kovil> temple_array_from_db = dbhand.Get_Temple();
System.out.print("CALLED View_all_temples");
for (int i = 0; i < temple_array_from_db.size(); i++) {
System.out.print("INTO LOOP");
int tidno = temple_array_from_db.get(i).getID();
String tempname = temple_array_from_db.get(i).gettemplename();
String city = temple_array_from_db.get(i).getcity();
String telphon = temple_array_from_db.get(i).gettelephone1();
kovil kov = new kovil();
kov.setID(tidno);
kov.settemplename(tempname);
kov.setcity(city);
kov.settelephone1(telphon);
temple_data.add(kov);
}
dbhand.close();
//tAdapter = new Temple_Adapter(Db_results.this, R.layout.display_db_result,temple_data);
//tAdapter = new Temple_Adapter(Db_results.this, R.layout.display_db_result);
//temple_listview.setAdapter(tAdapter);
tAdapter.notifyDataSetChanged();
}
public class Temple_Adapter extends ArrayAdapter<kovil> {
Activity activity;
int layoutResourceId;
kovil user;
LayoutInfalter mInfalter;
ArrayList<kovil> data = new ArrayList<kovil>();
ViewHolder holder;
public Temple_Adapter(Context act,
int layoutResourceId, ArrayList<kovil> data) {
super(act,layoutResourceId,data);
tAdapter = new Temple_Adapter(Db_results.this, R.layout.display_db_result,temple_data);
this.layoutResourceId = layoutResourceId;
this.activity = (Activity) act;
this.data = data;
}
#SuppressWarnings({ "unchecked", "null" })
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = null;
convertView = mInflater.inflate(R.layout.display_db_result,parent, false);
holder = new ViewHolder();
holder.tv = (TextView) convertView.findViewById(R.id.textView1);
convertView.setTag(holder); // set tag on view
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tv.setText((CharSequence) data.get(position).temple_name);
return convertView;
}
public class ViewHolder
{
TextView tv;
}
}
#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;
}
}
Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="lk.adspace.jaffnatemples"
android:versionCode="1"
android:versionName="1.0" xmlns:tools="http://schemas.android.com/tools">
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<permission android:name="lk.adspace.jaffnatemples.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="lk.adspace.jaffnatemples.permission.MAPS_RECEIVE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-feature android:glEsVersion="0x00020000"
android:required="true"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="lk.adspace.jaffnatemples.Main"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Search"/>
<activity
android:name="lk.adspace.jaffnatemples.Search_result"
android:label="#string/app_name" />
<activity android:name="lk.adspace.jaffnatemples.Map_view"
android:label="#string/app_name" />
<activity android:name="lk.adspace.jaffnatemples.Db_results"
android:label="#string/app_name" />
<meta-data android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyBbouC2RTAM-AC2Vh6MYFF2JrzFGDg" />
</application>
</manifest>
Display Db_result.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/textviewres"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true" >
</ListView>
<TextView
android:id="#+id/textviewres"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="TextView" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="38dp"
android:text="TextView" />
</RelativeLayout>
New error Stack
02-10 21:45:31.473: E/AndroidRuntime(31356): FATAL EXCEPTION: main
02-10 21:45:31.473: E/AndroidRuntime(31356): java.lang.RuntimeException: Unable to start activity ComponentInfo{lk.adspace.jaffnatemples/lk.adspace.jaffnatemples.Db_results}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.ListView
02-10 21:45:31.473: E/AndroidRuntime(31356): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2343)
02-10 21:45:31.473: E/AndroidRuntime(31356): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)
02-10 21:45:31.473: E/AndroidRuntime(31356): at android.app.ActivityThread.access$600(ActivityThread.java:162)
02-10 21:45:31.473: E/AndroidRuntime(31356): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
02-10 21:45:31.473: E/AndroidRuntime(31356): at android.os.Handler.dispatchMessage(Handler.java:107)
02-10 21:45:31.473: E/AndroidRuntime(31356): at android.os.Looper.loop(Looper.java:194)
02-10 21:45:31.473: E/AndroidRuntime(31356): at android.app.ActivityThread.main(ActivityThread.java:5371)
02-10 21:45:31.473: E/AndroidRuntime(31356): at java.lang.reflect.Method.invokeNative(Native Method)
02-10 21:45:31.473: E/AndroidRuntime(31356): at java.lang.reflect.Method.invoke(Method.java:525)
02-10 21:45:31.473: E/AndroidRuntime(31356): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
02-10 21:45:31.473: E/AndroidRuntime(31356): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
02-10 21:45:31.473: E/AndroidRuntime(31356): at dalvik.system.NativeStart.main(Native Method)
02-10 21:45:31.473: E/AndroidRuntime(31356): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.ListView
02-10 21:45:31.473: E/AndroidRuntime(31356): at lk.adspace.jaffnatemples.Db_results.onCreate(Db_results.java:36)
02-10 21:45:31.473: E/AndroidRuntime(31356): at android.app.Activity.performCreate(Activity.java:5122)
02-10 21:45:31.473: E/AndroidRuntime(31356): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
02-10 21:45:31.473: E/AndroidRuntime(31356): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2307)
02-10 21:45:31.473: E/AndroidRuntime(31356): ... 11 more
can someone plz help me to fix this error.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/textviewres"
android:layout_width="match_parent"
android:layout_height="match_parent" >
remove ID from this
relative layout and textview both have same id and when you get it in activity it is returning the ralative layout object.
Remove it from relative layout just keep it in textview
Please post your xml layout or check if this line is correct:
TextView result = (TextView) findViewById(R.id.textviewres);
Is the view with id textviewres really TextView? According logcat looks like it's RelativeLayout
You have duplicated view id. Try to use this layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true" >
</ListView>
<TextView
android:id="#+id/textviewres"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="TextView" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="38dp"
android:text="TextView" />
</RelativeLayout>
In your code:
convertView = mInflater.inflate(R.layout.display_db_result,parent, false);
You need to inflate layout which contains only TextView.

How to solve NullPointerExpression in Android?

I have a problem while using a database. When I run my SQLView.java, I get a fatal exception. I'll post all my database-related code.
See my commenting lines on Database class (line 71), and SQLView class (Line 14). Maybe there is something wrong? I've tried many things like put in: this, of null.
Also, I've read all related nullpointerexception-question on this website.
To begin: my Database class:
package com.jacob.eindproject;
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.database.sqlite.SQLiteDatabase.CursorFactory;
import java.sql.*;
public class Database {
public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "persons_name";
public static final String KEY_HOTNESS = "persons_hotness";
private static final String DATABASE_NAME = "Databasedb";
private static final String DATABASE_TABLE = "peopleTable";
private static final int DATABASE_VERSION = 1;
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DbHelper extends SQLiteOpenHelper{
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + " TEXT NOT NULL, " +
KEY_HOTNESS + " TEXT NOT NULL);"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
public void close(Database database) {
// TODO Auto-generated method stub
}
}
public Database(Context c){
ourContext = c;
}
public Database open() throws SQLException{
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close() {
ourHelper.close(); //This is line 71, where also an error is given, maybe there should me text between the brackets ()?
}
public long createEntry(String name, String hotness) {
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, name);
cv.put(KEY_HOTNESS, hotness);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
public String getData() {
// TODO Auto-generated method stub
String[] columns = new String[]{ KEY_ROWID, KEY_NAME, KEY_HOTNESS};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iName = c.getColumnIndex(DATABASE_NAME);
int iHotness = c.getColumnIndex(KEY_HOTNESS);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iRow) + " " + c.getString(iName) + " " + c.getString(iHotness) + "\n";
}
return result;
}
}
The SQLite class, to fix the input:
package com.jacob.eindproject;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.View.OnClickListener;
public class SQLite extends Activity implements View.OnClickListener {
Button sqlUpdate, sqlView;
EditText sqlName, sqlHotness;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sqllite);
sqlUpdate = (Button) findViewById(R.id.bSQLUpdate);
sqlName = (EditText) findViewById(R.id.etSQLName);
sqlHotness = (EditText) findViewById(R.id.etSQLHotness);
sqlView = (Button) findViewById(R.id.bSQLopenView);
sqlView.setOnClickListener((android.view.View.OnClickListener) this);
sqlUpdate.setOnClickListener((android.view.View.OnClickListener) this);
}
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.bSQLUpdate:
boolean didItWork = true;
try{
String name = sqlName.getText().toString();
String hotness = sqlHotness.getText().toString();
Database entry = new Database(SQLite.this);
entry.open();
entry.createEntry(name, hotness);
entry.close();
}catch (Exception e ){
didItWork = false;
}finally{
if (didItWork){
Dialog d = new Dialog(this);
d.setTitle("Heak Yeay");
TextView tv = new TextView(this);
tv.setText("Succes");
d.setContentView(tv);
d.show();
}
}
break;
case R.id.bSQLopenView:
Intent i = new Intent("com.jacob.eindproject.SQLVIEW");
startActivity(i);
}
}
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
}
}
After that, my SQLView class, to view the input from the SQLite class:
package com.jacob.eindproject;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class SQLView extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sqlview);
TextView tv = (TextView) findViewById(R.id.tvSQLinfo);
Database info = new Database(this); //as you can see in the logcat, this is line 14, where the error is. Maybe the "this" isn't right?
info.open();
String data = info.getData();
info.close();
tv.setText(data);
}
}
Now, my xml files, maybe I haven't configured a button not well, or something?
SQLView.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TableLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="#+id/tableLayout1">
<TableRow>
<TextView android:text="#string/Names" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1"/>
<TextView android:text="#string/Hotness" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1" />
</TableRow>
</TableLayout>
<TextView android:id="#+id/tvSQLinfo" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="#string/info"/>
</LinearLayout>
The sqllite.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/Naam"
android:text="#string/Naam"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall" />
<EditText
android:id="#+id/etSQLName"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</EditText>
<TextView
android:id="#+id/hotness"
android:text="#string/hotnessscale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<EditText
android:id="#+id/etSQLHotness"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</EditText>
<Button
android:id="#+id/bSQLUpdate"
android:text="#string/Update"
android:layout_width="wrap_content"
android:layout_height="wrap_content" ></Button>
<Button
android:id="#+id/bSQLopenView"
android:text="#string/View"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
></Button>
</LinearLayout>
The Menu class, to fix the menu, with an OnListItemClick (there are some other activities in there, such as Overgewicht. Don't mind these, I guess..?):
package com.jacob.eindproject;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class Menu extends ListActivity implements OnItemClickListener {
String classes[] = { "BMI- Calculator", "Ondergewicht", "Gezond Gewicht", "Overgewicht", "Database", "Bekijk Database"};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(Menu.this, android.R.layout.simple_list_item_1, classes));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
//Positie 0 is het eerste item (dus de BMI-Calculator.)
super.onListItemClick(l, v, position, id);
switch(position)
{
case 0:
Intent openStartingPoint = new Intent(getApplicationContext(),MainActivity.class);
startActivity(openStartingPoint);
break;
case 1:
Intent openOndergewicht = new Intent(getApplicationContext(),Ondergewicht.class);
startActivity(openOndergewicht);
break;
case 2:
Intent openGezondgewicht = new Intent(getApplicationContext(),Gezond_gewicht.class);
startActivity(openGezondgewicht);
break;
case 3:
Intent openOvergewicht = new Intent(getApplicationContext(),Overgewicht.class);
startActivity(openOvergewicht);
break;
case 4:
Intent openDatabase = new Intent(getApplicationContext(),SQLite.class);
startActivity(openDatabase);
break;
case 5:
Intent openViewdatabase = new Intent(getApplicationContext(),SQLView.class);
startActivity(openViewdatabase);
break;
}
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
}
}
My Android Manifest file: (again, I've declared some other things, don't mind these!)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jacob.eindproject"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.jacob.eindproject.Menu"
android:label="#string/app_name" >
</activity>
<activity
android:name="com.jacob.eindproject.Inleiding"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.jacob.eindproject.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.jacob.eindproject.Ondergewicht"
android:label="#string/app_name" >
</activity>
<activity
android:name="com.jacob.eindproject.Gezond_gewicht"
android:label="#string/app_name" >
</activity>
<activity
android:name="com.jacob.eindproject.Overgewicht"
android:label="#string/app_name" >
</activity>
<activity
android:name="com.jacob.eindproject.Database"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.jacob.eindproject.DATABASE" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".SQLView"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.jacob.eindproject.SQLVIEW" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.jacob.eindproject.SQLite"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.jacob.eindproject.SQLITE" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
At last, my LogCat, to show you the error:
12-14 11:04:18.227: E/AndroidRuntime(1577): FATAL EXCEPTION: main
12-14 11:04:18.227: E/AndroidRuntime(1577): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.jacob.eindproject/com.jacob.eindproject.SQLView}: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
12-14 11:04:18.227: E/AndroidRuntime(1577): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
12-14 11:04:18.227: E/AndroidRuntime(1577): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
12-14 11:04:18.227: E/AndroidRuntime(1577): at android.app.ActivityThread.access$600(ActivityThread.java:141)
12-14 11:04:18.227: E/AndroidRuntime(1577): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
12-14 11:04:18.227: E/AndroidRuntime(1577): at android.os.Handler.dispatchMessage(Handler.java:99)
12-14 11:04:18.227: E/AndroidRuntime(1577): at android.os.Looper.loop(Looper.java:137)
12-14 11:04:18.227: E/AndroidRuntime(1577): at android.app.ActivityThread.main(ActivityThread.java:5103)
12-14 11:04:18.227: E/AndroidRuntime(1577): at java.lang.reflect.Method.invokeNative(Native Method)
12-14 11:04:18.227: E/AndroidRuntime(1577): at java.lang.reflect.Method.invoke(Method.java:525)
12-14 11:04:18.227: E/AndroidRuntime(1577): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
12-14 11:04:18.227: E/AndroidRuntime(1577): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-14 11:04:18.227: E/AndroidRuntime(1577): at dalvik.system.NativeStart.main(Native Method)
12-14 11:04:18.227: E/AndroidRuntime(1577): Caused by: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
12-14 11:04:18.227: E/AndroidRuntime(1577): at android.database.CursorWindow.nativeGetString(Native Method)
12-14 11:04:18.227: E/AndroidRuntime(1577): at android.database.CursorWindow.getString(CursorWindow.java:434)
12-14 11:04:18.227: E/AndroidRuntime(1577): at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
12-14 11:04:18.227: E/AndroidRuntime(1577): at com.jacob.eindproject.Database.getData(Database.java:95)
12-14 11:04:18.227: E/AndroidRuntime(1577): at com.jacob.eindproject.SQLView.onCreate(SQLView.java:16)
12-14 11:04:18.227: E/AndroidRuntime(1577): at android.app.Activity.performCreate(Activity.java:5133)
12-14 11:04:18.227: E/AndroidRuntime(1577): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
12-14 11:04:18.227: E/AndroidRuntime(1577): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
12-14 11:04:18.227: E/AndroidRuntime(1577): ... 11 more
EDIT:
I have a new error now, please take a look at my LogCat. I think it's because I have a wrong column set or something? Thanks in advance.
The NPE occurs at line 71 of your Database class, somewhere within the constructor or when intializing variables (that's what <init> in the stacktrace stands for.
I just read that you figured that out yourself. So the only thing that can be null here is ourHelper.
Is this really your code?
public void close() {
} {
ourHelper.close(); //This is line 71, where also an error is given, maybe there should me text between the brackets ()?
}
There's something wrong with the brackets here. I'm not sure why this compiles but I guess it does and the compiler executes the
{
ourHelper.close();
}
immediately when instantiating the class.
Change this to
public void close() {
ourHelper.close();
}
and you should be fine.

java.lang.NullPointerException Cant figure out what is causing the error

I am creating a VERY basic POS system for an assignment for class. I keep getting that dreaded nullpointerexception. I know the error is coming from line 72 in main activity but it is declared in both the main activity and in the xml.
Here is the logcat:
10-07 18:05:36.946: D/AndroidRuntime(1279): Shutting down VM
10-07 18:05:36.946: W/dalvikvm(1279): threadid=1: thread exiting with uncaught exception (group=0x414c4700)
10-07 18:05:36.958: E/AndroidRuntime(1279): FATAL EXCEPTION: main
10-07 18:05:36.958: E/AndroidRuntime(1279): java.lang.RuntimeException: Unable to start activity ComponentInfo{hotchkissmobilesolutions.kudlerpos/hotchkissmobilesolutions.kudlerpos.MainActivity}: java.lang.NullPointerException
10-07 18:05:36.958: E/AndroidRuntime(1279): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
10-07 18:05:36.958: E/AndroidRuntime(1279): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
10-07 18:05:36.958: E/AndroidRuntime(1279): at android.app.ActivityThread.access$600(ActivityThread.java:141)
10-07 18:05:36.958: E/AndroidRuntime(1279): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
10-07 18:05:36.958: E/AndroidRuntime(1279): at android.os.Handler.dispatchMessage(Handler.java:99)
10-07 18:05:36.958: E/AndroidRuntime(1279): at android.os.Looper.loop(Looper.java:137)
10-07 18:05:36.958: E/AndroidRuntime(1279): at android.app.ActivityThread.main(ActivityThread.java:5103)
10-07 18:05:36.958: E/AndroidRuntime(1279): at java.lang.reflect.Method.invokeNative(Native Method)
10-07 18:05:36.958: E/AndroidRuntime(1279): at java.lang.reflect.Method.invoke(Method.java:525)
10-07 18:05:36.958: E/AndroidRuntime(1279): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
10-07 18:05:36.958: E/AndroidRuntime(1279): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-07 18:05:36.958: E/AndroidRuntime(1279): at dalvik.system.NativeStart.main(Native Method)
10-07 18:05:36.958: E/AndroidRuntime(1279): Caused by: java.lang.NullPointerException
10-07 18:05:36.958: E/AndroidRuntime(1279): at hotchkissmobilesolutions.kudlerpos.MainActivity.onCreate(MainActivity.java:72)
10-07 18:05:36.958: E/AndroidRuntime(1279): at android.app.Activity.performCreate(Activity.java:5133)
10-07 18:05:36.958: E/AndroidRuntime(1279): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
10-07 18:05:36.958: E/AndroidRuntime(1279): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
10-07 18:05:36.958: E/AndroidRuntime(1279): ... 11 more
Here is the android manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="hotchkissmobilesolutions.kudlerpos"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="hotchkissmobilesolutions.kudlerpos.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
here is the Main Activity:
package hotchkissmobilesolutions.kudlerpos;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.GridLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
double dairy = 4.99, seafood = 15.99, wine = 20, meat = 5.99,
cheese = 2.99, fruit = 1.99, vegetable = 0.69;
double total, tax = 0.0725;
String total2;
Button btnDairy, btnSeafood, btnWine, btnMeat, btnFruit, btnVegetable,
btnTotal, btnClear;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnDairy = (Button) findViewById(R.id.btnDairy);
btnSeafood = (Button) findViewById(R.id.btnSeafood);
btnWine = (Button) findViewById(R.id.btnWine);
btnMeat = (Button) findViewById(R.id.btnMeat);
btnFruit = (Button) findViewById(R.id.btnFruit);
btnVegetable = (Button) findViewById(R.id.btnVegetable);
btnClear = (Button) findViewById(R.id.btnClear);
btnDairy.setOnClickListener(new OnClickListener() {
public void onClick(View V) {
total = (total + dairy) + (total * tax);
System.out.println(total);
}
});
btnSeafood.setOnClickListener(new OnClickListener() {
public void onClick(View V) {
total = (total + seafood) + (total * tax);
System.out.println(total);
}
});
btnWine.setOnClickListener(new OnClickListener() {
public void onClick(View V) {
total = (total + wine) + (total * tax);
System.out.println(total);
}
});
btnMeat.setOnClickListener(new OnClickListener() {
public void onClick(View V) {
total = (total + meat) + (total * tax);
System.out.println(total);
}
});
btnFruit.setOnClickListener(new OnClickListener() {
public void onClick(View V) {
total = (total + fruit) + (total * tax);
System.out.println(total);
}
});
btnVegetable.setOnClickListener(new OnClickListener() {
public void onClick(View V) {
total = (total + vegetable) + (total * tax);
System.out.println(total);
}
});
btnTotal.setOnClickListener(new OnClickListener() {
public void onClick(View V) {
total2 = new Double(total).toString();
final TextView textView = (TextView) findViewById(R.id.textViewTotal);
textView.setText(total2);
System.out.println(total);
System.out.println(total2);
}
});
btnClear.setOnClickListener(new OnClickListener() {
public void onClick(View V) {
total = 0;
total2 = new Double(total).toString();
final TextView textView = (TextView) findViewById(R.id.textViewTotal);
textView.setText(total2);
System.out.println(total);
}
});
}
and here is the activity_main.xml:
<?xml version="1.0" encoding="UTF-8"?>
<GridLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnCount="6"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:rowCount="8"
tools:context=".MainActivity"
tools:targetApi="14" >
<TextView android:id="#+id/txtViewInstructions"
android:layout_column="0"
android:layout_gravity="left|top"
android:layout_row="0"
android:text="#string/InstructionText"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button android:id="#+id/btnDairy"
android:layout_column="0"
android:layout_gravity="left|top"
android:layout_row="3"
android:onClick="onCLickDairy"
android:text="#string/Dairy" />
<Button android:id="#+id/btnWine"
android:layout_column="0"
android:layout_gravity="center_horizontal|top"
android:layout_row="3"
android:onClick="onCLickWine"
android:text="#string/Wine" />
<Button android:id="#+id/btnMeat"
android:layout_column="0"
android:layout_gravity="left|top"
android:layout_row="4"
android:onClick="onCLickMeat"
android:text="#string/Meat" />
<Button android:id="#+id/btnSeafood"
android:layout_column="0"
android:layout_gravity="center_horizontal|top"
android:layout_row="4"
android:onClick="onCLickSeafood"
android:text="#string/Seafood" />
<Button android:id="#+id/btnVegetable"
android:layout_column="0"
android:layout_gravity="left|top"
android:layout_row="5"
android:onClick="onCLickVegetable"
android:text="#string/Vegetable" />
<TextView android:id="#+id/txtViewTotalDue"
android:layout_column="0"
android:layout_gravity="left|top"
android:layout_row="7"
android:text="#string/TotalDue"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView android:id="#+id/textViewTotal"
android:layout_width="260dp"
android:layout_height="93dp"
android:layout_column="0"
android:layout_gravity="left|bottom"
android:layout_row="6"
android:text="#string/total"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button android:id="#+id/btnTotal"
android:layout_column="0"
android:layout_gravity="left|center_vertical"
android:layout_row="7"
android:onClick="onCLickTotal"
android:text="#string/TotalButton" />
<Button android:id="#+id/btnFruit"
android:layout_column="0"
android:layout_gravity="center_horizontal|top"
android:layout_row="5"
android:onClick="onCLickFruit"
android:text="#string/Fruit" />
<Button android:id="#+id/btnClear"
android:layout_column="0"
android:layout_gravity="left|bottom"
android:layout_row="7"
android:text="#string/ClearButton" />
</GridLayout>
Any help in finding the issue with the btnTotal line in the main activity.java would be so helpful. Thanks in advance!
You don't have a btnTotal so when you click on it, the value is null.
See:
btnDairy = (Button) findViewById(R.id.btnDairy);
btnSeafood = (Button) findViewById(R.id.btnSeafood);
btnWine = (Button) findViewById(R.id.btnWine);
btnMeat = (Button) findViewById(R.id.btnMeat);
btnFruit = (Button) findViewById(R.id.btnFruit);
btnVegetable = (Button) findViewById(R.id.btnVegetable);
btnClear = (Button) findViewById(R.id.btnClear);
//add this
btnTotal = (Button) findViewById(R.id.btnTotal);
No button for btnTotal. Add that button and you'll be fine. Simple mistake. Happens all the time. Good luck.
You did not initialise your total field, so it throws NPE

RunTimeException when trying to implement GPS Locater

I am working on adding GPS location services to my app. However I get this error I just can't seem to fix. I have included all of my relevant coding. And if anybody has comments on any of my coding not related to the error I would appreciate them too.
Logcat
08-09 11:19:24.602: E/AndroidRuntime(715): FATAL EXCEPTION: main
08-09 11:19:24.602: E/AndroidRuntime(715): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.com.proto1/com.example.com.proto1.menu}: android.view.InflateException: Binary XML file line #77: Error inflating class com.google.android.maps.MapView
08-09 11:19:24.602: E/AndroidRuntime(715): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
08-09 11:19:24.602: E/AndroidRuntime(715): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
08-09 11:19:24.602: E/AndroidRuntime(715): at android.app.ActivityThread.access$600(ActivityThread.java:130)
08-09 11:19:24.602: E/AndroidRuntime(715): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
08-09 11:19:24.602: E/AndroidRuntime(715): at android.os.Handler.dispatchMessage(Handler.java:99)
08-09 11:19:24.602: E/AndroidRuntime(715): at android.os.Looper.loop(Looper.java:137)
08-09 11:19:24.602: E/AndroidRuntime(715): at android.app.ActivityThread.main(ActivityThread.java:4745)
08-09 11:19:24.602: E/AndroidRuntime(715): at java.lang.reflect.Method.invokeNative(Native Method)
08-09 11:19:24.602: E/AndroidRuntime(715): at java.lang.reflect.Method.invoke(Method.java:511)
08-09 11:19:24.602: E/AndroidRuntime(715): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
08-09 11:19:24.602: E/AndroidRuntime(715): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
08-09 11:19:24.602: E/AndroidRuntime(715): at dalvik.system.NativeStart.main(Native Method)
08-09 11:19:24.602: E/AndroidRuntime(715): Caused by: android.view.InflateException: Binary XML file line #77: Error inflating class com.google.android.maps.MapView
08-09 11:19:24.602: E/AndroidRuntime(715): at android.view.LayoutInflater.createView(LayoutInflater.java:613)
08-09 11:19:24.602: E/AndroidRuntime(715): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687)
08-09 11:19:24.602: E/AndroidRuntime(715): at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
08-09 11:19:24.602: E/AndroidRuntime(715): at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
08-09 11:19:24.602: E/AndroidRuntime(715): at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
08-09 11:19:24.602: E/AndroidRuntime(715): at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
08-09 11:19:24.602: E/AndroidRuntime(715): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:256)
08-09 11:19:24.602: E/AndroidRuntime(715): at android.app.Activity.setContentView(Activity.java:1867)
08-09 11:19:24.602: E/AndroidRuntime(715): at com.example.com.proto1.menu.onCreate(menu.java:62)
08-09 11:19:24.602: E/AndroidRuntime(715): at android.app.Activity.performCreate(Activity.java:5008)
08-09 11:19:24.602: E/AndroidRuntime(715): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
08-09 11:19:24.602: E/AndroidRuntime(715): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
08-09 11:19:24.602: E/AndroidRuntime(715): ... 11 more
08-09 11:19:24.602: E/AndroidRuntime(715): Caused by: java.lang.reflect.InvocationTargetException
08-09 11:19:24.602: E/AndroidRuntime(715): at java.lang.reflect.Constructor.constructNative(Native Method)
08-09 11:19:24.602: E/AndroidRuntime(715): at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
08-09 11:19:24.602: E/AndroidRuntime(715): at android.view.LayoutInflater.createView(LayoutInflater.java:587)
08-09 11:19:24.602: E/AndroidRuntime(715): ... 22 more
08-09 11:19:24.602: E/AndroidRuntime(715): Caused by: java.lang.IllegalArgumentException: MapViews can only be created inside instances of MapActivity.
08-09 11:19:24.602: E/AndroidRuntime(715): at com.google.android.maps.MapView.<init>(MapView.java:291)
08-09 11:19:24.602: E/AndroidRuntime(715): at com.google.android.maps.MapView.<init>(MapView.java:264)
08-09 11:19:24.602: E/AndroidRuntime(715): at com.google.android.maps.MapView.<init>(MapView.java:247)
08-09 11:19:24.602: E/AndroidRuntime(715): ... 25 more
Manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.com.proto1"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="7" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:icon="#drawable/theeye"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".mainj"
android:label="#string/title_activity_mainj" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".menu"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MENU" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".Infoactive"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.INFOSCREEN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".VoicePrompts"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.VOICEPROMPTS" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".VPon"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.VPON" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".VPoff"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.VPOFF" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<!-- android name must match the name of the java you want to use -->
<activity
android:name=".VoiceRecognition"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.RECOGNITIONMENU" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".Recognition"
android:label="#string/app_name" >
<intent-filter>
<action android:name="ACTION_RECOGNIZE_SPEECH" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".SpeakingAndroid"
android:label="tts" >
<intent-filter>
<action android:name="android.intent.action.SPEAK" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MyGPSActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="GPS_LOCATION" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<library
name="com.google.android.maps"
file="/system/framework/com.google.android.maps.jar" />
<uses-library android:name="com.google.android.maps" />
</application>
</manifest>
Main XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:weightSum="100" >
<ListView
android:id="#+id/list"
android:layout_width="wrap_content"
android:layout_height="5dp" >
</ListView>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"
android:gravity="bottom"
android:orientation="horizontal"
android:weightSum="100" >
<Button
android:id="#+id/aboutbutton"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="50"
android:gravity="center"
android:text="#string/a"
android:textSize="25dp" />
<Button
android:id="#+id/talk"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="50"
android:gravity="center"
android:text="talk"
android:textSize="25dp" />
</LinearLayout>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/textView1"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:orientation="horizontal"
android:weightSum="100" >
<Button
android:id="#+id/voicebutton"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="50"
android:gravity="center"
android:text="#string/starttalking"
android:textSize="25dp" />
<Button
android:id="#+id/btn_speak"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="50"
android:gravity="center"
android:text="#string/start"
android:textSize="25dp" />
</LinearLayout>
<com.google.android.maps.MapView
android:id="#+id/myGMap"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:apiKey="API_Key_String"
android:clickable="true"
android:enabled="true" />
<TextView
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true" />
</RelativeLayout>
Menu(Main) Java
package com.example.com.proto1;
import android.app.Activity;
import android.content.Intent;
import android.location.Location;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.speech.RecognizerIntent;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import android.speech.tts.TextToSpeech;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import com.example.com.proto1.MyGPSActivity.LocationResult;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
#SuppressWarnings("unused")
public class menu extends Activity implements TextToSpeech.OnInitListener,
OnClickListener {
LocationResult locationResult = new LocationResult() {
#Override
public void gotLocation(Location location) {
// Got the location!
}
};
MyGPSActivity myLocation = new MyGPSActivity();
// defined
TextToSpeech mTts;
public static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
// remember to include a listview on the xml or the voice recognition code
// will not work
public ListView mList;
// TTS object
Button speakButton, infoButton, voiceButton, talkButton;
// TTS object
public TextToSpeech myTTS;
// status check code
public int MY_DATA_CHECK_CODE = 0;
#Override
protected void onCreate(Bundle aboutmenu) {
super.onCreate(aboutmenu);
setContentView(R.layout.mainx);
SpeakingAndroid speak = new SpeakingAndroid();
VoiceRecognition voiceinput = new VoiceRecognition();
// get a reference to the button element listed in the XML layout
speakButton = (Button) findViewById(R.id.btn_speak);
infoButton = (Button) findViewById(R.id.aboutbutton);
voiceButton = (Button) findViewById(R.id.voicebutton);
talkButton = (Button) findViewById(R.id.talk);
// listen for clicks
infoButton.setOnClickListener(this);
speakButton.setOnClickListener(this);
talkButton.setOnClickListener(this);
// check for TTS data
Intent checkTTSIntent = new Intent();
checkTTSIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE);
// calling method
voiceinputbuttons();
// Check to see if a recognition activity is present
// if running on AVD virtual device it will give this message. The mic
// required only works on an actual android device//
PackageManager pm = getPackageManager();
List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (activities.size() != 0) {
voiceButton.setOnClickListener(this);
} else {
voiceButton.setEnabled(false);
voiceButton.setText("Recognizer not present");
}
}
// setup TTS
public void onInit(int initStatus) {
// check for successful instantiation
// returns a fail statement if speech doesn't work
if (initStatus == TextToSpeech.SUCCESS) {
if (myTTS.isLanguageAvailable(Locale.US) == TextToSpeech.LANG_AVAILABLE)
myTTS.setLanguage(Locale.US);
} else if (initStatus == TextToSpeech.ERROR) {
Toast.makeText(this, "Sorry! Text To Speech failed...",
Toast.LENGTH_LONG).show();
}
}
public void informationmenu() {
speakWords("information screen");
startActivity(new Intent("android.intent.action.INFOSCREEN"));
}
public void voicemenu() {
speakWords("voice recognition menu");
startActivity(new Intent("android.intent.action.RECOGNITIONMENU"));
}
public void mainmenu() {
speakWords("main menu");
startActivity(new Intent("android.intent.action.MENU"));
}
// creating method
public void voiceinputbuttons() {
speakButton = (Button) findViewById(R.id.btn_speak);
mList = (ListView) findViewById(R.id.list);
}
// respond to button clicks
public void onClick(View v) {
switch (v.getId()) {
// use switch case so each button does a different thing
// accurately(similar to an if statement)
case R.id.btn_speak:
String words1 = speakButton.getText().toString();
// speakwords(xxxx); is the piece of code that actually calls the
// text to speech
speakWords(words1);
myLocation.getLocation(this, locationResult);
break;
case R.id.aboutbutton:
String words2 = infoButton.getText().toString();
speakWords(words2);
Intent infoIntent = new Intent("android.intent.action.INFOSCREEN");
startActivity(infoIntent);
break;
case R.id.voicebutton:
speakWords("Speak Now");
startVoiceRecognitionActivity(); // call for voice recognition
// activity
break;
case R.id.talk:
speakWords("This is the main menu.");
break;
}
}
// speak the user text
// setting up the speakWords code
public void speakWords(String speech) {
// speak straight away
myTTS.speak(speech, TextToSpeech.QUEUE_FLUSH, null);
}
/**
* Fire an intent to start the speech recognition activity.
*/
public void startVoiceRecognitionActivity() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
"Speech recognition demo");
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}
/**
* Handle the results from the recognition activity.
*/
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE
&& resultCode == RESULT_OK) {
// Fill the list view with the strings the recognizer thought it
// could have heard
ArrayList<String> matches = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
mList.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, matches));
// matches is the result of voice input. It is a list of what the
// user possibly said.
// Using an if statement for the keyword you want to use allows the
// use of any activity if keywords match
// it is possible to set up multiple keywords to use the same
// activity so more than one word will allow the user
// to use the activity (makes it so the user doesn't have to
// memorize words from a list)
// to use an activity from the voice input information simply use
// the following format;
// if (matches.contains("keyword here") { startActivity(new
// == Intent("name.of.manifest.ACTIVITY")
if (matches.contains("information")) {
informationmenu();
}
if (matches.contains("info screen")) {
informationmenu();
}
if (matches.contains("info")) {
informationmenu();
}
if (matches.contains("about")) {
informationmenu();
}
if (matches.contains("home")) {
mainmenu();
}
if (matches.contains("menu")) {
mainmenu();
}
if (matches.contains("home screen")) {
mainmenu();
}
if (matches.contains("speak")) {
startActivity(new Intent("android.intent.action.SPEAK"));
}
if (matches.contains("close")) {
finish();
}
if (matches.contains("stop")) {
finish();
}
if (matches.contains("finish")) {
finish();
}
if (matches.contains("voice")) {
voicemenu();
}
if (matches.contains("recognition")) {
voicemenu();
}
if (matches.contains("voice recognition")) {
voicemenu();
}
}
// still in the onActivityResult: This is for the text to speech part
if (requestCode == MY_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
// the user has the necessary data - create the TTS
myTTS = new TextToSpeech(this, this);
} else {
// no data - install it now
Intent installTTSIntent = new Intent();
installTTSIntent
.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installTTSIntent);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
myTTS.shutdown();
}
}
GPS Java
package com.example.com.proto1;
import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
public class MyGPSActivity {
Timer timer1;
LocationManager lm;
LocationResult locationResult;
boolean gps_enabled = false;
boolean network_enabled = false;
public boolean getLocation(Context context, LocationResult result) {
// I use LocationResult callback class to pass location value from
// MyLocation to user code.
locationResult = result;
if (lm == null)
lm = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
// exceptions will be thrown if provider is not permitted.
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = lm
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
// don't start listeners if no provider is enabled
if (!gps_enabled && !network_enabled)
return false;
if (gps_enabled)
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
locationListenerGps);
if (network_enabled)
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
locationListenerNetwork);
timer1 = new Timer();
timer1.schedule(new GetLastLocation(), 20000);
return true;
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerNetwork);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
class GetLastLocation extends TimerTask {
#Override
public void run() {
lm.removeUpdates(locationListenerGps);
lm.removeUpdates(locationListenerNetwork);
Location net_loc = null, gps_loc = null;
if (gps_enabled)
gps_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (network_enabled)
net_loc = lm
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
// if there are both values use the latest one
if (gps_loc != null && net_loc != null) {
if (gps_loc.getTime() > net_loc.getTime())
locationResult.gotLocation(gps_loc);
else
locationResult.gotLocation(net_loc);
return;
}
if (gps_loc != null) {
locationResult.gotLocation(gps_loc);
return;
}
if (net_loc != null) {
locationResult.gotLocation(net_loc);
return;
}
locationResult.gotLocation(null);
}
}
public static abstract class LocationResult {
public abstract void gotLocation(Location location);
}
}
Put the following line in the application element of AndroidManifest.xml file.
<uses-library android:name="com.google.android.maps" />

Categories