[英]What to do when no results are returned from SQL query?
我的SQL數據庫是使用PHP從Android應用程序查詢的,但有時候搜索沒有返回任何結果,因為搜索條件沒有給出匹配。
這是我的ProgressTask:
public class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
protected void onPreExecute() {
dialog = new ProgressDialog(GetData.this);
dialog.setMessage("Searching Database");
dialog.show();
}
protected Boolean doInBackground(final String... args) {
JSONParser jParser = new JSONParser();
// get JSON data from URL
JSONArray json = jParser.getJSONFromUrl(url);
for (int i = 0; i < json.length(); i++) {
try {
JSONObject c = json.getJSONObject(i);
String Listing_ID = c.getString(lblListing_ID);
String Event_ID = c.getString(lblEvent_ID);
String Venue_ID = c.getString(lblVenue_ID);
String Start_Date = c.getString(lblStart_Date);
String End_Date = c.getString(lblEnd_Date);
String Frequency = c.getString(lblFrequency);
HashMap<String, String> map = new HashMap<String, String>();
// Add child node to HashMap key & value
map.put(lblListing_ID, Listing_ID);
map.put(lblEvent_ID, Event_ID);
map.put(lblVenue_ID, Venue_ID);
map.put(lblStart_Date, Start_Date);
map.put(lblEnd_Date, End_Date);
map.put(lblFrequency, Frequency);
jsonlist.add(map);
}
catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
ListAdapter adapter = new SimpleAdapter(GetData.this, jsonlist,
R.layout.list_item, new String[] { lblListing_ID , lblEvent_ID,
lblVenue_ID, lblStart_Date, lblEnd_Date, lblFrequency }, new int[] {
R.id.Listing_ID, R.id.Event_ID, R.id.Venue_ID,
R.id.Start_Date, R.id.End_Date, R.id.Frequency });
setListAdapter(adapter);
// select single ListView item
lv = getListView();
}
}
}
這是我的JSONParser類:
public class JSONParser {
static InputStream iStream = null;
static JSONArray jarray = null;
static String json = "";
public JSONParser() {
}
public JSONArray getJSONFromUrl(String url) {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
Log.e("==>", "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Parse String to JSON object
try {
JSONObject object = new JSONObject( builder.toString());
jarray = object.getJSONArray("listings");
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jarray;
}
}
當serach沒有返回結果時,PHP返回此JSON數據:
{
"listings": [
""
]
}
當JSON為空時,我希望輸出某種消息,說“找不到結果”。 我已經搜索了一下並嘗試了JSON.length()= 0或setEmptyView等方法但沒有成功。 我只是想知道是否有人對什么是沒有返回結果時的最佳響應方式有任何想法,如果是,如何實現它。
如果您有任何回復,請提前致謝,如果您需要更多信息,請在下面評論。 謝謝
檢查JSONArray的大小,如果它不超過0,則顯示一個toast。
JSONObject object = new JSONObject(builder.toString());
jarray = object.getJSONArray("listings");
if (jarray == null || jarray.length() == 0) {
Toast.makeText(context, "No results found", duration).show():
}
else{
// existing code to process entries
}
編輯
您可以使用以下布局,如果您的json數組為null或其大小== 0,則將listview的visiblity設置為已消失,textview的可見性為可見。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/screen_background"
tools:context=".FAQFragment" >
<ListView
android:id="@android:id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</ListView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="No Values to Show"
android:visibility="gone"
android:id="@+id/tvMsg" />
</RelativeLayout>
現在在AsyncTask中: -
public class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
private JSONArray json=null;
protected void onPreExecute() {
dialog = new ProgressDialog(GetData.this);
dialog.setMessage("Searching Database");
dialog.show();
}
protected Boolean doInBackground(final String... args) {
JSONParser jParser = new JSONParser();
// get JSON data from URL
JSON = jParser.getJSONFromUrl(url);
if(json!=null && json.length()>0)// returning from doInBackground() if json is null
return null;
for (int i = 0; i < json.length(); i++) {
try {
JSONObject c = json.getJSONObject(i);
String Listing_ID = c.getString(lblListing_ID);
String Event_ID = c.getString(lblEvent_ID);
String Venue_ID = c.getString(lblVenue_ID);
String Start_Date = c.getString(lblStart_Date);
String End_Date = c.getString(lblEnd_Date);
String Frequency = c.getString(lblFrequency);
HashMap<String, String> map = new HashMap<String, String>();
// Add child node to HashMap key & value
map.put(lblListing_ID, Listing_ID);
map.put(lblEvent_ID, Event_ID);
map.put(lblVenue_ID, Venue_ID);
map.put(lblStart_Date, Start_Date);
map.put(lblEnd_Date, End_Date);
map.put(lblFrequency, Frequency);
jsonlist.add(map);
}
catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
if(json!=null && json.length()>0){
ListAdapter adapter = new SimpleAdapter(GetData.this, jsonlist,
R.layout.list_item, new String[] { lblListing_ID , lblEvent_ID,
lblVenue_ID, lblStart_Date, lblEnd_Date, lblFrequency }, new int[] {
R.id.Listing_ID, R.id.Event_ID, R.id.Venue_ID,
R.id.Start_Date, R.id.End_Date, R.id.Frequency });
setListAdapter(adapter);
// select single ListView item
lv = getListView();
}else{
tvMsg.setVisibility(View.VISIBLE); // displaying overlay text when no data is present
yourListView.setVisibility(View.GONE);
}
}
}
}
通常, ListView
顯示在ListActivity
。 這樣的活動包含嵌入式機制來處理這種情況:
(可選)您的自定義視圖可以包含列表視圖為空時要顯示的任何類型的另一個視圖對象。 這個“空列表”通知符必須有一個id“android:id / empty”。 請注意,當存在空視圖時,如果沒有要顯示的數據,將隱藏列表視圖。
(在http://developer.android.com/reference/android/app/ListActivity.html中 )
基本上,你為列表放了一個@android:id/list
ListView,為No result found
消息放了一個@android:id/empty
TextView。 ListActivity處理2之間的切換。
從您使用的方法,例如setListAdapter
,我假設您確實使用ListActivity
。 因此,您可以輕松集成@android:id/empty
機制。
你可以檢查第一個元素
例如:
JSONArray json = jParser.getJSONFromUrl(url);
if(json == null){
//Oops!
showToast();
return null;
}
...
jarray = object.getJSONArray("listings");
if(jarray.get(0).toString().length() == 0)
//Oops!
return null;
...
編輯
EX2:
...
JSONArray json = jParser.getJSONFromUrl(url);
if(json.get(0).toString().length() == 0){
//Oops!
showToast();
return null;
}
...
祝好運
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.