我正在尝试实现一个android注册表单,当用户尝试注册应用程序只是崩溃和关闭时,该表单不起作用,但是,用户信息确实会插入到数据库中。
我的问题是,为什么它会在数据成功插入数据库时关闭。请指教和帮助。
Log cat错误消息
{"tag":"register","success":1,"error":0,"user":{"fname":"crisnfg","lname":"nawadv","email":"christina@gmail.com","uname":"crisitina","uid":"56e99196d80403.95127534","created_at":"2016-03-16 17:02:14"}}
03-16 17:01:48.945 8482-11204/com.bradvisor.bradvisor E/Buffer Error: Error converting result org.json.JSONException: Value 2016-03-16 of type java.lang.String cannot be converted to JSONObject
03-16 17:01:48.948 8482-8482/com.empier E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.empier, PID: 8482
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.getString(java.lang.String)' on a null object reference
at com.empier.Register$ProcessRegister.onPostExecute(Register.java:209)
at com.empier.Register$ProcessRegister.onPostExecute(Register.java:169)
03-16 19:34:03.519 19048-19048/com.empier D/debug_tag: false
03-16 19:34:10.110 19048-19048/com.empier D/debug_tag: false
03-16 19:34:10.198 19048-19048/com.empier D/debug_tag: false
03-16 19:35:42.417 19048-19048/com.empier D/debug_tag: false
03-16 19:35:43.093 19048-19048/com.empier D/debug_tag: false
03-16 19:37:07.778 19048-19048/com.empier D/debug_tag: false
03-16 19:38:22.195 19048-19048/com.empier D/debug_tag: false
03-16 19:40:23.161 19048-19048/com.empier D/debug_tag: false
03-16 19:42:56.833 24951-24951/com.empier D/debug_tag: true
03-16 19:58:16.518 29411-29411/? D/debug_tag: true
Register.Java代码
public class Register extends Activity {
/**
* JSON Response node names.
**/
private static String KEY_SUCCESS = "success";
private static String KEY_UID = "uid";
private static String KEY_FIRSTNAME = "fname";
private static String KEY_LASTNAME = "lname";
private static String KEY_USERNAME = "uname";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
private static String KEY_ERROR = "error";
/**
* Defining layout items.
**/
EditText inputFirstName;
EditText inputLastName;
EditText inputUsername;
EditText inputEmail;
EditText inputPassword;
ImageButton btnRegister;
TextView registerErrorMsg;
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
/**
* Defining all layout items
**/
inputFirstName = (EditText) findViewById(R.id.fname);
inputLastName = (EditText) findViewById(R.id.lname);
inputUsername = (EditText) findViewById(R.id.uname);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.pword);
btnRegister = (ImageButton) findViewById(R.id.Registerbtn);
registerErrorMsg = (TextView) findViewById(R.id.register_error);
/**
* Register Button click event.
* A Toast is set to alert when the fields are empty.
* Another toast is set to alert Username must be 5 characters.
**/
btnRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if ( ( !inputUsername.getText().toString().equals("")) && ( !inputPassword.getText().toString().equals("")) && ( !inputFirstName.getText().toString().equals("")) && ( !inputLastName.getText().toString().equals("")) && ( !inputEmail.getText().toString().equals("")) )
{
if ( inputUsername.getText().toString().length() > 4 ){
NetAsync(view);
}
else
{
Toast.makeText(getApplicationContext(),
"Username should be minimum 5 characters", Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(getApplicationContext(),
"One or more fields are empty", Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* Async Task to check whether internet connection is working
**/
private class NetCheck extends AsyncTask<String,String,Boolean>
{
private ProgressDialog nDialog;
@Override
protected void onPreExecute(){
super.onPreExecute();
nDialog = new ProgressDialog(Register.this);
nDialog.setMessage("Loading..");
nDialog.setTitle("Checking Network");
nDialog.setIndeterminate(false);
nDialog.setCancelable(true);
nDialog.show();
}
@Override
protected Boolean doInBackground(String... args){
/**
* Gets current device state and checks for working internet connection by trying Google.
**/
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return true;
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return false;
}
@Override
protected void onPostExecute(Boolean th){
if(th == true){
nDialog.dismiss();
new ProcessRegister().execute();
}
else{
nDialog.dismiss();
registerErrorMsg.setText("Error in Network Connection");
}
}
}
private class ProcessRegister extends AsyncTask<String, String, JSONObject> {
/**
* Defining Process dialog
**/
private ProgressDialog pDialog;
String email,password,fname,lname,uname;
@Override
protected void onPreExecute() {
super.onPreExecute();
inputUsername = (EditText) findViewById(R.id.uname);
inputPassword = (EditText) findViewById(R.id.pword);
fname = inputFirstName.getText().toString();
lname = inputLastName.getText().toString();
email = inputEmail.getText().toString();
uname= inputUsername.getText().toString();
password = inputPassword.getText().toString();
pDialog = new ProgressDialog(Register.this);
pDialog.setTitle("Contacting Servers");
pDialog.setMessage("Registering ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected JSONObject doInBackground(String... args) {
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.registerUser(fname, lname, email, uname, password);
return json;
}
@Override
protected void onPostExecute(JSONObject json) { Log.d("debug_tag", json == null ? "true" : "false");
try {
if (json.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
String red = json.getString(KEY_ERROR);
if(Integer.parseInt(res) == 1){
pDialog.setTitle("Getting Data");
pDialog.setMessage("Loading Info");
registerErrorMsg.setText("Successfully Registered");
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user"); Log.d("debug_tag", "User json :: " + json_user==null ? "true": "false");
/**
* Removes all the previous data in the SQlite database
**/
UserFunctions logout = new UserFunctions();
logout.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_FIRSTNAME),json_user.getString(KEY_LASTNAME),json_user.getString(KEY_EMAIL),json_user.getString(KEY_USERNAME),json_user.getString(KEY_UID),json_user.getString(KEY_CREATED_AT));
/**
* Stores registered data in SQlite Database
* Launch Registered screen
**/
Intent registered = new Intent(getApplicationContext(), Registered.class);
/**
* Close all views before launching Registered screen
**/
registered.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pDialog.dismiss();
startActivity(registered);
finish();
}
else if (Integer.parseInt(red) ==2){
pDialog.dismiss();
registerErrorMsg.setText("User already exists");
}
else if (Integer.parseInt(red) ==3){
pDialog.dismiss();
registerErrorMsg.setText("Invalid Email id");
}
}
else{
pDialog.dismiss();
registerErrorMsg.setText("Error occurred in registration");
}
} catch (JSONException e) {
e.printStackTrace();
}
}}
public void NetAsync(View view){
new NetCheck().execute();
}}
Userfunction.java代码
/**
* Function to Register
**/
public JSONObject registerUser(String fname, String lname, String email, String uname, String password){
// Building Parameters
List params = new ArrayList();
params.add(new BasicNameValuePair("tag", register_tag));
params.add(new BasicNameValuePair("fname", fname));
params.add(new BasicNameValuePair("lname", lname));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("uname", uname));
params.add(new BasicNameValuePair("password", password));
JSONObject json = jsonParser.getJSONFromUrl(registerURL, params);
return json;
}
Registered.java文件
public class Registered extends Activity {
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.registered);
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
HashMap<String,String> user = new HashMap<String, String>();
user = db.getUserDetails();
/**
* Displays the registration details in Text view
**/
final TextView fname = (TextView)findViewById(R.id.fname);
final TextView lname = (TextView)findViewById(R.id.lname);
final TextView uname = (TextView)findViewById(R.id.uname);
final TextView email = (TextView)findViewById(R.id.email);
final TextView created_at = (TextView)findViewById(R.id.regat);
fname.setText(user.get("fname"));
lname.setText(user.get("lname"));
uname.setText(user.get("uname"));
email.setText(user.get("email"));
created_at.setText(user.get("created_at"));
ImageButton loginbtn = (ImageButton) findViewById(R.id.loginscreenbtn);
loginbtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), Login.class);
startActivityForResult(myIntent, 0);
finish();
}
});
}}
Register.XML文件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
tools:context="bradvisor.bradvisor.com.bradvisor.LoginActivity"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:background="#ffffffff"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<ImageView
android:layout_width="match_parent"
android:layout_height="150dp"
android:id="@+id/imageView5"
android:layout_gravity="center_horizontal|top"
android:src="@drawable/logofinal"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<ImageButton
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/Registerbtn"
android:src="@drawable/registerbtn"
android:background="#00000000"
android:layout_below="@+id/pword"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:text="First Name"
android:ems="10"
android:id="@+id/fname"
android:textColor="#ff3b5998"
android:layout_below="@+id/imageView5"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:singleLine="false" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:text="Last Name"
android:ems="10"
android:id="@+id/lname"
android:layout_below="@+id/fname"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:textColor="#3b5998" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ems="10"
android:id="@+id/uname"
android:textSize="20dp"
android:layout_below="@+id/lname"
android:layout_alignParentLeft="true"
android:text="Username"
android:textColor="#3b5998"
android:inputType="textPersonName" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:ems="10"
android:id="@+id/email"
android:layout_below="@+id/uname"
android:layout_centerHorizontal="true"
android:text="Email"
android:textColor="#3b5998" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:id="@+id/pword"
android:layout_below="@+id/email"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:text="Password"
android:textColor="#3b5998" />
<TextView
android:layout_width="fill_parent"
android:layout_height="56dp"
android:textColor="#3b5998"
android:id="@+id/register_error"
android:layout_below="@+id/Registerbtn"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="30dp" />
</RelativeLayout>
registered.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
tools:context="bradvisor.bradvisor.com.bradvisor.LoginActivity"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:background="#ffffffff"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<ImageView
android:layout_width="match_parent"
android:layout_height="150dp"
android:id="@+id/imageView5"
android:layout_gravity="center_horizontal|top"
android:src="@drawable/logofinal"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<ImageButton
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/Registerbtn"
android:src="@drawable/registerbtn"
android:background="#00000000"
android:layout_below="@+id/pword"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:text="First Name"
android:ems="10"
android:id="@+id/fname"
android:textColor="#ff3b5998"
android:layout_below="@+id/imageView5"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:singleLine="false" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:text="Last Name"
android:ems="10"
android:id="@+id/lname"
android:layout_below="@+id/fname"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:textColor="#3b5998" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ems="10"
android:id="@+id/uname"
android:textSize="20dp"
android:layout_below="@+id/lname"
android:layout_alignParentLeft="true"
android:text="Username"
android:textColor="#3b5998"
android:inputType="textPersonName" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:ems="10"
android:id="@+id/email"
android:layout_below="@+id/uname"
android:layout_centerHorizontal="true"
android:text="Email"
android:textColor="#3b5998" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:id="@+id/pword"
android:layout_below="@+id/email"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:text="Password"
android:textColor="#3b5998" />
<TextView
android:layout_width="fill_parent"
android:layout_height="56dp"
android:textColor="#3b5998"
android:id="@+id/register_error"
android:layout_below="@+id/Registerbtn"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="30dp" />
</RelativeLayout>
当我调试应用程序时,我没有得到任何东西,因为一切正常。请帮忙并提出建议?。
答案 0 :(得分:0)
崩溃日志显示onPostExecute()
方法中存在NullPointerException。因此,json
作为参数onPostExecute()
的{{1}}对象是null
或json_user
-
JSONObject json_user = json.getJSONObject("user");
是null
。您可以为这两个对象添加日志,并检查null以找出导致问题的原因。
从日志中可以清楚地看到json
有时会null
对象protected void onPostExecute(JSONObject json)
这就是为什么当你致电json.getString()
时,你会得到NullPointerException
。
为了避免崩溃,
在onPostExecute()
检查null并显示一些错误消息
if(json == null){
//Show error message toast or something
}