您好我试着在我的应用程序中创建一个简单的数据库,但是当我启动它时会崩溃。我认为问题与addButton,deleteButton和PrintDb方法有关,但我无法修复它。这是MainActivity的代码
public class MainActivity extends AppCompatActivity {
//Definizione Variabili-------------------------------------------------------------------------
Toolbar toolbar;
private ActionBarDrawerToggle actionBarDrawerToggle; //Per collegare il Drawer alla toolbar
private NavigationView navigationView;
private DrawerLayout drawerLayout;
private FloatingActionMenu actionMenu;
private FloatingActionButton actionButton;
private MenuItem mSearchAction;
private boolean isSearchOpened = false;
private EditText search;
private FragmentTransaction fragmentTransaction;
//Definizione variabili per Database
EditText maguiInput;
TextView maguiText;
MyDBHandler dbhandler;
//----------------------------------------------------------------------------------------------
//Definizione dei metodi della MainActivity-----------------------------------------------------
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initializing Toolbar and setting it as the actionbar
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Initializing NavigationView
navigationView = (NavigationView) findViewById(R.id.navigation_view);
HomeFragment home = new HomeFragment();
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame, home);
fragmentTransaction.commit();
//PORZIONE DI CODICE PER GESTIONE DATABASE
maguiInput =(EditText)findViewById(R.id.maguiEditText);
maguiText = (TextView)findViewById(R.id.maguiTextView);
dbhandler = new MyDBHandler(this,null,null,1);
printDatabase();
//---------------------------------------------------------
//Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger on item Click of navigation menu
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//Checking if the item is in checked state or not, if not make it in checked state
if(menuItem.isChecked()) menuItem.setChecked(false);
else menuItem.setChecked(true);
//Closing drawer on item click
drawerLayout.closeDrawers();
//Pemette di poter selezionare le voci del navigation drawer
switch (menuItem.getItemId())
{
case R.id.home:
actionButton.setVisibility(View.VISIBLE);
HomeFragment home = new HomeFragment();
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame, home);
fragmentTransaction.commit();
return true;
case R.id.profilo:
actionButton.setVisibility(View.INVISIBLE);
ProfileFragment profilo = new ProfileFragment();
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame, profilo);
fragmentTransaction.commit();
return true;
case R.id.impostazioni:
actionButton.setVisibility(View.INVISIBLE);
SettingsFragment impostazioni = new SettingsFragment();
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame, impostazioni);
fragmentTransaction.commit();
return true;
case R.id.info:
actionButton.setVisibility(View.INVISIBLE);
InfoFragment info = new InfoFragment();
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame, info);
fragmentTransaction.commit();
return true;
case R.id.help:
actionButton.setVisibility(View.INVISIBLE);
HelpFragment help = new HelpFragment();
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame, help);
fragmentTransaction.commit();
return true;
case R.id.logout:
actionButton.setVisibility(View.INVISIBLE);
LogoutFragment logout = new LogoutFragment();
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame, logout);
fragmentTransaction.commit();
return true;
default:
Toast.makeText(getApplicationContext(),"Somethings Wrong",Toast.LENGTH_SHORT).show();
return true;
}
}
});
// Initializing Drawer Layout and ActionBarToggle
drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.openDrawer, R.string.closeDrawer){
@Override
public void onDrawerClosed(View drawerView) {
// Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
super.onDrawerClosed(drawerView);
//supportInvalidateOptionsMenu();
}
@Override
public void onDrawerOpened(View drawerView) {
// Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank
super.onDrawerOpened(drawerView);
//supportInvalidateOptionsMenu();
}
@Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
onDSlide(slideOffset);
toolbar.setAlpha(1-slideOffset/2);
}
};
//Setting the actionbarToggle to drawer layout
drawerLayout.setDrawerListener(actionBarDrawerToggle);
//calling sync state is necessay or else your hamburger icon wont show up
actionBarDrawerToggle.syncState();
// Creo il bottone add che conterrà due sotto-bottoni
ImageView icon = new ImageView(this); // Create an icon
icon.setImageResource(R.drawable.ic_add_white_24dp);
actionButton = new FloatingActionButton.Builder(this)
.setContentView(icon)
.build();
// Creo i sotto-bottoni edit e photo
SubActionButton.Builder itemBuilder = new SubActionButton.Builder(this);
ImageView itemIcon = new ImageView(this);
itemIcon.setImageResource(R.drawable.ic_edit_white_24dp);
ImageView itemPhoto = new ImageView(this);
itemIcon.setImageResource(R.drawable.ic_camera_alt_white_24dp);
SubActionButton button1 = itemBuilder.setContentView(itemIcon).build();
SubActionButton button2 = itemBuilder.setContentView(itemPhoto).build();
actionMenu = new FloatingActionMenu.Builder(this)
.addSubActionView(button1)
.addSubActionView(button2)
.attachTo(actionButton)
.build();
}
//Metodi per la gestione del database
//add a product to the db
public void addButtonClicked(View v){
Producto p = new Producto(maguiInput.getText().toString());
dbhandler.addProducto(p);
//printDatabase();
}
//delete a product to the db
public void deleteButtonClicked(View v){
String inputText = maguiInput.getText().toString();
dbhandler.deleteProducto(inputText);
//printDatabase();
}
public void printDatabase() {
String dbString =dbhandler.databaseToString();
maguiText.setText(dbString);
maguiInput.setText("");
}
//-----------------------------------------------
@Override
public void onPostCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onPostCreate(savedInstanceState, persistentState);
actionBarDrawerToggle.syncState();
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
mSearchAction = menu.findItem(R.id.action_cerca);
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//Attiva il click sul'icona di ricerca presente sull'actionBar
if (id == R.id.action_cerca) {
handleMenuSearch();
return true;
}
return super.onOptionsItemSelected(item);
}
private void toggleTranslateFAB (float slideOffset) {
//Permette di far scomparire/apparire il FAB alla apertura/chiusura del Drawer
if (actionMenu != null) {
if (actionMenu.isOpen()) {
actionMenu.close(true);
}
actionButton.setTranslationX(slideOffset * 200);
}
}
public void onDSlide(float slideOffset){
toggleTranslateFAB(slideOffset);
}
protected void handleMenuSearch(){
//Gestione della ricerca testuale presente sulla actionBar
ActionBar action = getSupportActionBar(); //get the actionbar
if(isSearchOpened){ //test if the search is open
action.setDisplayShowCustomEnabled(false); //disable a custom view inside the actionbar
action.setDisplayShowTitleEnabled(true); //show the title in the action bar
//hides the keyboard
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(search.getWindowToken(), 0);
//add the search icon in the action bar
mSearchAction.setIcon(getResources().getDrawable(R.drawable.ic_search_white_24dp));
isSearchOpened = false;
} else { //open the search entry
action.setDisplayShowCustomEnabled(true); //enable it to display a
// custom view in the action bar
action.setCustomView(R.layout.search_bar);//add the custom view
action.setDisplayShowTitleEnabled(false); //hide the title
search = (EditText)action.getCustomView().findViewById(R.id.editSearch); //the text editor
//this is a listener to do a search when the user clicks on search button
search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
doSearch();
return true;
}
return false;
}
});
search.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(search, InputMethodManager.SHOW_IMPLICIT);
//add the close icon
mSearchAction.setIcon(getResources().getDrawable(R.drawable.ic_search_white_24dp));
isSearchOpened = true;
}
}
//Metodi per la gestione della ricerca
private void doSearch() {
//Definire la tipologia di ricerca da effettuare
}
@Override
public void onBackPressed() {
if (isSearchOpened){
handleMenuSearch();
return;
}
super.onBackPressed();
}
//---------------------------------------------------------
这是MyDBHandler类
public class MyDBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "productDB.db";
public static final String TABLE_PRODUCTS = "products";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_PRODUCTNAME = "productname";
//We need to pass database information along to superclass
public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_PRODUCTS + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_PRODUCTNAME + " TEXT " +
");";
db.execSQL(query);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PRODUCTS);
onCreate(db);
}
//Add a new row to the database
public void addProducto(Producto product){
ContentValues values = new ContentValues();
values.put(COLUMN_PRODUCTNAME, product.get_productName());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_PRODUCTS, null, values);
db.close();
}
//Delete a product from the database
public void deleteProducto(String productName){
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_PRODUCTS + " WHERE " + COLUMN_PRODUCTNAME + "=\"" + productName + "\";");
}
public String databaseToString(){
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";
//Cursor points to a location in your results
Cursor c = db.rawQuery(query, null);
//Move to the first row in your results
c.moveToFirst();
//Position after the last row means the end of the results
while (!c.isAfterLast()) {
if (c.getString(c.getColumnIndex("productname")) != null) {
dbString += c.getString(c.getColumnIndex("productname"));
dbString += "\n";
}
c.moveToNext();
}
db.close();
return dbString;
}
}
这就是错误
09-23 17:04:26.914 23457-23457/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.android4dev.navigationview, PID: 23457
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.android4dev.navigationview/com.android4dev.navigationview.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2429)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2493)
at android.app.ActivityThread.access$800(ActivityThread.java:166)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5584)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.android4dev.navigationview.MainActivity.printDatabase(MainActivity.java:226)
at com.android4dev.navigationview.MainActivity.onCreate(MainActivity.java:77)
at android.app.Activity.performCreate(Activity.java:5442)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2393)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2493)
at android.app.ActivityThread.access$800(ActivityThread.java:166)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5584)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:0)
尝试使用getReadableDatabase读取值
public String databaseToString(){
String dbString = "";
SQLiteDatabase db = this.getReadableDatabase();
String query= "SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";;
Cursor cursor = db.rawQuery(query, null);
if(cursor.moveToFirst()) {
do {
if(cursor.getColumnIndex("productname")!=null)
{
dbString +=cursor.getString(cursor.getColumnIndex("productname"))+"\n";
}
}while(cursor.moveToNext());
}
cursor.close();
db.close();
return dbString;
}