我需要关于我的代码的建议。
我试图解析php函数json_encode()
生成的json数组。
我的JSON:{"data": [{"streamer":"froggen","yt_length":"25078"},{"streamer":"wingsofdeath","yt_length":"8979"},{"streamer":"guardsmanbob","yt_length":"4790"},{"streamer":"kaostv","yt_length":"4626"},{"streamer":"kungentv","yt_length":"3883"},{"streamer":"destiny","yt_length":"3715"},{"streamer":"zekent","yt_length":"3428"},{"streamer":"athenelive","yt_length":"1673"},{"streamer":"frommaplestreet","yt_length":"1614"},{"streamer":"keyorikeys","yt_length":"1410"},{"streamer":"riotgamesturkish","yt_length":"1397"},{"streamer":"vman7","yt_length":"1022"},{"streamer":"tiensinoakuma","yt_length":"967"},{"streamer":"affenklappe","yt_length":"748"},{"streamer":"teamkeyd","yt_length":"747"},{"streamer":"lagtvmaximusblack","yt_length":"683"},{"streamer":"lolgameru","yt_length":"665"},{"streamer":"gruntartv","yt_length":"585"},{"streamer":"entenzwerg","yt_length":"579"},{"streamer":"lolgameru_cauthonpro","yt_length":"506"},{"streamer":"basickz","yt_length":"488"},{"streamer":"ilysuiteheart","yt_length":"491"},{"streamer":"kireiautumn","yt_length":"485"},{"streamer":"ultimavv","yt_length":"471"}]}
Java类:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
String response = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet(url);
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 {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is), 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;
}
}
以及我的活动:
public class AndroidJSONParsingActivity extends ListActivity {
// url to make request
private static String url = "http://ololo.tv/vasa";
// JSON Node names
private static final String TAG_DATA = "data";
private static final String TAG_STREAMER = "streamer";
private static final String TAG_VIEWERS = "yt_length";
// contacts JSONArray
JSONArray data = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Hashmap for ListView
ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser Parser = new JSONParser();
// getting JSON string from URL
JSONObject json = null;
json = Parser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
data = json.getJSONArray(TAG_DATA);
// looping through All Contacts
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
// Storing each json item in variable
String streamer = c.getString(TAG_STREAMER);
String viewers = c.getString(TAG_VIEWERS);
//String link = c.getString();
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_STREAMER, streamer);
map.put(TAG_VIEWERS, viewers);
//map.put(TAG_URL, link);
// adding HashList to ArrayList
dataList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, dataList,
R.layout.list_item,
new String[] { TAG_STREAMER, TAG_VIEWERS /*TAG_URL*/ }, new int[] {
R.id.streamer, R.id.viewers /*R.id.url*/ });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.streamer)).getText().toString();
String viewers_count = ((TextView) view.findViewById(R.id.viewers)).getText().toString();
//String url = ((TextView) view.findViewById(R.id.url)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_STREAMER, name);
in.putExtra(TAG_VIEWERS, viewers_count);
//in.putExtra(TAG_PHONE_MOBILE, url);
startActivity(in);
}
});
}
}
我尝试使用断点,并看到当我在
GetEntity
之后放置断点时,程序不会到达那里,因为它很早就崩溃了,或者是其他什么原因。这是我的异步任务。
public class ParsingTask extends AsyncTask<String, Void, Void>{
JSONParser Parser = new JSONParser();
protected Void doInBackground(String... urls) {
ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>();
JSONObject json = Parser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
data = json.getJSONArray(TAG_DATA);
// looping through All Contacts
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
// Storing each json item in variable
String streamer = c.getString(TAG_STREAMER);
String viewers = c.getString(TAG_VIEWERS);
//String link = c.getString();
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_STREAMER, streamer);
map.put(TAG_VIEWERS, viewers);
//map.put(TAG_URL, link);
// adding HashList to ArrayList
dataList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, dataList,
R.layout.list_item,
new String[] { TAG_STREAMER, TAG_VIEWERS /*TAG_URL*/ }, new int[] {
R.id.streamer, R.id.viewers /*R.id.url*/ });
setListAdapter(adapter);
return null;
}
protected void onProgressUpdate() {
}
protected void onPostExecute() {
}
}
listadapter错误,似乎是“this”中的错误。这个我的版本如何切断代码,在哪里停止返回变量。对不起,英语不好,但我希望你能理解我:)
添加我的php json maker。有MB问题吗?啊!
<?php
mysql_connect("localhost","root","");
if (!mysql_select_db("ololo")) {
echo "Unable to select ololo: " . mysql_error();
}
$sql=mysql_query("select streamer, yt_length from pm_videos where category='1'");
if(!$sql) exit("Error - ".mysql_error().", ".$tmp_q);
while($row=mysql_fetch_assoc($sql)){
$output[]=$row;
}
$json = json_encode($output);
header('Content-Type: application/json');
print "{\"data\": ${json}}";
mysql_close();
?>
最佳答案
你的程序崩溃是因为你正在运行
json = Parser.getJSONFromUrl(url);
在ui线程上下文中。你必须使用AsyncTask
代码看起来不错。唯一的问题是
public class ParsingTask extends AsyncTask<String, Void, ArrayList<HashMap<String, String>>>{
JSONParser Parser = new JSONParser();
protected Void doInBackground(String... urls) {
ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>();
JSONObject json = Parser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
data = json.getJSONArray(TAG_DATA);
// looping through All Contacts
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
// Storing each json item in variable
String streamer = c.getString(TAG_STREAMER);
String viewers = c.getString(TAG_VIEWERS);
//String link = c.getString();
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_STREAMER, streamer);
map.put(TAG_VIEWERS, viewers);
//map.put(TAG_URL, link);
// adding HashList to ArrayList
dataList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
return dataList;
}
protected void onPostExecute(ArrayList<HashMap<String, String>> dataList) {
ListAdapter adapter = new SimpleAdapter(AndroidJSONParsingActivity.this, dataList,
R.layout.list_item,
new String[] { TAG_STREAMER, TAG_VIEWERS /*TAG_URL*/ }, new int[] {
R.id.streamer, R.id.viewers /*R.id.url*/ });
setListAdapter(adapter);
}
关于java - JSON解析Android,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16882037/