【发布时间】:2018-04-03 15:36:06
【问题描述】:
我正在从 android 应用程序中搜索 api,当搜索没有从 api 中返回结果时,我想向用户显示 Toast/错误消息。
当 api 没有返回结果时,日志中会显示以下内容:
{boards: null}
这是我想显示消息/祝酒词的地方。
我试过了:
if (name.equals ("null");
我还发现了许多其他“解决方案”,但似乎没有一个有效。
请看下面的代码:
public class apitestsearch extends AppCompatActivity {
EditText boardName;
TextView resultView;
public void findBoard (View view){
// Log.i("board", boardName.getText().toString());
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(boardName.getWindowToken(), 0);
DownloadTask task = new DownloadTask();
task.execute("https://www.api.com/airquality/api/json.php?boardID="+ boardName.getText().toString());
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_apitestsearch);
boardName = (EditText)findViewById(R.id.boardName);
resultView = (TextView) findViewById(R.id.resultView);
}
public class DownloadTask extends AsyncTask<String, Void, String>{
@Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1)
{
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "No results found", Toast.LENGTH_SHORT);
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
String message = " ";
JSONObject jsonObject = new JSONObject(result);
String board = jsonObject.getString("boards");
// Log.i("boardID", board);
JSONArray arr = new JSONArray(board);
for(int i = 0; i < 1; i++)
{
JSONObject jsonPart = arr.getJSONObject(i);
String name = "";
name = jsonPart.getString("boardID");
if(name != ""){
message += name + "\r\n";
}
}
if (message != "") {
resultView.setText(message);
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "No results found", Toast.LENGTH_SHORT);
}
// Log.i("Content", result);
}
}
}
【问题讨论】: