使用PHP通过Android从MySQL插入和接收数据
我在运行此应用程序时遇到类似的错误。 “解析数据org.json.JSONException:Value时出错 这是我的register\u user.java使用PHP通过Android从MySQL插入和接收数据,php,android,mysql,json,eclipse,Php,Android,Mysql,Json,Eclipse,我在运行此应用程序时遇到类似的错误。 “解析数据org.json.JSONException:Value时出错 这是我的register\u user.java package com.iwantnew.www; import java.util.ArrayList; import java.util.List; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; imp
package com.iwantnew.www;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class register_user extends Activity{
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText signup_username;
EditText signup_email;
EditText signup_password;
Button registerBtn;
TextView registerErrorMsg;
// url to create new product
private static String url_create_users = "http://10.0.2.2/http://10.0.2.2/android_iwant/signup_success.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.signup_form);
// Edit Text
signup_username = (EditText) findViewById(R.id.signup_username);
signup_email = (EditText) findViewById(R.id.signup_email);
signup_password = (EditText) findViewById(R.id.signup_password);
registerBtn = (Button) findViewById(R.id.regiserBtn);
// button click event
registerBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// creating new product in background thread
new CreateNewUser().execute();
}
});
}
class CreateNewUser extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(register_user.this);
pDialog.setMessage("Creating Users..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
/*String username = signup_username.getText().toString();
String email = signup_email.getText().toString();
String password = signup_password.getText().toString();*/
//Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", signup_username.getText().toString()));
params.add(new BasicNameValuePair("email",signup_email.getText().toString()));
params.add(new BasicNameValuePair("password", signup_password.getText().toString()));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_users,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created users
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create users
}
} 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 done
pDialog.dismiss();
}
}
}
package.com.iwantnew.www;
导入java.util.ArrayList;
导入java.util.List;
导入org.apache.http.NameValuePair;
导入org.apache.http.message.BasicNameValuePair;
导入org.json.JSONException;
导入org.json.JSONObject;
导入android.app.Activity;
导入android.app.ProgressDialog;
导入android.content.Intent;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.util.Log;
导入android.view.view;
导入android.widget.Button;
导入android.widget.EditText;
导入android.widget.TextView;
公共类注册用户扩展活动{
//进度对话框
私人对话;
JSONParser JSONParser=新的JSONParser();
EditText注册\用户名;
EditText注册电子邮件;
EditText注册密码;
按钮寄存器;
TextView注册表errormsg;
//创建新产品的url
私有静态字符串url\u创建用户=”http://10.0.2.2/http://10.0.2.2/android_iwant/signup_success.php";
//JSON节点名称
私有静态最终字符串标记_SUCCESS=“SUCCESS”;
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.signup_表单);
//编辑文本
注册\用户名=(EditText)findViewById(R.id.signup\用户名);
注册\电子邮件=(EditText)findViewById(R.id.signup\电子邮件);
注册密码=(EditText)findViewById(R.id.signup\u密码);
registerBtn=(按钮)findviewbyd(R.id.regisebtn);
//按钮点击事件
registerBtn.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
//在后台线程中创建新产品
新建CreateNewUser().execute();
}
});
}
类CreateNewUser扩展异步任务{
/**
*在启动后台线程显示进度对话框之前
* */
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
pDialog=新建进度对话框(注册用户。此);
pDialog.setMessage(“创建用户…”);
pDialog.setUndeterminate(假);
pDialog.setCancelable(真);
pDialog.show();
}
/**
*创造产品
* */
受保护的字符串doInBackground(字符串…args){
/*字符串username=signup_username.getText().toString();
字符串email=signup_email.getText().toString();
String password=signup_password.getText().toString()*/
//建筑参数
List params=new ArrayList();
add(新的BasicNameValuePair(“用户名”,signup_username.getText().toString());
add(新的BasicNameValuePair(“email”,signup_email.getText().toString());
add(新的BasicNameValuePair(“密码”,signup_password.getText().toString());
//获取JSON对象
//请注意,创建产品url接受POST方法
JSONObject json=jsonParser.makeHttpRequest(url\u create\u users,
“POST”,params);
//检查cat fro响应日志
d(“创建响应”,json.toString());
//检查成功标签
试一试{
int success=json.getInt(TAG_success);
如果(成功==1){
//已成功创建用户
Intent i=新的Intent(getApplicationContext(),MainActivity.class);
星触觉(i);
//关闭此屏幕
完成();
}否则{
//未能创建用户
}
}捕获(JSONException e){
e、 printStackTrace();
}
返回null;
}
/**
*完成后台任务后,关闭“进度”对话框
* **/
受保护的void onPostExecute(字符串文件\u url){
//完成后关闭对话框
pDialog.disclose();
}
}
}
这是JSONParser.java。这是android的数据解析类
package com.iwantnew.www;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET method
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;
}
}
package.com.iwantnew.www;
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.io.UnsupportedEncodingException;
导入java.util.List;
导入org.apache.http.HttpEntity;
导入org.apache.http.HttpResponse;
导入org.apache.http.NameValuePair;
导入org.apache.http.client.ClientProtocolException;
导入org.apache.http.client.entity.UrlEncodedFormEntity;
导入org.apache.http.client.methods.HttpGet;
导入org.apache.http.client.methods.HttpPost;
导入org.apache.http.client.utils.URLEncodedUtils;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.json.JSONException;
导入org.json.JSONObject;
导入android.util.Log;
公共类JSONParser{
静态InputStream为空;
静态JSONObject jObj=null;
静态字符串json=“”;
//建造师
公共JSONParser(){
}
//函数从url获取json
//通过使用HTTP POST或GET方法
公共JSONObject makeHttpRequest(字符串url、字符串方法、,
列表参数){
//发出HTTP请求
试一试{
//检查请求方法
如果(方法==“POST”){
//请求方法为POST
//defaultHttpClient
DefaultHttpClient httpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(url);
setEntity(新的UrlEncodedFormEntity(参数));
<?php
// array for JSON response
$response = array();
if(isset($_POST['username']) && isset($_POST['email']) && isset($_POST['password'])){
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
$uuid = uniqid('', true);
$hash = $this->hashSSHA($password);
$encrypted_password = $hash["encrypted"]; // encrypted password
$salt = $hash["salt"]; // salt
$result = mysql_query("INSERT INTO users(unique_id, name, email, encrypted_password, salt, created_at) VALUES('$uuid', '$username', '$email', '$encrypted_password', '$salt', NOW())");
// check for successful store
if ($result) {
// get user details
$uid = mysql_insert_id(); // last inserted id
$result = mysql_query("SELECT * FROM users WHERE uid = $uid");
// return user details
return mysql_fetch_array($result);
} else {
return false;
}
$result = mysql_query("INSERT INTO users(name,email,password) VALUES ('$username','$email,$password')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "successfully signed Up.";
// echoing JSON response
echo json_encode($response);}
else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
// check for successful store
if ($result) {
// get user details
$uid = mysql_insert_id(); // last inserted id
$result = mysql_query("SELECT * FROM users WHERE uid = $uid");
// return user details
return mysql_fetch_array($result);
} else {
return false;
}
// check for successful store
if ($result) {
// get user details
$uid = mysql_insert_id(); // last inserted id
$result = mysql_query("SELECT * FROM users WHERE uid = $uid");
// return user details
echo json_encode(mysql_fetch_array($result));
exit;
}