jjzjj

java - 实现 Getextra() 和 Putextra

coder 2023-12-16 原文

我正在尝试使用 putextra()getextra() 但我的程序在执行后崩溃了 检查我的代码,让我知道我的错误 如果我不使用 getextra()putextra() 代码运行完美

这是我获得值(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;
    }
    }

}

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

    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 变量不为空。

    getListView().setOnItemClickListener(new OnItemClickListener() {

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

在您的另一个 Activity 中获取字符串,如下所示:

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

关于java - 实现 Getextra() 和 Putextra,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21543066/

有关java - 实现 Getextra() 和 Putextra的更多相关文章

  1. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  2. ruby - 如何根据特征实现 FactoryGirl 的条件行为 - 2

    我有一个用户工厂。我希望默认情况下确认用户。但是鉴于unconfirmed特征,我不希望它们被确认。虽然我有一个基于实现细节而不是抽象的工作实现,但我想知道如何正确地做到这一点。factory:userdoafter(:create)do|user,evaluator|#unwantedimplementationdetailshereunlessFactoryGirl.factories[:user].defined_traits.map(&:name).include?(:unconfirmed)user.confirm!endendtrait:unconfirmeddoenden

  3. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

  4. java - 我的模型类或其他类中应该有逻辑吗 - 2

    我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我

  5. java - 什么相当于 ruby​​ 的 rack 或 python 的 Java wsgi? - 2

    什么是ruby​​的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht

  6. 华为OD机试用Python实现 -【明明的随机数】 2023Q1A - 2

    华为OD机试题本篇题目:明明的随机数题目输入描述输出描述:示例1输入输出说明代码编写思路最近更新的博客华为od2023|什么是华为od,od薪资待遇,od机试题清单华为OD机试真题大全,用Python解华为机试题|机试宝典【华为OD机试】全流程解析+经验分享,题型分享,防作弊指南华为o

  7. Observability:从零开始创建 Java 微服务并监控它 (二) - 2

    这篇文章是继上一篇文章“Observability:从零开始创建Java微服务并监控它(一)”的续篇。在上一篇文章中,我们讲述了如何创建一个Javaweb应用,并使用Filebeat来收集应用所生成的日志。在今天的文章中,我来详述如何收集应用的指标,使用APM来监控应用并监督web服务的在线情况。源码可以在地址 https://github.com/liu-xiao-guo/java_observability 进行下载。摄入指标指标被视为可以随时更改的时间点值。当前请求的数量可以改变任何毫秒。你可能有1000个请求的峰值,然后一切都回到一个请求。这也意味着这些指标可能不准确,你还想提取最小/

  8. 【Java 面试合集】HashMap中为什么引入红黑树,而不是AVL树呢 - 2

    HashMap中为什么引入红黑树,而不是AVL树呢1.概述开始学习这个知识点之前我们需要知道,在JDK1.8以及之前,针对HashMap有什么不同。JDK1.7的时候,HashMap的底层实现是数组+链表JDK1.8的时候,HashMap的底层实现是数组+链表+红黑树我们要思考一个问题,为什么要从链表转为红黑树呢。首先先让我们了解下链表有什么不好???2.链表上述的截图其实就是链表的结构,我们来看下链表的增删改查的时间复杂度增:因为链表不是线性结构,所以每次添加的时候,只需要移动一个节点,所以可以理解为复杂度是N(1)删:算法时间复杂度跟增保持一致查:既然是非线性结构,所以查询某一个节点的时候

  9. 基于C#实现简易绘图工具【100010177】 - 2

    C#实现简易绘图工具一.引言实验目的:通过制作窗体应用程序(C#画图软件),熟悉基本的窗体设计过程以及控件设计,事件处理等,熟悉使用C#的winform窗体进行绘图的基本步骤,对于面向对象编程有更加深刻的体会.Tutorial任务设计一个具有基本功能的画图软件**·包括简单的新建文件,保存,重新绘图等功能**·实现一些基本图形的绘制,包括铅笔和基本形状等,学习橡皮工具的创建**·设计一个合理舒适的UI界面**注明:你可能需要先了解一些关于winform窗体应用程序绘图的基本知识,以及关于GDI+类和结构的知识二.实验环境Windows系统下的visualstudio2017C#窗体应用程序三.

  10. MIMO-OFDM无线通信技术及MATLAB实现(1)无线信道:传播和衰落 - 2

     MIMO技术的优缺点优点通过下面三个增益来总体概括:阵列增益。阵列增益是指由于接收机通过对接收信号的相干合并而活得的平均SNR的提高。在发射机不知道信道信息的情况下,MIMO系统可以获得的阵列增益与接收天线数成正比复用增益。在采用空间复用方案的MIMO系统中,可以获得复用增益,即信道容量成倍增加。信道容量的增加与min(Nt,Nr)成正比分集增益。在采用空间分集方案的MIMO系统中,可以获得分集增益,即可靠性性能的改善。分集增益用独立衰落支路数来描述,即分集指数。在使用了空时编码的MIMO系统中,由于接收天线或发射天线之间的间距较远,可认为它们各自的大尺度衰落是相互独立的,因此分布式MIMO

随机推荐