我从我的android应用程序连接到外部数据库。它是使用PHP JSON的MS SQL Server。
我已成功连接到数据库并在浏览器中获得结果。虽然来到android我没有得到任何结果它显示Error Parsing Data org.json.JSONException: Value of type java.lang.String cannot be converted to JSONArray
。以下是我的代码。
getDatabase.php
<?php header('content-type: application/json; charset=utf-8');
$myServer = "example";
$myUser = "user";
$myPass = "pq";
$myDB = "dbname";
$conn = new COM ("ADODB.Connection")
or die("Cannot start ADO");
$connStr ="PROVIDER=SQLOLEDB;SERVER=".$myServer.";
UID=".$myUser.";PWD=".$myPass.";DATABASE=".$myDB;
$conn->open($connStr);
$query = "SELECT parkingtitle,address FROM parkd_dailyparkingslots";
$rs = $conn->execute($query);
$num_columns = $rs->Fields->Count();
for ($i=0; $i < $num_columns; $i++) {
$fld[$i] = $rs->Fields($i);
}
while (!$rs->EOF)
{
for ($i=0; $i < $num_columns; $i++) {
print(json_encode($fld[$i]->value));
}
$rs->MoveNext(); //move on to the next record
}
$rs->Close();
$conn->Close();
$rs = null;
$conn = null;
?>
数据库活动
public class Database extends Activity {
/** Called when the activity is first created. */
TextView resultView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.database);
StrictMode.enableDefaults(); // STRICT MODE ENABLED
resultView = (TextView) findViewById(R.id.result);
getData();
}
public void getData() {
String result = "";
InputStream isr = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://www.example.com/getDatabase.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
isr = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
resultView.setText("Couldnt connect to database");
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
isr, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
// parse json data
try {
String s = "";
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
String json = jArray.getString(i); // JSONObject
// json = jArray.getJSONObject(i);
JSONObject jObj = new JSONObject(json);
s = s + "Name: " + jObj.getString("parkingtitle") + "\n\n"
+ "Address: " + jObj.getString("address") + "\n\n";
}
resultView.setText(s);
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error Parsing Data " + e.toString());
}
}
}
我在谷歌搜索并查看所有帖子,但我没有得到任何解决方案。 请帮帮我。 提前谢谢。
答案 0 :(得分:0)
尝试使用:
JSONObject jObj = jArray.getJSONObject(i);
而不是:
jArray.getString(i); // JSONObject // json = jArray.getJSONObject(i);
JSONObject jObj = new JSONObject(json);