gpt4 book ai didi

java - Android:用数据库填充Listview,崩溃且不显示

转载 作者:行者123 更新时间:2023-12-01 13:12:03 26 4
gpt4 key购买 nike

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

主要:

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: 无法启动 Activity ComponentInfo{com.habit/com.habit.HabitMain}: java.lang.NullPointerException。我认为该 Activity 甚至无法开始,我找不到导致此情况的原因。

如果有人可以帮助我完成这项工作,那将会非常有帮助。在过去的几天里,我一直在努力让它发挥作用。

最佳答案

我认为您在创建数据库助手之前调用 displayData() ..

所以尝试这样调用它:

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

添加:

在初始化 ListView 后调用上面的两行..在此之后:

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

由于您在初始化之前访问 listview,因此它是 null..

关于java - Android:用数据库填充Listview,崩溃且不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22775282/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com