Android:使用数据库填充Listview,崩溃而不显示

时间:2014-04-01 01:38:15

标签: java android database sqlite listview

我对Android开发很新,这是我开始研究的第一个非常复杂的项目。我试图在我的主活动中创建一个列表视图,显示数据库中的字符串列表。同时,我希望用户能够从单独的活动中添加新字符串,并能够删除它们。我主要遵循本教程here。以下是我的活动:

主:

public class HabitMain extends Activity {

private DbHelper mHelper;
private SQLiteDatabase dataBase;

private Button newHabit;
private ListView listview;

private ArrayList<String> hId = new ArrayList<String>();
private ArrayList<String> hName = new ArrayList<String>();

final Context context = this;

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

    displayData();

    mHelper = new DbHelper(this);

    //Initialize Button
    newHabit = (Button) findViewById(R.id.mbButton);
    ListView listview = (ListView)findViewById(R.id.listview);

    OnClickListener listener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent CreateHabit = new Intent(HabitMain.this, CreateNewHabit.class);
            startActivityForResult(CreateHabit, 1);
        }
    };



    listview.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

            Toast.makeText( getApplicationContext(), " Click Confirmed.", Toast.LENGTH_SHORT).show();
        }
    });

    newHabit.setOnClickListener(listener);

}

@Override
protected void onResume() {

    super.onResume();
}

private void displayData() 
{
    dataBase = mHelper.getWritableDatabase();
    Cursor mCursor = dataBase.rawQuery("SELECT * FROM " + DbHelper.TABLE_NAME, null);

    hId.clear();
    hName.clear();
    if (mCursor.moveToFirst()) {
        do {
            hId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
            hName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_NAME)));

        } while (mCursor.moveToNext());
    }
    DisplayAdapter disadpt = new DisplayAdapter(HabitMain.this, hId, hName);
    listview.setAdapter(disadpt);
    mCursor.close();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.habit_main, menu);
    return true;
}

创建新项目:

public class CreateNewHabit extends Activity{

private EditText newHabit;
private TextView fDate;
private String futuredate, habitName;
private Button newHabitButton;
private SQLiteDatabase dataBase;
private DbHelper mHelper;

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

     getActionBar().setDisplayHomeAsUpEnabled(true);

     newHabit = (EditText)findViewById(R.id.editDialog);

     newHabitButton = (Button)findViewById(R.id.dialogButton);

     fDate = (TextView)findViewById(R.id.fDate);

     mHelper = new DbHelper(this);

     newHabitButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            habitName= newHabit.getText().toString();
            if(habitName.length()>0)
            {
                addHabit();
            }
            else
            {
                AlertDialog.Builder alertBuilder=new AlertDialog.Builder(CreateNewHabit.this);
                alertBuilder.setTitle("No Name");
                alertBuilder.setMessage("You didn't enter a name!");
                alertBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                           dialog.cancel();

                    }
                });
                alertBuilder.create().show();
        }

        }
     });

}

private void addHabit()
{
    dataBase=mHelper.getWritableDatabase();
    ContentValues values=new ContentValues();

    values.put(DbHelper.KEY_NAME,habitName );

    System.out.println("");

    //insert data into database
    dataBase.insert(DbHelper.TABLE_NAME, null, values);

    //close database
    dataBase.close();
    finish();
}

数据库助手:

public class DbHelper extends SQLiteOpenHelper {
static String DATABASE_NAME="habits";
public static final String TABLE_NAME="habit";
public static final String KEY_NAME="hname";
public static final String KEY_ID="id";
public DbHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);

}

@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY KEY, "+KEY_NAME+" TEXT)";
    db.execSQL(CREATE_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
    onCreate(db);
}

显示适配器:

public class DisplayAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<String> id;
private ArrayList<String> Name;


public DisplayAdapter(Context c, ArrayList<String> id,ArrayList<String> Name) {
    this.mContext = c;

    this.id = id;
    this.Name = Name;
}

public int getCount() {
    // TODO Auto-generated method stub
    return id.size();
}

public Object getItem(int position) {
    // TODO Auto-generated method stub
    return null;
}

public long getItemId(int position) {
    // TODO Auto-generated method stub
    return 0;
}

public View getView(int pos, View child, ViewGroup parent) {
    Holder mHolder;
    LayoutInflater layoutInflater;
    if (child == null) {
        layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        child = layoutInflater.inflate(R.layout.habit_items, null);
        mHolder = new Holder();
        mHolder.txt_id = (TextView) child.findViewById(R.id.value);
        mHolder.txt_Name = (TextView) child.findViewById(R.id.label);
        child.setTag(mHolder);
    } else {
        mHolder = (Holder) child.getTag();
    }
    mHolder.txt_id.setText(id.get(pos));
    mHolder.txt_Name.setText(Name.get(pos));

    return child;
}

public class Holder {
    TextView txt_id;
    TextView txt_Name;
}

我不太确定这里出了什么问题。我通常无法在没有响应的情况下打开应用程序。我收到错误:E / AndroidRuntime(28415):java.lang.RuntimeException:无法启动活动ComponentInfo {com.habit / com.habit.HabitMain}:java.lang.NullPointerException。我认为活动甚至无法开始,我找不到导致这种情况的原因。

如果有人可以帮我解决这个问题,那会非常有帮助。在过去的几天里,我一直在试着让我的头发脱落。

2 个答案:

答案 0 :(得分:1)

我认为在创建数据库帮助程序之前调用displayData() ..

所以试着这样称呼它:

mHelper = new DbHelper(this);
displayData();

<强> ADDITION

初始化列表视图后,

调用上面的两行...之后:

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

因为您在初始化之前访问listview,所以它是null ..

答案 1 :(得分:0)

http://androidsolution4u.blogspot.kr/2013/09/android-populate-listview-from-sqlite.html

本文作者最后给出了源代码。下载源代码并使其正常工作。