为什么我不能在URLConnection中使用收到的数据供以后使用?

时间:2015-08-26 20:03:37

标签: android

请参阅以下代码。在以下代码中,当我使用Toast.makeText(getApplicationContext(),text,Toast.LENGTH_SHORT).show();时,我可以看到 text小部件中Toast字符串的内容,但是当我想使用时 text字符串的内容供以后使用,例如转到其他活动,我很有成功。请注意,我的php代码仅将yes流发送到android,并且以下代码中的条件为真。

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
   try{
        GetText();
    }
catch(Exception e) {Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_SHORT).show();}}
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
void GetText(){
    BufferedReader reader = null;
    String text = null;
    try{
    URL url = new URL("http://127.0.0.1:8080/apps/request.php");
        URLConnection urlConnection = url.openConnection();
        reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line = null;

        // Read Server Response
        while((line = reader.readLine()) != null)
        {
            // Append server response in string
            sb.append(line);
        }


        text = sb.toString();
    }
    catch(Exception ex)
    {

    }
    finally
    {
        try
        {

            reader.close();
        }

        catch(Exception ex) {}
    }

    // Show response on activity
    Toast.makeText(getApplicationContext(),text,Toast.LENGTH_SHORT).show();
if(text.equals("yes")){

    Intent intent = new Intent(MainActivity.this,Test.class);//I can not go to the Test.class
startActivity(intent);
}}
    }

PHP.CODE

<?php

echo "yes";
?>

0 个答案:

没有答案