user2057220
user2057220

Reputation: 33

NullPointeException on StartActivity from button

I'm trying to launch an actvivity via onClickListener of a button, and always I get Null pointer exception. I've searched and tried a lot of different things, and I cannot find where I have made a mistake. Here is the related code/classes

The crashing activity:

    public class DisplayData extends Activity{

    TextView displayData;
    DataObjectsProvider provider;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.displaydb);

        provider = new DataObjectsProvider(this);
        displayData = (TextView) findViewById(R.id.tvDisplayData);      
        displayData.setText(provider.getAlldobjects().toString());
    }

}

(I've tried commended out the provider and setText code)

The onClickListener from the working main activity:

bDisplay.setOnClickListener(new OnClickListener(){

        public void onClick(View v) {
            // TODO Auto-generated method stub
             Intent intent = new Intent(MainActivity.this, DisplayData.class);
            startActivity(intent);
        }

    });

Here is the layout for the crashing activity:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/scrollView1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView
       android:id="@+id/tvDisplayData"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="showData"
       android:textAppearance="?android:attr/textAppearanceMedium" />

</ScrollView>

(I've already tried and with only a linear layout and textview)

and here is the Android manifest code:

<activity
        android:name=".MainActivity"
        android:label="@string/title_activity_main" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

   <activity
        android:name=".DisplayData"
        android:label="" >
    </activity>

Am I doing something wrong? Is there any mistake which I don't see or I'm missing something?

EDIT: log:

02-09 23:52:35.002: W/dalvikvm(24849): threadid=1: thread exiting with uncaught exception (group=0x40c971f8) 02-09 23:52:35.052: E/AndroidRuntime(24849): FATAL EXCEPTION: main 02-09 23:52:35.052: E/AndroidRuntime(24849): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.d69.dancesongsdb/com.d69.dancesongsdb.DisplayData}: java.lang.NullPointerException 02-09 23:52:35.052: E/AndroidRuntime(24849): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956) 02-09 23:52:35.052: E/AndroidRuntime(24849): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981) 02-09 23:52:35.052: E/AndroidRuntime(24849): at android.app.ActivityThread.access$600(ActivityThread.java:123) 02-09 23:52:35.052: E/AndroidRuntime(24849): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147) 02-09 23:52:35.052: E/AndroidRuntime(24849): at android.os.Handler.dispatchMessage(Handler.java:99) 02-09 23:52:35.052: E/AndroidRuntime(24849): at android.os.Looper.loop(Looper.java:137) 02-09 23:52:35.052: E/AndroidRuntime(24849): at android.app.ActivityThread.main(ActivityThread.java:4424) 02-09 23:52:35.052: E/AndroidRuntime(24849): at java.lang.reflect.Method.invokeNative(Native Method) 02-09 23:52:35.052: E/AndroidRuntime(24849): at java.lang.reflect.Method.invoke(Method.java:511) 02-09 23:52:35.052: E/AndroidRuntime(24849): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:787) 02-09 23:52:35.052: E/AndroidRuntime(24849): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554) 02-09 23:52:35.052: E/AndroidRuntime(24849): at dalvik.system.NativeStart.main(Native Method) 02-09 23:52:35.052: E/AndroidRuntime(24849): Caused by: java.lang.NullPointerException 02-09 23:52:35.052: E/AndroidRuntime(24849): at com.d69.dancesongsdb.DataObjectsProvider.getAlldobjects(DataObjectsProvider.java:58) 02-09 23:52:35.052: E/AndroidRuntime(24849): at com.d69.dancesongsdb.DisplayData.onCreate(DisplayData.java:19) 02-09 23:52:35.052: E/AndroidRuntime(24849): at android.app.Activity.performCreate(Activity.java:4465) 02-09 23:52:35.052: E/AndroidRuntime(24849): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049) 02-09 23:52:35.052: E/AndroidRuntime(24849): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920) 02-09 23:52:35.052: E/AndroidRuntime(24849): ... 11 more

EDIT2 I've abandoned db4o and recreated my classes with sqlite instead. But this error still happens on the activity. I've edited the code of crashing activity also. The latest line(which use the provider) is the one which causes the crash. I've tested it on the main activity by changing the the code of the button which start the activity with the below code:

public void onClick(View v) {       
    Toast.makeText(MainActivity.this, provider.getAlldobjects().toString(), Toast.LENGTH_LONG).show();

and the database' s items displaying correct on toast. On the main activity(from which is the above code) I've declared the DataObjectsProvider class with exactly the same way as on the crashing activity. I cannot understand why on the one activity works and not on the other.

DataObjectsProvider:

public class DataObjectsProvider {

  // Database fields
  private SQLiteDatabase database;
  private DbHelper dbHelper;
  private String[] allColumns = { DbHelper.COLUMN_ID,
      DbHelper.COLUMN_SONGNAME, DbHelper.COLUMN_SONGARTIST, DbHelper.COLUMN_SONGGENRE };

  public DataObjectsProvider (Context context) {
        dbHelper = new DbHelper(context);
      }

  public void open() throws SQLException {
        database = dbHelper.getWritableDatabase();
      }

      public void close() {
        dbHelper.close();
      }

      public DataObjects createDataObjects (String songName, String songArtist, String songGenre){
        ContentValues values = new ContentValues();
        values.put(DbHelper.COLUMN_SONGNAME, songName + ", ");
        values.put(DbHelper.COLUMN_SONGARTIST, songArtist + ", ");
        values.put(DbHelper.COLUMN_SONGGENRE, songGenre);
        long insertId = database.insert(DbHelper.TABLE_SONGS, null,
                values);
            Cursor cursor = database.query(DbHelper.TABLE_SONGS,
                allColumns, DbHelper.COLUMN_ID + " = " + insertId, null,
                null, null, null);
            cursor.moveToFirst();
            DataObjects newDobject = cursorToDataObjects(cursor);
            cursor.close();
            return newDobject;

      }

      public void deleteDobjects(DataObjects dobjects) {
            long id = dobjects.getId();
            System.out.println("Comment deleted with id: " + id);
            database.delete(DbHelper.TABLE_SONGS, DbHelper.COLUMN_ID
                + " = " + id, null);
          }

      public List<DataObjects> getAlldobjects() {
            List<DataObjects> dobjects = new ArrayList<DataObjects>();

            Cursor cursor = database.query(DbHelper.TABLE_SONGS,
                allColumns, null, null, null, null, null);

            cursor.moveToFirst();
            while (!cursor.isAfterLast()) {
              DataObjects dobject = cursorToDataObjects(cursor);
              dobjects.add(dobject);
              cursor.moveToNext();
            }
            // Make sure to close the cursor
            cursor.close();
            return dobjects;
          }

    private DataObjects cursorToDataObjects(Cursor cursor) {
        DataObjects dobject = new DataObjects();
        dobject.setId(cursor.getLong(0));
        dobject.setSongName(cursor.getString(1));
        dobject.setSongArtist(cursor.getString(2));
        dobject.setSongGenre(cursor.getString(3));
        return dobject;
    }

}

Upvotes: 0

Views: 130

Answers (2)

user2057220
user2057220

Reputation: 33

Finally, searching and reading decreased my stupidity. I was trying to query without to first open the database. On the MainActivity, database was opened from another method call(to store items), but on DisplayData activity wasn't. So needed first to use:

provider.open();

and then:

provider.getAllObjects();

Upvotes: 0

jelgh
jelgh

Reputation: 706

Hard to see what the problem is without a stacktrace (post one).

But from what I can see it looks like the NPE could come from any of these two rows:

displayData = (TextView) findViewById(R.id.tvDisplayData);      
displayData.setText(provider.list.toString());

Either displayData (the TextView) is null, or the provider's list. Are you sure you are creating the list in the constructor of the provider?

EDIT:

The error is at row 24 in your DataObjectsProvider:

"at com.d69.dancesongsdb.DataObjectsProvider.(DataObjectsProvider.java:24)"

EDIT2:

You never called open. Hence the database object is null. There's your crash. You can also check if your cursor you retrieve from that query is null before doing the move to operations on it.

Upvotes: 1

Related Questions