我正在尝试将我的onilne数据库中的数据导入我的android应用程序中的listview。但是我收到错误。请帮助,这是我项目的一个重要部分。这是代码
MainActivity.java
public class MainActivity extends Activity {
private String jsonResult;
private String url = "http://pixography.netai.net/json.php";
private ListView listView;
private TextView textv1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView1);
textv1=(TextView)findViewById(R.id.textView1);
accessWebService();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
@Override
protected void onPostExecute(String result) {
ListDrwaer();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public void ListDrwaer() {
List<Map<String, String>> dslrList = new ArrayList<Map<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("dslrstore");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.getString("Name");
String location = jsonChildNode.getString("Location");
String outPut = name + "-" + location;
//textv1.setText(name);
//textv1.setText(jsonResult);
dslrList.add(createdslr("dslr", outPut));
}
} catch (JSONException e) {
textv1.setText( "Error" + e.toString());
}
SimpleAdapter simpleAdapter = new SimpleAdapter(this, dslrList,
android.R.layout.simple_list_item_1,
new String[] { "dslr" }, new int[] { android.R.id.text1 });
listView.setAdapter(simpleAdapter);
}
private HashMap<String, String> createdslr(String name, String location) {
HashMap<String, String> dslrNamelocate = new HashMap<String, String>();
dslrNamelocate.put(name,location);
return dslrNamelocate;
}
}
main.xml中
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TableRow
android:id="@+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</TableRow>
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
</ListView>
</LinearLayout>
JSON.php
<?php
$host = "mysql13.000webhost.com";
$user = "a2464928_rajat";
$password = "rajat123";
$db = "a2464928_minor";
$sql = "select * from dslrstore;";
$con= mysqli_connect($host,$user,$password,$db);
$result = mysqli_query($con,$sql);
$response = array();
while($row = mysqli_fetch_array($result))
{
array_push($response,array("Name"=>$row[0],"Location"=>$row[1]));
}
echo json_encode(array($response));
mysqli_close($con);
?>
错误是JSONArray无法转换为JSONObject。
答案 0 :(得分:0)
首先,我不确定Android,但是当你返回JSON时,设置正确的标头是一种很好的方式。
到目前为止,您的php脚本(http://pixography.netai.net/json.php)将返回以下内容:
HTTP/1.1 200 OK
Date: Sun, 06 Dec 2015 20:37:02 GMT
Server: Apache
X-Powered-By: PHP/5.2.17
Content-Length: 238
Connection: close
Content-Type: text/html
尝试在脚本中的任何输出之前放置header('Content-type: application/json; charset=utf-8');
,同时检查UTF-8 BOM问题,因为它会破坏php中正确的标头输出。
至少你会得到适当的JSON标题。
-
我在你的php代码中看到的另一件事 - 数组键是数字的,我不太确定,但我认为JSON对象键应该是字符串。那么也许你应该试试$response[$row[0]] = array("Name"=>$row[0],"Location"=>$row[1]);
?
-
我还认为您应该在mysqli_close($con);
之前加echo
,以获得更好的效果。在为输出填满数据之后,没有理由保持mysql连接打开。