Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9051055
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T12:48:43+00:00 2026-06-16T12:48:43+00:00

As the title says I get a NullPointerException when I try to get a

  • 0

As the title says I get a NullPointerException when I try to get a list from a database. Here is the code:

public List<String> getAllRockBands() {
     List<String> bandList = new ArrayList<String>();

     String selection = BAND_GENRE + "=1";

     SQLiteDatabase db = sqLiteHelper.getReadableDatabase();
     Cursor cursor = db.query(BANDDATABASE_TABLE,new String[]{BAND_NAME}, selection, null, null, null, BAND_NAME);

     int index = cursor.getColumnIndex(BAND_NAME);

     if (cursor.moveToFirst()) {
         do {
          String bandName = cursor.getString(index);
             bandList.add(bandName);
         } while (cursor.moveToNext());
     }

     return bandList;
 }

`

public class RockAllFragment extends SherlockListFragment {

    private BandDatabaseAdapter mySQLiteAdapter;
    private List<String> bandList = mySQLiteAdapter.getAllRockBands();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    return inflater.inflate(R.layout.my_list, null);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onViewCreated(view, savedInstanceState);

    setListAdapter(new ArrayAdapter<String>(getSherlockActivity(), android.R.layout.simple_list_item_multiple_choice, android.R.id.text1, bandList));
    }
}

I am still learning to code in this environment, so I guess this is just some beginner mistake?

EDIT: (it’s a bit much but you asked)

public class BandDatabaseAdapter {

 private static final String TAG = "BandDatabase";

 private static final String BANDDATABASE_NAME = "BAND_DATABASE";
 private static final String BANDDATABASE_TABLE = "BAND_TABLE";
 private static final int BANDDATABASE_VERSION = 1;
 public static final String BAND_NAME = "name";
 public static final String BAND_GENRE = "genre";
 public static final String BAND_POPULAR = "popular";
 public static final String BAND_SELECTED = "selected";

 private static final String BANDDATABASE_CREATE="CREATE TABLE IF NOT EXISTS " + BANDDATABASE_TABLE
 + " (_id integer primary key autoincrement, " + BAND_NAME
 + " TEXT NOT NULL, " + BAND_GENRE + " TEXT NOT NULL, " + BAND_POPULAR
 + " TEXT NOT NULL, " + BAND_SELECTED + " TEXT NOT NULL)";

 private SQLiteHelper sqLiteHelper;
 private SQLiteDatabase sqLiteDatabase;
 private final Context context;

 public BandDatabaseAdapter(Context c) {
       sqLiteHelper = new SQLiteHelper(c, BANDDATABASE_NAME, null, BANDDATABASE_VERSION);
       context = c;
    }

 public BandDatabaseAdapter openToRead() throws android.database.SQLException {
  sqLiteDatabase = sqLiteHelper.getReadableDatabase();
  return this; 
 }

 public BandDatabaseAdapter openToWrite() throws android.database.SQLException {
  sqLiteDatabase = sqLiteHelper.getWritableDatabase();
  return this; 
 }

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

 public void updateBand(String name, String selected) {
     ContentValues contentValues = new ContentValues();
     contentValues.put(BAND_SELECTED, selected);
     sqLiteDatabase.update(BANDDATABASE_TABLE, contentValues, "BAND_NAME=" + name, null);
     close();
 }

 public List<String> getAllRockBands() {
     List<String> bandList = new ArrayList<String>();

     String selection = BAND_GENRE + "=1";

     SQLiteDatabase db = sqLiteHelper.getReadableDatabase();
     Cursor cursor = db.query(BANDDATABASE_TABLE,new String[]{BAND_NAME}, selection, null, null, null, BAND_NAME);

     if(cursor!=null)
     {
     int index = cursor.getColumnIndex(BAND_NAME);

     if (cursor.moveToFirst()) {
         do {
          String bandName = cursor.getString(index);
             bandList.add(bandName);
         } while (cursor.moveToNext());
     }
     }
     return bandList;
 }

 public List<String> getMyList() {
     List<String> myList = new ArrayList<String>();

     String selection = BAND_SELECTED + "=1";

     SQLiteDatabase db = sqLiteHelper.getReadableDatabase();
     Cursor cursor = db.query(BANDDATABASE_TABLE,new String[]{BAND_NAME}, selection, null, null, null, BAND_NAME);

     int index = cursor.getColumnIndex(BAND_NAME);

     if (cursor.moveToFirst()) {
         do {
          String bandName = cursor.getString(index);
             myList.add(bandName);
         } while (cursor.moveToNext());
     }

     return myList;
 }

 public class SQLiteHelper extends SQLiteOpenHelper {

  public SQLiteHelper(Context context, String name,
    CursorFactory factory, int version) {
   super(context, name, factory, version);
  }

  private boolean doesDatabaseExist(Context context, String dbName) {
        File dbFile=context.getDatabasePath(dbName);
        return dbFile.exists();
    }

  @Override
  public void onCreate(SQLiteDatabase db) {
   // TODO Auto-generated method stub
   if(!(doesDatabaseExist(context,BANDDATABASE_NAME)))
   {
      db.execSQL(BANDDATABASE_CREATE);
      loadDatabase();
   }
  }

  /**
   * Starts a thread to load the database table with bands
   */
  private void loadDatabase() {
      new Thread(new Runnable() {
          public void run() {
              try {
                  loadBands();
              } catch (IOException e) {
                  throw new RuntimeException(e);
              }
          }
      }).start();
  }

  //loads a database from a txt file
  private void loadBands() throws IOException {
      Log.d(TAG, "Loading bands...");
      final Resources resources = context.getResources();
      InputStream inputStream = resources.openRawResource(R.raw.bands);
      BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

      try {
          String line;
          while ((line = reader.readLine()) != null) {
              String[] strings = TextUtils.split(line, "^");
              if (strings.length < 4) continue;
              long id = addBand(strings[0].trim(), strings[1].trim(), strings[2].trim());
              if (id < 0) {
                  Log.e(TAG, "unable to add band: " + strings[0].trim());
              }
          }
      } finally {
          reader.close();
      }
      Log.d(TAG, "DONE loading words.");
  }

  public long addBand(String name, String genre, String popular) {
      ContentValues initialValues = new ContentValues();
      initialValues.put(BAND_NAME, name);
      initialValues.put(BAND_GENRE, genre);
      initialValues.put(BAND_POPULAR, popular);
      initialValues.put(BAND_SELECTED, "0");

      return sqLiteDatabase.insert(BANDDATABASE_TABLE, null, initialValues);
  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
   // TODO Auto-generated method stub
    // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + BANDDATABASE_TABLE);

        // Create tables again
        onCreate(db);
  }

 }

}

Additional info: Some people have told me to use SimpleCursorAdapter, but it says it is deprecated. Also, note that my list has over 150k rows, tho I will greatly lessen that if the need arises. 🙂

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-16T12:48:44+00:00Added an answer on June 16, 2026 at 12:48 pm

    It looks like you haven’t created SqliteHelper Class object before calling getAllRockBands() Please check that once or else post your SqliteHelper Class Constructor code

    Changing your code here check it.

    public class RockAllFragment extends SherlockListFragment {
    
        private BandDatabaseAdapter mySQLiteAdapter;
        private List<String> bandList;
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
    
        return inflater.inflate(R.layout.my_list, null);
        }
    
        @Override
        public void onViewCreated(View view, Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onViewCreated(view, savedInstanceState);
        mySQLiteAdapter= new BandDatabaseAdapter(getSherlockActivity());
        bandList  = mySQLiteAdapter.getAllRockBands();
    
        setListAdapter(new ArrayAdapter<String>(getSherlockActivity(), android.R.layout.simple_list_item_multiple_choice, android.R.id.text1, bandList));
        }
    }
    

    you got NullPointerException because you have declared BandDatabaseAdapter but not created its instance. you need create its instance and then call it. in the above code I have created the object first and then called. Hope it helps you.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Title says all. Sample code: ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>(); HashMap<String, Object>
as the title says, I keep getting undefined when I try to get the
Like the title says, I can't get Canvas/CanvasLayer working in PlayN. My sample code
Well I think my title says it... Using following code: public int getCorrectAnswersPrev(int level,
As the title says, I want to get the wireless signal strength from adapter
As the title says, I cannot get padding around the text. Here's my xml:
so as the title says..... here is the code I currently wrote thinking it
As the title says I am trying to get help simplifing my code. I
As the title says, I want to get my database to a known state
As the title says, is it possible to get the holidays from the android

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.