所以每次点击任何按钮时都会出现NullPointerException。出于某种原因,当我在switch语句中时,我收到错误。我的DB帮助程序类只返回一个游标,所以我在我的特定活动中使用该Cursor。我只是希望能够根据用户偏好来回切换数据库条目。而且我还想显示行的不同元素而不是整行。任何建议将不胜感激。我认为这种方法将提供我需要的东西,但我无法让它发挥作用。
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class SQLView extends Activity implements OnClickListener{
/* these 3 variables are the same as in the Database class */
public static final String KEY_ROWID = "_id";
public static final String KEY_FRONT = "card_front";
public static final String KEY_BACK = "card_back";
/* variables are made global so we can use them in all of our functions here */
private Cursor myCursor;
private TextView tv;
private int iRow;
private int iFront;
private int iBack;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sqlview);
TextView tv = (TextView)findViewById(R.id.tvSQLinfo);
String result = null;
Flashcards info = new Flashcards(this);
info.open();
myCursor = info.getCursor();
//info.close();
iRow = myCursor.getColumnIndex(KEY_ROWID);
iFront = myCursor.getColumnIndex(KEY_FRONT);
iBack = myCursor.getColumnIndex(KEY_BACK);
Button front = (Button) findViewById(R.id.front);
Button back = (Button) findViewById(R.id.back);
Button next = (Button) findViewById(R.id.next);
Button prev = (Button) findViewById(R.id.prev);
front.setOnClickListener(this);
back.setOnClickListener(this);
next.setOnClickListener(this);
prev.setOnClickListener(this);
myCursor.moveToFirst();
//Set the TextView to be the first card in our database
tv.setText(myCursor.getString(iFront));
}
@Override
public void onClick(View v) {
/* check if we are at our last entry in the DB */
if(myCursor.isAfterLast()){
/* move our cursor back to the first entry */
myCursor.moveToFirst();
}
// TODO Auto-generated method stub
switch (v.getId()){
case R.id.front:
tv.setText(myCursor.getString(iFront));
break;
case R.id.back:
tv.setText(myCursor.getString(iBack));
break;
case R.id.next:
if(myCursor.moveToNext()){
tv.setText(myCursor.getString(iFront));
}else{
myCursor.moveToFirst();
}
break;
case R.id.prev:
myCursor.moveToPrevious();
tv.setText(myCursor.getString(iFront));
break;
}
}
}
答案 0 :(得分:2)
tv
中的局部变量onCreate
实际上并未分配给同名的类成员变量,导致NPE
语句中的switch
。取代
TextView tv = (TextView)findViewById(R.id.tvSQLinfo);
与
tv = (TextView)findViewById(R.id.tvSQLinfo);