Android アプリを作成していて、リモート データベースからデータを取得しようとしています。
私の質問は、クエリ結果にデータが含まれていて空でないかどうかを確認するにはどうすればよいですか?
JSONを使用していますが、初めてです。これが私のコードです:
public class MainActivity extends Activity {
private TextView txt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout rootLayout = new LinearLayout(getApplicationContext());
txt = new TextView(getApplicationContext());
rootLayout.addView(txt);
setContentView(rootLayout);
txt.setText("Connexion...");
txt.setText(getServerData(strURL));
}
public static final String strURL = "http://.../marecherche/adresse.php";
private String getServerData(String returnString) {
InputStream is = null;
String result = "";
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("adresse","adr casa"));
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(strURL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
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());
}
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{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","raison sociale: "+json_data.getString("raison_social")+
", Adresse: "+json_data.getString("adresse")
);
returnString += "\n\t" + jArray.getJSONObject(i);
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data " + e.toString());
}
return returnString;
}
}
そしてphpファイル:
<?php
mysql_connect("localhost", "root", "passwd");
mysql_select_db("dbname");
$mots = explode(' ', $_REQUEST['adresse']);
$like = array();
foreach ($mots AS $mot) {
$like[] = ' "%' . mysql_real_escape_string($mot) . '%" ';
}
$condition = implode(' OR adresse LIKE ', $like);
$sql = mysql_query("SELECT * FROM entreprise WHERE adresse like " . $condition);
while ($row = mysql_fetch_assoc($sql))
$output[] = $row;
print(json_encode($output));
mysql_close();
?>