0

This is my code for database class (DatabaseHelper.java)

public Cursor getAllData(){
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor res = db.rawQuery("select * from "+TABLE_NAME,null);
        return res;
    }

This is another class which is (MainSuggestion.java)

public class MenuSuggestion extends AppCompatActivity {
    DatabaseHelper myDb;
    @Override 
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_menu_suggestion);
<br/>
        Cursor res = myDb.getAllData();
        if (res.moveToFirst()) {             
            TextView bmi = (TextView) findViewById(R.id.textView9);
            TextView kcal = (TextView) findViewById(R.id.textView10);
            bmi.setText(res.getString(3));
            kcal.setText(res.getString(4));
        }
    }
}

Can someone tell me, what's wrong with my code?

11
  • Did you check that you actually have records in your cursor? Commented Oct 15, 2015 at 14:41
  • are you seeing any error message? post it here. Also do db calls on background threads the simplest one is to use asynctasks. Commented Oct 15, 2015 at 14:41
  • There is no error message, but when I run it using emulator, the emulator shows "Unfortunately, MnutriHealth has stopped". Commented Oct 15, 2015 at 14:43
  • Then you need to post the stacktrace, else we don't have any way to help you. Commented Oct 15, 2015 at 14:43
  • 1
    there is no recursion :) Commented Oct 15, 2015 at 15:12

2 Answers 2

4

The exact reason this isn't working is because "myDb" is null on this line.

 Cursor res = myDb.getAllData();

However, I recommend you Running a Query with a CursorLoader. It might seem overkill, loading stuff from the database on the main thread like you are can lead to ANR errors.

Sign up to request clarification or add additional context in comments.

Comments

0

Query data from database, you have to use:

this.getReadableDatabase();

You use getWritableDatabase() when you want to write, update, delete data into/from database.

6 Comments

This is good as a recommendation but it is still possible to read from writable databse, so this could not be the cause for the error.
@MoLab why dont you provide what you are asked? post the error if you want a solution.
Is it the main activity? if not, did you add this class in Manifest ?
@DegenSharew There is no error but when I run it using emulator, the emulator shows "Unfortunately, MnutriHealth has stopped".
@MoLab check the log cat there is always an error logged there when app crashes this way.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.