java - Android 应用程序在传递字符串时崩溃

标签 java android string http bundle

我在两个 Activity 之间传递两个字符串,由于某种原因,当我尝试接受该字符串时它崩溃了。我觉得,我错过了一些重要的事情,但找不到任何我可能错过的代码。谷歌几乎没有结果,我真的很生气,因为这似乎是一个非常基本的任务。

任何帮助,我们将不胜感激:)

日志猫:

 03-25 04:23:03.476: E/AndroidRuntime(1174): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gta5news.bananaphone/com.gta5news.bananaphone.ChatService}: java.lang.NullPointerException
03-25 04:23:03.476: E/AndroidRuntime(1174):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
03-25 04:23:03.476: E/AndroidRuntime(1174):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
03-25 04:23:03.476: E/AndroidRuntime(1174):     at android.app.ActivityThread.access$2300(ActivityThread.java:125)
03-25 04:23:03.476: E/AndroidRuntime(1174):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
03-25 04:23:03.476: E/AndroidRuntime(1174):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-25 04:23:03.476: E/AndroidRuntime(1174):     at android.os.Looper.loop(Looper.java:123)
03-25 04:23:03.476: E/AndroidRuntime(1174):     at android.app.ActivityThread.main(ActivityThread.java:4627)
03-25 04:23:03.476: E/AndroidRuntime(1174):     at java.lang.reflect.Method.invokeNative(Native Method)
03-25 04:23:03.476: E/AndroidRuntime(1174):     at java.lang.reflect.Method.invoke(Method.java:521)
03-25 04:23:03.476: E/AndroidRuntime(1174):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
03-25 04:23:03.476: E/AndroidRuntime(1174):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
03-25 04:23:03.476: E/AndroidRuntime(1174):     at dalvik.system.NativeStart.main(Native Method)
03-25 04:23:03.476: E/AndroidRuntime(1174): Caused by: java.lang.NullPointerException
03-25 04:23:03.476: E/AndroidRuntime(1174):     at com.gta5news.bananaphone.ChatService.GetLogInData(ChatService.java:76)
03-25 04:23:03.476: E/AndroidRuntime(1174):     at com.gta5news.bananaphone.ChatService.onCreate(ChatService.java:47)
03-25 04:23:03.476: E/AndroidRuntime(1174):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
03-25 04:23:03.476: E/AndroidRuntime(1174):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
03-25 04:23:03.476: E/AndroidRuntime(1174):     ... 11 more

代码(第二个 Activity ,崩溃)

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

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




    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        GetLogInData();


        try {
            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 GetLogInData() {
        // TODO Auto-generated method stub
        Bundle gotData = getIntent().getExtras();
        GotPass = gotData.getString("key!");
        GotUname = gotData.getString("key!!");

    }




    private void CheckLogin() throws UnsupportedEncodingException {

    }
    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"

}

第一个 Activity

public class LogIn extends Activity implements OnClickListener {

    Button ok, back, exit;
    TextView result;
    EditText pword;
    EditText uname;

    /** 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() {
        // 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
            uname = (EditText) findViewById(R.id.txt_username);
            String username = uname.getText().toString();


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


            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", "Execute HTTP Post Request");
            HttpResponse response = httpclient.execute(httppost);

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

            if (str.toString().equalsIgnoreCase("true")) {
                Log.w("HttpPost", "TRUE");
                result.setText("Login successful");
                try {Thread.sleep(250);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                Intent login = new Intent(LogIn.this, ChatService.class);
                startActivity(login);

            } else {
                Log.w("HttpPost", "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

最佳答案

检查null:

Bundle gotData = getIntent().getExtras();
if(gotData != null)
{
    GotPass = gotData.getString("key!");
    GotUname = gotData.getString("key!!");
}

关于java - Android 应用程序在传递字符串时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10044699/

相关文章:

java - 错误 :Could not determine the dependencies of task ':app:compileDebugJavaWithJavac'

android - 从 SD 卡浏览图像以在 android 的 ImageView 中显示它?

C#:是否与 C# 的 php ctype_digit 函数类似?

python - 如何有效地将两列合并为一列/合并字符串?

java - 如何从 Servlet 向 JSP 发送数据?

java - Apache Curator 锁定食谱撤销

Java Swing : return value when button clicked

android - 如何识别 ListViewItem 以更新单行

Android:定期(每 30 秒)在后台发送位置数据并向服务器请求新数据

javascript - 如何使用 JS Regex 从 google 查询链接获取查询值? (Chrome 扩展)