I'm currently working on an Android application. It is connected to the free database provided by 000webhost. I have a table created in the database. The data storing and retrieving process work fine if there are data stored in the table. But if there are no data stored in the table, the application cannot even be run. So I guess one way to sort out the problem is to add a database checking method. However, I don't know how to do it in java as I use php file to connect to the server. I tried adding php codes to check if db is empty, but it doesn't work. So I'm wondering how I could check if db is empty.
This is my php file:
<?php
//I just hide my personal info.
$con = mysql_connect('serveraddress', 'username', 'dbpw');
mysql_select_db('dbname', $con);
$r = mysql_query('SELECT * FROM ForumData');
while($row = mysql_fetch_array($r)){
$out[] = $row;
}
print(json_encode($out));
mysql_close($con);
?>
This is how I retrieve the data from the db, it works when there are data in the database, but doesn't work when there is none.
private class RetrieveTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(SERVER_ADDRESS + "RetrieveReplyData.php");
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), exceptionMessage + ", Ex1", Toast.LENGTH_SHORT).show();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "
");
}
result = sb.toString();
System.out.println("-----JSON Data-----");
System.out.println(result);
is.close();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), exceptionMessage + ", Ex2", Toast.LENGTH_SHORT).show();
}
try {
JSONArray jsonArray = new JSONArray(result);
int totalCount = jsonArray.length();
for (int i = 0; i < totalCount; i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
respondent = jsonObject.getString("reply_user");
content = jsonObject.getString("reply_content");
datetime = jsonObject.getString("reply_datetime");
itemList.add(new ReplyItemList(respondent, content, datetime));
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), exceptionMessage + ", Ex3", Toast.LENGTH_SHORT).show();
}
return null;
}