I’m a newbie in Android development. I’m facing a problem and I did spend two days trying to find out what’s wrong with the code.
In my application I want to have a Button which executes a database update. When clicking this Button, I’m getting a NullPointerException.
Here’s my class:
package com.test.database;
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class SQLiteExample extends Activity implements OnClickListener {
Button sqlUpdate, sqlView;
EditText sqlName, sqlHotness;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sqliteexample);
sqlUpdate = (Button) findViewById(R.id.bSQLUpdate);
sqlName = (EditText)findViewById(R.id.etName);
sqlHotness = (EditText)findViewById(R.id.etSQLHotness);
sqlView = (Button) findViewById(R.id.bSQLopenView);
sqlView.setOnClickListener(this);
sqlUpdate.setOnClickListener(this);
}
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch(arg0.getId()){
case R.id.bSQLUpdate:
boolean didItWork = true;
try{
String name = sqlName.getText().toString();
String hotness = sqlHotness.getText().toString();
HotOrNot entry = new HotOrNot(SQLiteExample.this);
entry.open();
entry.createEntry(name, hotness);
entry.close();
}catch (Exception e){
didItWork = false;
}finally{
if(didItWork){
Dialog d = new Dialog(this);
d.setTitle("Heck Yea!");
TextView tv = new TextView(this);
tv.setText("Success");
d.setContentView(tv);
d.show();
}
}
break;
case R.id.bSQLopenView:
break;
}
}
}
Here’s my layout xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name" />
<EditText
android:id="@+id/etSQLName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hotness scale 1 to 10" />
<EditText
android:id="@+id/etSQLHotness"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" />
<Button
android:id="@+id/bSQLUpdate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Update SQLite Database" />
<Button
android:id="@+id/bSQLopenView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="View" />
</LinearLayout>
First thing you take wrong id in edit text . It is etSQLName and you take etName.
So change the below line and check again.
to