:facepalm1: po co rozdzielać na dwa pliki
dla autora tematu jak byś podał zrzut błędu to byś już dawno wiedział ze implementacja JSON używana w Androidzie nie przewiduje w pustym zakodowanym ciągu znaku [ oraz ]
wiec [{"id":"1","name":"Janusz","sex":"1","birthyear":"4 0791"}] nie jest poprawne, poprawnie jest
{"id":"1","name":"Janusz","sex":"1","birthyear":"4 0791"} dla zbiory powinno być
{"klucz":{"klucz":"wartość"}} czyli popranie tak jak generuje implementacja PHP
tu masz klasę JAVA, wraz ze sposobem urzycia
public class Mysql {
private final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
private URI serverAdress = null;
private StringBuilder responseContent = null;
private Mysql.onFinish callBack = null;
public Mysql(Mysql.onFinish callBack) {
this.callBack = callBack;
}
public interface onFinish {
void result(JSONObject result);
}
public void addValuePair(String name, String value) {
nameValuePairs.add(new BasicNameValuePair(name, value));
}
public void setServerAdress(String adresss) {
try {
serverAdress = new URI(adresss);
} catch (URISyntaxException e) {
Log.d("Info", "URISyntaxException", e);
}
}
public String getResponseString() {
return responseContent.toString();
}
public JSONObject getResponseObject() {
JSONObject jSONObject = null;
try {
jSONObject = new JSONObject(responseContent.toString());
} catch (JSONException e) {
Log.d("Info", "JSONException", e);
}
return jSONObject;
}
public static String getMD5(String plaintext) {
BigInteger bigInt = null;
try {
final MessageDigest message = MessageDigest.getInstance("MD5");
message.reset();
message.update(plaintext.getBytes());
bigInt = new BigInteger(1, message.digest());
} catch (NoSuchAlgorithmException e) {
Log.i("Info", "NoSuchAlgorithmException", e);
return plaintext;
}
return bigInt.toString(16);
}
public void sendServerData() {
final HttpClient httpclient = new DefaultHttpClient();
final HttpPost httppost = new HttpPost(serverAdress);
InputStream inRead = null;
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
final HttpResponse response = httpclient.execute(httppost);
inRead = response.getEntity().getContent();
responseContent = new StringBuilder();
final byte[] mBufffer = new byte[1024];
int mLength;
while ((mLength = inRead.read(mBufffer)) > 0) {
responseContent.append(new String(mBufffer, 0, mLength));
}
} catch (ClientProtocolException e) {
Log.d("Info", "ClientProtocolException", e);
} catch (Exception e) {
Log.d("Info", "Exception", e);
} finally {
try {
if (inRead != null) inRead.close();
} catch (IOException e) {
Log.e("Error", "IOException", e);
}
if (callBack != null && responseContent != null) callBack.result(getResponseObject());
}
}
}
final Mysql mysql = new Mysql(new Mysql.onFinish() {
public void result(JSONObject result) {
//result to jest wynik
}
});
mysql.setServerAdress("http://localhost/");
mysql.addValuePair("user", Mysql.getMD5("admin"));
mysql.addValuePair("passwd", Mysql.getMD5("passwd"));
mysql.addValuePair("query", "SELECT * FROM `api_array` LIMIT 0 , 30");
mysql.sendServerData();
oraz gotowy kod PHP w postaci 3 plików dla wygody podzieliłem to nie jest koniecznie, to jest oczywiście wersja mocno robocza, zapytanie nie powinno być przesyłane otwartym tekstem, nazwa użytkownika i hasło potrzebne do autoryzacji z pośrednikiem jest zakodowane MD5 więc w pewnym sensie jest bezpieczne
plik indeksowy index.php
<?php
//ustawienia połączenia bazą danych
define("DB_CHARSET", "utf8");
define("DB_ADRESS", "localhost");
define("DB_USER", "");
define("DB_PASSWD", "");
define("DB_PORT", "");
define("DB_BAZA", "");
//autoryzacja dostępu do pośrednika
define("USERNAME", "admin");
define("PASSWD", "passwd");
define("INDEX", true);
require_once(dirname(__FILE__).'/include.php');
require_once(dirname(__FILE__).'/database.php');
error_reporting(E_ALL);
set_error_handler("error_hand");
register_shutdown_function('shutdown_hand');
set_exception_handler('exception_hand');
ob_start();
$sql = new Database();
$sql->open();
$user = filter_input(INPUT_POST, 'user', FILTER_SANITIZE_STRING);
$passwd = filter_input(INPUT_POST, 'passwd', FILTER_SANITIZE_STRING);
if (strcmp($user, md5(USERNAME)) != 0 || strcmp($passwd, md5(PASSWD)) != 0) die('Unauthorized');
unset($user, $passwd);
$query = urldecode(filter_input(INPUT_POST, 'query', FILTER_SANITIZE_ENCODED));
if ($query && !is_null($query)) {
$result = $sql->query($query);
$return = array();
if (mysql_num_rows($result)) {
$count = 0;
while ($wiersz = mysql_fetch_assoc($result)) {
$return['pos_'.$count] = $wiersz;
$count++;
}
$sql->free();
}
echo json_encode($return);
}
$sql->close();
?>
funkcje pomocnicze include.php
<?php
if (!defined('INDEX') || !INDEX) die('Unauthorized');
function save_error_log($wiadomosc,$dziennik) {
$dziennik = './'.$dziennik.'.log';
if (file_exists($dziennik)) if (filesize($dziennik) > 10000) @unlink($dziennik);
if ($file = @fopen($dziennik,"a")) {
@fputs($file,date("Y-m-d H:i:s").': '.$wiadomosc."\n");
@fclose($file);
}
}
function error_hand($errno, $errstr, $errfile, $errline) {
save_error_log("Error: [$errno] $errstr, $errfile ($errline)",'error');
if ($errno > 8 && $errno != E_USER_WARNING) {
@ob_end_clean();
die(json_encode(array('error', $errstr)));
}
}
function shutdown_hand() {
if ($error = error_get_last()) {
switch($error['type']) {
case E_ERROR:
case E_CORE_ERROR:
case E_COMPILE_ERROR:
case E_USER_ERROR:
trigger_error('Cleaning', E_USER_WARNING);
@ob_get_clean();
echo json_encode(array('exit', $error['file'] . ' ['.$error['line'] . '] '. $error['message']));
break;
}
}
}
function exception_hand($e) {
save_error_log("Exception: ".$e->getMessage(),'error');
@ob_get_clean();
die(json_encode(array('exception', $e->getMessage())));
}
?>
oraz klasa do obsługi bazy danych database.php
<?php
if (!defined('INDEX') || !INDEX) die('Unauthorized');
class Database {
private $result;
private $database_id;
public function open() {
$this->database_id = @mysql_connect(DB_ADRESS.':'.DB_PORT,DB_USER,DB_PASSWD,false);
if (!is_resource($this->database_id)) trigger_error('SQL: connection error', E_USER_ERROR);
if (!@mysql_select_db(DB_BAZA)) trigger_error('SQL: '.mysql_error(), E_USER_ERROR);
$this->query('SET CHARSET '.DB_CHARSET);
$this->query('SET NAMES '.DB_CHARSET);
}
public function query($q) {
if (!is_resource($this->database_id)) @trigger_error('SQL: connection error', E_USER_ERROR);
$this->result = @mysql_query($q,$this->database_id);
if (mysql_error()) trigger_error('SQL: '.mysql_error().', query: '.$q, E_USER_ERROR);
return $this->result;
}
public function free() {
if (is_resource($this->result)) @mysql_free_result($this->result);
}
public function close() {
if (is_resource($this->database_id)) @mysql_close($this->database_id);
}
}
?>