Creating database in seperate activity/class is giving errors - java

Please have a look at the following code
Form.java
Form.java is the Main activity, which means the Java file for the first page. Lot of code related to creating "List" and menu are removed.
package com.example.esoftcallmanager;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class Form extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_form);
DatabaseConnector databaseConnector = new DatabaseHandler();
databaseConnector.createConnection();
ListView lv = (ListView)findViewById(android.R.id.list);
String arr[] = getResources().getStringArray(R.array.branch_list);
//lv.setAdapter(new MyAdapter(this,android.R.layout.simple_list_item_1,R.id.listText,arr));
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
});
}
}
DataBaseConnector.java
This is the interface for the code, which perform database actions
package com.example.esoftcallmanager;
public interface DatabaseConnector
{
public void createConnection();
public void closeConnection();
public String getPhoneNumber();
}
DataBaseHandler.java
This is the one which perform the database operations
package com.example.esoftcallmanager;
import android.app.Activity;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.widget.Toast;
public class DatabaseHandler extends Activity implements DatabaseConnector
{
private SQLiteDatabase database;
private String dbPath = "data//data//com.example.esoftcallmanager.sqllite//esoftDatabase";
#Override
public void createConnection()
{
try
{
database = this.openOrCreateDatabase("esoftDatabase", MODE_PRIVATE, null);
database.execSQL("create table BranchNetwork(" +
"brID integer primary key autoincrement,"
+"city text,"
+"steetAddress text"
+"phoneNumber1 text"
+"phoneNumber2 text"
+"email text"
+");");
}
catch(SQLException sql)
{
Toast.makeText(this, sql.getMessage(), Toast.LENGTH_LONG).show();
}
}
#Override
public void closeConnection() {
// TODO Auto-generated method stub
}
#Override
public String getPhoneNumber() {
// TODO Auto-generated method stub
return null;
}
}
However, I am unable to run the code, because I am getting the following error.
02-11 20:35:59.350: D/dalvikvm(434): GC_EXTERNAL_ALLOC freed 52K, 53% free 2552K/5379K, external 1949K/2137K, paused 80ms
02-11 20:40:34.021: D/dalvikvm(1131): GC_EXTERNAL_ALLOC freed 42K, 53% free 2552K/5379K, external 1949K/2137K, paused 122ms
02-11 20:40:34.361: D/AndroidRuntime(1131): Shutting down VM
02-11 20:40:34.361: W/dalvikvm(1131): threadid=1: thread exiting with uncaught exception (group=0x40015560)
02-11 20:40:34.401: E/AndroidRuntime(1131): FATAL EXCEPTION: main
02-11 20:40:34.401: E/AndroidRuntime(1131): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.esoftcallmanager/com.example.esoftcallmanager.Form}: java.lang.NullPointerException
02-11 20:40:34.401: E/AndroidRuntime(1131): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
02-11 20:40:34.401: E/AndroidRuntime(1131): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
02-11 20:40:34.401: E/AndroidRuntime(1131): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
02-11 20:40:34.401: E/AndroidRuntime(1131): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
02-11 20:40:34.401: E/AndroidRuntime(1131): at android.os.Handler.dispatchMessage(Handler.java:99)
02-11 20:40:34.401: E/AndroidRuntime(1131): at android.os.Looper.loop(Looper.java:123)
02-11 20:40:34.401: E/AndroidRuntime(1131): at android.app.ActivityThread.main(ActivityThread.java:3683)
02-11 20:40:34.401: E/AndroidRuntime(1131): at java.lang.reflect.Method.invokeNative(Native Method)
02-11 20:40:34.401: E/AndroidRuntime(1131): at java.lang.reflect.Method.invoke(Method.java:507)
02-11 20:40:34.401: E/AndroidRuntime(1131): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
02-11 20:40:34.401: E/AndroidRuntime(1131): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
02-11 20:40:34.401: E/AndroidRuntime(1131): at dalvik.system.NativeStart.main(Native Method)
02-11 20:40:34.401: E/AndroidRuntime(1131): Caused by: java.lang.NullPointerException
02-11 20:40:34.401: E/AndroidRuntime(1131): at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:203)
02-11 20:40:34.401: E/AndroidRuntime(1131): at com.example.esoftcallmanager.DatabaseHandler.createConnection(DatabaseHandler.java:19)
02-11 20:40:34.401: E/AndroidRuntime(1131): at com.example.esoftcallmanager.Form.onCreate(Form.java:30)
02-11 20:40:34.401: E/AndroidRuntime(1131): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
02-11 20:40:34.401: E/AndroidRuntime(1131): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
02-11 20:40:34.401: E/AndroidRuntime(1131): ... 11 more
02-11 20:40:37.381: I/Process(1131): Sending signal. PID: 1131 SIG: 9
Whenever I remove the database connection part from the Form.java, this works fine! So the error must be in the following code
DatabaseConnector databaseConnector = new DatabaseHandler();
databaseConnector.createConnection();
I do not want to add all the database operations in the Form.java. I need to split the work as I have done. But, how can I do that? Please help!

if DatabaseHandler is non Activity class then no need to extends Activity to it. you will need to create a parameterized constructor of DatabaseHandler to pass Activity context to it for creating database . change your DatabaseHandler class as:
public class DatabaseHandler implements DatabaseConnector
{
private SQLiteDatabase database;
....
Context context;
public DatabaseHandler(Context context){
this.context=context;
}
#Override
public void createConnection()
{
try
{
database = context.openOrCreateDatabase("esoftDatabase",
MODE_PRIVATE, null);
// your code here....
}
catch(SQLException sql)
{
Toast.makeText(context, sql.getMessage(),
Toast.LENGTH_LONG).show();
}
}
and pass Activity Context as from Form Activity :
DatabaseConnector databaseConnector =
new DatabaseHandler(Form.this);
databaseConnector.createConnection();

One Thing I saw was:
database.execSQL("create table BranchNetwork(" +
"brID integer primary key autoincrement,"
+"city text,"
+"steetAddress text"
+"phoneNumber1 text"
+"phoneNumber2 text"
+"email text"
+");");
You have to write:
database.execSQL("create table BranchNetwork(" +
"brID integer primary key autoincrement,"
+"city text,"
+"steetAddress text," //forgot comma
+"phoneNumber1 text," //forgot comma
+"phoneNumber2 text," // forgot commas
+"email text"
+");");
I donĀ“t know if this was the mistake, but try it...

Related

java.lang.NullPointerException, FATAL EXCEPTION at listview

Hi I'm new to android and pardon me as it is my first time developing a mobile application for my school assignment. I have an error which made my app crashed whenever I try to start the app and my guess is that the retrieving is the culprit.
I am creating an activity that is supposed to display an empty list which will allow the user the input of CRUD. I do understand that the error is due to null but how do I make it so that it allows the display of an empty list? I would appreciate any help on how to go about this, thank you!
Here is the logcat:
02-11 18:41:53.803: W/dalvikvm(18334): threadid=1: thread exiting with uncaught exception (group=0x41763da0)
02-11 18:41:53.803: E/AndroidRuntime(18334): FATAL EXCEPTION: main
02-11 18:41:53.803: E/AndroidRuntime(18334): Process: com.example.sgrecipe, PID: 18334
02-11 18:41:53.803: E/AndroidRuntime(18334): java.lang.NullPointerException
02-11 18:41:53.803: E/AndroidRuntime(18334): at com.example.sgrecipe.FavouriteFragment.fetchData(FavouriteFragment.java:174)
02-11 18:41:53.803: E/AndroidRuntime(18334): at com.example.sgrecipe.FavouriteFragment.initControls(FavouriteFragment.java:92)
02-11 18:41:53.803: E/AndroidRuntime(18334): at com.example.sgrecipe.FavouriteFragment.onStart(FavouriteFragment.java:50)
02-11 18:41:53.803: E/AndroidRuntime(18334): at android.support.v4.app.Fragment.performStart(Fragment.java:1484)
02-11 18:41:53.803: E/AndroidRuntime(18334): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:941)
02-11 18:41:53.803: E/AndroidRuntime(18334): at android.support.v4.app.FragmentManagerImpl.performPendingDeferredStart(FragmentManager.java:807)
02-11 18:41:53.803: E/AndroidRuntime(18334): at android.support.v4.app.FragmentManagerImpl.startPendingDeferredFragments(FragmentManager.java:1112)
02-11 18:41:53.803: E/AndroidRuntime(18334): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1461)
02-11 18:41:53.803: E/AndroidRuntime(18334): at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:461)
02-11 18:41:53.803: E/AndroidRuntime(18334): at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
02-11 18:41:53.803: E/AndroidRuntime(18334): at android.support.v4.view.ViewPager.populate(ViewPager.java:1064)
02-11 18:41:53.803: E/AndroidRuntime(18334): at android.support.v4.view.ViewPager.populate(ViewPager.java:911)
02-11 18:41:53.803: E/AndroidRuntime(18334): at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1432)
02-11 18:41:53.803: E/AndroidRuntime(18334): at android.view.View.measure(View.java:17396)
02-11 18:41:53.803: E/AndroidRuntime(18334): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5365)
02-11 18:41:53.803: E/AndroidRuntime(18334): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
02-11 18:41:53.803: E/AndroidRuntime(18334): at android.view.View.measure(View.java:17396)
02-11 18:41:53.803: E/AndroidRuntime(18334): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5365)
02-11 18:41:53.803: E/AndroidRuntime(18334): at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:382)
02-11 18:41:53.803: E/AndroidRuntime(18334): at android.view.View.measure(View.java:17396)
02-11 18:41:53.803: E/AndroidRuntime(18334): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5365)
02-11 18:41:53.803: E/AndroidRuntime(18334): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
02-11 18:41:53.803: E/AndroidRuntime(18334): at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2505)
02-11 18:41:53.803: E/AndroidRuntime(18334): at android.view.View.measure(View.java:17396)
02-11 18:41:53.803: E/AndroidRuntime(18334): at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2175)
02-11 18:41:53.803: E/AndroidRuntime(18334): at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1316)
02-11 18:41:53.803: E/AndroidRuntime(18334): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1513)
02-11 18:41:53.803: E/AndroidRuntime(18334): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1200)
02-11 18:41:53.803: E/AndroidRuntime(18334): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6401)
02-11 18:41:53.803: E/AndroidRuntime(18334): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:803)
02-11 18:41:53.803: E/AndroidRuntime(18334): at android.view.Choreographer.doCallbacks(Choreographer.java:603)
02-11 18:41:53.803: E/AndroidRuntime(18334): at android.view.Choreographer.doFrame(Choreographer.java:573)
02-11 18:41:53.803: E/AndroidRuntime(18334): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:789)
02-11 18:41:53.803: E/AndroidRuntime(18334): at android.os.Handler.handleCallback(Handler.java:733)
02-11 18:41:53.803: E/AndroidRuntime(18334): at android.os.Handler.dispatchMessage(Handler.java:95)
02-11 18:41:53.803: E/AndroidRuntime(18334): at android.os.Looper.loop(Looper.java:157)
02-11 18:41:53.803: E/AndroidRuntime(18334): at android.app.ActivityThread.main(ActivityThread.java:5335)
02-11 18:41:53.803: E/AndroidRuntime(18334): at java.lang.reflect.Method.invokeNative(Native Method)
02-11 18:41:53.803: E/AndroidRuntime(18334): at java.lang.reflect.Method.invoke(Method.java:515)
02-11 18:41:53.803: E/AndroidRuntime(18334): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
02-11 18:41:53.803: E/AndroidRuntime(18334): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
02-11 18:41:53.803: E/AndroidRuntime(18334): at dalvik.system.NativeStart.main(Native Method)
FavouriteFragment.java:
package com.example.sgrecipe;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
public class FavouriteFragment extends Fragment implements OnClickListener{
// Primitive Variables
String selected_ID = "";
// Widget GUI Declare
EditText txtTitle, txtDesc, txtSalary;
Button btnAdd, btnUpdate, btnDelete;
ListView lvNotes;
// DB Objects
DBHelper helper;
SQLiteDatabase db;
// Adapter Object
SimpleCursorAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_favourite_fragment, container, false);
return rootView;
}
#Override
public void onStart() {
super.onStart();
initControls();
// Init DB Objects
helper = new DBHelper(getActivity());}
// Widget GUI Init
private void initControls(){
txtTitle = (EditText)getView().findViewById(R.id.txtTitle);
txtDesc = (EditText)getView().findViewById(R.id.txtDes);
txtSalary = (EditText)getView().findViewById(R.id.txtSalary);
lvNotes = (ListView)getView().findViewById(R.id.lvNotes);
btnAdd = (Button)getView().findViewById(R.id.btnAdd);
btnUpdate = (Button)getView().findViewById(R.id.btnUpdate);
btnDelete = (Button)getView().findViewById(R.id.btnDelete);
// Attached Listener
btnAdd.setOnClickListener(this);
btnUpdate.setOnClickListener(this);
btnDelete.setOnClickListener(this);
lvNotes.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View v,
int position, long id) {
String title, desc, salary;
// Display Selected Row of Listview into EditText widget
Cursor row = (Cursor) adapter.getItemAtPosition(position);
selected_ID = row.getString(0);
title = row.getString(1);
desc = row.getString(2);
salary = row.getString(3);
txtTitle.setText(title);
txtDesc.setText(desc);
txtSalary.setText(salary);
}
});
// Fetch Data from database
fetchData();
}
#Override
public void onClick(View v) {
// Perform CRUD Operation
if (v == btnAdd) {
// Add Record with help of ContentValues and DBHelper class object
ContentValues values = new ContentValues();
values.put(DBHelper.C_TITLE, txtTitle.getText().toString());
values.put(DBHelper.C_DESCRIPTION, txtDesc.getText().toString());
values.put(DBHelper.C_SALARY, txtSalary.getText().toString());
// Call insert method of SQLiteDatabase Class and close after
// performing task
db = helper.getWritableDatabase();
db.insert(DBHelper.TABLE, null, values);
db.close();
clearFields();
Toast.makeText(this.getActivity(), "Successfully Added",
Toast.LENGTH_LONG).show();
// Fetch Data from database and display into listview
fetchData();
}
if (v == btnUpdate) {
// Update Record with help of ContentValues and DBHelper class
// object
ContentValues values = new ContentValues();
values.put(DBHelper.C_TITLE, txtTitle.getText().toString());
values.put(DBHelper.C_DESCRIPTION, txtDesc.getText().toString());
values.put(DBHelper.C_SALARY, txtSalary.getText().toString());
// Call update method of SQLiteDatabase Class and close after
// performing task
db = helper.getWritableDatabase();
db.update(DBHelper.TABLE, values, DBHelper.C_ID + "=?",
new String[] { selected_ID });
db.close();
// Fetch Data from database and display into listview
fetchData();
Toast.makeText(this.getActivity(), "Record Updated Successfully",
Toast.LENGTH_LONG).show();
clearFields();
}
if (v == btnDelete) {
// Call delete method of SQLiteDatabase Class to delete record and
// close after performing task
db = helper.getWritableDatabase();
db.delete(DBHelper.TABLE, DBHelper.C_ID + "=?",
new String[] { selected_ID });
db.close();
// Fetch Data from database and display into listview
fetchData();
Toast.makeText(this.getActivity(), "Record Deleted Successfully",
Toast.LENGTH_LONG).show();
clearFields();
}
}
// Clear Fields
private void clearFields() {
txtTitle.setText("");
txtDesc.setText("");
txtSalary.setText("");
}
// Fetch Fresh data from database and display into listview
private void fetchData() {
db = helper.getReadableDatabase();
Cursor c = db.query(DBHelper.TABLE, null, null, null, null, null, null);
adapter = new SimpleCursorAdapter(
getActivity(),
R.layout.row,
c,
new String[] { DBHelper.C_TITLE, DBHelper.C_SALARY,
DBHelper.C_DESCRIPTION },
new int[] { R.id.lblTitle, R.id.lblSalary, R.id.lblDescription });
lvNotes.setAdapter(adapter);
}
}
activity_favourite_fragment.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:focusable="true"
android:focusableInTouchMode="true"
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:layout_gravity="center"
android:text="Notes"
android:textAppearance="?android:attr/textAppearanceLarge" >
</TextView>
<EditText
android:id="#+id/txtTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Title" >
<requestFocus>
</requestFocus>
</EditText>
<EditText
android:id="#+id/txtDes"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Description" >
</EditText>
<EditText
android:id="#+id/txtSalary"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Salary" >
</EditText>
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add" >
</Button>
<Button
android:id="#+id/btnUpdate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Update Record" >
</Button>
<Button
android:id="#+id/btnDelete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete" >
</Button>
</LinearLayout>
<ListView
android:id="#+id/lvNotes"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
I am just starting off with android development, any help would be appreciated!
Your problem is in the onStart method:
public void onStart()
{
super.onStart();
initControls();
// Init DB Objects
helper = new DBHelper(getActivity());
}
Notice that you're creating your helper object AFTER calling initControls(), which then calls fetchData().
In fetchData you have this line:
db = helper.getWritableDatabase();
This is the line that causes the null pointer exception because helper is null.
Change your onStart method like so:
public void onStart()
{
super.onStart();
// Init DB Objects
helper = new DBHelper(getActivity());
initControls();
}
This should solve your problem.
helper is not initialized.
In your onStart() you're only initializing it after calling initControls() which calls fetchData() that uses helper. Move the helper initialization before the initControls() call.
Better solution, move code line:
helper = new DBHelper(getActivity());
from onStart() to onCreate() where is right place to initiate object

NullPionter Exception when passing string via Bundle

I am trying to pass a String form one activity to another in my app, however I keep getting a null pointer error. This is what shows up in my LogCat:
12-29 02:49:03.256: D/(663): HostConnection::get() New Host Connection established 0x96cb850, tid 663
12-29 02:49:06.288: W/KeyCharacterMap(663): No keyboard for id 0
12-29 02:49:06.288: W/KeyCharacterMap(663): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
12-29 02:49:09.600: D/AndroidRuntime(663): Shutting down VM
12-29 02:49:09.600: W/dalvikvm(663): threadid=1: thread exiting with uncaught exception (group=0xb5f444f0)
12-29 02:49:09.604: E/AndroidRuntime(663): FATAL EXCEPTION: main
12-29 02:49:09.604: E/AndroidRuntime(663): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.helloworld3/com.example.helloworld3.FloorPlan}: java.lang.NullPointerException
12-29 02:49:09.604: E/AndroidRuntime(663): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
12-29 02:49:09.604: E/AndroidRuntime(663): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
12-29 02:49:09.604: E/AndroidRuntime(663): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
12-29 02:49:09.604: E/AndroidRuntime(663): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
12-29 02:49:09.604: E/AndroidRuntime(663): at android.os.Handler.dispatchMessage(Handler.java:99)
12-29 02:49:09.604: E/AndroidRuntime(663): at android.os.Looper.loop(Looper.java:130)
12-29 02:49:09.604: E/AndroidRuntime(663): at android.app.ActivityThread.main(ActivityThread.java:3683)
12-29 02:49:09.604: E/AndroidRuntime(663): at java.lang.reflect.Method.invokeNative(Native Method)
12-29 02:49:09.604: E/AndroidRuntime(663): at java.lang.reflect.Method.invoke(Method.java:507)
12-29 02:49:09.604: E/AndroidRuntime(663): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
12-29 02:49:09.604: E/AndroidRuntime(663): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
12-29 02:49:09.604: E/AndroidRuntime(663): at dalvik.system.NativeStart.main(Native Method)
12-29 02:49:09.604: E/AndroidRuntime(663): Caused by: java.lang.NullPointerException
12-29 02:49:09.604: E/AndroidRuntime(663): at com.example.helloworld3.FloorPlan.onCreate(FloorPlan.java:24)
12-29 02:49:09.604: E/AndroidRuntime(663): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
12-29 02:49:09.604: E/AndroidRuntime(663): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
12-29 02:49:09.604: E/AndroidRuntime(663): ... 11 more
12-29 02:49:12.316: D/(677): HostConnection::get() New Host Connection established 0x96c5790, tid 677
This is my ManActivity.java:
package com.example.helloworld3;
import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.provider.ContactsContract.RawContacts.Data;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText destination = (EditText)findViewById(R.id.roomdinput);
final Button floorPlan = (Button)findViewById(R.id.floorPlanButton);
floorPlan.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
String roomName = destination.getText().toString();
Bundle myb = new Bundle();
myb.putString("key1", roomName);
Intent a = new Intent(MainActivity.this, FloorPlan.class);
a.putExtras(myb);
startActivity(a);
startActivity(new Intent("com.example.helloworld3.FLOORPLAN"));
}
});
}
#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;
}
#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);
}
}
And this is my FloorPan.java:
package com.example.helloworld3;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class FloorPlan extends Activity{
DrawView2 drawView;
String roomName2;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.floorplan);
Bundle myb2= getIntent().getExtras();
roomName2 = myb2.getString("key1");
drawView = new DrawView2(this);
drawView.setBackgroundResource(R.drawable.tait1st);
setContentView(drawView);
}
public class DrawView2 extends View {
Paint paint = new Paint();
float ux, dx, rx,lx;
public String getRoomName(){
return roomName2;
}
public void setCoordinates(){
if(roomName2 == "C154"){
ux =90;
dx = 250;
rx = 90;
lx = 400;
}else {
ux =76;
dx = 98;
rx = 140;
lx = 300;
}
};
public DrawView2(Context context) {
super(context);
paint.setColor(Color.RED);
//roomName2 = drawView.getTag();
}
#Override
public void onDraw(Canvas canvas) {
canvas.drawLine(ux, dx , rx, lx, paint);
canvas.drawLine(20, 0, 0, 20, paint);
canvas.drawCircle(150, 400, 30, paint);
}
}
}
Thank you for all your help!
I think , This line in OnClickListener of floorPlan in your MainActivity causing problem :
startActivity(new Intent("com.example.helloworld3.FLOORPLAN"));
putString method is correct. It's inherited from android.os.BaseBundle.
The logcat shows your bundle get from intent.getExtras() is null:
Bundle myb2= getIntent().getExtras();
roomName2 = myb2.getString("key1");//here myb2 is null
Maybe you should override onNewIntent to setIntent:
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
}
Why you have started activity 2 times in below code ?
Intent a = new Intent(MainActivity.this, FloorPlan.class);
a.putExtras(myb); startActivity(a);
startActivity(new Intent("com.example.helloworld3.FLOORPLAN")); // this intent doesnt`t have bundle
This might be the reason which lead where Bundle object is null in intent and causing nullpointerexception.

Null pointer exception on CursorAdapter

I am getting a NullPointerException. Below you can find my Logcat and the relevant code.
Logcat:
12-23 00:17:35.330: E/AndroidRuntime(2019): FATAL EXCEPTION: main
12-23 00:17:35.330: E/AndroidRuntime(2019): Process: com.android.timesheet, PID: 2019
12-23 00:17:35.330: E/AndroidRuntime(2019): java.lang.NullPointerException
12-23 00:17:35.330: E/AndroidRuntime(2019): at com.android.timesheet.adapter.CustomCursorAdapter$1.onClick(CustomCursorAdapter.java:54)
12-23 00:17:35.330: E/AndroidRuntime(2019): at android.view.View.performClick(View.java:4438)
12-23 00:17:35.330: E/AndroidRuntime(2019): at android.view.View$PerformClick.run(View.java:18422)
12-23 00:17:35.330: E/AndroidRuntime(2019): at android.os.Handler.handleCallback(Handler.java:733)
12-23 00:17:35.330: E/AndroidRuntime(2019): at android.os.Handler.dispatchMessage(Handler.java:95)
12-23 00:17:35.330: E/AndroidRuntime(2019): at android.os.Looper.loop(Looper.java:136)
12-23 00:17:35.330: E/AndroidRuntime(2019): at android.app.ActivityThread.main(ActivityThread.java:5017)
12-23 00:17:35.330: E/AndroidRuntime(2019): at java.lang.reflect.Method.invokeNative(Native Method)
12-23 00:17:35.330: E/AndroidRuntime(2019): at java.lang.reflect.Method.invoke(Method.java:515)
12-23 00:17:35.330: E/AndroidRuntime(2019): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
12-23 00:17:35.330: E/AndroidRuntime(2019): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
12-23 00:17:35.330: E/AndroidRuntime(2019): at dalvik.system.NativeStart.main(Native Method)
CustomCursorAdapter.java:
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.TextView;
import com.android.timesheet.ModifyMember;
import com.android.timesheet.R;
public class CustomCursorAdapter extends CursorAdapter {
Button delete_btn;
TextView memID_tv, memName_tv;
#SuppressWarnings("deprecation")
public CustomCursorAdapter(Activity context, Cursor c) {
super(context, c);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// when the view will be created for first time,
// we need to tell the adapters, how each item will look
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View retView = inflater.inflate(R.layout.single_row_item, parent, false);
return retView;
}
#Override
public void bindView(View view, final Context context, Cursor cursor) {
// here we are setting our data
// that means, take the data from the cursor and put it in views
TextView textViewPersonName = (TextView) view.findViewById(R.id.tv_person_name);
textViewPersonName.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(1))));
delete_btn=(Button)view.findViewById(R.id.delete_btn);
delete_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
memID_tv = (TextView)v.findViewById(R.id.member_id);
memName_tv = (TextView)v.findViewById(R.id.member_name);
String memberID_val = memID_tv.getText().toString();; ---->54th Line
String memberName_val = memName_tv.getText().toString();
Intent i = new Intent(context,
ModifyMember.class);
i.putExtra("memberName", memberName_val);
i.putExtra("memberID", memberID_val);
((Activity)context).startActivity(i);
}
});
}
}
I am using a delete button to delete all the listview row items. At that point I am getting the NullPointerException.
Use view(view of row) instead of v parameter of onClick method which is view of Button :
delete_btn=(Button)view.findViewById(R.id.delete_btn);
delete_btn.setTag(view);
delete_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View rowview=(View)v.getTag();
memID_tv = (TextView)rowview.findViewById(R.id.member_id);
memName_tv = (TextView)rowview.findViewById(R.id.member_name);
}
});
Use view instead of v
memID_tv = (TextView)view.findViewById(R.id.member_id);
In bindview try this-
if (view == null) {
view = inflater.inflate(R.layout.single_row_item, parent, null);
}
TextView textViewPersonName = (TextView) view.findViewById(R.id.tv_person_name);
textViewPersonName.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(1))));
delete_btn=(Button)view.findViewById(R.id.delete_btn);
.
.
.
you are getting the view from clicked view, but you have to get the views from the root view.
memID_tv = (TextView)v. findViewById(R.id.member_id);
memName_tv = (TextView)v.findViewById(R.id.member_name);
change these lines into this:
memID_tv = (TextView)view. findViewById(R.id.member_id);
memName_tv = (TextView)view.findViewById(R.id.member_name);

Display random month from a button click on android?

I am trying to create an app that lets the user click a button and it will display a random month. I have created a string array in my strings.xml file. Bellow is my main.java, strings.xml and activity.xml. I try to run the app and it just force closes.
package com.example.datebutton;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.graphics.Color;
public class Main extends Activity
{
Button btn;
#Override
public void onCreate(Bundle b)
{
super.onCreate(b);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.btn1);
final String[] months = getResources().getStringArray(R.array.Months);
final TextView tv =(TextView)findViewById(R.id.text1);
btn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
int rand = (int) (Math.random() * 12);
tv.setText(months[rand]);
}
});
}
}
here is my activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:id="#+id/btn1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="updateMonth"
android:text="#string/app_name" />
<TextView
android:id="#+id/text1"
android:layout_width="68dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center_vertical"
android:text="#array/Months" />
</LinearLayout>
here is my strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">DateButton</string>
<string-array name="Months">
<item>January</item>
<item>Feburary</item>
<item>March</item>
<item>April</item>
<item>May</item>
<item>June</item>
<item>July</item>
<item>August</item>
<item>September</item>
<item>October</item>
<item>November</item>
<item>December</item>
</string-array>
</resources>
I'm still getting errors and the app still says unfortunately your app closed. The logcat is below.
09-11 16:55:17.472: W/Resources(1638): Converting to string: TypedValue{t=0x1/d=0x7f0c0000 a=-1 r=0x7f0c0000}
09-11 16:55:17.512: D/AndroidRuntime(1638): Shutting down VM
09-11 16:55:17.512: W/dalvikvm(1638): threadid=1: thread exiting with uncaught exception (group=0xb3a8fba8)
09-11 16:55:17.532: E/AndroidRuntime(1638): FATAL EXCEPTION: main
09-11 16:55:17.532: E/AndroidRuntime(1638): Process: com.example.datebutton, PID: 1638
09-11 16:55:17.532: E/AndroidRuntime(1638): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.datebutton/com.example.datebutton.Main}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.Button
09-11 16:55:17.532: E/AndroidRuntime(1638): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
09-11 16:55:17.532: E/AndroidRuntime(1638): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
09-11 16:55:17.532: E/AndroidRuntime(1638): at android.app.ActivityThread.access$800(ActivityThread.java:135)
09-11 16:55:17.532: E/AndroidRuntime(1638): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
09-11 16:55:17.532: E/AndroidRuntime(1638): at android.os.Handler.dispatchMessage(Handler.java:102)
09-11 16:55:17.532: E/AndroidRuntime(1638): at android.os.Looper.loop(Looper.java:136)
09-11 16:55:17.532: E/AndroidRuntime(1638): at android.app.ActivityThread.main(ActivityThread.java:5017)
09-11 16:55:17.532: E/AndroidRuntime(1638): at java.lang.reflect.Method.invokeNative(Native Method)
09-11 16:55:17.532: E/AndroidRuntime(1638): at java.lang.reflect.Method.invoke(Method.java:515)
09-11 16:55:17.532: E/AndroidRuntime(1638): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
09-11 16:55:17.532: E/AndroidRuntime(1638): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
09-11 16:55:17.532: E/AndroidRuntime(1638): at dalvik.system.NativeStart.main(Native Method)
09-11 16:55:17.532: E/AndroidRuntime(1638): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.Button
09-11 16:55:17.532: E/AndroidRuntime(1638): at com.example.datebutton.Main.onCreate(Main.java:24)
09-11 16:55:17.532: E/AndroidRuntime(1638): at android.app.Activity.performCreate(Activity.java:5231)
09-11 16:55:17.532: E/AndroidRuntime(1638): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
09-11 16:55:17.532: E/AndroidRuntime(1638): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
09-11 16:55:17.532: E/AndroidRuntime(1638): ... 11 more
You forgot to add the line: setContentView(R.layout.activity); before trying to instantiate your button object btn.
To use layout in you Activity you have to connect them both together. Below is how your code should look like:
#Override
public void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.activity);
btn = (Button) findViewById(R.id.btn1);
final String[] months = getResources().getStringArray(R.array.Months);
final TextView tv =(TextView)findViewById(R.id.text1);
btn.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
int r, g, b;
int rand = (int) (Math.random() * 12);
tv.setText(months[rand]);
}
});
}

Getting a DialogFragment to instantiate

I am new to Android.
Trying to show a dialog on press of a button like below using DialogFragments
File : Dialog2/LoginDialog.java
package com.kartnet.Dialog2;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.LayoutInflater;
import android.widget.Toast;
import android.content.Context;
import android.app.Dialog;
import android.content.DialogInterface;
import android.app.AlertDialog;
import android.app.DialogFragment;
import android.util.Log;
public class LoginDialog extends DialogFragment
{
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder ad_builder = new AlertDialog.Builder(getActivity());
//ad_builder.setMessage(R.string.login_dialog);
DialogInterface.OnClickListener ad_listener =
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dlg1, int id) {
final String tag = "CustomDlg";
Log.d(tag, id + " clicked");
}
};
ad_builder.setTitle(R.string.btn_dialog_custom_title);
LayoutInflater linf = getActivity().getLayoutInflater();
ad_builder.setView(linf.inflate(R.layout.dialog_signin, null));
ad_builder.setNegativeButton("Cancel", ad_listener);
ad_builder.setPositiveButton("Ok", ad_listener);
return ad_builder.create();
}
}
File : Dialog2/Dialog2App.java
package com.kartnet.Dialog2;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.LayoutInflater;
import android.widget.Toast;
import android.content.Context;
import android.app.Dialog;
import android.content.DialogInterface;
import android.app.DialogFragment;
import android.app.AlertDialog;
import android.util.Log;
public class Dialog2App extends Activity
{
/* Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void displayDialogCustom(View v)
{
LoginDialog ld = new LoginDialog(); /*<<=== FAILS with runtime exception */
// ld.show(getFragmentManager(), "login_dialog");
} /* displayCustomDialog */
}
Why should it fail at runtime, with no errors during compile time? Also, since both files are declared to be in the same package (com.kartnet.Dialog2), is there anything special I need to get these two java files to be in the application?
Here is what the error displayed
I/ActivityManager( 69): Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=com.kartnet.Dialog2/.Dialog2App } from pid 210
I/ActivityManager( 69): Start proc com.kartnet.Dialog2 for activity com.kartnet.Dialog2/.Dialog2App: pid=1328 uid=10034 gids={1015}
W/dalvikvm( 1328): Unable to resolve superclass of Lcom/kartnet/Dialog2/LoginDialog; (7)
W/dalvikvm( 1328): Link of class 'Lcom/kartnet/Dialog2/LoginDialog;' failed
E/dalvikvm( 1328): Could not find class 'com.kartnet.Dialog2.LoginDialog', referenced from method com.kartnet.Dialog2.Dialog2App.displayDialogCustom
W/dalvikvm( 1328): VFY: unable to resolve new-instance 25 (Lcom/kartnet/Dialog2/LoginDialog;) in Lcom/kartnet/Dialog2/Dialog2App;
D/dalvikvm( 1328): VFY: replacing opcode 0x22 at 0x0000
D/dalvikvm( 1328): VFY: dead code 0x0002-0005 in Lcom/kartnet/Dialog2/Dialog2App;.displayDialogCustom (Landroid/view/View;)V
I/ActivityManager( 69): Displayed com.kartnet.Dialog2/.Dialog2App: +1s956ms
D/dalvikvm( 317): GC_EXPLICIT freed 19K, 55% free 2588K/5703K, external 1625K/2137K, paused 3208ms
D/AndroidRuntime( 1328): Shutting down VM
W/dalvikvm( 1328): threadid=1: thread exiting with uncaught exception (group=0x40015560)
E/AndroidRuntime( 1328): FATAL EXCEPTION: main
E/AndroidRuntime( 1328): java.lang.IllegalStateException: Could not execute method of the activity
E/AndroidRuntime( 1328): at android.view.View$1.onClick(View.java:2144)
E/AndroidRuntime( 1328): at android.view.View.performClick(View.java:2485)
E/AndroidRuntime( 1328): at android.view.View$PerformClick.run(View.java:9080)
E/AndroidRuntime( 1328): at android.os.Handler.handleCallback(Handler.java:587)
E/AndroidRuntime( 1328): at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime( 1328): at android.os.Looper.loop(Looper.java:123)
E/AndroidRuntime( 1328): at android.app.ActivityThread.main(ActivityThread.java:3683)
E/AndroidRuntime( 1328): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime( 1328): at java.lang.reflect.Method.invoke(Method.java:507)
E/AndroidRuntime( 1328): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
E/AndroidRuntime( 1328): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
E/AndroidRuntime( 1328): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime( 1328): Caused by: java.lang.reflect.InvocationTargetException
E/AndroidRuntime( 1328): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime( 1328): at java.lang.reflect.Method.invoke(Method.java:507)
E/AndroidRuntime( 1328): at android.view.View$1.onClick(View.java:2139)
E/AndroidRuntime( 1328): ... 11 more
E/AndroidRuntime( 1328): Caused by: java.lang.NoClassDefFoundError: com.kartnet.Dialog2.LoginDialog
E/AndroidRuntime( 1328): at com.kartnet.Dialog2.Dialog2App.displayDialogCustom(Dialog2App.java:104)
E/AndroidRuntime( 1328): ... 14 more
Based on the attached log, it appears you're trying to run the code on an older device which does not offer native support to Fragments:
Unable to resolve superclass of Lcom/kartnet/Dialog2/LoginDialog;
Above basically means that android.app.DialogFragment could not be resolved, which will happen on pre-Honeycomb (< Android 3.0 / API level 11) devices. You were probably looking for the backwards compatible Fragment classes that are part of the support library (in the android.support.v4.app.* package).
To migrate your code to the classes in the support libary, you should:
Set up the support library.
Change all android.app.DialogFragment references to android.support.v4.app.DialogFragment (and also any other Fragment classes you may be using).
Change your Activity to a FragmentActivity (also located in the support libary).
Use this dialog manager to display simple dialogs.
public class AlertDialogManager {
/**
* Function to display simple Alert Dialog
* #param context - application context
* #param title - alert dialog title
* #param message - alert message
* #param status - success/failure (used to set icon)
* - pass null if you don't want icon
* */
public void showAlertDialog(Context context, String title, String message,
Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
if(status != null)
// Setting alert dialog icon
alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
// Showing Alert Message
alertDialog.show();
}
}
In your activity you can use this
alert.showAlertDialog(MainActivity.this,"Header","Message", false);
Try this:
Properties->Java Build Path->Order and Export and check Android Private Libraries
You can try to create the dialog before you return it with
Dialog d = ad_builder.create();
return d;
to see if it fail to create the dialog.
DialogFragment are singletons, so you cannot do:
LoginDialog ld = new LoginDialog(); /*<<=== FAILS with runtime exception */
you should use LoginDialog.instantiate(...) method

Categories