【问题标题】:SQL Database on AndroidAndroid 上的 SQL 数据库
【发布时间】:2014-02-27 02:05:14
【问题描述】:

我正在开发一种应用程序来控制您的 Day Pills。它包含一个药丸列表(带有名称和时间),您可以添加一个药丸。

应用程序正确启动,我可以转到添加布局,但是当我单击“添加”时它会停止。我不知道它为什么会停止;我认为这与将新药丸保存到database 有关。

我尝试将时间和名称作为意图附加内容(意图从添加布局转到主布局)并尝试将它们从 Main 类中保存(我认为它可能无法保存因为我试图从 Add Class 中做到这一点)。

这里是主要活动:

package com.example.pilladvisor;

import android.os.Bundle;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity {

private ListView listPastilles;
private SQLiteDatabase db;
private Pastilla[] datos;
private TextView pastis;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Intent h = getIntent();
    Boolean afegit = h.getBooleanExtra("AFEGIT",false);

    if (afegit) {
        int hora = h.getIntExtra("HORA", 0);
        String nom = h.getStringExtra("NOM");

        ContentValues nuevoRegistro = new ContentValues();
        nuevoRegistro.put("nom", nom);
        nuevoRegistro.put("hora", hora);
        db.insert("Pastilles", null, nuevoRegistro);
    }

    PastillesSQLiteHelper bdh =
            new PastillesSQLiteHelper(this, "DBPastilles", null, 1);

        db = bdh.getWritableDatabase();


    //startService (new Intent(this, ServeiHora.class));    

    Cursor c = db.rawQuery("SELECT nom, hora FROM Pastilles", null);

    int i = 0;

    if (c.moveToFirst()) {
         //Recorremos el cursor hasta que no haya más registros
        i = 0;
         do {
              String nom = c.getString(0);
              int hora = c.getInt(1);

              datos[i] = new Pastilla(nom,hora);

              ++i;
         } while(c.moveToNext());
    }

    pastis = (TextView)findViewById(R.id.textView1);

    if (i == 0){
        pastis.setText("No tens pastilles!");
    }
    else {
        pastis.setText("Hi ha " + i + " alarmes programades.");

        AdaptadorPastilles adaptador = new AdaptadorPastilles(this);

        listPastilles = (ListView)findViewById(R.id.listPastilles);

        listPastilles.setAdapter(adaptador);
    }

    Button Boto1 = (Button)findViewById(R.id.button1);
    Boto1.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, Afegir.class);
            startActivity(intent);
        }
    });
}

class AdaptadorPastilles extends ArrayAdapter<Pastilla> {

    Activity context;

    AdaptadorPastilles(Activity context) {
        super(context, R.layout.listitem_pastilla, datos);
        this.context = context;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = context.getLayoutInflater();
        View item = inflater.inflate(R.layout.listitem_pastilla, null);

        TextView lblTitulo = (TextView)item.findViewById(R.id.LblTitulo);
        lblTitulo.setText(datos[position].getTitulo());

        TextView lblSubtitulo =(TextView)item.findViewById(R.id.LblSubTitulo);               lblSubtitulo.setText(datos[position].getSubtitulo());

        return(item);
    }
    }
}

这里有 Add 活动:

package com.example.pilladvisor;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class Afegir extends Activity{

private EditText field_nom;
private EditText field_hora;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_afegir);

    field_nom = (EditText)findViewById(R.id.editText1);
    field_hora = (EditText)findViewById(R.id.editText2);

    Button Boto1 = (Button)findViewById(R.id.button1);
    Boto1.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(Afegir.this, MainActivity.class);
            startActivity(intent);
        }
    });



    Button Boto2 = (Button)findViewById(R.id.button2);
    Boto2.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            String nom = field_nom.getText().toString();
            int hora =     Integer.parseInt(field_hora.getText().toString()); 

            Intent intent = new Intent(Afegir.this, MainActivity.class);
            intent.putExtra("AFEGIT",true);
            intent.putExtra("NOM", nom);
            intent.putExtra("HORA", hora);
            startActivity(intent);
        }
    });

}

}

最后是数据库类:

package com.example.pilladvisor;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class PastillesSQLiteHelper extends SQLiteOpenHelper {

String sqlCreate = "CREATE TABLE Pastilles (nom TEXT, hora INTEGER)";

public PastillesSQLiteHelper(Context contexto, String nom, CursorFactory factory, int version) {
    super(contexto, nom, factory, version);
}

@Override
public void onCreate(SQLiteDatabase db){
    db.execSQL(sqlCreate);
}

@Override
public void onUpgrade(SQLiteDatabase db, int versionAnterior, int versionNueva){
    db.execSQL("DROP TABLE IF EXISTS Pastilles");

    db.execSQL(sqlCreate);
}


}

错误提示:

02-03 15:23:33.492: E/AndroidRuntime(666): FATAL EXCEPTION: main
02-03 15:23:33.492: E/AndroidRuntime(666): java.lang.RuntimeException: Unable to start     activity ComponentInfo{com.example.pilladvisor/com.example.pilladvisor.MainActivity}:     java.lang.NullPointerException
02-03 15:23:33.492: E/AndroidRuntime(666):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2092)
02-03 15:23:33.492: E/AndroidRuntime(666):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2117)
02-03 15:23:33.492: E/AndroidRuntime(666):  at android.app.ActivityThread.access$700(ActivityThread.java:134)
02-03 15:23:33.492: E/AndroidRuntime(666):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1218)
02-03 15:23:33.492: E/AndroidRuntime(666):  at android.os.Handler.dispatchMessage(Handler.java:99)
02-03 15:23:33.492: E/AndroidRuntime(666):  at android.os.Looper.loop(Looper.java:137)
02-03 15:23:33.492: E/AndroidRuntime(666):  at android.app.ActivityThread.main(ActivityThread.java:4867)
02-03 15:23:33.492: E/AndroidRuntime(666):  at java.lang.reflect.Method.invokeNative(Native Method)
02-03 15:23:33.492: E/AndroidRuntime(666):  at java.lang.reflect.Method.invoke(Method.java:511)
02-03 15:23:33.492: E/AndroidRuntime(666):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
02-03 15:23:33.492: E/AndroidRuntime(666):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
02-03 15:23:33.492: E/AndroidRuntime(666):  at dalvik.system.NativeStart.main(Native Method)
02-03 15:23:33.492: E/AndroidRuntime(666): Caused by: java.lang.NullPointerException
02-03 15:23:33.492: E/AndroidRuntime(666):  at com.example.pilladvisor.MainActivity.onCreate(MainActivity.java:40)
02-03 15:23:33.492: E/AndroidRuntime(666):  at android.app.Activity.performCreate(Activity.java:5047)
02-03 15:23:33.492: E/AndroidRuntime(666):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
02-03 15:23:33.492: E/AndroidRuntime(666):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2056)
02-03 15:23:33.492: E/AndroidRuntime(666):  ... 11 more

【问题讨论】:

  • Caused by: java.lang.NullPointerException at com.example.pilladvisor.MainActivity.onCreate(MainActivity.java:40) -- 第 40 行是什么?有些东西是空的,不应该是空的。

标签: android sql eclipse exception


【解决方案1】:

会员db在发起前不能使用。

在第 40 行:db.insert("Pastilles", null, nuevoRegistro); db 的值为 null,这就是它崩溃的原因。

将以“if (afegit) {”开头的代码块移动到启动数据库的代码下方:

db = bdh.getWritableDatabase();

【讨论】:

    【解决方案2】:

    您不集成数据库实例。这就是你在 null ponter 异常中崩溃的原因:

     db.insert("Pastilles", null, nuevoRegistro);
    

    【讨论】:

      【解决方案3】:

      当你打电话时

      db.insert("Pastilles", null, nuevoRegistro);
      

      db 为空。你必须这样做

      PastillesSQLiteHelper bdh =
              new PastillesSQLiteHelper(this, "DBPastilles", null, 1);
      
          db = bdh.getWritableDatabase();
      

      在 db.insert() 之前;

      希望对你有帮助。

      【讨论】:

        【解决方案4】:

        在提出问题之前,您应该尝试调试代码并阅读日志。 正如您的日志在第 15 行所说,有一个 java.lang.NullPointerException,这意味着您正在尝试访问一个尚未初始化的对象。

        在第 16 行的日志中,有提示抛出异常:

        at com.example.pilladvisor.MainActivity.onCreate(MainActivity.java:40)
        

        这意味着在第 40 行的文件“MainActivity.java”中抛出异常。

        那么让我们看看你的代码的这一点:

        33: if (afegit) {
        34:     int hora = h.getIntExtra("HORA", 0);
        35:     String nom = h.getStringExtra("NOM");
        36: 
        37:     ContentValues nuevoRegistro = new ContentValues();
        38:     nuevoRegistro.put("nom", nom);
        39:     nuevoRegistro.put("hora", hora);
        40:     db.insert("Pastilles", null, nuevoRegistro);
        41: }
        42: 
        43: PastillesSQLiteHelper bdh =
        44:         new PastillesSQLiteHelper(this, "DBPastilles", null, 1);
        45: 
        46:     db = bdh.getWritableDatabase();
        

        在 if-case 中,您尝试从“db”对象调用方法。但是初始化还没有完成。它发生在第 46 行。

        解决办法应该是把第43行到第46行的代码放在if-case前面。

        33: PastillesSQLiteHelper bdh =
        34:     new PastillesSQLiteHelper(this, "DBPastilles", null, 1);
        35:
        36: db = bdh.getWritableDatabase();
        37:
        38: if (afegit) {
        39:     int hora = h.getIntExtra("HORA", 0);
        40:     String nom = h.getStringExtra("NOM");
        41:
        42:     ContentValues nuevoRegistro = new ContentValues();
        43:     nuevoRegistro.put("nom", nom);
        44:     nuevoRegistro.put("hora", hora);
        45:     db.insert("Pastilles", null, nuevoRegistro);
        46: }
        

        如果您使用 Eclipse 进行开发,这里是一个很好的调试教程。

        http://www.vogella.com/tutorials/EclipseDebugging/article.html

        虽然它是一个很棒的教程,但它不是基于 Android 开发的,应该对你很有帮助。 另外,您应该查看 Android Debugging 的官方线程,以便在 Eclipse 中使用 ADT - 插件进行开发

        http://developer.android.com/tools/debugging/debugging-projects.html

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-10-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-06-23
          相关资源
          最近更新 更多