将两个值作为字符串传递给同一个活动会返回一个值null

时间:2017-04-27 04:24:30

标签: java android string android-intent

这是我的代码,显示两个值:推荐的胰岛素剂量和给予的胰岛素剂量。这两个值被传递给另一个活动。

我使用了两个intent将两个值传递给另一个活动(NewActivity)。

问题是使用两个意图只显示一个值。输出显示为:

  

推荐的胰岛素用量:无效,给药的胰岛素用量:10(计算的正确值)。

如果从button.setOnClickListener中删除了startActivity(intent),则输出显示为:

  

推荐的胰岛素剂量:23(正确值),给药的胰岛素剂量:无效。

其中一个值变为null。如何显示两个值?

我尝试将字符串声明为公共

MainActivity.java

public class MainActivity extends Activity implements View.OnClickListener {

public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn;
private ProgressDialog mProgressDialog;
private Button button;
private Button button2;
private EditText editText;
private EditText editText2;
private EditText editText4;
public static String myid;
public static String insulin;
private Spinner dynamicSpinner;
private ProgressDialog loading;





   @Override
   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Intent intent=getIntent();
    String carbval=intent.getStringExtra("carbval");

    final EditText editText2 = (EditText) findViewById(R.id.editText2);
    editText2.setText(carbval);
    dynamicSpinner = (Spinner) findViewById(R.id.dynamic_spinner);

    editText = (EditText) findViewById(R.id.editText);
    button2 = (Button) findViewById(R.id.button2);
    button = (Button) findViewById(R.id.button);

    editText4=(EditText) findViewById(R.id.editText4);




   button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            String carbohydrate = editText2.getText().toString().trim();
            String dailydose = editText4.getText().toString().trim();
            int cc = Integer.parseInt(carbohydrate);
            int dd = Integer.parseInt(dailydose);
            int goc = 450 / dd;
            int ab = cc / goc;
            myid = Integer.toString(ab);
            Intent intent1=new Intent(MainActivity.this,NewActivity.class);
            intent1.putExtra("ids",myid);
            startActivity(intent1);


        }
    });




Spinner staticSpinner = (Spinner) findViewById(R.id.static_spinner);

    // Create an ArrayAdapter using the string array and a default spinner
    ArrayAdapter<CharSequence> staticAdapter = ArrayAdapter
            .createFromResource(this, R.array.brew_array,
                    android.R.layout.simple_spinner_item);

    // Specify the layout to use when the list of choices appears
    staticAdapter
            .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    // Apply the adapter to the spinner
    staticSpinner.setAdapter(staticAdapter);

    Spinner dynamicSpinner = (Spinner) findViewById(R.id.dynamic_spinner);

    String[] items = new String[] { "---SELECT---", "LOW", "MODERATE", "HIGH" };

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item, items);

    dynamicSpinner.setAdapter(adapter);

    dynamicSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view,
                                   int position, long id) {
            Log.v("item", (String) parent.getItemAtPosition(position));
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            // TODO Auto-generated method stub
        }
       });


    }




private void getData() {


    String bloodglucose = editText.getText().toString().trim();
    if (bloodglucose.equals("")) {
        Toast.makeText(this, "Please enter bloodglucose", Toast.LENGTH_LONG).show();
        return;
    }
    String dosage =dynamicSpinner.getSelectedItem().toString().trim();
    if (dosage.equals("")) {
        Toast.makeText(this, "Please enter dosage", Toast.LENGTH_LONG).show();
        return;
    }
    loading = ProgressDialog.show(this,"Please wait...","Calculating insulin dosage...",false,false);

    String url1 = "http://10.1.6.21/getData1.php?bloodglucose="+editText.getText().toString().trim()+"&dosage="+dynamicSpinner.getSelectedItem().toString().trim();


    StringRequest stringRequest = new StringRequest(url1, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            loading.dismiss();
            showJSON(response);
        }
     },
            new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(MainActivity.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
                }
            });


    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);

     }

    private void showJSON(String response){

    String insulin="";



    try {
        JSONObject jsonObject = new JSONObject(response);
        JSONArray result = jsonObject.getJSONArray(Confignew.JSON_ARRAY);
        JSONObject collegeData = result.getJSONObject(0);

         insulin = collegeData.getString(Confignew.KEY_INSULIN);

        Intent intent1=new Intent(MainActivity.this,NewActivity.class);
        intent1.putExtra("value",insulin);

       startActivity(intent1);


       } catch (JSONException e) {
        e.printStackTrace();
       }


    }

    @Override
    public void onClick(View v) {
    getData();

    }

    }

NewActivity.java

public class NewActivity extends AppCompatActivity {

   private Button mBtGoBack;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_new);
    TextView tvmessage=(TextView) findViewById(R.id.tv_message);
    tvmessage.setText("Recommended Insulin Dosage:  "+getIntent().getExtras().getString("value"));

    TextView tvmessage1=(TextView) findViewById(R.id.tv_message1);
    tvmessage1.setText("Administered Insulin Dosage:  "+getIntent().getExtras().getString("ids"));
    mBtGoBack = (Button) findViewById(R.id.bt_go_back);

    mBtGoBack.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            finish();
        }
      });

      }
     }

4 个答案:

答案 0 :(得分:0)

查看代码,看起来您在开始活动之前重新创建了意图。您创建的每个意图只有一个值传递给NewActivity.java。您需要将两个值添加到同一个intent而不是重新创建它。

以下是您的问题:

    Intent intent1=new Intent(MainActivity.this,NewActivity.class);
    intent1.putExtra("ids",myid);

    Intent intent1=new Intent(MainActivity.this,NewActivity.class);
    intent1.putExtra("value",insulin);

您应该只创建一次Intent,然后根据需要添加额外内容,而不是将其实例化两次。

答案 1 :(得分:0)

  

这两个值被传递给另一个活动

您只在每个startActivity来电中将一个值传递给意图,而不是两个。这就是为什么一个是空的而另一个不是。

下面

   Intent intent1=new Intent(MainActivity.this,NewActivity.class);
   intent1.putExtra("value",insulin);
   startActivity(intent1);

在这里

    Intent intent1=new Intent(MainActivity.this,NewActivity.class);
    intent1.putExtra("ids",myid);
    startActivity(intent1);

仅仅因为您将其命名为intent1并不意味着数据是共享的。

您需要在意图中放置两个附加内容 如何制作一个帮助方法,所以你不要忘记?

private void startNewActivity(String recommended, String administered) {
    Intent i = new Intent(MainActivity.this,NewActivity.class);
    i.putExtra("value",recommended);
    i.putExtra("ids", administered);
    startActivity(i);
}

然后使用它来获得两个正确的值。

startNewActivity("23", "10"); 

顺便说一下,这个按钮事件从未实际运行过。

 button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        String carbohydrate = editText2.getText().toString().trim();
        String dailydose = editText4.getText().toString().trim();
        int cc = Integer.parseInt(carbohydrate);
        int dd = Integer.parseInt(dailydose);
        int goc = 450 / dd;
        int ab = cc / goc;
        myid = Integer.toString(ab);

       // Replace this code with the method
       /*
        Intent intent1=new Intent(MainActivity.this,NewActivity.class);
        intent1.putExtra("ids",myid);
        startActivity(intent1);
      */


    }
});

这是......它会覆盖前一个。

button.setOnClickListener(this);

这是

@Override
public void onClick(View v) {
    getData();
}

答案 2 :(得分:0)

一个Intent可以打开一个Activity。您要做的是从Intent内重新创建的两个onClicks发送值。

您必须使用任何一种方法提供onClick。您首先使用clickListener类在Button上设置了Anonymous,并同时实施了OnClickListener

从按钮中删除onClickListener

下面的部分
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        String carbohydrate = editText2.getText().toString().trim();
        String dailydose = editText4.getText().toString().trim();
        int cc = Integer.parseInt(carbohydrate);
        int dd = Integer.parseInt(dailydose);
        int goc = 450 / dd;
        int ab = cc / goc;
        myid = Integer.toString(ab);
        Intent intent1=new Intent(MainActivity.this,NewActivity.class);
        intent1.putExtra("ids",myid);
        startActivity(intent1);


    }
});

保持你的overrdien onClick不变。

@Override
public void onClick(View v) {
    getData();
}

现在编辑您的getData()方法以添加已删除的代码

private void getData() {
    String bloodglucose = editText.getText().toString().trim();
    if (bloodglucose.equals("")) {
        Toast.makeText(this, "Please enter bloodglucose", Toast.LENGTH_LONG).show();
        return;
    }
    String dosage =dynamicSpinner.getSelectedItem().toString().trim();
    if (dosage.equals("")) {
        Toast.makeText(this, "Please enter dosage", Toast.LENGTH_LONG).show();
        return;
    }
    loading = ProgressDialog.show(this,"Please wait...","Calculating insulin dosage...",false,false);

    String url1 = "http://10.1.6.21/getData1.php?bloodglucose="+editText.getText().toString().trim()+"&dosage="+dynamicSpinner.getSelectedItem().toString().trim();


    StringRequest stringRequest = new StringRequest(url1, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            loading.dismiss();
            showJSON(response);
        }
     }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(MainActivity.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
            }
        });


    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);

}

最后showJSON

private void showJSON(String response){
    String insulin="";
    try {
        JSONObject jsonObject = new JSONObject(response);
        JSONArray result = jsonObject.getJSONArray(Confignew.JSON_ARRAY);
        JSONObject collegeData = result.getJSONObject(0);

        //The code from button's onClickListener
        String carbohydrate = editText2.getText().toString().trim();
        String dailydose = editText4.getText().toString().trim();
        int cc = Integer.parseInt(carbohydrate);
        int dd = Integer.parseInt(dailydose);
        int goc = 450 / dd;
        int ab = cc / goc;
        myid = Integer.toString(ab);
        Intent intent1 = new Intent(MainActivity.this,NewActivity.class);
        intent1.putExtra("ids",myid);
        //startActivity(intent1); Put second value too before starting activity


        insulin = collegeData.getString(Confignew.KEY_INSULIN);

        intent1.putExtra("value",insulin);

       startActivity(intent1);


    } catch (JSONException e) {
        e.printStackTrace();
    `enter code here`}
}

答案 3 :(得分:-1)

@Rasiga你可以告诉我为什么2 OnCickListener被设置为

`button.setOnClickListener(this)` 

button.setOnClickListener(new OnCLickListner){.....} 

您为同一个视图设置2 onCLickListener