运行android项目时“关闭VM”错误

时间:2014-05-16 04:43:31

标签: android nullpointerexception android-activity runtimeexception

以下是例外的 logcat

05-09 15:03:37.623: D/AndroidRuntime(25205): Shutting down VM  05-09 15:03:37.643: W/dalvikvm(25205): threadid=1: thread exiting with uncaught exception (group=0x40a71930)   
05-09 15:03:37.763: E/AndroidRuntime(25205): FATAL EXCEPTION: main   
05-09 15:03:37.763: E/AndroidRuntime(25205): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.bugs3.munishgupta.cabup/com.bugs3.munishgupta.cabup.Profile}: java.lang.NullPointerException   
05-09 15:03:37.763: E/AndroidRuntime(25205):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)   
05-09 15:03:37.763: E/AndroidRuntime(25205):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)   
05-09 15:03:37.763: E/AndroidRuntime(25205):    at android.app.ActivityThread.access$600(ActivityThread.java:141)   
05-09 15:03:37.763: E/AndroidRuntime(25205):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)   
05-09 15:03:37.763: E/AndroidRuntime(25205):    at android.os.Handler.dispatchMessage(Handler.java:99)   
05-09 15:03:37.763: E/AndroidRuntime(25205):    at android.os.Looper.loop(Looper.java:137)   
05-09 15:03:37.763: E/AndroidRuntime(25205):    at android.app.ActivityThread.main(ActivityThread.java:5041)   
05-09 15:03:37.763: E/AndroidRuntime(25205):    at java.lang.reflect.Method.invokeNative(Native Method)   
05-09 15:03:37.763: E/AndroidRuntime(25205):    at java.lang.reflect.Method.invoke(Method.java:511)   
05-09 15:03:37.763: E/AndroidRuntime(25205):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)   
05-09 15:03:37.763: E/AndroidRuntime(25205):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)   
05-09 15:03:37.763: E/AndroidRuntime(25205):    at dalvik.system.NativeStart.main(Native Method)   
05-09 15:03:37.763: E/AndroidRuntime(25205): Caused by: java.lang.NullPointerException   
05-09 15:03:37.763: E/AndroidRuntime(25205):    at com.bugs3.munishgupta.cabup.Profile.onCreate(Profile.java:29)   
05-09 15:03:37.763: E/AndroidRuntime(25205):    at android.app.Activity.performCreate(Activity.java:5104)  \
05-09 15:03:37.763: E/AndroidRuntime(25205):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)   
05-09 15:03:37.763: E/AndroidRuntime(25205):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)   
05-09 15:03:37.763: E/AndroidRuntime(25205):     ... 11 more   
05-09 15:04:07.774: I/Process(25205): Sending signal. PID: 25205 SIG: 9

以下是有错误的代码(Login.java)

package com.bugs3.munishgupta.cabup;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import com.bugs3.munishgupta.cabup.R;
import com.bugs3.munishgupta.cabup.JSONParser;
import com.bugs3.munishgupta.cabup.Login;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;


public class Login extends Activity {

    CheckBox ocbShowPass;
    RadioGroup type;
    RadioButton rbType;
    EditText oetEmail,oetPassword;
    Button obtSignup, obtSubmit;
    private ProgressDialog pDialog;
    JSONParser jsonParser = new JSONParser();

    String stre,strp, radio;
    private static final String LOGIN_URL = "http://10.0.2.2/android_login_api/max.php";
    Intent iprofile;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        ocbShowPass=(CheckBox)findViewById(R.id.showPassCB);
        oetEmail=(EditText)findViewById(R.id.eUserName);
        type=(RadioGroup)findViewById(R.id.logType);
        oetPassword=(EditText)findViewById(R.id.ePassword);
        obtSignup=(Button)findViewById(R.id.btnRegister);
        obtSubmit=(Button)findViewById(R.id.btnSubmit);
        ocbShowPass.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // TODO Auto-generated method stub
                if(isChecked)
                {
                    oetPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                }
                else
                {
                    oetPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
            }
        });
        obtSignup.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent regIntent=new Intent(Login.this, Registration.class);
                startActivity(regIntent);
            }
        });
        obtSubmit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                stre=oetEmail.getText().toString();
                strp=oetPassword.getText().toString();
                if(stre.equals("")||stre.length()!=10)//(android.util.Patterns.PHONE.matcher("+91"+stre).matches()==false)||
                {
                    oetEmail.setError("Enter valid Mobile no.");
                }
                else if(strp.equals(""))
                {
                    oetPassword.setError("Enter Password");
                }
                else
                {

                    rbType=(RadioButton)findViewById(type.getCheckedRadioButtonId());
                    radio=rbType.getText().toString();
                    new AttemptLogin().execute();
                /*  if(loginForm(stre,strp,rbType.getText().toString().toLowerCase()))
                    {
                        iprofile=new Intent(Login.this,Profile.class);
                        startActivity(iprofile);
                    }
                    else
                    {
                        Toast.makeText(getApplicationContext(), "Login Failed ", Toast.LENGTH_SHORT).show();
                        Toast.makeText(getApplicationContext(), "Email or Password not matched ", Toast.LENGTH_SHORT).show();
                    }
                */
                }
            }
        });
    }
   /* public boolean loginForm(String mob, String password, String UserType)
    {
        new AttemptLogin().execute();
        return true;
    }*/
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.taxi_pool, menu);
        return true;
    }

    class AttemptLogin extends AsyncTask<String, String, String> {

         /**
        * Before starting background thread Show Progress Dialog
        * */
        boolean failure = false;

       @Override
       protected void onPreExecute() {
           super.onPreExecute();
           pDialog = new ProgressDialog(Login.this);
           pDialog.setMessage("Attempting login...");
           pDialog.setIndeterminate(false);
           pDialog.setCancelable(true);
           pDialog.show();
       }

        @Override
        protected String doInBackground(String... args) {
            // TODO Auto-generated method stub
             // Check for success tag
           String username = oetEmail.getText().toString();
           String password = oetPassword.getText().toString();
           try {
               // Building Parameters
               List<NameValuePair> params = new ArrayList<NameValuePair>();
               params.add(new BasicNameValuePair("op", "select"));
               params.add(new BasicNameValuePair("query","select * from "+ radio
                       + " where `mob`='" + username + "' and `password`='" + password +"'" ));

               Log.d("request!", "starting");
               // getting product details by making HTTP request
               JSONObject json = jsonParser.makeHttpRequest(
                      LOGIN_URL, "GET", params);

               // check your log for json response
               Log.d("Login attempt", json.toString());

               // json success tag

               if (json.getString("mob").toString().equalsIgnoreCase(username)) {

                    Log.d("Login Successful!", json.getString("mob"));
                    pDialog.dismiss();
                    //Toast.makeText(getApplicationContext(), "Logging in...", Toast.LENGTH_SHORT).show();
                    Intent i = new Intent(Login.this, Profile.class);
                    i.putExtra("mob", username);   
                    if(radio.equalsIgnoreCase("driver"))
                    {               
                        Log.d("putting Car no",json.getString("carNo"));
                        i.putExtra("carno",json.getString("carNo"));
                    }
                    finish();
                    startActivity(i);
                    return json.getString("mob");
               }
               else{
                    Log.d("Login Failure!", "no info exits");
                    return null;
               }
           } catch (Exception e) {
               Log.d("JSON Error",e.getMessage());
           }
           return null;         
        }
        /**
        * After completing background task Dismiss the progress dialog
        * **/
       protected void onPostExecute(String file_url) {
           // dismiss the dialog once product deleted
           pDialog.dismiss();
           if (file_url != null){
            Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
           }

       }

    }
}
}

这是Profile.java代码

package com.bugs3.munishgupta.cabup;

import com.bugs3.munishgupta.cabup.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class Profile extends Activity {

    Button obhier, obshare, obsettings;
    Intent info;
    String mob;
    Bundle b;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.profile);
        obhier=(Button) findViewById(R.id.btnHier);
        obshare=(Button) findViewById(R.id.btnShare);
        obsettings=(Button) findViewById(R.id.btnSetting);
        info = getIntent();
        b  = info.getExtras();
        if( ! (b.getString("carno").equals(null) ) )
        Toast.makeText(getApplicationContext(), b.get("carno").toString(), Toast.LENGTH_SHORT).show();
        obshare.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent wshare=new Intent(Profile.this,WannaShare.class);
                if(b.getString("mob")!=null)
            {
                mob = b.getString("mob");
                    wshare.putExtra("mob", mob);
                }
                startActivity(wshare);
            }
        });
        obhier.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent whier=new Intent(Profile.this,WannaHier.class);
                if(b.getString("mob")!=null)
            {
                mob = b.getString("mob");
                    whier.putExtra("mob", mob);
                }
                startActivity(whier);
            }
        });
        obsettings.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent isetting = new Intent(Profile.this,ChangeSetting.class);
                if(b.getString("mob")!=null)
            {
                mob = b.getString("mob");
                    isetting.putExtra("mob", mob);
                }
                startActivity(isetting);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.profile, menu);
        return true;
    }
}

1 个答案:

答案 0 :(得分:1)

在Login.java中,传递给intent的String处于if条件

 if(radio.equalsIgnoreCase("driver"))
                    {               
                        Log.d("putting Car no",json.getString("carNo"));
                        i.putExtra("carno",json.getString("carNo"));
                    }  

所以在Profile.java的onCreate()中,

 b.get("carno").toString()

会在未通过值时抛出NPE,我认为这是这种情况。

把吐司放在里面  if(b.get("carno").getString!=null)
OR
在if条件之前,在Login.java中,默认情况下传递一些东西,如:

i.putExtra("carno","!(radio equals driver)");  

需要检查一下,检查吐司内部的修正:

 if((b.getString("carno")!=null) ){
        Toast.makeText(this, b.getString("carno").toString(), Toast.LENGTH_SHORT).show();}