实现Getextra()和Putextra

时间:2014-02-04 04:37:50

标签: java android methods

我正在尝试使用putextra()getextra(),但我的程序在实现后崩溃了 浏览我的代码,让我知道我的错误 如果我没有使用getextra()putextra(),则代码可以正常运行

这是我获得价值的第一堂课

public class Assess extends ListActivity {
String itm;

ArrayAdapter<String> Adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    getListView().setBackgroundResource(R.drawable.background);
    Adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, getResources()
                    .getStringArray(R.array.English));

    setListAdapter(Adapter);
    getListView().setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
                long arg3) {
            selectItem(pos);
            itm = getListView().getItemAtPosition(pos).toString();
            // Toast.makeText(getApplicationContext(), "CLicked",
            // Toast.LENGTH_SHORT).show();

        }
    });

}

public void selectItem(int pos) {
    switch (pos) {
    case 0: {
        Intent i;
        List<Question> questions = getQuestionSetFromDb();

        // Initialise Game with retrieved question set ///
        GamePlay c = new GamePlay();
        c.setQuestions(questions);
        c.setNumRounds(getNumQuestions());
        ((ChuckApplication) getApplication()).setCurrentGame(c);

        // Start Game Now.. //



        i = new Intent(this, QuestionActivity.class);
        **i.putExtra("itemname", itm);**
        //startActivityForResult(i, Constants.PLAYBUTTON);
        startActivity(i);
        //this.finish();
        break;
    }
    }

}

现在我正在尝试传递项目名称的第二课

    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.question);
    topic1 = i.getStringExtra("itemname");

    Log.i("sanket", topic1);

    /**
     * Configure current game and get question
     */
    currentGame = ((ChuckApplication) getApplication()).getCurrentGame();
    currentQ = currentGame.getNextQuestion();

    RadioGroup rdgb = (RadioGroup) findViewById(R.id.group1);
    rdgb.setOnCheckedChangeListener(this);
    /**
     * Update the question and answer options..
     */
    setQuestions();

}


/**
 * Method to set the text for the question and answers from the current
 * games current question
 */
private void setQuestions() {
    // set the question text from current question
    String question = Utility.capitalise(currentQ.getQuestion()) + "?";
    TextView qText = (TextView) findViewById(R.id.question);
    qText.setText(question);

    // set the available options
    List<String> answers = currentQ.getQuestionOptions();
    TextView option1 = (TextView) findViewById(R.id.answer1);
    option1.setText(Utility.capitalise(answers.get(0)));

    TextView option2 = (TextView) findViewById(R.id.answer2);
    option2.setText(Utility.capitalise(answers.get(1)));

    TextView option3 = (TextView) findViewById(R.id.answer3);
    option3.setText(Utility.capitalise(answers.get(2)));

    TextView option4 = (TextView) findViewById(R.id.answer4);
    option4.setText(Utility.capitalise(answers.get(3)));
}

/*
 * @Override public void onClick(View arg0) { //Log.d("Questions",
 * "Moving to next question");
 *//**
 * validate a checkbox has been selected
 */
/*
 * if (!checkAnswer()) return;
 *//**
 * check if end of game
 */
/*
 * if (currentGame.isGameOver()){ //Log.d("Questions",
 * "End of game! lets add up the scores.."); //Log.d("Questions",
 * "Questions Correct: " + currentGame.getRight()); //Log.d("Questions",
 * "Questions Wrong: " + currentGame.getWrong()); Intent i = new
 * Intent(this, EndgameActivity.class); startActivity(i); finish(); } else{
 * Intent i = new Intent(this, QuestionActivity.class); startActivity(i);
 * finish(); } }
 */

public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (a > 0) {
        switch (keyCode) {
        case KeyEvent.KEYCODE_BACK:
            return true;
        }
    }
    return super.onKeyDown(keyCode, event);

}

/**
 * Check if a checkbox has been selected, and if it has then check if its
 * correct and update gamescore
 */
private boolean checkAnswer() {
    String answer = getSelectedAnswer();
    if (answer == null) {
        // Log.d("Questions", "No Checkbox selection made - returning");
        return false;
    } else {
        // Log.d("Questions",
        // "Valid Checkbox selection made - check if correct");
        if (currentQ.getAnswer().equalsIgnoreCase(answer)) {
            // Log.d("Questions", "Correct Answer!");
            currentGame.incrementRightAnswers();
        } else {
            // Log.d("Questions", "Incorrect Answer!");
            currentGame.incrementWrongAnswers();
        }

        return true;
    }
}

/**
 * 
 */
public String getSelectedAnswer() {
    RadioButton c1 = (RadioButton) findViewById(R.id.answer1);
    RadioButton c2 = (RadioButton) findViewById(R.id.answer2);
    RadioButton c3 = (RadioButton) findViewById(R.id.answer3);
    RadioButton c4 = (RadioButton) findViewById(R.id.answer4);
    if (c1.isChecked()) {
        return c1.getText().toString();

    }
    if (c2.isChecked()) {
        return c2.getText().toString();
    }
    if (c3.isChecked()) {
        return c3.getText().toString();
    }
    if (c4.isChecked()) {
        return c4.getText().toString();
    }

    return null;
}

@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
    // TODO Auto-generated method stub
    // Log.d("Questions", "Moving to next question");
    a++;
    /**
     * validate a checkbox has been selected
     */
    if (!checkAnswer())
        return;

    /**
     * check if end of game
     */
    if (currentGame.isGameOver()) {
        // db.open();
        // db.insertOptions(topic1, currentGame.getRight(), month);
        // Log.d("Questions", "End of game! lets add up the scores..");
        // Log.d("Questions", "Questions Correct: " +
        // currentGame.getRight());
        // Log.d("Questions", "Questions Wrong: " + currentGame.getWrong());
        Intent i = new Intent(this, EndgameActivity.class);
        startActivity(i);
        finish();
        // db.close();
    } else {
        Intent i = new Intent(this, QuestionActivity.class);
        startActivity(i);
        finish();
    }
}

}

或者是否有其他方式可以将数据从一个页面传送到putextra()getextra()以外的其他页面。

这是我的LOGCAT

02-04 10:33:35.697: E/AndroidRuntime(1776): FATAL EXCEPTION: main
02-04 10:33:35.697: E/AndroidRuntime(1776): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.tmm.android.chuck/com.tmm.android.chuck.QuestionActivity}: java.lang.NullPointerException: println needs a message
02-04 10:33:35.697: E/AndroidRuntime(1776):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
02-04 10:33:35.697: E/AndroidRuntime(1776):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
02-04 10:33:35.697: E/AndroidRuntime(1776):     at android.app.ActivityThread.access$1500(ActivityThread.java:117)
02-04 10:33:35.697: E/AndroidRuntime(1776):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
02-04 10:33:35.697: E/AndroidRuntime(1776):     at android.os.Handler.dispatchMessage(Handler.java:99)
02-04 10:33:35.697: E/AndroidRuntime(1776):     at android.os.Looper.loop(Looper.java:130)
02-04 10:33:35.697: E/AndroidRuntime(1776):     at android.app.ActivityThread.main(ActivityThread.java:3683)
02-04 10:33:35.697: E/AndroidRuntime(1776):     at java.lang.reflect.Method.invokeNative(Native Method)
02-04 10:33:35.697: E/AndroidRuntime(1776):     at java.lang.reflect.Method.invoke(Method.java:507)
02-04 10:33:35.697: E/AndroidRuntime(1776):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
02-04 10:33:35.697: E/AndroidRuntime(1776):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
02-04 10:33:35.697: E/AndroidRuntime(1776):     at dalvik.system.NativeStart.main(Native Method)
02-04 10:33:35.697: E/AndroidRuntime(1776): Caused by: java.lang.NullPointerException: println needs a message
02-04 10:33:35.697: E/AndroidRuntime(1776):     at android.util.Log.println_native(Native Method)
02-04 10:33:35.697: E/AndroidRuntime(1776):     at android.util.Log.i(Log.java:158)
02-04 10:33:35.697: E/AndroidRuntime(1776):     at com.tmm.android.chuck.QuestionActivity.onCreate(QuestionActivity.java:48)
02-04 10:33:35.697: E/AndroidRuntime(1776):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
02-04 10:33:35.697: E/AndroidRuntime(1776):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
02-04 10:33:35.697: E/AndroidRuntime(1776):     ... 11 more

4 个答案:

答案 0 :(得分:1)

尝试获取如下字符串:

首先更改onItemClickListener,如下所示:您需要为itm变量指定值,然后调用selectItem()方法,以使itm变量不为空。

    getListView().setOnItemClickListener(new OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
            long arg3) {
        itm = getListView().getItemAtPosition(pos).toString();
        selectItem(pos);
     }
 });

在另一项活动中获取字符串,如下所示:

String topic1 =getIntent().getStringExtra("itemname");

答案 1 :(得分:1)

首先在itm的{​​{1}}实现中初始化OnItemClickListener字符串,然后调用ListView方法。

selectItem()

并在收到 getListView().setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) { itm = getListView().getItemAtPosition(pos).toString(); // initialize it first. selectItem(pos); // Toast.makeText(getApplicationContext(), "CLicked", // Toast.LENGTH_SHORT).show(); } }); 时,将此字符串设为

Activity

答案 2 :(得分:0)

您应该从getIntent()读取字符串。阅读如下

topic1 = getIntent().getStringExtra("itemname");

答案 3 :(得分:0)

它必须是NullPointerException,因为“itm”在该范围内始终为null 你为什么不这样做:

itm = getListView().getItemAtPosition(pos).toString(); selectItem(pos,itm);

然后在此方法中将其作为额外传递 希望有所帮助:)