我是Android應用程序開發的初學者。我現在正在創建一個求職應用程序,它允許用戶輸入關鍵字來搜索工作。如果搜索後沒有結果,我會嘗試顯示一個對話框,指出找不到結果並要求用戶再次搜索。 Howerver,即使沒有任何搜索結果,對話框也不會出現。當你引用doInBackground()時,有Log.d(「Response:」,「>」+ jsonStr);因此,有兩種情況:alertDialog不顯示onClick按鈕時
第一種情況下(有搜索結果):
響應::> { 「信息」:[{ 「INSIDE這裏是作業信息」}
第二種情況(無搜索後的結果):
響應::> {「成功」:0,「消息」:「沒有信息找到」}
我的邏輯是,如果有搜索後沒有結果,一個alertDialog出現提醒用戶再次搜索。我在私有類GetContacts的doInBackground()中實現這個部分擴展了AsyncTask。你可以看看,並提供幫助嗎?謝謝 !
MainActivityJsonParsing.java
public class MainActivityJsonParsing extends ListActivity {
List<NameValuePair> params = new ArrayList<NameValuePair>();
String PostNameInputByUser;
String LocationInputByUser;
private ProgressDialog pDialog;
final Context context = this;
// URL to get contacts JSON
private static String url = "http://192.168.0.102/get_json.php";
// JSON Node names
private static final String TAG_INFO = "info";
private static final String TAG_POSTNAME = "PostName";
private static final String TAG_LOCATION = "Location";
private static final String TAG_SALARY = "Salary";
private static final String TAG_RESPONSIBILITY = "Responsibility";
private static final String TAG_COMPANY = "Company";
private static final String TAG_CONTACT = "Contact";
// contacts JSONArray
JSONArray infos = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> infoList;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_json_parsing);
infoList = new ArrayList<HashMap<String, String>>();
Intent intent = getIntent();
PostNameInputByUser = intent.getStringExtra("PostName");
LocationInputByUser = intent.getStringExtra("Location");
params.add(new BasicNameValuePair("PostName", PostNameInputByUser));
params.add(new BasicNameValuePair("Location", LocationInputByUser));
final ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.PostName))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.Location))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.Salary))
.getText().toString();
HashMap<String, String> info = new HashMap<String, String>();
info = (HashMap<String, String>) lv.getAdapter().getItem(position);
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleJobActivity.class);
in.putExtra(TAG_POSTNAME, name);
in.putExtra(TAG_LOCATION, cost);
in.putExtra(TAG_SALARY, description);
in.putExtra(TAG_RESPONSIBILITY, info.get(TAG_RESPONSIBILITY));
in.putExtra(TAG_COMPANY, info.get(TAG_COMPANY));
in.putExtra(TAG_CONTACT, info.get(TAG_CONTACT));
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivityJsonParsing.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET, params);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != "{" + "\"" + "success" + "\"" + ":0," + "\"" + "message"+ "\"" + ":" + "\"" + "No info found" + "\"" + "}") {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
infos = jsonObj.getJSONArray(TAG_INFO);
// looping through All Contacts
for (int i = 0; i < infos.length(); i++) {
JSONObject c = infos.getJSONObject(i);
String id = c.getString(TAG_POSTNAME);
String name = c.getString(TAG_LOCATION);
String email = c.getString(TAG_SALARY);
String address = c.getString(TAG_RESPONSIBILITY);
String gender = c.getString(TAG_COMPANY);
String mobile = c.getString(TAG_CONTACT);
// tmp hashmap for single contact
HashMap<String, String> info = new HashMap<String, String>();
// adding each child node to HashMap key => value
info.put(TAG_POSTNAME, id);
info.put(TAG_LOCATION, name);
info.put(TAG_SALARY, email);
info.put(TAG_RESPONSIBILITY, address);
info.put(TAG_COMPANY, gender);
info.put(TAG_CONTACT, mobile);
// adding contact to contact list
infoList.add(info);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setTitle("Job Search Result");
alertDialogBuilder.setMessage("No jobs found !");
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setPositiveButton("Search Again", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(context, MainActivity.class);
startActivity(intent);
}
});
alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id){
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivityJsonParsing.this, infoList,
R.layout.list_item_json_parsing, new String[] { TAG_POSTNAME, TAG_LOCATION,
TAG_SALARY }, new int[] { R.id.PostName,
R.id.Location, R.id.Salary });
setListAdapter(adapter);
}
}
ServiceHandler.java
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/**
* Making service call
* @url - url to make request
* @method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/**
* Making service call
* @url - url to make request
* @method - http request method
* @params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
保護無效doInBackground(虛空......爲arg0),Android Studio中說, 「空缺」 是不兼容的返回類型,當談到 「返回結果」 在doInBackground結束( )。我該如何糾正它?謝謝 –
道歉。更新答案爲doInBackground簽名應更改爲 protected Boolean doInBackground(Void ... arg0) –
它的工作!我非常感謝你的幫助。非常感謝你:) @布朗布朗 –