Working on developing a Class for my android app that will randomly generate NPCs and their stats. Since these methods will be called in different activities figured putting them in their own class would be best. Yet having some trouble getting the cursors they contain to work correctly.
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
public class startscreen extends Activity {
private dbhelper mydbhelper;
Intent intent;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.startscreen);
mydbhelper = dbhelper.getInstance(startscreen.this);
}
public void onClickNew(View v){
intent = new Intent(getBaseContext(), newgame.class);
startActivity(intent);
}
public void onClickLoad(View v){
//intent = new Intent(getBaseContext(), mainmenu.class);
//startActivity(intent);
Generator obj = new Generator();
obj.randomName();
}
I am calling the method on this bottom button to my main menu for easy testing.
import java.util.Random;
import android.database.Cursor;
import android.util.Log;
public class Generator {
public dbhelper mydbhelper;
public String randomName(){
Cursor name;
Random nameRandom = new Random();
int first = nameRandom.nextInt(171)+1;
name = mydbhelper.getRandomName(first); //This is where I get the error. "NullPointerException"
String firstName = name.getString(name.getColumnIndex(dbhelper.KEY_FIRST));
int last = nameRandom.nextInt(245)+1;
name = mydbhelper.getRandomName(last);
String lastName = name.getString(name.getColumnIndex(dbhelper.KEY_LAST));
String fullName = firstName + " " + lastName;
Log.e(fullName, "was the generated name");
return fullName;
}
}
If I take out the cursors and put in a stat string to return it works fine. So I’m handling this cursors incorrectly. Sadly Singleton and using methods from other classes is on of my short comings so hoping someone here will be able to explain what I’m doing wrong.
public Cursor getRandomName(int number){
return myDataBase.query(NAME_TABLE, new String[]{KEY_ID, KEY_FIRST, KEY_LAST},
KEY_ID + " = " + number , null, null, null, KEY_ID);
}
This is the cursor I’m working with, located in my dbhelper class.
mydbhelperin yourActivityclass is a different reference than themydbhelperin yourGeneratorclass. You need to callmydbhelper = dbhelper.getInstance()in yourGeneratorclass or pass in the reference before you use it.A quick way to do it would be:
Remember to close both your cursor and your database when you’re done with it. Close the Cursor first.