Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/234.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 单击按钮时不显示alertDialog_Android_Android Asynctask_Android Alertdialog_Getjson - Fatal编程技术网

Android 单击按钮时不显示alertDialog

Android 单击按钮时不显示alertDialog,android,android-asynctask,android-alertdialog,getjson,Android,Android Asynctask,Android Alertdialog,Getjson,我是android应用程序开发的初学者。我现在正在创建一个求职应用程序,允许用户输入关键字来搜索工作。如果搜索后没有结果,我会尝试显示一个对话框,说明没有找到结果,并要求用户再次搜索。然而,即使没有任何搜索结果,对话框也不会出现。当您参考doInBackground()时,有Log.d(“Response:”,“>”+jsonStr);因此有两种情况: 第一个案例(有搜索结果): 答复:﹕ > {“info”:[{“这里面是工作信息”} 第2例(搜索后无结果): 答复:﹕ > {“成功”:0,“

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

第一个案例(有搜索结果):

答复:﹕ > {“info”:[{“这里面是工作信息”}

第2例(搜索后无结果):

答复:﹕ > {“成功”:0,“消息”:“未找到任何信息”}

我的逻辑是,如果搜索后没有结果,会出现一个alertDialog来提醒用户再次搜索。我在私有类GetContacts Extendes 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);

    }
}
public类MainActivityJsonParsing扩展了ListActivity{
List params=new ArrayList();
字符串PostNameInputByUser;
字符串位置InputByUser;
私人对话;
最终上下文=此;
//获取联系人JSON的URL
专用静态字符串url=”http://192.168.0.102/get_json.php";
//JSON节点名称
私有静态最终字符串标记_INFO=“INFO”;
私有静态最终字符串标记_POSTNAME=“POSTNAME”;
私有静态最终字符串TAG_LOCATION=“LOCATION”;
私有静态最终字符串TAG_SALARY=“SALARY”;
私有静态最终字符串标记_RESPONSIBILITY=“RESPONSIBILITY”;
私有静态最终字符串标记_COMPANY=“COMPANY”;
专用静态最终字符串标记\u CONTACT=“CONTACT”;
//联系JSONArray
JSONArray infos=null;
//ListView的Hashmap
ArrayList信息列表;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u main\u json\u解析);
infoList=newarraylist();
Intent=getIntent();
PostNameInputByUser=intent.getStringExtra(“PostName”);
LocationInputByUser=intent.getStringExtra(“位置”);
添加(新的BasicNameValuePair(“PostName”,PostNameInputByUser));
添加参数(新的BasicNameValuePair(“位置”,LocationInputByUser));
最终ListView lv=getListView();
//单击项目上的Listview侦听器
lv.setOnItemClickListener(新的OnItemClickListener(){
@凌驾
public void onItemClick(AdapterView父级、视图、,
内部位置,长id){
//从选定的ListItem获取值
字符串名称=((TextView)view.findViewById(R.id.PostName))
.getText().toString();
字符串成本=((TextView)view.findViewById(R.id.Location))
.getText().toString();
字符串描述=((TextView)view.findViewById(R.id.Salary))
.getText().toString();
HashMap info=新的HashMap();
info=(HashMap)lv.getAdapter().getItem(位置);
//启动单一联系人活动
Intent in=新的Intent(getApplicationContext(),
单一作业(活动类);
in.putExtra(TAG_POSTNAME,name);
in.putExtra(标签位置、成本);
in.putExtra(标签、工资、说明);
in.putExtra(TAG_RESPONSIBILITY,info.get(TAG_RESPONSIBILITY));
in.putExtra(TAG_COMPANY,info.get(TAG_COMPANY));
in.putExtra(TAG_CONTACT,info.get(TAG_CONTACT));
星触觉(in);
}
});
//调用异步任务以获取json
新建GetContacts().execute();
}
/**
*异步任务类通过HTTP调用获取json
* */
私有类GetContacts扩展异步任务{
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
//显示进度对话框
pDialog=newprogressdialog(MainActivityJsonParsing.this);
setMessage(“请稍候…”);
pDialog.setCancelable(假);
pDialog.show();
}
@凌驾
受保护的Void doInBackground(Void…arg0){
//创建服务处理程序类实例
ServiceHandler sh=新的ServiceHandler();
//向url发出请求并获得响应
字符串jsonStr=sh.makeServiceCall(url,ServiceHandler.GET,params);
Log.d(“响应:”、“>”+jsonStr);
如果(jsonStr!=“成功”+“成功”+“+”:0“+”消息“+”\+”:“+”未找到信息“+”\+”){
试一试{
JSONObject jsonObj=新的JSONObject(jsonStr);
//获取JSON数组节点
infos=jsonObj.getJSONArray(TAG_INFO);
//通过所有触点循环
对于(int i=0;ivalue
信息放置(标签号、邮编、id);
信息放置(标签位置、名称);
信息输入(工资标签、电子邮件);
信息放置(标签、责任、地址);
信息放置(标签公司,性别);
信息输入(TAG_联系人,手机);
//将联系人添加到联系人列表
添加(信息);
}
}捕获(JSONException e){
e、 printStackTrace();
}
}否则{
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;

}
}
/**
 * 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();
    }
}
    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);