gpt4 book ai didi

java - Android JAVA从php获取数组

转载 作者:行者123 更新时间:2023-12-01 13:21:02 25 4
gpt4 key购买 nike

我有这个 php,它返回一个包含数据库中的值的数组:

public function getHashTags(){
$res = array();
$i = 0;

$userID = $this->getUserID();
$db_ = $this->dbSelect("hashTags","userID = '$userID' ORDER BY hashTag ASC");

while($db = $this->dbAssoc($db_)){
$key = $db['id'];
$res[$key] = $db['hashTag'];
$i++;
}

return $this->genResponse($res);
}

而且我不知道如何在 JAVA 上接收这个数组,因为这个数组没有名称......我试过这个:

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

protected String doInBackground(String... args) {

// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("token", token));

// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(getHashTagsURL, "POST", params);

// Check your log cat for JSON response
Log.d("All hashTags: ", json.toString());

try { //Trying to get hashTags

JSONArray hashTagsArray = new JSONArray(json.toString());

// Looping through all videos
for (int i = 0; i < hashTagsArray.length(); i++) {

JSONObject c = hashTagsArray.getJSONObject(i);

int hashTagId = c.getInt("id");
String hashTagTxt = c.getString("hashTag");

// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();

// adding each child node to HashMap key => value
map.put("hashId", hashTagId);
map.put("hashTagTxt", hashTagTxt);

// adding HashList to ArrayList
hashTagsList.add(map);

} //End for

} catch (JSONException e) {

e.printStackTrace();

}

return null;
}

protected void onPostExecute(String file_url) {

runOnUiThread(new Runnable() {

public void run() {

Toast.makeText(getApplicationContext(), "HashTags Loaded", Toast.LENGTH_LONG).show();
}
});

// dismiss the dialog after getting all hashTags
pDialog.dismiss();

// updating UI from Background Thread
runOnUiThread(new Runnable() {

public void run() {

ListAdapter adapter = new SimpleAdapter(

VideoUpload.this, hashTagsList,
R.layout.hashTags_list_item, new String[] { "hashTagId", "hashTagTxt"},
new int[] { R.id.hashTagId, R.id.hashTagTxt}
);

// updating spinner
setListAdapter(adapter);
}
});

} //Close PostExecute

} // CLOSER LOAD HASHTAGS

但它抛出异常:

02-25 22:48:58.450: W/System.err(1639): org.json.JSONException: Value {"270":"My hashTag      test","272":"my hastag test2","271":"my hashtag test2","274":"my hashtag test5","273":"my   hashtag test3"} of type org.json.JSONObject cannot be converted to JSONArray
02-25 22:48:58.450: W/System.err(1639): at org.json.JSON.typeMismatch(JSON.java:111)
02-25 22:48:58.460: W/System.err(1639): at org.json.JSONArray.<init> (JSONArray.java:96)
02-25 22:48:58.460: W/System.err(1639): at org.json.JSONArray.<init>(JSONArray.java:108)
02-25 22:48:58.460: W/System.err(1639): at com.example.kroosky.VideoUpload$LoadHashTags.doInBackground(VideoUpload.java:484)
02-25 22:48:58.480: W/System.err(1639): at com.example.kroosky.VideoUpload$LoadHashTags.doInBackground(VideoUpload.java:1)
02-25 22:48:58.480: W/System.err(1639): at android.os.AsyncTask$2.call(AsyncTask.java:288)
02-25 22:48:58.490: W/System.err(1639): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
02-25 22:48:58.490: W/System.err(1639): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
02-25 22:48:58.490: W/System.err(1639): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
02-25 22:48:58.490: W/System.err(1639): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
02-25 22:48:58.490: W/System.err(1639): at java.lang.Thread.run(Thread.java:841)

有什么想法吗?谢谢

最佳答案

这是我用来获取 json 数组的方法:

// send a httpRequest to the url
// and parse the json response to a string
public String sendHttpRequest(String url) {
try {
// the HTTP request
HttpParams p = new BasicHttpParams();
HttpClient httpclient = new DefaultHttpClient(p);
HttpPost httppost = new HttpPost(url);
httppost.setHeader("charset", "UTF-8");
httppost.setHeader("Content-Type", "application/json");

httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();

} catch (Exception e) {
Log.e("taghttppost", "" + e.toString());
}
// conversion of the httpResponse to a string
try {
InputStreamReader isr = new InputStreamReader(inputStream, "UTF-8");
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();

String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
inputStream.close();
result = sb.toString();
result = new String(sb.toString().getBytes("UTF-8"));

} catch (Exception e) {
Log.e("tagconvertstr", "" + e.toString());
}

return result;
}

然后我这样调用它:

JSONArray jArray;
JSONObject jobj = new JSONObject(); // if you need it
String result = sendHttpRequest("www.yourUrl.com");
// Parse the string to get a json array
try {
jArray = new JSONArray(result);
jobj = jArray.getJSONObject(0); // 0 is the index in the json array...
} catch (JSONException e) {
}

然后你就可以随意使用这个json对象了...

int id = Integer.parseInt(jobj.getString("id")); 
// or simply :
int id=jobj.getInt("op_country_id");
String str = jobj.getString("str");

希望对你有帮助。

关于java - Android JAVA从php获取数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22028298/

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