简体   繁体   English

实现Getextra()和Putextra

[英]Implementing Getextra() and Putextra

I am trying to use putextra() and getextra() but my program is crashing after implementing it Go through my code and let me know my mistake If I am not using getextra() and putextra() the code is working flawlessly 我正在尝试使用putextra()getextra()但是我的程序在实现之后崩溃了解我的代码并让我知道我的错误如果我没有使用getextra()putextra()代码正在运行完美

This is 1st class from where I am getting the value 这是我从中获得价值的第一类

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;
    }
    }

}

Now the Second class where I am trying to Pass the item name 现在我正在尝试传递项目名称的第二课程

    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();
    }
}

} }

Or is there any other way to carry data from one page to other page other than putextra() and getextra() . 或者除了putextra()getextra()之外,还有其他方法可以将数据从一个页面传送到其他页面。

Here is my LOGCAT 这是我的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

Try out to get the string as below : 尝试获取如下字符串:

First change your onItemClickListener as below: You need to assign value to your itm variable and then call the selectItem() method so that your itm variable is not null. 首先更改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);
     }
 });

Get the String in your another activity as below: 在您的另一个活动中获取字符串,如下所示:

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

first initialize the itm String in OnItemClickListener implementation of ListView , then call selectItem() method. 首先在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();

        }
    });

and in reeiving Activity , get this String as 并在reeiving Activity ,将此String作为

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

You should read string from getIntent() . 你应该从getIntent()读取字符串。 Read like below 阅读如下

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

It must be a NullPointerException because "itm" will always be null in that scope Why don't you make it like this: 它必须是NullPointerException,因为“itm”在该范围内始终为null为什么不这样做:

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

And then pass it as extra in this method Hope that helps :) 然后在这个方法中将其作为额外传递希望有帮助:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM