尝试通过JSON登录,但有运行时错误

时间:2013-12-08 04:14:30

标签: android json

这是我的logcat

12-08 13:37:39.849: W/dalvikvm(5757): threadid=1: thread exiting with uncaught exception (group=0x40018578)
12-08 13:37:39.859: E/AndroidRuntime(5757): FATAL EXCEPTION: main
12-08 13:37:39.859: E/AndroidRuntime(5757): java.lang.NullPointerException
12-08 13:37:39.859: E/AndroidRuntime(5757):     at com.pmss.Login$1.onClick(Login.java:55)
12-08 13:37:39.859: E/AndroidRuntime(5757):     at android.view.View.performClick(View.java:2485)
12-08 13:37:39.859: E/AndroidRuntime(5757):     at android.view.View$PerformClick.run(View.java:9080)
12-08 13:37:39.859: E/AndroidRuntime(5757):     at android.os.Handler.handleCallback(Handler.java:587)
12-08 13:37:39.859: E/AndroidRuntime(5757):     at android.os.Handler.dispatchMessage(Handler.java:92)
12-08 13:37:39.859: E/AndroidRuntime(5757):     at android.os.Looper.loop(Looper.java:130)
12-08 13:37:39.859: E/AndroidRuntime(5757):     at android.app.ActivityThread.main(ActivityThread.java:3687)
12-08 13:37:39.859: E/AndroidRuntime(5757):     at java.lang.reflect.Method.invokeNative(Native Method)
12-08 13:37:39.859: E/AndroidRuntime(5757):     at java.lang.reflect.Method.invoke(Method.java:507)
12-08 13:37:39.859: E/AndroidRuntime(5757):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
12-08 13:37:39.859: E/AndroidRuntime(5757):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
12-08 13:37:39.859: E/AndroidRuntime(5757):     at dalvik.system.NativeStart.main(Native Method)

这是我的Login.java

public class Login extends ActionBarActivity implements OnClickListener  {

private Button login,register;
private EditText email,password;
// Progress Dialog
    private ProgressDialog pDialog;
    JSONParser jsonParser = new JSONParser();

    private static final String LOGIN_URL = "http://192.168.1.14:1234/PMSS/login.php";      
  //JSON element ids from repsonse of php script:
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";


@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    login = (Button) findViewById(R.id.login);
    register = (Button) findViewById(R.id.register);
    email = (EditText) findViewById(R.id.emailtext);
    password = (EditText) findViewById(R.id.passwordtext);

    login.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            new AttemptLogin().execute();
        }
    });

    register.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(Login.this, Register.class);
            startActivity(intent);

        }
    });
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        // For the main activity, make sure the app icon in the action bar
        // does not behave as a button
        getSupportActionBar().setDisplayHomeAsUpEnabled(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.login, menu);
    return true;
}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
    /*case R.id.login:
            new AttemptLogin().execute();
        break;
    case R.id.register:
            Intent i = new Intent(Login.this, Register.class);
            startActivity(i);
        break;
*/
    default:
        break;
    }
}

//AsyncTask is a seperate thread than the thread that runs the GUI
    //Any type of networking should be done with asynctask.
    class AttemptLogin extends AsyncTask<String, String, String> {

        //three methods get called, first preExecture, then do in background, and once do
        //in back ground is completed, the onPost execture method will be called.
            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) {
            int success;
            String Username = email.getText().toString();
            String Password = password.getText().toString();
            try {
                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("username", Username));
                params.add(new BasicNameValuePair("password", Password));

                Log.d("request!", "starting");
                // getting product details by making HTTP request
                JSONObject json = jsonParser.makeHttpRequest(
                       LOGIN_URL, "POST", params);
                System.out.print("Here");
                // check your log for json response
                Log.d("Login attempt", json.toString());

                // json success tag
                success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    Log.d("Login Successful!", json.toString());
                    Intent i = new Intent(Login.this, MainMenu.class);
                    finish();
                    startActivity(i);
                    return json.getString(TAG_MESSAGE);
                }else{
                    Log.d("Login Failure!", json.getString(TAG_MESSAGE));
                    return json.getString(TAG_MESSAGE);

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;

        }

        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();
            }

        }
    }

}

正如我应该提到的,一旦我点击登录按钮,它就会出现Attemping Login ...然后几秒钟就会变得强行关闭..我发现了logcat错误,但不知道要纠正它...

顺便说一句,我的Android应用程序连接到Wi-Fi,我的笔记本电脑也连接到同一个Wi-Fi,我可以通过我的手机访问login.php,其URL为{{1} }

这是我的activity.login.xml

http://192.168.XX.XX:1234/PMSS/login.php

1 个答案:

答案 0 :(得分:0)

试试这个..

您的异步class AttemptLogin extends AsyncTask<String, String, String> {

您无法在Intent中传递doInBackground,以便发生错误,请尝试以下代码

    protected String doInBackground(String... args) {
        int success;
        String res;
        String Username = email.getText().toString();
        String Password = password.getText().toString();
        try {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("username", Username));
            params.add(new BasicNameValuePair("password", Password));

            Log.d("request!", "starting");
            // getting product details by making HTTP request
            JSONObject json = jsonParser.makeHttpRequest(
                   LOGIN_URL, "POST", params);
            System.out.print("Here");
            // check your log for json response
            Log.d("Login attempt", json.toString());

            // json success tag
            success = json.getInt(TAG_SUCCESS);
            res = json.getString(TAG_MESSAGE);

            return null;
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;

    }

    protected void onPostExecute(String result) {
        // dismiss the dialog once product deleted
        pDialog.dismiss();

            if (success == 1) {
                Log.d("Login Successful!", res);
                Intent i = new Intent(Login.this, MainMenu.class);
                finish();
                startActivity(i);
                return ;
                Toast.makeText(Login.this, res, Toast.LENGTH_LONG).show();
            }else{
                Log.d("Login Failure!", json.getString(TAG_MESSAGE));
                Toast.makeText(Login.this, res, Toast.LENGTH_LONG).show();
            }

    }
}

编辑:

login.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            String Username = email.getText().toString();
            String Password = password.getText().toString();
            new AttemptLogin(Username,Password).execute();
        }
    });

和异步

 class AttemptLogin extends AsyncTask<String, String, String> {
    //three methods get called, first preExecture, then do in background, and once do
    //in back ground is completed, the onPost execture method will be called.
        boolean failure = false;
   String res;
   String Username; 
   String Password;
   int success;
   public AttemptLogin(String Username, String Password) {
            this.Username = Username;
            this.Password = Password;
   }

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

    }

    protected String doInBackground(String... args) {

        try {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("username", Username));
            params.add(new BasicNameValuePair("password", Password));

            Log.d("request!", "starting");
            // getting product details by making HTTP request
            JSONObject json = jsonParser.makeHttpRequest(
                   LOGIN_URL, "POST", params);
            System.out.print("Here");
            // check your log for json response
            Log.d("Login attempt", json.toString());

            // json success tag
            success = json.getInt(TAG_SUCCESS);
            res = json.getString(TAG_MESSAGE);

            return res;
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;

    }

    protected void onPostExecute(String result) {
        // dismiss the dialog once product deleted
        pDialog.dismiss();

            if (success == 1) {
                Log.d("Login Successful!", res);
                Intent i = new Intent(Login.this, MainMenu.class);
                startActivity(i);
                Toast.makeText(Login.this, res, Toast.LENGTH_LONG).show();
            }else{
                Log.d("Login Failure!", json.getString(TAG_MESSAGE));
                Toast.makeText(Login.this, res, Toast.LENGTH_LONG).show();
            }

    }
}
}
相关问题