字符串无法在两个活动之间传递

时间:2012-04-06 19:21:45

标签: java android string http

我在两个活动之间传递了两个字符串,由于一些奇怪的原因,字符串没有被传递。我已经完成了所有正确的协议,似乎没有任何工作,尽管在几个小时内修改代码,我确信这是一个简单的解决方案,但我不知道,有什么用。

第一课:

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"

}

3 个答案:

答案 0 :(得分:1)

试试这种方式。

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

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

答案 1 :(得分:0)

您应该在Manifest.xml文件中添加两个活动

答案 2 :(得分:0)

检查您是否在清单文件中注册了您的活动。