以下是相关的log-cat信息:
11-09 16:45:47.354 5149-5149/com.example.apex.apex E/Buffer Error﹕ Error converting result java.lang.NullPointerException: lock == null
11-09 16:45:47.354 5149-5149/com.example.apex.apex E/JSON Parser﹕ Error parsing data org.json.JSONException: End of input at character 0 of
11-09 16:45:47.354 5149-5149/com.example.apex.apex D/AndroidRuntime﹕ Shutting down VM
11-09 16:45:47.354 5149-5149/com.example.apex.apex W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41bd9ce0)
Process: com.example.apex.apex, PID: 5149
java.lang.NullPointerException
at com.example.apex.apex.RegisterActivity$1.onClick(RegisterActivity.java:70)
at android.view.View.performClick(View.java:4445)
at android.view.View$PerformClick.run(View.java:18446)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5146)
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:732)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
at dalvik.system.NativeStart.main(Native Method)
11-09 16:46:36.686 5149-5149/com.example.apex.apex I/Process﹕ Sending signal. PID: 5149 SIG: 9
RegisterActivity.java:
我是Java和Android开发的新手,因此我最初硬编码数据以通过PHP与远程服务器通信。
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class RegisterActivity extends Activity {
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
Button btnRegister;
TextView registerErrorMsg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
if(Build.VERSION.SDK_INT > 8)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
// import all assets
btnRegister = (Button) findViewById(R.id.btnRegister);
btnRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// inputs
String fName = "John";
String lName = "Smith";
String email = "someone@example.com";
String password = "123345";
String location = "Sligo";
String dob = "07-10-1993";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
java.util.Date date = null;
try {
date = sdf.parse(dob);
} catch (ParseException e) {
e.printStackTrace();
}
java.sql.Date sqlDob = new Date(date.getTime());
String gender = "Male";
int height = 128;
double weight = 78.5;
CyclistFunctions cyclistFunction = new CyclistFunctions();
JSONObject json = cyclistFunction.registerCyclist(fName, lName, email, password,
location, sqlDob, gender, height, weight);
// check for register response
try {
if (json.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1) {
// user successfully registered
// store user details in SQLite DB
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// clear all previous data in database
finish();
} else {
registerErrorMsg.setText("Error in registration occurred! :/");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.register, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
activity_register.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
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"
tools:context="com.example.apex.apex.RegisterActivity">
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/btnRegister"
android:text="Click!"/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/btnRegister"
android:layout_marginTop="50dp"/>
JSONParser.java
package com.example.apex.apex;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
// make HTTP request
try {
// creates a new HTTP client from parameters and a connection manager
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();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
// buffer input from is
BufferedReader reader = new BufferedReader(new InputStreamReader
(is, HTTP.UTF_8), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try to parse the string to JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
CyclistFunctions.java
package com.example.apex.apex;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
public class CyclistFunctions {
private JSONParser jsonParser;
private static final String registerURL = "http://127.0.0.1/apexdb/include/db_functions.php/";
private static String register_tag = "register";
// constructor
public CyclistFunctions() {
jsonParser = new JSONParser();
}
/**
* make register request
*/
public JSONObject registerCyclist(String first_name, String last_name, String email_address,
String password, String location, Date birth_date, String gender,
int height_cm, double weight_kg) {
// build parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", register_tag));
params.add(new BasicNameValuePair("first_name", first_name));
params.add(new BasicNameValuePair("last_name", last_name));
params.add(new BasicNameValuePair("email_address", email_address));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("location", location));
params.add(new BasicNameValuePair("birth_date", String.valueOf(birth_date)));
params.add(new BasicNameValuePair("gender", gender));
params.add(new BasicNameValuePair("height_cm", String.valueOf(height_cm)));
params.add(new BasicNameValuePair("weight_kg", String.valueOf(weight_kg)));
// fetch JSON object
JSONObject json = jsonParser.getJSONFromUrl(registerURL, params);
// return json
return json;
}
}
db_functions.php
<?php
class DB_Functions {
private $db;
// constructor
function __construct() {
require_once 'db_connect.php';
// connecting to database
$this->db = new db_connect();
$this->db->connect();
}
// destructor
function __destruct() {
}
/**
Storing new cyclist
return user details
**/
public function storeCyclist($first_name, $last_name, $email_address,
$password, $birth_date, $gender, $height_cm, $weight_kg) {
$hash = $this->hashSSHA($password);
$encrypted_password = $hash["encrypted"]; // password
$salt = $hash["salt"]; // salt
$result = mysqli_query("INSERT INTO cyclist (first_name, last_name, email_address,
encrypted_password, salt, birth_date, gender, height_cm, weight_kg, date_created)
VALUES ('$first_name', '$last_name', '$email_address', '$encrypted_password', '$salt', '$birth_date',
'$gender', '$height_cm', '$weight_kg', NOW())");
if($result) {
// successfully inserted cyclist into database
$response["success"] = 1;
$response["message"] = "Cyclist succesfully created";
// echo JSON response
echo json_encode($response);
} else {
// insert fail
$response["success"] = 1;
$response["message"] = "Woops, something went wrong - failed to create new cyclist! :(";
}
}
public function userExists($email_address) {
$result = mysqli_query("SELECT email_address from cyclist WHERE email_address = '$email_address'");
$no_of_rows = mysqli_num_rows($result);
if($no_of_rows > 0) {
// user exists
return true;
} else {
// user exists
return false;
}
}
/**
encrypt password
@param password
returns salt
**/
public function hashSSHA($password) {
$salt = sha1(rand());
$salt = substr($salt, 0, 10);
$encrypted = base64_encode(sha1($password . $salt, true) . $salt);
$hash = array("salt" => $salt, "encrypted" => $encrypted);
return $hash;
}
/**
decrypting password
@params salt, password
returns hash string
**/
public function checkSSHA($salt, $password) {
$hash = base64_encode(sha1($password . $salt, true) . $salt);
return $hash;
}
}
?>
DB_Connect.php
<?php
class DB_Connect {
// constructor
function __construct() {
}
// destructor
function __destruct() {
// $this->close();
}
// connecting to database
public function connect() {
require_once 'config.php';
// connecting to mysqli
$con = new mysqli_connect($db_host, $db_user, $db_password, $db_name);
// check connection
if(mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " .mysqli_connect_errno();
}
// return db handler
return $con;
}
public function close() {
// close connection
mysqli_close();
}
}
?>
答案 0 :(得分:0)
你没有给registerErrorMsg
赋值,因为你得到空指针。
registerErrorMsg = (TextView) findViewById(R.id.registerErrorMsg);
我认为这可以解决您的问题。
答案 1 :(得分:0)
您必须发布您的json模型和循环函数,以确定确切的问题。
此行正在创建错误
JSONObject json = cyclistFunction.registerCyclist(fName, lName, email, password,
location, sqlDob, gender, height, weight);
必须是这样的
String result_json = cyclistFunction.registerCyclist(fName, lName, email, password,location, sqlDob, gender, height, weight);
if (result_json != null) {
try {
JSONObject jsonObj = new JSONObject(result_json );
if (jsonObj != null) {
String res = json.getString(KEY_SUCCESS);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}