微调器值不从一个活动传递到另一个活动

时间:2018-03-16 18:28:46

标签: java android

ViewToken.class:

    spinnerGenre = (Spinner) findViewById(R.id.spinnerGenres);
    spinnerGenre1 = (Spinner) findViewById(R.id.spinner);

    docname = spinnerGenre1.getSelectedItem().toString();
    session = spinnerGenre.getSelectedItem().toString();

    next=(Button)findViewById(R.id.button4);
    next.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent next=new Intent(ViewToken.this,Tokens.class);
            next.putExtra("docname", docname.toString());
            next.putExtra("session", session.toString());
            startActivity(next);
        }
    });

Tokens.class

    Intent i2 = getIntent();
    final String docname = i2.getStringExtra("docname");
    final String session = i2.getStringExtra("session");

ViewToken.class中的微调器值未传递给Tokens.class

4 个答案:

答案 0 :(得分:1)

在ViewToken.class中更改此内容

next.putExtra("docname", docname);
next.putExtra("session", session);

您可以在Tokens.class中执行以下操作

Bundle extras = getIntent().getExtras();
String docname = extras.getString("docname");
String session = extras.getString("session");

答案 1 :(得分:1)

getSelectedItem()的调用应在onClick侦听器中进行,以便获取所选的最新值。

相反,onClick()方法将是:

@Override
public void onClick(View v) {
    docname = spinnerGenre1.getSelectedItem().toString();
    session = spinnerGenre.getSelectedItem().toString();
    Intent next=new Intent(ViewToken.this,Tokens.class);
    next.putExtra("docname", docname);
    next.putExtra("session", session);
    startActivity(next);
}

可能会在选择任何内容之前调用getSelectedItem(),因此意图内的值put()不正确。

答案 2 :(得分:0)

在发送之前从微调器中获取值。

next.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        docname = spinnerGenre1.getSelectedItem().toString();
        session = spinnerGenre.getSelectedItem().toString();

        Intent next=new Intent(ViewToken.this,Tokens.class);
        next.putExtra("docname", docname.toString());
        next.putExtra("session", session.toString());
        startActivity(next);
    }
});

答案 3 :(得分:0)

int positionOfSelectedDataFromSpinner;
iv.putExtra("position", positionOfSelectedDataFromSpinner);

创建一个新方法

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                positionOfSelectedDataFromSpinner= i;
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

在第二个活动中

int positionToShowToSpinner = iv.getIntExtra("position",0);
spinner.setSelection(positionToShowToSpinner);