尝试在空对象引用上调用虚拟方法'void android.widget.TableLayout.addView(android.view.View)'

时间:2018-11-13 22:19:47

标签: java android sqlite

我正在尝试使用表格向学生显示以下数据:

    public class Main5Activity extends AppCompatActivity {
    DataBaseConnection db;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main5);
    setContentView(R.layout.activity_main);

    final TableLayout stk = findViewById(R.id.datatable);
    TableRow tbrow0 = new TableRow(this);
    TextView SNo = new TextView(this);
    SNo.setText(" Student NO ");
    SNo.setTextColor(Color.WHITE);
    tbrow0.addView(SNo);
    TextView StudentName = new TextView(this);
    StudentName.setText(" Student Name ");
    StudentName.setTextColor(Color.WHITE);
    tbrow0.addView(StudentName);
    TextView hmewrk = new TextView(this);
    hmewrk.setText(" Homework mark ");
    hmewrk.setTextColor(Color.WHITE);
    TextView orlmrk = new TextView(this);
    orlmrk.setText(" Oral Mark ");
    orlmrk.setTextColor(Color.WHITE);
    TextView ttlwrkmrk = new TextView(this);
    ttlwrkmrk.setText(" Total Works Mark");
    ttlwrkmrk.setTextColor(Color.WHITE);
    TextView orlexm = new TextView(this);
    orlexm.setText(" Oral Exam");
    orlexm.setTextColor(Color.WHITE);
    TextView exm = new TextView(this);
    exm.setText(" Exam ");
    exm.setTextColor(Color.WHITE);
    TextView exmttl = new TextView(this);
    exmttl.setText(" Exam total");
    exmttl.setTextColor(Color.WHITE);
    TextView textView9 = new TextView(this);
    textView9.setText(" Average");
    textView9.setTextColor(Color.WHITE);
    tbrow0.addView(hmewrk);
    tbrow0.addView(orlexm);
    stk.addView(tbrow0);
    for (String i = db.stdntnmbr();; ) {

从数据库中调用学生编号值以创建相同值的行时,出现以下错误: 代码是:

public class DataBaseConnection {

private final DataBase dataBase;

DataBaseConnection(Context context) {
    dataBase = new DataBase(context);
}
public String stdntnmbr(){
    SQLiteDatabase sqLiteDatabase = dataBase.getWritableDatabase();
    String uid = DataBase.UID;
    Cursor cursor = sqLiteDatabase.query(DataBase.tablename1 , null, uid, null
    , null , null , null , null);
    StringBuilder stringBuilder = new StringBuilder();
    while (cursor.moveToNext()) {
        int studentnmbr = cursor.getInt(1);
        stringBuilder.append(studentnmbr + " " +"+/n");
    }
    return String.valueOf(stringBuilder);   

数据库类型为SQLite,我正在使用SQLiteOpenHelper。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

您可能不希望行setContentView(R.layout.activity_main);仅是行setContentView(R.layout.activity_main5);(反之亦然),这取决于所使用的布局具有TableLayout和TextViews等。

,然后要包含一行以实例化DataBaseConnection db。因此,添加一行db = new DataBaseConnection(this);(紧接在setContentView之后)。

如果您仍然遇到空指针异常的问题,请编辑您的问题以包括堆栈跟踪(即不仅是错误消息)。