English 中文(简体)
如何利用进展 等待服务器的回复
原标题:How to use ProgressBar to show a spinner while waiting a httpResponse from server

I m trying to show a loading icon to the user when the application makes a query to online Database. I ve tried using a AnimationDrawable (I gave up because there was no need of a custom icon), ProgressDialog and ProgressBar. The ProgressBar seems most appropriate, since I don t want a message, just a spinning icon. But I can not even make a ProgressBar appear on the screen, doesn t matter where I call it. I ve got the ProgressDialog appearing in screen, but it only appears after the server s response, and if I use dismiss() or cancel() it doesn t even appear at all.

我利用AsyncTasks或Threads取得了任何成功。

与此相对照的是,有一门JogarActative。 java, 当时计划列出各种备选办法。 用户功能和用户功能等一些参数:

public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);

    setContentView(R.layout.jogar_layout);
    Intent in = getIntent();
    String url = this.getString(R.string.urlSite);
    ArrayList<HashMap<String, String>> respostaList = new ArrayList<HashMap<String, String>>();

    String idt = in.getStringExtra(TAG_ID);
    primeiraPergunta = in.getBooleanExtra(TAG_PRIMEIRAPERGUNTA, true);

    TextView insertPergunta = (TextView) findViewById(R.id.insertPergunta);
    ListView insertRespostas = (ListView) findViewById(R.id.listResposta);

    SharedPreferences settings = getSharedPreferences("PREFS_LOGIN", MODE_PRIVATE);
    Integer idUsuario = settings.getInt("idUsuario", 0);
    String idUser = idUsuario.toString();


    if (primeiraPergunta){
        UserFunctions userFunction = new UserFunctions();
        json = userFunction.getJogar(idt, idUser);
    }else{
        try {
            json = new JSONArray(in.getStringExtra(TAG_JSON));
            json = json.getJSONArray(2);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

Below is the getJogar function in userFunctions: public JSONArray getJogar(String categoria, String usuarioId){ List params = new ArrayList();

    params.add(new BasicNameValuePair("categoria", categoria));
    params.add(new BasicNameValuePair("idUsuario", usuarioId));
    JSONArray json = jsonParser.getJSONFromUrl(perguntaURL, params);

    return json;
}

JSONParser.java is the class that makes the httpRequest: public JSONArray getJSONFromUrl(String url, List params) {

    // Making HTTP request
    try {
        // defaultHttpClient
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(params));



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



        // json = EntityUtils.toString(httpEntity);
        // HttpEntity httpEntity2 = httpEntity;
        json = EntityUtils.toString(httpEntity);
        // is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } 
            //then makes the JSON manipulation

只要JSONParser和用户功能是固定的,我就不使用他们内部的“进步”(Can t获得应用环境)。 所有服务器申请均在JSONParser提出。 java, 这就是为什么一夫先试图将“进步”/ProgressBar带走。

到达的“一号”最接近于在JogarActive公司使用这一代码(它显示进步运动,但经过服务器的反应)。 而且,如果我被解雇,甚至似乎就没有。

   final ProgressDialog loader = new ProgressDialog(JogarActivity.this);
    loader.show();
    //...the if-else code i ve pasted above
    loader.dismiss();

即便是使用OnUiThread,它还是用 t子做工! I m 没有选择......

感谢一切帮助。

最佳回答

这项工作:

public class RegisterActivity extends Activity{
EditText reg_fullname;
EditText reg_email;
EditText reg_login;
EditText reg_password;
EditText reg_password2;
Spinner reg_country;
Spinner reg_genre;
EditText reg_birthday;
EditText reg_promocode;
Button btnRegister;
Context ctx = this;
ProgressDialog pDialog;
JSONArray json;
String status;
String msg;

String fullname;
String email;
String login;
String password;
String password2;
String country;
String genre;
String birthday;
String promocode;

boolean finishActivity = false;

/**
 * @see android.app.Activity#onCreate(Bundle)
 */

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.register);

    TextView loginScreen = (TextView) findViewById(R.id.link_to_login);

    loginScreen.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {
                            // Closing registration screen
            // Switching to Login Screen/closing register screen
            finish();
        }
    });

    reg_fullname = (EditText) findViewById(R.id.reg_fullname);
    reg_email = (EditText) findViewById(R.id.reg_email);
    reg_login = (EditText) findViewById(R.id.reg_login);
    reg_password = (EditText) findViewById(R.id.reg_password);
    reg_password2 = (EditText) findViewById(R.id.reg_password2); //confirmação de senha
    reg_country = (Spinner) findViewById(R.id.reg_country);
    reg_genre = (Spinner) findViewById(R.id.reg_genre);
    reg_birthday = (EditText) findViewById(R.id.reg_birthday);
    reg_promocode = (EditText) findViewById(R.id.reg_promocode);

    btnRegister = (Button) findViewById(R.id.btnRegister);


    btnRegister.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            fullname = reg_fullname.getText().toString();
            email = reg_email.getText().toString();
            login = reg_login.getText().toString();
            password = reg_password.getText().toString();
            password2 = reg_password2.getText().toString();
            country = reg_country.getSelectedItem().toString();
            genre = reg_genre.getSelectedItem().toString();
            birthday = reg_birthday.getText().toString();
            promocode = reg_promocode.getText().toString();

            boolean validation = true;
            String message = "Campo de preencimento obrigatório";

            if(fullname.equalsIgnoreCase("")){
                reg_fullname.setError(message);
                validation = false;
            }
            if(email.equalsIgnoreCase("")){
                reg_email.setError(message);
                validation = false;
            }
            if(!email.matches(".*@.*")){
                reg_email.setError("O endereço de email não é válido");
                validation = false;
            }
            if(login.equalsIgnoreCase("")){
                reg_login.setError(message);
                validation = false;
            }
            if(password.equalsIgnoreCase("")){
                reg_password.setError(message);
                validation = false;
            }
            if(password2.equalsIgnoreCase("")){
                reg_password2.setError(message);
                validation = false;
            }
            if(!password.equals(password2)){
                reg_password2.setError("A confirmação de senha não confere");
                validation = false;
            }
            if(birthday.equalsIgnoreCase("")){
                reg_birthday.setError(message);
                validation = false;
            }
            SimpleDateFormat bd = new SimpleDateFormat("dd/MM/yyyy");
            if(bd.parse(birthday, new ParsePosition(0)) == null){
                reg_birthday.setError("Esta data não é válida! Preencha novamente, usando o formato dd/mm/aaaa");
                validation = false;
            }

            if(validation){
            new Register().execute();
            }

        }
    });



}


class Register extends AsyncTask<Void, Void, JSONArray>{

@Override
protected void onPreExecute() {
    super.onPreExecute();
    pDialog = new ProgressDialog(ctx);
    pDialog.setMessage("Aguarde...");
    pDialog.setIndeterminate(true);
    pDialog.setCancelable(false);
    pDialog.show();
}

@Override
protected JSONArray doInBackground(Void... params) {
    UserFunctions userFunction = new UserFunctions();
    json = userFunction.newUser(fullname, email, login, password, country, genre, birthday, promocode);

    return json;

}

protected void onPostExecute(JSONArray result) {
    // dismiss the dialog once done
    pDialog.dismiss();
    final AlertDialog alertDialog = new AlertDialog.Builder(
            RegisterActivity.this).create();

            try {
                status = json.getString(0);
                msg = json.getString(1);
                Log.d("Status", status);
            } catch (JSONException e) {
                Log.e("RegisterActiviry", "Error converting result " + e.toString());
                e.printStackTrace();
                status = null;
            }

            if (status.equalsIgnoreCase("erro")){
                alertDialog.setTitle("Erro");
                alertDialog.setMessage(msg);

            }else if (status.equalsIgnoreCase("sucesso")){
                alertDialog.setTitle("Sucesso!");
                alertDialog.setMessage(msg);
                finishActivity = true;
            }else{
                alertDialog.setTitle("Erro");   
                alertDialog.setMessage("Não foi possível realizar seu cadastro, tente novamente mais tarde.");
            }


            alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    if(finishActivity){
                    finish();
                    }else{
                        alertDialog.dismiss();
                    }
                }
        });

        alertDialog.show();

}

}


}
问题回答

暂无回答




相关问题
Android - ListView fling gesture triggers context menu

I m relatively new to Android development. I m developing an app with a ListView. I ve followed the info in #1338475 and have my app recognizing the fling gesture, but after the gesture is complete, ...

AsyncTask and error handling on Android

I m converting my code from using Handler to AsyncTask. The latter is great at what it does - asynchronous updates and handling of results in the main UI thread. What s unclear to me is how to handle ...

Android intent filter for a particular file extension?

I want to be able to download a file with a particular extension from the net, and have it passed to my application to deal with it, but I haven t been able to figure out the intent filter. The ...

Android & Web: What is the equivalent style for the web?

I am quite impressed by the workflow I follow when developing Android applications: Define a layout in an xml file and then write all the code in a code-behind style. Is there an equivalent style for ...

TiledLayer equivalent in Android [duplicate]

To draw landscapes, backgrounds with patterns etc, we used TiledLayer in J2ME. Is there an android counterpart for that. Does android provide an option to set such tiled patterns in the layout XML?

Using Repo with Msysgit

When following the Android Open Source Project instructions on installing repo for use with Git, after running the repo init command, I run into this error: /c/Users/Andrew Rabon/bin/repo: line ...

Android "single top" launch mode and onNewIntent method

I read in the Android documentation that by setting my Activity s launchMode property to singleTop OR by adding the FLAG_ACTIVITY_SINGLE_TOP flag to my Intent, that calling startActivity(intent) would ...

From Web Development to Android Development

I have pretty good skills in PHP , Mysql and Javascript for a junior developer. If I wanted to try my hand as Android Development do you think I might find it tough ? Also what new languages would I ...

热门标签