当我想注册时应用程序崩溃(java)

时间:2014-12-30 12:50:27

标签: java android

我的申请需要帮助。在该应用程序中,我想进行登录和注册,但每当我按下登录和注册按钮时,它都会使整个应用程序崩溃。我使用xampp作为服务器。

RegisterActivity.java

protected EditText mUsername;
protected EditText mUserEmail;
protected EditText mUserPassword;
protected Button mRegisterButton;

// Progress Dialog
private ProgressDialog pDialog;

// JSON parser class
JSONParser jsonParser = new JSONParser();

//php login script

//localhost :
//testing on your device
//put your local ip instead,  on windows, run CMD > ipconfig
//or in mac's terminal type ifconfig and look for the ip under en0 or en1
// private static final String LOGIN_URL = "http://xxx.xxx.x.x:1234/webservice/register.php";

//testing on Emulator:
private static final String LOGIN_URL = "http://127.0.0.1/webservice/register.php";



//testing from a real server:
//private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/register.php";

//ids
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);

    //initialize
    mUsername = (EditText)findViewById(R.id.usernameRegisterEditText);
    mUserEmail = (EditText)findViewById(R.id.emailRegisterEditText);
    mUserPassword = (EditText)findViewById(R.id.passwordRegisterEditText);
    mRegisterButton = (Button)findViewById(R.id.registerButton);

    //listen to register button click
    mRegisterButton.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub

    new CreateUser().execute();

}

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

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

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

    @Override
    protected String doInBackground(String... args) {
        // TODO Auto-generated method stub
        // Check for success tag
        int success;
        String username = mUsername.getText().toString();
        String email = mUserEmail.getText().toString();
        String password = mUserPassword.getText().toString();
        try {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("username", username));
            params.add(new BasicNameValuePair("email", email));
            params.add(new BasicNameValuePair("password", password));

            Log.d("request!", "starting");

            //Posting user data to script
            JSONObject json = jsonParser.makeHttpRequest(
                    LOGIN_URL, "POST", params);



            // full json response
            Log.d("Login attempt", json.toString());

            // json success element
            success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                Log.d("User Created!", json.toString());
                finish();
                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;

    }
    /**
     * 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(RegisterActivity.this, file_url, Toast.LENGTH_LONG).show();
        }

    }

}

}



JSONParser
------------
public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}


public JSONObject getJSONFromUrl(final String url) {

    // Making HTTP request
    try {
        // Construct the client and the HTTP request.
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        // Execute the POST request and store the response locally.
        HttpResponse httpResponse = httpClient.execute(httpPost);
        // Extract data from the response.
        HttpEntity httpEntity = httpResponse.getEntity();
        // Open an inputStream with the data content.
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        // Create a BufferedReader to parse through the inputStream.
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        // Declare a string builder to help with the parsing.
        StringBuilder sb = new StringBuilder();
        // Declare a string to store the JSON object data in string form.
        String line = null;

        // Build the string until null.
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }

        // Close the input stream.
        is.close();
        // Convert the string builder data to an actual string.
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // Try to parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // Return the JSON Object.
    return jObj;

}


// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
                                  List<NameValuePair> params) {

    // Making HTTP request
    try {

        // check for request method
        if(method == "POST"){
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        }else if(method == "GET"){
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}


}

AndroidManifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="sergio.applicationone"
android:versionCode="1"
android:versionName="1.0">



<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="17"/>
<uses-permission android:name="android.permission.INTERNET"/>


<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".LoginActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".HomepageActivity"
        android:label="HomepageActivity" >
    </activity>
    <activity
        android:name=".RegisterActivity"
        android:label="RegisterActivity" >
    </activity>
</application>

</manifest>

------ logcat的

12-30 13:33:34.341    6574-6574/sergio.applicationone E/﹕ Device driver API match
    Device driver API version: 23
    User space API version: 23
12-30 13:33:34.341    6574-6574/sergio.applicationone E/﹕ mali: REVISION=Linux-r3p2-01rel3 BUILD_DATE=Fri Mar 21 13:52:50 KST 2014
    12-30 13:34:35.676    6574-6804/sergio.applicationone E/Buffer Error﹕ Error converting result java.lang.NullPointerException: lock == null
12-30 13:34:40.731    6574-6804/sergio.applicationone E/JSON Parser﹕ Error parsing data org.json.JSONException: End of input at character 0 of
12-30 13:34:56.866    6574-6574/sergio.applicationone I/Choreographer﹕ Skipped 1267 frames!  The application may be doing too much work on its main thread.
12-30 13:35:24.221    6574-6804/sergio.applicationone W/dalvikvm﹕ threadid=11: thread exiting with uncaught exception (group=0x41de5c08)
12-30 13:35:24.361    6574-6574/sergio.applicationone I/Choreographer﹕ Skipped 1593 frames!  The application may be doing too much work on its main thread.
12-30 13:35:24.451    6574-6804/sergio.applicationone E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
    Process: sergio.applicationone, PID: 6574
    java.lang.RuntimeException: An error occured while executing doInBackground()
            at android.os.AsyncTask$3.done(AsyncTask.java:300)
            at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
            at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
            at java.util.concurrent.FutureTask.run(FutureTask.java:242)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:841)
     Caused by: java.lang.NullPointerException
            at sergio.applicationone.RegisterActivity$CreateUser.doInBackground(RegisterActivity.java:118)
            at sergio.applicationone.RegisterActivity$CreateUser.doInBackground(RegisterActivity.java:77)
            at android.os.AsyncTask$2.call(AsyncTask.java:288)
            at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:841)
12-30 13:35:25.971    6574-6574/sergio.applicationone E/WindowManager﹕ android.view.WindowLeaked: Activity sergio.applicationone.RegisterActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{425e22d8 V.E..... R......D 0,0-639,128} that was originally added here
            at android.view.ViewRootImpl.<init>(ViewRootImpl.java:468)
            at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:267)
            at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
            at android.app.Dialog.show(Dialog.java:289)
            at sergio.applicationone.RegisterActivity$CreateUser.onPreExecute(RegisterActivity.java:91)
            at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
            at android.os.AsyncTask.execute(AsyncTask.java:535)
            at sergio.applicationone.RegisterActivity.onClick(RegisterActivity.java:73)
            at android.view.View.performClick(View.java:4640)
            at android.view.View$PerformClick.run(View.java:19425)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:146)
            at android.app.ActivityThread.main(ActivityThread.java:5593)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
            at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:0)

将所有这些代码放在doinbackground之外

    String username = mUsername.getText().toString();
    String email = mUserEmail.getText().toString();
    String password = mUserPassword.getText().toString();