簡體   English   中英

實現Getextra()和Putextra

[英]Implementing Getextra() and Putextra

我正在嘗試使用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

嘗試獲取如下字符串:

首先更改onItemClickListener,如下所示:您需要為itm變量賦值,然后調用selectItem()方法,以使您的itm變量不為null。

    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");

首先在ListView OnItemClickListener實現中初始化itm String,然后調用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();

        }
    });

並在reeiving Activity ,將此String作為

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

你應該從getIntent()讀取字符串。 閱讀如下

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

它必須是NullPointerException,因為“itm”在該范圍內始終為null為什么不這樣做:

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

然后在這個方法中將其作為額外傳遞希望有幫助:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM