[英]What to do when no results are returned from SQL query?
My SQL database is queried from an android app using PHP, however sometimes no results are returned from the search because the search criteria give no matches. 我的SQL数据库是使用PHP从Android应用程序查询的,但有时候搜索没有返回任何结果,因为搜索条件没有给出匹配。
Here is my ProgressTask: 这是我的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();
}
}
}
And here is my JSONParser class: 这是我的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;
}
} }
PHP returns this JSON data when the serach returns no results: 当serach没有返回结果时,PHP返回此JSON数据:
{
"listings": [
""
]
}
When the JSON is empty i wish to output some kind of message saying "No results found". 当JSON为空时,我希望输出某种消息,说“找不到结果”。 I have searched around a bit and tried out methods such as JSON.length() = 0 or setEmptyView but with no success.
我已经搜索了一下并尝试了JSON.length()= 0或setEmptyView等方法但没有成功。 I was just wondering if anyone had any ideas on what is the best way to respond when no results are returned and if so how to implement it.
我只是想知道是否有人对什么是没有返回结果时的最佳响应方式有任何想法,如果是,如何实现它。
Thanks in advance for any responses and if you need anymore information please comment below. 如果您有任何回复,请提前致谢,如果您需要更多信息,请在下面评论。 Thanks
谢谢
check the size of JSONArray if its not more than 0 , then show a toast. 检查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
}
EDIT 编辑
you can use following layout, if your json array is null or its size == 0 then set the visiblity of your listview to gone and visibility of textview to visible. 您可以使用以下布局,如果您的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>
now in your AsyncTask:- 现在在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);
}
}
}
}
Usually, ListView
are displayed in a ListActivity
. 通常,
ListView
显示在ListActivity
。 Such an activity contains embedded a mechanism to handle exactly this situation: 这样的活动包含嵌入式机制来处理这种情况:
Optionally, your custom view can contain another view object of any type to display when the list view is empty.
(可选)您的自定义视图可以包含列表视图为空时要显示的任何类型的另一个视图对象。 This "empty list" notifier must have an id "android:id/empty".
这个“空列表”通知符必须有一个id“android:id / empty”。 Note that when an empty view is present, the list view will be hidden when there is no data to display.
请注意,当存在空视图时,如果没有要显示的数据,将隐藏列表视图。
(in http://developer.android.com/reference/android/app/ListActivity.html ) (在http://developer.android.com/reference/android/app/ListActivity.html中 )
Basically, you put a @android:id/list
ListView for your list, and a @android:id/empty
TextView for the No result found
message. 基本上,你为列表放了一个
@android:id/list
ListView,为No result found
消息放了一个@android:id/empty
TextView。 The ListActivity handles the switch between the 2. ListActivity处理2之间的切换。
From the methods you use, such as setListAdapter
, I assume you are indeed using a ListActivity
. 从您使用的方法,例如
setListAdapter
,我假设您确实使用ListActivity
。 You can therefore easily integrate the @android:id/empty
mechanism. 因此,您可以轻松集成
@android:id/empty
机制。
You can check the first element 你可以检查第一个元素
Ex: 例如:
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;
...
Edit 编辑
Ex2: EX2:
...
JSONArray json = jParser.getJSONFromUrl(url);
if(json.get(0).toString().length() == 0){
//Oops!
showToast();
return null;
}
...
Good luck 祝好运
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.