android中的ProgressDialog即使使用异步任务也未显示

android中的ProgressDialog即使使用异步任务也未显示,android,android-asynctask,show,progressdialog,Android,Android Asynctask,Show,Progressdialog,大家好:) 我有点小问题。我想在单击Login时显示ProgressDialog,但没有显示任何内容。它只是在没有ProgressDialog的情况下执行任务。我正在使用AsyncTask并在该线程中打开ProgressDialog,但什么也没有出现。以下是我的源代码: 这就是所谓的: ProgressDialog progress = new ProgressDialog(mainActivity); progress.setMessage("Sie werden registriert...

大家好:) 我有点小问题。我想在单击Login时显示ProgressDialog,但没有显示任何内容。它只是在没有ProgressDialog的情况下执行任务。我正在使用AsyncTask并在该线程中打开ProgressDialog,但什么也没有出现。以下是我的源代码:

这就是所谓的:

ProgressDialog progress = new ProgressDialog(mainActivity);
progress.setMessage("Sie werden registriert...");

jsonParser = new JSONParser(progress, url_create_user, "POST", params);
这是JSONParser类:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

public class JSONParser extends AsyncTask<Context, Void, JSONObject>{

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    String url = "";
    String method = "";
    List<NameValuePair> parameters;
    ProgressDialog prog;

    // constructor
    public JSONParser(ProgressDialog prog, String url, String method, List<NameValuePair> param) {
        this.url = url;
        this.method = method;
        this.parameters = param;
        this.prog = prog;
    }

    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0)
            {
                prog.show();
            }
            else
            {
                prog.dismiss();
            }

        }
    };

    @Override
    protected JSONObject doInBackground(Context... params) {
        try {
            handler.sendEmptyMessage(0);
            // Überprüfen welche Request Methode benutzt werden soll
            if(method == "POST"){
                DefaultHttpClient httpClient = new DefaultHttpClient();
                httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY,
                        CookiePolicy.BROWSER_COMPATIBILITY);
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(this.parameters));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method == "GET"){
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(this.parameters, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }          

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //Stream in ein String umwandeln
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Fehler!", "Fehler mein umwandeln von Stream in String: " + e.toString());
        }

        // JSON Object parsen
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error beim parsen " + e.toString());
        }
        handler.sendEmptyMessage(1);
        // Das JSONObject zurückgeben
        return jObj;
    }
}
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.io.UnsupportedEncodingException;
导入java.util.List;
导入org.apache.http.HttpEntity;
导入org.apache.http.HttpResponse;
导入org.apache.http.NameValuePair;
导入org.apache.http.client.ClientProtocolException;
导入org.apache.http.client.entity.UrlEncodedFormEntity;
导入org.apache.http.client.methods.HttpGet;
导入org.apache.http.client.methods.HttpPost;
导入org.apache.http.client.params.ClientPNames;
导入org.apache.http.client.params.CookiePolicy;
导入org.apache.http.client.utils.URLEncodedUtils;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.json.JSONException;
导入org.json.JSONObject;
导入android.app.ProgressDialog;
导入android.content.Context;
导入android.os.AsyncTask;
导入android.os.Handler;
导入android.os.Looper;
导入android.os.Message;
导入android.util.Log;
公共类JSONParser扩展了异步任务{
静态InputStream为空;
静态JSONObject jObj=null;
静态字符串json=“”;
字符串url=“”;
字符串方法=”;
列出参数;
进程对话程序;
//建造师
公共JSONParser(ProgressDialog程序、字符串url、字符串方法、列表参数){
this.url=url;
这个方法=方法;
this.parameters=param;
this.prog=prog;
}
私有处理程序=新处理程序(){
@凌驾
公共无效handleMessage(消息消息消息){
如果(msg.what==0)
{
prog.show();
}
其他的
{
程序解除();
}
}
};
@凌驾
受保护的JSONObject doInBackground(上下文…参数){
试一试{
handler.sendEmptyMessage(0);
//Überprüfen welche请求方法
如果(方法==“POST”){
DefaultHttpClient httpClient=新的DefaultHttpClient();
httpClient.getParams().setParameter(ClientPNames.COOKIE_策略,
CookiePolicy.BROWSER_兼容性);
HttpPost HttpPost=新的HttpPost(url);
setEntity(新的UrlEncodedFormEntity(this.parameters));
HttpResponse HttpResponse=httpClient.execute(httpPost);
HttpEntity HttpEntity=httpResponse.getEntity();
is=httpEntity.getContent();
}else if(方法==“GET”){
DefaultHttpClient httpClient=新的DefaultHttpClient();
String paramString=URLEncodedUtils.format(this.parameters,“utf-8”);
url+=“?”+参数字符串;
HttpGet HttpGet=新的HttpGet(url);
HttpResponse HttpResponse=httpClient.execute(httpGet);
HttpEntity HttpEntity=httpResponse.getEntity();
is=httpEntity.getContent();
}          
}捕获(不支持的编码异常e){
e、 printStackTrace();
}捕获(客户端协议例外e){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
//ein字符串umwandeln中的流
试一试{
BufferedReader reader=新的BufferedReader(新的InputStreamReader(
is,“iso-8859-1”),8);
StringBuilder sb=新的StringBuilder();
字符串行=null;
而((line=reader.readLine())!=null){
sb.追加(第+行“\n”);
}
is.close();
json=sb.toString();
}捕获(例外e){
Log.e(“Fehler!”,“Fehler mein umwandeln von Stream in String:”+e.toString());
}
//JSON对象解析
试一试{
jObj=新的JSONObject(json);
}捕获(JSONException e){
e(“JSON解析器”,“错误beim parsen”+e.toString());
}
handler.sendEmptyMessage(1);
//这是祖鲁克本的工作目标
返回jObj;
}
}

您无法比较两个字符串之间的==值

使用:

请参阅以下带有异步任务的JSON解析器示例代码
包com.androidhive.json解析;
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.io.UnsupportedEncodingException;
导入java.util.ArrayList;
导入java.util.HashMap;
导入org.apache.http.HttpEntity;
导入org.apache.http.HttpResponse;
导入org.apache.http.client.ClientProtocolException;
导入org.apache.http.client.methods.HttpPost;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.json.JSONArray;
导入org.json.JSONException;
导入org.json.JSONObject;
导入android.app.ListActivity;
导入android.app.ProgressDialog;
导入android.content.Intent;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.util.Log;
导入android.view.view;
导入android.widget.AdapterView;
导入android.widget.AdapterView.OnItemClickListener;
导入android.widget.ListAdapter;
导入android.widget.ListView;
导入android.widget.simpledapter;
导入android.widget.TextView;
公共类AndroidJSONParsingActivity扩展了ListActivity{
//发出请求的url
专用静态字符串url=”http://api.androidhive.info/contacts/";
//JSON节点名称
专用静态最终字符串标记_CONTACTS=“CONTACTS”;
私有静态最终字符串标记\u ID=“ID”;
私有静态最终Strin
method.equals("POST");
see the following example code of JSON parser with async task

package com.androidhive.jsonparsing;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class AndroidJSONParsingActivity extends ListActivity {

    // url to make request
    private static String url = "http://api.androidhive.info/contacts/";

    // JSON Node names
    private static final String TAG_CONTACTS = "contacts";
    private static final String TAG_ID = "id";
    private static final String TAG_NAME = "name";
    private static final String TAG_EMAIL = "email";
    private static final String TAG_ADDRESS = "address";
    private static final String TAG_GENDER = "gender";
    private static final String TAG_PHONE = "phone";
    private static final String TAG_PHONE_MOBILE = "mobile";
    private static final String TAG_PHONE_HOME = "home";
    private static final String TAG_PHONE_OFFICE = "office";
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // contacts JSONArray
    JSONArray contacts = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        new GetEventsTask().execute("");
    }

    protected class GetEventsTask extends
            AsyncTask<String, Integer, ArrayList<HashMap<String, String>>> {
        protected ArrayList<HashMap<String, String>> contactList;

        private final ProgressDialog dialog = new ProgressDialog(
                AndroidJSONParsingActivity.this);

        //PreExecute Method

        protected void onPreExecute() {
            this.dialog.setMessage("Loading, Please Wait..");
            this.dialog.setCancelable(false);
            this.dialog.show();
        }

        //doInBackground Method

        @Override
        protected ArrayList<HashMap<String, String>> doInBackground(
                String... params) {
            contactList = new ArrayList<HashMap<String, String>>();
            // Making HTTP request
            try {
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                json = sb.toString();

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            // try parse the string to a JSON object
            try {
                jObj = new JSONObject(json);
                Log.i("json objects",""+json);
            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }
            try {
                // Getting Array of Contacts
                contacts = jObj.getJSONArray(TAG_CONTACTS);

                // looping through All Contacts
                for (int i = 0; i < contacts.length(); i++) {
                    JSONObject c = contacts.getJSONObject(i);

                    // Storing each json item in variable
                    String id = c.getString(TAG_ID);
                    String name = c.getString(TAG_NAME);
                    String email = c.getString(TAG_EMAIL);
                    String address = c.getString(TAG_ADDRESS);
                    String gender = c.getString(TAG_GENDER);

                    // Phone number is agin JSON Object
                    JSONObject phone = c.getJSONObject(TAG_PHONE);
                    String mobile = phone.getString(TAG_PHONE_MOBILE);
                    String home = phone.getString(TAG_PHONE_HOME);
                    String office = phone.getString(TAG_PHONE_OFFICE);

                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    map.put(TAG_ID, id);
                    map.put(TAG_NAME, name);
                    map.put(TAG_EMAIL, email);
                    map.put(TAG_PHONE_MOBILE, mobile);

                    // adding HashList to ArrayList
                    contactList.add(map);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return contactList;
        }

        //onPostExecute Method 


        protected void onPostExecute(ArrayList<HashMap<String, String>> result) {

            ListAdapter adapter = new SimpleAdapter(getApplicationContext(),
                    contactList, R.layout.list_item, new String[] { TAG_NAME,
                            TAG_EMAIL, TAG_PHONE_MOBILE }, new int[] {
                            R.id.name, R.id.email, R.id.mobile });
            // selecting single ListView item
            ListView lv = getListView();
            lv.setAdapter(adapter);



            // Launching new screen on Selecting Single ListItem
            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.name)).getText().toString();
                    String cost = ((TextView) view.findViewById(R.id.email)).getText().toString();
                    String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();

                    // Starting new intent
                    Intent in = new Intent(getApplicationContext(),SingleMenuItemActivity.class);
                    in.putExtra(TAG_NAME, name);
                    in.putExtra(TAG_EMAIL, cost);
                    in.putExtra(TAG_PHONE_MOBILE, description);
                    startActivity(in);
                }
            });
            if (this.dialog.isShowing()) {
                this.dialog.dismiss();
            }
        }

    }

}