gpt4 book ai didi

php - 需要帮助将 JSON 数据从 MYSQL 数据库获取到 Android 应用程序

转载 作者:行者123 更新时间:2023-11-29 20:16:51 25 4
gpt4 key购买 nike

我正在开发一个 Android 应用程序,它连接到远程 MYSQL 数据库并通过 JSON 数据检索信息。我遇到问题的应用程序部分涉及通过 userID 进行搜索在应用程序中,并从数据库返回关联的用户信息,例如 ID、名字、公司和职位。

问题在于解析应用程序内的 JSON 数据。我收到的错误消息是 System.err: org.json.JSONException: No value for id

php页面显示JSON数据。输出两个 JSON 对象:a success对象和一个result目的。 success对象由应用程序正确解析,并通过 if 语句告诉应用程序要做什么。所以if success == 1 ,应用程序执行一段应该解析 result 的代码块。对象并将数组的每个元素分配给 String应用程序中的值(value)。 php 页面的输出是:

{"success":1,"message":"UserID found!"}{"result":[{"id":"1100011","firstname":"Kevin","company":"company","position":"bartender"}]}

问题是 results 中的值应用程序未解析对象。这是 php 页面:

 <?php
define('HOST','localhost');
define('USER','********');
define('PASS','**********');
define('DB','**********');

if (!empty($_POST)){

if (empty($_POST['userID'])){
$response["success"] = 0;
$response["message"] = "Please enter a User ID";
die(json_encode($response));
}

$userID = mysql_escape_string($_POST['userID']);

$con = mysqli_connect(HOST,USER,PASS,DB);

$sql = "SELECT * FROM users WHERE id = $userID";

$res = mysqli_query($con,$sql);

$result = array();

while($row = mysqli_fetch_array($res)){
array_push($result, array(
'id'=>$row[0],
'firstname'=>$row[4],
'company'=>$row[6],
'position'=>$row[7],
)
);
}

if($result){
$response["success"] = 1;
$response["message"] = "UserID found!";
echo json_encode($response); // if I comment out this line, the result array gets parsed properly by the app.
echo json_encode(array("result"=>$result));

}else{
$response["success"] = 0;
$response["message"] = "UserID not found. Please try again.";
die(json_encode($response));
}

mysqli_close($con);


} else {
?>
<h1>Search by User ID:</h1>
<form action="searchbyuserid.php" method="post">
Enter the UserID of the receipient:<br />
<input type="text" name="userID" placeholder="User ID" />
<br /><br />
<input type="submit" value="Submit" />
</form>
<a href="register.php">Register</a>
<?php
}

?>

如果我注释掉上面提到的行,应用程序的日志将显示应用程序为 results 解析的正确数据。数组:

D/UserID Lookup:: {"result":[{"id":"1100011","firstname":"Kevin","company":"company","position":"bartender"}]} ,但随后我收到 W/System.err: org.json.JSONException: No value for success 的错误因为success没有被发送(显然)。

这是我的 Android 代码:

import android.app.ProgressDialog; ... 

public class SearchByUserID extends ActionBarActivity implements View.OnClickListener {

// Buttons
private Button mSubmitButton, mBackButton;

// EditText Field
EditText enterUserID;

// Progress Dialog
private ProgressDialog pDialog;

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

// Variable for holding URL:
private static final String LOGIN_URL = "http://www.***********/webservice/searchbyuserid.php";

//JSON element ids from response of php script:
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private static final String TAG_USERID = "id";
private static final String TAG_FIRSTNAME = "firstname";
private static final String TAG_COMPANY = "company";
private static final String TAG_POSITION = "POSITION";



@Override
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
this.supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.search_by_user_id_layout);

mSubmitButton = (Button)findViewById(R.id.submit);
mBackButton = (Button)findViewById(R.id.back);

mSubmitButton.setOnClickListener(this);
mBackButton.setOnClickListener(this);

enterUserID = (EditText)findViewById(R.id.enterUserIdNumber);
}

@Override
public void onClick(View v) {

switch (v.getId()) {
case R.id.submit:
new SearchUserId().execute();
break;
case R.id.back:
finish();
break;

default:
break;
}
}

class SearchUserId extends AsyncTask<String, String, String> {

// Show progress dialog
boolean failure = false;

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

@Override
protected String doInBackground(String... args) {
// Check for success tag
int success;
String userID = enterUserID.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("userID", userID));

Log.d("UserID:", userID);
Log.d("request!", "starting");

JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST", params);

// check your log for json response
Log.d("UserID Lookup:", json.toString());

// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
JSONObject json2 = jsonParser.makeHttpRequest(LOGIN_URL, "POST", params);
String userid = json2.getString(TAG_USERID);
String firstName = json2.getString(TAG_FIRSTNAME);
String company = json2.getString(TAG_COMPANY);
String position = json2.getString(TAG_POSITION);

Log.d("User ID Found!", json.toString());
Log.d("userid:", userid);
Log.d("firstName:", firstName);
Log.d("company:", company);
Log.d("position:", position);

Intent i = new Intent(SearchByUserID.this, HomeActivity.class);
finish();
startActivity(i);
return json.getString(TAG_MESSAGE);
}else{
Log.d("User ID not found.", 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(SearchByUserID.this, file_url, Toast.LENGTH_LONG).show();
}

}

}
}

所以基本上我能够正确解析 success对象或 results对象,但不是两者。如果我尝试解析两者,则会收到 no value for id 的 JSON 错误。 。

最佳答案

JSONObject json2 = jsonParser.makeHttpRequest(LOGIN_URL, "POST", params);
JSONArray jsArray = json2.getJSONArray("result");

String usrid = jsArray.getJSONObject("id");
String firstName = jsArray.getJSONObject("firstname");
String company = jsArray.getJSONObject("company");
String position = jsArray.getJSONObject("position");

尝试将您的代码转换为此。

关于php - 需要帮助将 JSON 数据从 MYSQL 数据库获取到 Android 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39714573/

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