java - 字符串无法在两个 Activity 之间传递

标签 java android string http

我在两个 Activity 之间传递两个字符串,由于某种奇怪的原因,这些字符串没有被传递。我已经完成了所有正确的协议(protocol),但似乎没有任何效果,尽管对代码进行了几个小时的修改,我确信这是一个简单的解决方案,但我不知道,到底是怎么回事。

一级:

public class LogIn extends Activity implements OnClickListener {

    Button ok, back, exit;
    TextView result;
    EditText pword;
    String password;
    EditText uname;
    String username;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Login button clicked
        ok = (Button) findViewById(R.id.btn_login);
        ok.setOnClickListener(this);

        result = (TextView) findViewById(R.id.lbl_result);

    } 
    //create bracket.

    public void postLoginData() {
        uname = (EditText) findViewById(R.id.txt_username);
        uname.getText().toString();


        pword = (EditText) findViewById(R.id.txt_password);
        pword.getText().toString();
        Bundle basket = new Bundle();
        basket.putString("keypass", password);
        basket.putString("keyuname", username);
        Intent a = new Intent(LogIn.this, ChatService.class );
        a.putExtras(basket);
        startActivity(a);


        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();

        /* login.php returns true if username and password is equal to saranga */
        HttpPost httppost = new HttpPost("http://gta5news.com/login.php");

        try {
            // Add user name and password


            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("username", username));
            nameValuePairs.add(new BasicNameValuePair("password", password));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            Log.w("HttpPost(Login)", "Execute HTTP Post Request(Login 1)");
            HttpResponse response = httpclient.execute(httppost);

            String str = inputStreamToString(response.getEntity().getContent())
                    .toString();
            Log.w("HttpPost", str);

            if (str.toString().equalsIgnoreCase("true")) {
                Log.w("HttpPost(Login2)", "TRUE");
                result.setText("Login successful");
                Intent login = new Intent(LogIn.this, ChatService.class);
                startActivity(login);

            }else {
                Log.w("HttpPost(Login(3)", "FALSE");
                result.setText(str);
            }

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private StringBuilder inputStreamToString(InputStream is) {
        String line = "";
        StringBuilder total = new StringBuilder();
        // Wrap a BufferedReader around the InputStream
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        // Read response until the end
        try {
            while ((line = rd.readLine()) != null) {
                total.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        // Return full string
        return total;
    }

    public void onClick(View view) {
        if (view == ok) {

            postLoginData();
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(pword.getWindowToken(), 0);
        }
        // Click end
    }
    // if statement
}

// class ends here

二等:

public class ChatService extends ListActivity {
    /** Called when the activity is first created. */

    BufferedReader in = null;
    String data = null;
    List headlines;
    List links;
    String GotPass;
    String GotUname;




    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //get strings
        Bundle gotData = getIntent().getExtras();
        if(gotData !=null) {
        GotPass = gotData.getString("keypass");
        GotUname = gotData.getString("keyuname");


        try {
            //listview method
            ContactsandIm();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            CheckLogin();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    }


    private void CheckLogin() throws UnsupportedEncodingException {
// posts login data from "LogIn" class
        // Create a new HttpClient and Post Header
                HttpClient httpclient = new DefaultHttpClient();

                /* login.php returns true if username and password is equal to saranga */
                HttpPost httppost = new HttpPost("http://gta5news.com/login.php");

                try {
                    // Add user name and password


                    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                    nameValuePairs.add(new BasicNameValuePair("username", GotUname));
                    nameValuePairs.add(new BasicNameValuePair("password", GotPass));
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                    // Execute HTTP Post Request
                    Log.w("HttpPost(Login)", "Execute HTTP Post Request(ChatService 1)");
                    HttpResponse response = httpclient.execute(httppost);

                    String str = inputStreamToString(response.getEntity().getContent())
                            .toString();
                    Log.w("HttpPost", str);

                    if (str.toString().equalsIgnoreCase("true")) {
                        Log.w("HttpPost(ChatService 2)", "TRUE");
                        // make toast if str.equals("True")
                        Toast.makeText(getApplicationContext(), "Yayayaya, loged in", Toast.LENGTH_LONG );


                    }else {
                        Log.w("HttpPost(ChatService 3", "FALSE");
                        Toast.makeText(getApplicationContext(), "failed", Toast.LENGTH_LONG);
                    }

                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            private StringBuilder inputStreamToString(InputStream is) {
                String line = "";
                StringBuilder total = new StringBuilder();
                // Wrap a BufferedReader around the InputStream
                BufferedReader rd = new BufferedReader(new InputStreamReader(is));
                // Read response until the end
                try {
                    while ((line = rd.readLine()) != null) {
                        total.append(line);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                // Return full string
                return total;
            }

    public void ContactsandIm() throws URISyntaxException,
            ClientProtocolException, IOException {
        headlines = new ArrayList();

        // TODO Auto-generated method stub
        BufferedReader in = null;
        String data = null;

        HttpClient get = new DefaultHttpClient();
        URI website = new URI("http://www.gta5news.com/test.php");
        HttpGet webget = new HttpGet();
        webget.setURI(website);
        HttpResponse response = get.execute(webget);
        Log.w("HttpPost", "Execute HTTP Post Request");
        in = new BufferedReader(new InputStreamReader(response.getEntity()
                .getContent()));
        StringBuffer sb = new StringBuffer("");
        String l ="";
        String nl ="";
        while ((l =in.readLine()) !=null) {
            sb.append(l + nl);  
        }
        in.close();
         data = sb.toString();
         if(data.contains("null"));
         ListView lv = getListView();
         lv.setTextFilterEnabled(true);

        headlines.add(data);


        ArrayAdapter adapter = new ArrayAdapter(this,
                android.R.layout.simple_list_item_1, headlines);

        setListAdapter(adapter);



    }

    // end bracket for "ContactsandIm"

}

最佳答案

试试这个方法。

    Intent a = new Intent(context, MyActivity.class);
    a.putExtra("String1", "Hello World");
    context.startActivity(a);

    Bundle extras = getIntent().getExtras();
    String s1 = extras.getString("String1");

关于java - 字符串无法在两个 Activity 之间传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10048220/

相关文章:

java - Saxon 是否提供了对返回节点进行排序的方法?

java - SWIG C++ 列表到 Java

android - 如何在 Android Studio 3.0 版本中打开 AVD 管理器?

android - UiAutomator Android - setText 方法不起作用。!

arrays - 如何快速获取字符串数组中的最后 8 个字符?

java - 如何创建与引号外的特定文本匹配的正则表达式

java - ProcessBuilder 向命令行添加额外的引号

java - 如何将java应用程序嵌入到jsp页面中

java - 使用重写方法之外的值会导致 null

c++ - C 字符串和 std::string 之间的转换导致平台特定方式出现乱码