gpt4 book ai didi

java - Android - 解析数据 org.json.jsonException 在字符 0 处输入结束时出错

转载 作者:行者123 更新时间:2023-11-29 23:56:05 25 4
gpt4 key购买 nike

我一整天都在检查我的代码,但找不到为什么会发生这种情况。数据输入到数据库中,但当我提交新数据时,Android应用程序总是崩溃。

这里注册.java

public class Register extends Activity implements OnClickListener{

private EditText nama, alamat, noidentitas, notelepon, username, password;
private Button rgister, bktlogin;


// Progress Dialog
private ProgressDialog pDialog;

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

private static final String LOGIN_URL = "http://192.168.43.226/jualan/login/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.register);

nama = (EditText)findViewById(R.id.et_nama);
alamat = (EditText)findViewById(R.id.et_alamat);
noidentitas = (EditText)findViewById(R.id.et_noidentitas);
notelepon = (EditText)findViewById(R.id.et_notelepon);
username = (EditText)findViewById(R.id.et_username);
password = (EditText)findViewById(R.id.et_password);


rgister = (Button)findViewById(R.id.bt_register);
rgister.setOnClickListener(this);
bktlogin = (Button)findViewById(R.id.bktologin);
bktlogin.setOnClickListener(this);

}

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bt_register:
new CreateUser().execute();

break;
case R.id.bktologin:
Intent ii = new Intent(this, Login.class);
startActivity(ii);
break;

default:
break;
}
}

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(Register.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 nm = nama.getText().toString();
String almt = alamat.getText().toString();
String noid = noidentitas.getText().toString();
String notelp = notelepon.getText().toString();
String user = username.getText().toString();
String pass = password.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("nama", nm));
params.add(new BasicNameValuePair("alamat", almt));
params.add(new BasicNameValuePair("noidentitas", noid));
params.add(new BasicNameValuePair("notelepon", notelp));
params.add(new BasicNameValuePair("username", user));
params.add(new BasicNameValuePair("password", pass));

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());
//Intent i = new Intent(Register.this, Login.class);
//startActivity(i);
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(Register.this, file_url, Toast.LENGTH_LONG).show();
}

}


}


}

这是我的 JSONParser.java

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 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;

}
}

这是我的 php 代码 register.php

<?php
include('connection.php');

$id = (int)$_POST['id'];
$nama = $_POST['nama'];
$alamat = $_POST['alamat'];
$noidentitas = (int)$_POST['noidentitas'];
$notelepon = (int)$_POST['notelepon'];
$username = $_POST['username'];
$password = $_POST['password'];

$query = 'insert into akun (nama, alamat, noidentitas, notelepon, username, password) values ("'.$nama.'", "'.$alamat.'", "'.$noidentitas.'", "'.$notelepon.'", "'.$username.'", "'.$password.'")';
if($id > 0){
$query = 'update akun set nama = "'.$nama.'", alamat = "'.$alamat.'", noidentitas = "'.$noidentitas.'", notelepon = "'.$notelepon.'", username = "'.$username.'", password = "'.$password.'" where id = '.$id;
$result=mysql_query($query);
}
mysql_query($query) or die(mysql_error());

?>

logcat 输出是

08-17 20:13:06.215: E/JSON Parser(28309): Error parsing data org.json.JSONException: End of input at character 0 of 
08-17 20:13:06.215: W/dalvikvm(28309): threadid=11: thread exiting with uncaught exception (group=0x4118a2a0)
08-17 20:13:06.215: E/AndroidRuntime(28309): FATAL EXCEPTION: AsyncTask #1
08-17 20:13:06.215: E/AndroidRuntime(28309): java.lang.RuntimeException: An error occured while executing doInBackground()
08-17 20:13:06.215: E/AndroidRuntime(28309): at android.os.AsyncTask$3.done(AsyncTask.java:299)
08-17 20:13:06.215: E/AndroidRuntime(28309): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
08-17 20:13:06.215: E/AndroidRuntime(28309): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
08-17 20:13:06.215: E/AndroidRuntime(28309): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
08-17 20:13:06.215: E/AndroidRuntime(28309): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
08-17 20:13:06.215: E/AndroidRuntime(28309): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
08-17 20:13:06.215: E/AndroidRuntime(28309): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
08-17 20:13:06.215: E/AndroidRuntime(28309): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
08-17 20:13:06.215: E/AndroidRuntime(28309): at java.lang.Thread.run(Thread.java:856)
08-17 20:13:06.215: E/AndroidRuntime(28309): Caused by: java.lang.NullPointerException
08-17 20:13:06.215: E/AndroidRuntime(28309): at akun.Register$CreateUser.doInBackground(Register.java:143)
08-17 20:13:06.215: E/AndroidRuntime(28309): at akun.Register$CreateUser.doInBackground(Register.java:1)
08-17 20:13:06.215: E/AndroidRuntime(28309): at android.os.AsyncTask$2.call(AsyncTask.java:287)
08-17 20:13:06.215: E/AndroidRuntime(28309): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
08-17 20:13:06.215: E/AndroidRuntime(28309): ... 5 more

最佳答案

更改 register.php 中的代码

     if($id > 0){
$query = 'update akun set nama = "'.$nama.'", alamat = "'.$alamat.'", noidentitas = "'.$noidentitas.'", notelepon = "'.$notelepon.'", username = "'.$username.'", password = "'.$password.'" where id = '.$id;
} else {
$query = 'insert into akun (nama, alamat, noidentitas, notelepon, username, password) values ("'.$nama.'", "'.$alamat.'", "'.$noidentitas.'", "'.$notelepon.'", "'.$username.'", "'.$password.'")';
}
$result=mysql_query($query);
if ($result) { // This validates if Query was successful
echo '{"success":1,
"message":"Registered Successfully"}';

} else {
echo '{"success":2,
"message":"Registration failed"}';

}

如果您尝试从 url 获取 json 响应,请不要使用 die mysql 错误。 json 响应必须包含有效的 json 内容。

关于java - Android - 解析数据 org.json.jsonException 在字符 0 处输入结束时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25349516/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com