PHP를 사용하여 mySQL 데이터베이스에서 데이터를 가져 오려고합니다. 이것은 JSON을 사용하여 데이터를 원격으로 가져 오는 내 주먹 실제 시도입니다 &. php 파일은 JSON 문자열로 브라우저에 출력하고 JSONLint을 사용하여 valadated했기 때문에 올바르게 작동합니다. 그래서, 나는 여기서 내가 무엇이 잘못되었는지 확신하지 못한다. 어떤 도움을 크게 이것은 로그 캣 던지고있는 것이다PHP LogCat의 JSON : 문자열을 JSONObject로 변환 할 수 없습니다.
을 감상 할 수있다 :
Error parsing data org.json.JSONException: Value <?xml of type java.lang.String cannot be converted to JSONObject
threadid=9: thread exiting with uncaught exception (group=0x401dce20)
FATAL EXCEPTION: Thread-10
java.lang.NullPointerException
at com.andaero.test.JSON.JSONMain$1.run(JSONMain.java:39)
at java.lang.Thread.run(Thread.java:1020)
UPDATE : 마크의 요청에 따라내가 PHP 파일에서 에코 방법을 제거했습니다. . 나는 "JSONArray A = json.getJSONArray (" "규제가) 나는 또한 우선 아니오 다른 사람의 접근 노력과 관련이있다 생각 여기
클래스입니다.
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "regulatory";
JSONObject jArray = null;
// http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// convert response to string
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();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
리스트의 활동 :
public class JSONMain extends ListActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview);
final ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
new Thread(new Runnable() {
public void run() {
JSONObject json = JSONfunctions
.getJSONfromURL("http://192.168.1.34/andaero/regulatory_list_ASC.php");
try {
JSONArray a = json.getJSONArray("regulatory");
for (int i = 0; i < a.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = a.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("label", e.getString("label"));
map.put("title", e.getString("title"));
map.put("caption", e.getString("description"));
map.put("dummy", e.getString("gotoURL"));
mylist.add(map);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
}
}).start();
ListAdapter adapter = new SimpleAdapter(this, mylist,
R.layout.list_item, new String[] { "label", "title", "caption",
"dummy" }, new int[] { R.id.label, R.id.listTitle,
R.id.caption, R.id.dummy });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
@SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv
.getItemAtPosition(position);
Toast.makeText(JSONMain.this,
"ID '" + o.get("id") + "' was clicked.",
Toast.LENGTH_SHORT).show();
}
});
}
}
편집 : PHP의 :
<?php
//MySQL Database Connect
include 'andaerologin.php';
mysql_select_db("andaero");
$sql=mysql_query("select * from regulatory_list");
$output = new stdClass();
$output->regulatory = array();
while($row = mysql_fetch_assoc($sql)) {
$output->regulatory[] = $row;
}
header('Cache-Control: no-cache, must-revalidate');
header('Content-type: application/json');
echo (json_encode($output));
mysql_close();
?>
json으로는 ** 데이터를 반환 (에 - 부분 - 데이터는 기밀 & JSON은 !! 위에 따라 검증되었습니다)
[
{
_id: "**",
label: "**",
title: "**",
description: "**",
date: "**",
gotoURL: null,
intent: "QueryDisplay"
}, * additional rows.....>
]
}
JSON 부분을 보면 매우 유용 할 것입니다. ' xml' 문자가 유효한 JAVA 또는 Android JSON으로 인식되지 않을 수 있습니다. –
@Rafael 반환 된 JSON 데이터를 추가했습니다. JSON은 제 질문에 따라 유효성이 확인되었습니다. Thnx. – CelticParser
웹 서버이며 GARBAGE를 제공합니다. json을 가져 오는 방법을 테스트했으며 정상적으로 작동합니다. 나는 당신이 mysql에서 json을 만들어야하는 PHP를 만들었다. 모든 것이 완벽하게 작동합니다. 먼저 서버를 수정해야합니다. 그렇지 않으면 내가 json에 사용했던 URL을 던져서 테스트 할 수 있습니다. –