简体   繁体   中英

Android App Crashing, when passing strings

I'm passing two strings between two activities and for some reason, it crashes when I try to accept the string. I feel like, I've missed something important out, but can't find any code, that I could of missed out. Google yielded, little to no results and I'm really annoyed as this seems to be a pretty basic task.

Any help, would be gratefully appreciated:)

LogCat:

 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

Code(Second activity, that crashes)

  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"

}

1st 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

Check for null :

Bundle gotData = getIntent().getExtras();
if(gotData != null)
{
    GotPass = gotData.getString("key!");
    GotUname = gotData.getString("key!!");
}
 in.close();
     data = sb.toString();
     if(data.contains("null"));
     ListView lv = getListView();
     lv.setTextFilterEnabled(true);

Why is null in quotes here? If you are looking for the string "null" that's one thing, but contains() throws nullpointerexception if it references a null string.

Also, it looks like you have an unnecessary semicolon at the end of your if statement.

Make ensure that your second activity class is added into your app manifest file or not. If it is already added into your manifest file, then call -

startActivity(yourSecondIntentActivity);
finish();

Have fun...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM