я написал & запустил этот код, но попробовал еще раз, чтобы получить ошибку. Скрипт PHP по-прежнему отлично работает в браузере. Я понимаю, что сервер ничего не анализирует, но не могу понять, почему. Я просмотрел все (я думаю) вопросы с той же ошибкой LogCat здесь и множеством других онлайн-источников, но тщетно. Я не понимаю, что могло измениться, когда я выключил свой Mac, что повлияло на код. Спасибо
Вот код Java
public class downloadData extends AsyncTask<Void, Void, Boolean> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading list...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected Boolean doInBackground(Void... voids) {
updateJSONData();
return null;
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
pDialog.dismiss();
Log.i("onPostExecute", "downloadData complete.");
DBAdapter handler = new DBAdapter(getBaseContext());
}
}
public void updateJSONData() {
JSONArray listJsonArray;
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(READ_ENTRIES_URL);
if (json != null) {
Log.i("updateJSONData", "MySQL download complete.");
DBAdapter handler = new DBAdapter(getBaseContext());
handler.wipeMainTable();
try {
listJsonArray = json.getJSONArray(TAG_ENTRIES);
Log.i("updateJSONData", listJsonArray.length() + " entries downloaded");
handler.open();
for (int i = 0; i < listJsonArray.length(); i++) {
JSONObject listJsonArrayObject = listJsonArray.getJSONObject(i);
int entry_id = listJsonArrayObject.getInt(TAG_ID);
String title = listJsonArrayObject.getString(TAG_TITLE);
String link = listJsonArrayObject.getString(TAG_LINK);
String published = listJsonArrayObject.getString(TAG_PUBLISHED);
handler.insertEntry(entry_id, title, link, published);
Log.i("updateJSONData", "saved entry " + entry_id + " to SQLite database.");
}
handler.close();
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.i("JsonUpdate", "Nothing returned from server");
}
}
Мой класс JSONParser.
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(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, "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 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 JSONObject makeHttpRequest(String url, String method,
List < NameValuePair > params) {
// Making HTTP request
try {
// check for request method
if (method == "POST") {
// request method is POST
// defaultHttpClient
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") {
// request method is 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 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;
}
}
PHP скрипт
<?php
require("config.inc.php");
$query = "Select * FROM entry";
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
$rows = $stmt->fetchAll();if ($rows) {
$response["success"] = 1;
$response["message"] = "Post Available!";
$response["entries"] = array();
foreach ($rows as $row) {
$post = array();
$post["ID"] = $row["entry_id"];
$post["title"] = $row["title"];
$post["link"] = $row["link"];
$post["published"] = $row["published"];
array_push($response["entries"], $post);
}
echo json_encode($response);} else {
$response["success"] = 0;
$response["message"] = "No Post Available!";
die(json_encode($response));
}
?>
Мой LogCat
12-09 22:54:00.156: I/mainActivity(1431): Starting ...
12-09 22:54:00.164: D/OpenGLRenderer(1431): Render dirty regions requested: true
12-09 22:54:00.165: D/(1431): HostConnection::get() New Host Connection established 0xa5c11170, tid 1431
12-09 22:54:00.184: D/Atlas(1431): Validating map...
12-09 22:54:00.219: D/libEGL(1431): loaded /system/lib/egl/libEGL_genymotion.so
12-09 22:54:00.220: D/(1431): HostConnection::get() New Host Connection established 0xa5c113a0, tid 1447
12-09 22:54:00.225: W/System.err(1431): org.apache.http.conn.HttpHostConnectException: Connection to http://192.168.0.6:8888 refused
12-09 22:54:00.227: W/System.err(1431): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:183)
12-09 22:54:00.227: W/System.err(1431): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
12-09 22:54:00.227: W/System.err(1431): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
12-09 22:54:00.227: W/System.err(1431): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
12-09 22:54:00.227: W/System.err(1431): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
12-09 22:54:00.227: W/System.err(1431): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
12-09 22:54:00.227: W/System.err(1431): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
12-09 22:54:00.227: W/System.err(1431): at com.example.sine.JSONParser.getJSONFromUrl(JSONParser.java:43)
12-09 22:54:00.227: W/System.err(1431): at com.example.sine.MainActivity.updateJSONData(MainActivity.java:67)
12-09 22:54:00.227: W/System.err(1431): at com.example.sine.MainActivity$downloadData.doInBackground(MainActivity.java:293)
12-09 22:54:00.227: W/System.err(1431): at com.example.sine.MainActivity$downloadData.doInBackground(MainActivity.java:1)
12-09 22:54:00.227: W/System.err(1431): at android.os.AsyncTask$2.call(AsyncTask.java:288)
12-09 22:54:00.227: W/System.err(1431): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
12-09 22:54:00.227: W/System.err(1431): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
12-09 22:54:00.227: W/System.err(1431): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
12-09 22:54:00.227: W/System.err(1431): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
12-09 22:54:00.227: W/System.err(1431): at java.lang.Thread.run(Thread.java:818)
12-09 22:54:00.227: W/System.err(1431): Caused by: java.net.ConnectException: failed to connect to /192.168.0.6 (port 8888): connect failed: ENETUNREACH (Network is unreachable)
12-09 22:54:00.228: W/System.err(1431): at libcore.io.IoBridge.connect(IoBridge.java:124)
12-09 22:54:00.228: W/System.err(1431): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
12-09 22:54:00.228: W/System.err(1431): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:456)
12-09 22:54:00.228: W/System.err(1431): at java.net.Socket.connect(Socket.java:882)
12-09 22:54:00.228: W/System.err(1431): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
12-09 22:54:00.228: W/System.err(1431): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
12-09 22:54:00.228: W/System.err(1431): ... 16 more
12-09 22:54:00.228: W/System.err(1431): Caused by: android.system.ErrnoException: connect failed: ENETUNREACH (Network is unreachable)
12-09 22:54:00.228: W/System.err(1431): at libcore.io.Posix.connect(Native Method)
12-09 22:54:00.228: W/System.err(1431): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:111)
12-09 22:54:00.228: W/System.err(1431): at libcore.io.IoBridge.connectErrno(IoBridge.java:137)
12-09 22:54:00.228: W/System.err(1431): at libcore.io.IoBridge.connect(IoBridge.java:122)
12-09 22:54:00.228: W/System.err(1431): ... 21 more
12-09 22:54:00.228: E/Buffer Error(1431): Error converting result java.lang.NullPointerException: lock == null
12-09 22:54:00.228: E/JSON Parser(1431): Error parsing data org.json.JSONException: End of input at character 0 of
12-09 22:54:00.229: I/JsonUpdate(1431): Nothing returned from web service
12-09 22:54:00.230: D/libEGL(1431): loaded /system/lib/egl/libGLESv1_CM_genymotion.so
12-09 22:54:00.233: D/libEGL(1431): loaded /system/lib/egl/libGLESv2_genymotion.so
12-09 22:54:00.239: I/OpenGLRenderer(1431): Initialized EGL, version 1.4
12-09 22:54:00.254: D/OpenGLRenderer(1431): Enabling debug mode 0
12-09 22:54:00.259: W/EGL_genymotion(1431): eglSurfaceAttrib not implemented
12-09 22:54:00.259: W/OpenGLRenderer(1431): Failed to set EGL_SWAP_BEHAVIOR on surface 0xa5c766a0, error=EGL_SUCCESS
12-09 22:54:00.269: W/EGL_genymotion(1431): eglSurfaceAttrib not implemented
12-09 22:54:00.269: W/OpenGLRenderer(1431): Failed to set EGL_SWAP_BEHAVIOR on surface 0xa5c766c0, error=EGL_SUCCESS
12-09 22:54:00.365: I/onPostExecute(1431): downloadData complete.
Задача ещё не решена.
Других решений пока нет …