0

I am new to programming in Java for Android programming. I am creating an activity that displays an ArrayList that I created from a database.

The array works perfectly in my main activity, but when I try to display and call the method in another activity, it displays the following message:

java.lang.RuntimeException: Unable to start activity >ComponentInfo{com.example.carlos.application1/com.example.carlos.application1.ema>il}: java.lang.NullPointerException: Attempt to invoke virtual method >'java.util.ArrayList com.example.carlos.application1.DBHelper.getAllCotacts()' on >a null object reference

What is happening here? Why is there a NullPointerException? I have to initialized?

Activity:

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.ArrayAdapter;
import java.util.ArrayList;

/**
 * Created by Carlos on 16/05/2016.
 */
public class email extends Activity {

    private Button send;
    DBHelper mydb1;
    private ListView obj;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.email_display);
        ArrayList array_list = mydb1.getAllCotacts();
        ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, array_list);
        //ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, array_list);
        //obj = (ListView) findViewById(R.id.listView1);
        //obj.setAdapter(arrayAdapter);

        send = (Button) findViewById(R.id.send_button);

        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    Intent emailIntent = new Intent(Intent.ACTION_SEND);
                    emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] {
                        "example@gmail.com"
                    });
                    emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
                    emailIntent.putExtra(Intent.EXTRA_TEXT, "HEY");
                    emailIntent.putExtra(Intent.EXTRA_CC, "example@gmail.com");
                    emailIntent.setType("message/rfc822");
                    startActivity(emailIntent);
                } catch (ActivityNotFoundException anfe) {
                    Toast toast = Toast.makeText(email.this, "Sorry, no email client found", Toast.LENGTH_LONG);
                    toast.show();
                }
            }
        });
    }
}

Database Handler

package com.example.carlos.application1;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;

public class DBHelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "MyDBName.db";
    public static final String CONT_TABLE_NAME = "tablename";
    public static final String CONT_COLUMN_ID = "id";
    public static final String CONT_COLUMN_CONDUCTIVITY = "conductivity";
    public static final String CONT_COLUMN_MOISTURE = "moisture";
    public static final String CONT_COLUMN_OXYGEN = "oxygen";
    public static final String CONT_COLUMN_PH = "ph";

    private HashMap hp;

    public DBHelper(Context context)
    {
        super(context, DATABASE_NAME , null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL(
                "create table tablename " +
                        "(id integer primary key, conductivity text,ph text,oxygen text, moisture text)"
        );
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        db.execSQL("DROP TABLE IF EXISTS tablename");
        onCreate(db);
    }

    public boolean insertContact  (String conductivity, String ph, String oxygen, String moisture)
    {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("conductivity", conductivity);
        contentValues.put("ph", ph);
        contentValues.put("oxygen", oxygen);
        contentValues.put("moisture", moisture);

        db.insert("tablename", null, contentValues);
        return true;
    }

    public Cursor getData(int id){
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res =  db.rawQuery( "select * from tablename where id="+id+"", null );
        return res;
    }

    public int numberOfRows(){
        SQLiteDatabase db = this.getReadableDatabase();
        int numRows = (int) DatabaseUtils.queryNumEntries(db, CONT_TABLE_NAME);
        return numRows;
    }

    public boolean updateContact (Integer id, String conductivity, String ph, String oxygen, String moisture)
    {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("conductivity", conductivity);
        contentValues.put("ph", ph);
        contentValues.put("oxygen", oxygen);
        contentValues.put("moisture", moisture);

        db.update("tablename", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
        return true;
    }

    public Integer deleteContact (Integer id)
    {
        SQLiteDatabase db = this.getWritableDatabase();
        return db.delete("tablename",
                "id = ? ",
                new String[] { Integer.toString(id) });
    }

    public ArrayList<String> getAllCotacts()
    {
        ArrayList<String> array_list = new ArrayList<String>();

        //hp = new HashMap();
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res =  db.rawQuery( "select * from tablename", null );
        res.moveToFirst();

        while(res.isAfterLast() == false){
            array_list.add(res.getString(res.getColumnIndex(CONT_COLUMN_CONDUCTIVITY)));
            res.moveToNext();
        }
        return array_list;
    }
}
Chris Forrence
  • 10,042
  • 11
  • 48
  • 64

3 Answers3

4

It looks like you're trying to call a method on a object that you haven't instantiated yet. Before you do this...

ArrayList array_list = mydb1.getAllCotacts();

...add a line like this somewhere in your onCreate method:

mydb1 = new DBHelper(this);

Until you've actually created a DBHelper, you can't call methods on it. That's what the message 'Attempt to invoke virtual method DBHelper.getAllCotacts() on a null object reference' means.

Joshua Carmody
  • 13,410
  • 16
  • 64
  • 83
0

You need to initialize mydb1. mydb1 = new DBHelper(mycontext);

aleb2000
  • 452
  • 4
  • 10
0

You forgot to initialize it :( like this :

mydb1 = new DBHelper(this);

then call the get method from it .

ArrayList array_list = mydb1.getAllCotacts();
Omar
  • 458
  • 2
  • 10