【问题标题】:alertDialog not showing when onClick on a button当单击按钮时,alertDialog 不显示
【发布时间】:2015-06-30 02:47:06
【问题描述】:

我是 android 应用程序开发的初学者。我现在正在创建一个工作搜索应用程序,它允许用户输入关键字来搜索工作。如果搜索后没有结果,我会尝试显示一个对话框说没有找到结果并要求用户再次搜索。但是,即使没有任何搜索结果,对话框也不会出现。当你提到 doInBackground() 时,有 Log.d("Response: ", "> " + jsonStr);所以有2种情况:

第一种情况(有搜索结果):

回应:﹕ > {"info":[{"INSIDE HERE IS THE JOB INFORMATION"}

第二种情况(搜索后没有结果):

响应:﹕ > {"success":0,"message":"No info found"}

我的逻辑是,如果搜索后没有结果,就会出现alertDialog提醒用户再次搜索。我在私有类 GetContacts 扩展 AsyncTask 的 doInBackground() 中实现了这一部分。你能看看并帮忙吗?谢谢!

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;

}
}

【问题讨论】:

    标签: android android-asynctask android-alertdialog getjson


    【解决方案1】:

    !doInBackground 方法在 UI 线程外执行,因此任何 UI 更改都不会反映在 UI 中。要显示对话框,您需要在 onProgressUpdateonPostExecute 的 UI 线程上执行此操作:

    /**
     * Async task class to get json by making HTTP call
     **/
    private class GetContacts extends AsyncTask<Void, Void, Boolean> {
    
    ....
    
    @Override
    protected Boolean 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);
    
        //really should be using the JSONObject or regex here instead of concatenating a bunch of strings.
        boolean result = ! jsonStr.equals("{" + "\"" + "success" + "\"" + ":0," + "\"" + "message" + "\"" + ":" + "\"" + "No info found" + "\"" + "}");
    
        if (result) {
            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();
    
            }
        }
        return result;
    }
    
    @Override
    protected void onPostExecute(Boolean foundResults) {
        super.onPostExecute(foundResults);
        if (foundResults) {
    
            /**
             * 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);
        } else {
            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();
        }
    
        // Dismiss the progress dialog
        if (pDialog.isShowing()) {
            pDialog.dismiss();
        }
    }
    

    【讨论】:

    • protected Void doInBackground(Void... arg0) ,Android Studio 说“void”是不兼容的返回类型,当涉及到 doInBackground() 末尾的“返回结果”时。我该如何纠正它?谢谢
    • 道歉。更新了答案,因为 doInBackground 签名应更改为 protected Boolean doInBackground(Void... arg0)
    • 成功了!我真的很感谢你的帮助。非常感谢 :) @Brad Brown
    【解决方案2】:

    以上答案是正确的。另一种方法是在 MainActivity 中定义一个处理程序,并将处理程序引用作为参数传递给 Async 任务的构造函数。然后从 doInBackGround() 通过处理程序发送消息。您可以通过它显示对话框! 希望对您有所帮助!

        class MyActivity extends Activity{ 
    
                private Handler handler = null;
    
                public void onCreate(){
                    handler = new Handler( new Handler.Callback(){
    
                        @Override
                        public boolean handleMessage(final Message msg) {
    
                         if(msg.what == 0){
                            showDialog();
                         } else{
                              removeDialog();
                          }
                      );
                }
    
    public SomeTask extends AsyncTask{
    
    Handler handler;
    public SomeTask(Handler handler){
        this.handler = handler;
    }
    
    public void doInBackground(){
       //do your work
      if(search results in zero)
         handler.sendEmptyMessage(0);
      else
         handler.sendEmptyMessage(1);
    

    } }

    【讨论】:

    • 我不清楚如何制作。我确实有一个处理程序类。你能检查一下我刚刚上传的 ServiceHandler.java,你能告诉我如何修改代码吗?提前致谢。
    猜你喜欢
    • 2013-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-19
    • 2011-12-14
    • 2022-01-05
    相关资源
    最近更新 更多