当我单击UserInfo按钮时如果强制关闭我的应用程序

时间:2013-12-11 14:55:49

标签: php android json

这是我的logcat

12-11 22:42:30.949: E/AndroidRuntime(11497): FATAL EXCEPTION: main
12-11 22:42:30.949: E/AndroidRuntime(11497): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.pmss/com.pmss.UserInfo}: java.lang.NullPointerException
12-11 22:42:30.949: E/AndroidRuntime(11497):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1573)
12-11 22:42:30.949: E/AndroidRuntime(11497):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
12-11 22:42:30.949: E/AndroidRuntime(11497):    at android.app.ActivityThread.access$1500(ActivityThread.java:117)
12-11 22:42:30.949: E/AndroidRuntime(11497):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
12-11 22:42:30.949: E/AndroidRuntime(11497):    at android.os.Handler.dispatchMessage(Handler.java:99)
12-11 22:42:30.949: E/AndroidRuntime(11497):    at android.os.Looper.loop(Looper.java:130)
12-11 22:42:30.949: E/AndroidRuntime(11497):    at android.app.ActivityThread.main(ActivityThread.java:3687)
12-11 22:42:30.949: E/AndroidRuntime(11497):    at java.lang.reflect.Method.invokeNative(Native Method)
12-11 22:42:30.949: E/AndroidRuntime(11497):    at java.lang.reflect.Method.invoke(Method.java:507)
12-11 22:42:30.949: E/AndroidRuntime(11497):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
12-11 22:42:30.949: E/AndroidRuntime(11497):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
12-11 22:42:30.949: E/AndroidRuntime(11497):    at dalvik.system.NativeStart.main(Native Method)
12-11 22:42:30.949: E/AndroidRuntime(11497): Caused by: java.lang.NullPointerException
12-11 22:42:30.949: E/AndroidRuntime(11497):    at android.content.ContextWrapper.getPackageName(ContextWrapper.java:120)
12-11 22:42:30.949: E/AndroidRuntime(11497):    at android.preference.PreferenceManager.getDefaultSharedPreferencesName(PreferenceManager.java:353)
12-11 22:42:30.949: E/AndroidRuntime(11497):    at android.preference.PreferenceManager.getDefaultSharedPreferences(PreferenceManager.java:348)
12-11 22:42:30.949: E/AndroidRuntime(11497):    at com.pmss.UserInfo.<init>(UserInfo.java:37)
12-11 22:42:30.949: E/AndroidRuntime(11497):    at java.lang.Class.newInstanceImpl(Native Method)
12-11 22:42:30.949: E/AndroidRuntime(11497):    at java.lang.Class.newInstance(Class.java:1409)
12-11 22:42:30.949: E/AndroidRuntime(11497):    at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
12-11 22:42:30.949: E/AndroidRuntime(11497):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1565)
12-11 22:42:30.949: E/AndroidRuntime(11497):    ... 11 more

这是我的UserInfo.java

public class UserInfo extends ActionBarActivity implements OnClickListener {

EditText nametext, useridtext, passwordtext,
        mobilenumbertext, addresstext, citytext, postcodetext, statetext;
Button update;
SharedPreferences sp = PreferenceManager
        .getDefaultSharedPreferences(UserInfo.this);
String post_username = sp.getString("username", "anon");

private JSONArray mComments = null;
// Progress Dialog
private ProgressDialog pDialog;

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

private static final String USERINFO_URL = "http://xxx.xxx.x.xx:1234/PMSS/userinfo.php";
private static final String USERINFOUPDATE_URL = "http://xxx.xxx.x.xx:1234/PMSS/userinfoupdate.php";
// ids
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private static final String TAG_POSTS = "posts";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_PASSWORD = "password";
private static final String TAG_MOBILENUMBER = "mobilenumber";
private static final String TAG_ADDRESS = "address";
private static final String TAG_CITY = "city";
private static final String TAG_POSTCODE = "postcode";
private static final String TAG_STATE = "state";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_user_info);
    // Show the Up button in the action bar.
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    update = (Button) findViewById(R.id.update);
    nametext = (EditText) findViewById(R.id.nametext);
    useridtext = (EditText) findViewById(R.id.useridtext);
    passwordtext = (EditText) findViewById(R.id.passwordtext);
    mobilenumbertext = (EditText) findViewById(R.id.mobilenumbertext);
    addresstext = (EditText) findViewById(R.id.addresstext);
    citytext = (EditText) findViewById(R.id.citytext);
    postcodetext = (EditText) findViewById(R.id.postcodetext);
    statetext = (EditText) findViewById(R.id.statetext);

    update.setOnClickListener(new View.OnClickListener() {

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

             String Name = nametext.getText().toString();
             String Email = useridtext.getText().toString();
             String Password = passwordtext.getText().toString();
             String MobileNumber = mobilenumbertext.getText().toString();
             String Address = addresstext.getText().toString();
             String City = citytext.getText().toString();
             String PostCode = postcodetext.getText().toString();
             String State = statetext.getText().toString();
            new RetrieveUser().execute();
        }
    });
}

/**
 * Set up the {@link android.app.ActionBar}, if the API is available.
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        getActionBar().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.user_info, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home:
        // This ID represents the Home or Up button. In the case of this
        // activity, the Up button is shown. Use NavUtils to allow users
        // to navigate up one level in the application structure. For
        // more details, see the Navigation pattern on Android Design:
        //
        // http://developer.android.com/design/patterns/navigation.html#up-vs-back
        //
        NavUtils.navigateUpFromSameTask(this);
        return true;
    }
    return super.onOptionsItemSelected(item);
}

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

}

class RetrieveUser extends AsyncTask<Void, Void, Boolean> {

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

    @Override
    protected Boolean doInBackground(Void... arg0) {
        updateJSONdata();
        return null;

    }

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);
        pDialog.dismiss();
        nametext.setText(Name);
        useridtext.setText(Email);
        passwordtext.setText(Password);
        mobilenumbertext.setText(MobileNumber);
        addresstext.setText(Address);
        citytext.setText(City);
        postcodetext.setText(PostCode);
        statetext.setText(State);

    }

    String Name, Email, Password, MobileNumber, Address, City, PostCode, State;

    public void updateJSONdata() {
        // ///////////////////////////////////////////////////////////////////////////////////////
        // Instantiate the arraylist to contain all the JSON data.
        // we are going to use a bunch of key-value pairs, referring
        // to the json element name, and the content, for example,
        // message it the tag, and "I'm awesome" as the content..

        // Bro, it's time to power up the J parser
        JSONParser jParser = new JSONParser();
        // Feed the beast our comments url, and it spits us
        // back a JSON object. Boo-yeah Jerome.
        // JSONObject json = jParser.getJSONFromUrl(READ_COMMENTS_URL);

        // Retrieving Saved Username Data:

        try {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("emailretrieve",
                    post_username));

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

            // I know I said we would check if "Posts were Avail."
            // (success==1)
            // before we tried to read the individual posts, but I lied...
            // mComments will tell us how many "posts" or comments are
            // available
            mComments = json.getJSONArray(TAG_POSTS);

            // looping through all posts according to the json object
            // returned
            for (int i = 0; i < mComments.length(); i++) {
                JSONObject c = mComments.getJSONObject(i);

                // gets the content of each tag
                // String content = c.getString(TAG_USERID);
                Name = c.getString(TAG_NAME);
                Email = c.getString(TAG_EMAIL);
                Password = c.getString(TAG_PASSWORD);
                MobileNumber = c.getString(TAG_MOBILENUMBER);
                Address = c.getString(TAG_ADDRESS);
                City = c.getString(TAG_CITY);
                PostCode = c.getString(TAG_POSTCODE);
                State = c.getString(TAG_STATE);

            }

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

    }
}

class UpdateUser extends AsyncTask<String, String, Integer> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    boolean failure = false;
    String res;
    int success;
    String Name, Email, Password, ConfirmPassword, MobileNumber, Address,
            City, PostCode, State;

    public UpdateUser(String Name, String Email, String Password,
            String ConfirmPassword, String MobileNumber, String Address,
            String City, String PostCode, String State) {
        this.Name = Name;
        this.Email = Email;
        this.Password = Password;
        this.ConfirmPassword = ConfirmPassword;
        this.MobileNumber = MobileNumber;
        this.Address = Address;
        this.City = City;
        this.PostCode = PostCode;
        this.State = State;
    }

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

    @Override
    protected Integer doInBackground(String... params) {
        // TODO Auto-generated method stub
        // Check for success tag

        try {
            // Building Parameters
            List<NameValuePair> params2 = new ArrayList<NameValuePair>();
            params2.add(new BasicNameValuePair("name", Name));
            params2.add(new BasicNameValuePair("email", Email));
            params2.add(new BasicNameValuePair("password", Password));
            params2.add(new BasicNameValuePair("confirmpassword",
                    ConfirmPassword));
            params2.add(new BasicNameValuePair("mobilenumber", MobileNumber));
            params2.add(new BasicNameValuePair("address", Address));
            params2.add(new BasicNameValuePair("postcode", PostCode));
            params2.add(new BasicNameValuePair("city", City));
            params2.add(new BasicNameValuePair("state", State));

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

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

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

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

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

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(Integer success) {
        // dismiss the dialog once product deleted
        pDialog.dismiss();

        if (success != null && success == 1) {
            Log.d("User Updated!", res);
            Intent r = new Intent(UserInfo.this, Login.class);
            startActivity(r);
            finish();
            Toast.makeText(
                    UserInfo.this,
                    res == null ? "Please enter the require field that marked with **"
                            : res, Toast.LENGTH_LONG).show();
            nametext.setText(null);
            useridtext.setText(null);
            passwordtext.setText(null);
            mobilenumbertext.setText(null);
            addresstext.setText(null);
            citytext.setText(null);
            postcodetext.setText(null);
            statetext.setText(null);

        } else {
            Log.d("Update Failure!", "res: " + res);
            Toast.makeText(
                    UserInfo.this,
                    res == null ? "Please enter the require field that marked with **"
                            : res, Toast.LENGTH_LONG).show();

        }

    }
}

}

我想知道当我点击UserInfo界面中的MainMenu时,它只是挂在那里并强制关闭......

我的userinfo.php

<?php

require("config.inc.php");

if (!empty($_POST)) {

$query = "Select * FROM user WHERE email = :emailretrieve ";

$query_params = array(
    ':emailretrieve' => $_POST['emailretrieve']
);
//execute query
try {
$stmt   = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}

// Finally, we can retrieve all of the found rows into an array using fetchAll 
$rows = $stmt->fetchAll();


if ($rows) {
$response["success"] = 1;
$response["message"] = "Post Available!";
$response["posts"]   = array();

foreach ($rows as $row) {
    $post = array();
    $post["name" = $row["name"];
    $post["email"] = $row["email"];
$post["password"] = $row["password"];
$post["mobilenumber"] = $row["mobilenumber"];
    $post["address"] = $row["address"];
$post["city"] = $row["city"];
$post["postcode"] = $row["postcode"];
$post["state"] = $row["state"];


    //update our repsonse JSON data
    array_push($response["posts"], $post);
}

// echoing JSON response
echo json_encode($response);


} else {
$response["success"] = 0;
$response["message"] = "No Post Available!";
die(json_encode($response));
}
}
?>

有人可以帮帮我吗?我真的不知道如何解决NullPointerException,因为我需要将EditText留空UserInfo interface以加载数据并粘贴到EditText以显示我的{{1}}数据..

1 个答案:

答案 0 :(得分:0)

SharedPreferences sp = PreferenceManager
    .getDefaultSharedPreferences(UserInfo.this);

无法从初始化程序调用上述内容。请等到onCreate()(更具体地说,直到super.onCreate()之后)才能尝试阅读SharedPreferences