使用listview
从JSON
显示asyntask
时出现问题。我希望在特定radiobutton
点击下显示数据,但DDMS结果显示为"Caused by: java.lang.NullPointerException"
。
ListResult.java
public class ListResult extends ListActivity implements OnClickListener {
private ProgressDialog pDialog;
String paramString;
JSONParser jsonParser = new JSONParser();
ArrayList<HashMap<String, String>> busList;
RadioButton rbSUN;
RadioButton rbFRI;
RadioButton rbSAT;
ListView lv;
private int success;
private static String url_insert_new = "http://10.0.2.2/onlineLibrary/getallbus.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_IDIOMS = "idioms";
private static final String TAG_ID = "id";
private static final String TAG_TIME = "time";
private static final String TAG_STATUS = "status";
JSONArray idioms = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_result);
busList = new ArrayList<HashMap<String, String>>();
lv = getListView();
rbSUN = (RadioButton) findViewById(R.id.radioSUN);
rbFRI = (RadioButton) findViewById(R.id.radioFRI);
rbSAT = (RadioButton) findViewById(R.id.radioSAT);
rbSUN.setOnClickListener(this);
rbFRI.setOnClickListener(this);
rbSAT.setOnClickListener(this);
new InsertNewIdiom().execute();
}
@Override
public void onClick(View v) {
if (v.getId()==R.id.radioSUN){
new InsertNewIdiom().execute();
if (success==1){
Toast.makeText(getApplicationContext(), "New item saved...", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "New item FAILED to saved...", Toast.LENGTH_LONG).show();
}
paramString="SUN";
}
if (v.getId()==R.id.radioFRI){
new InsertNewIdiom().execute();
if (success==1){
Toast.makeText(getApplicationContext(), "New item saved...", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "New item FAILED to saved...", Toast.LENGTH_LONG).show();
}
paramString="FRI";
}
if (v.getId()==R.id.radioSAT){
new InsertNewIdiom().execute();
if (success==1){
Toast.makeText(getApplicationContext(), "New item saved...", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "New item FAILED to saved...", Toast.LENGTH_LONG).show();
}
paramString="SAT";
}
}
class InsertNewIdiom extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ListResult.this);
pDialog.setMessage("Loading ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("time", TAG_TIME));
params.add(new BasicNameValuePair("status", TAG_STATUS));
JSONObject json = jsonParser.makeHttpRequest(url_insert_new,
"GET", params);
Log.d("Insert New item Response", json.toString());
try {
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
idioms = json.getJSONArray(TAG_IDIOMS);
for (int i = 0; i < idioms.length(); i++) {
JSONObject c = idioms.getJSONObject(i);
String id = c.getString(TAG_ID);
String time = c.getString(TAG_TIME);
String status = c.getString(TAG_STATUS);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ID, id);
map.put(TAG_TIME, time);
map.put(TAG_STATUS, status);
busList.add(map);
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
// pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
ListResult.this, busList,
R.layout.list_view, new String[]
{ TAG_ID, TAG_TIME, TAG_STATUS},
new int[] { R.id.id, R.id.time, R.id.status});
setListAdapter(adapter);
}
});
}
}
}
JsonParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser() {
}
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
try {
if(method == "POST"){
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"){
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 {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}
}
activity_list_result.xml
<LinearLayout xmlns:android=
"http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ScrollView
android:id="@+id/scrollView1"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_gravity="center"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#B3E5FC"
>
<TextView
android:id="@+id/textGranular"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="BUS Schedule:"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#0000ff"
android:padding="7dp"
android:textStyle="italic"
/>
<HorizontalScrollView
android:id="@+id/horizontalScrollView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<RadioGroup
android:id="@+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<RadioButton
android:id="@+id/radioSUN"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Sunday-Thursday" />
<RadioButton
android:id="@+id/radioFRI"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Friday" />
<RadioButton
android:id="@+id/radioSAT"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Saturnday" />
</RadioGroup>
</LinearLayout>
</HorizontalScrollView>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="@android:id/list"
android:layout_width="wrap_content"
android:layout_height="396dp" >
</ListView>
</LinearLayout>
</LinearLayout>
</ScrollView>
</LinearLayout>
list_view.xlm
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="6"
>
<TextView
android:id="@+id/textView2"
android:layout_width="57dp"
android:layout_height="wrap_content"
android:padding="2dp"
android:text="Time:"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#000"
android:textSize="14sp" />
<TextView
android:id="@+id/time"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="2dp"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#000"
android:textSize="14sp" />
</LinearLayout>
<!-- Entry data display -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="6"
>
<TextView
android:id="@+id/textView3"
android:layout_width="57dp"
android:layout_height="wrap_content"
android:padding="2dp"
android:text="Status:"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#000"
android:textSize="14sp" />
<TextView
android:id="@+id/status"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="2dp"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#000"
android:textSize="14sp" />
</LinearLayout>
</LinearLayout>
getallbus.php
<?php
$response=array();
$paramString=$_REQUEST[''];
require_once __DIR__.'/db_connect.php';
$db=new DB_CONNECT();
$sql="SELECT * FROM getbus WHERE day='$paramString'";
$result=mysql_query($sql);
if(!empty($result))
{
if(mysql_num_rows($result)>0)
{
$response['idioms']=array();
while ($row = mysql_fetch_array($result)) {
$book=array();
$book['day']=$row['day'];
$book['time']=$row['time'];
$book['status']=$row['status'];
array_push($response['idioms'], $book);
}
$response['success']=1;
echo json_encode($response);
}
else {
$response['success']=0;
$response['message']='No data found';
echo json_encode($response);
}
}
?>
logcat的
02-07 14:37:09.761: E/JSON Parser(1195): Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
02-07 14:37:19.091: E/JSON Parser(1195): Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
答案 0 :(得分:0)
您的PHP文件失败,反过来,显示的异常(作为HTML数据,因为它是一个PHP文件)被传递回您的应用程序,而不是检查成功代码。由于您的应用程序只是获取数据并运行它,它正在尝试将您的PHP文件中的异常解析为JSON,这显然不起作用。您需要在PHP文件中验证不会抛出任何异常并且它会提供有效的JSON响应。
就您的PHP异常而言,您尝试访问$_REQUEST
中不存在的数组索引,因为您将空字符串传递给[]
。这导致您的PHP文件失败。当PHP抛出一个异常时,它会给出一个描述错误的默认响应(作为HTML),而你的应用程序正试图将其解析为JSON,并且失败了。
因此,如果您将请求发送到PHP文件
getallbus.php?requestParam=[yourRequestParam] // aka `GET`
然后你会用
$paramString = $_GET['requestParam'];
如果您将请求作为POST
发送,则可以使用
$paramString = $_POST['requestParam'];
这样,只要实际存在名为“requestParam”的索引,PHP就不应抛出异常。希望这会有所帮助。