如何在android中显示额外20秒的进度条?

时间:2017-08-30 08:18:05

标签: java android progress-bar

我有一个调用java类(JsonTaskPost)的活动(LoginActivity)。我希望在用户单击按钮时显示progessbar,同时java类执行其任务。我想代码必须运行得太快才能看到进度条。那么我怎样才能增加进度条的可见性,例如20秒?或逻辑错误?

LoginActivity.java

package com.example.mymobileforumbrowser2;

import android.app.ProgressDialog;
import android.content.Intent;
import android.icu.util.TimeUnit;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import static com.example.mymobileforumbrowser2.MainActivity.LOGIN_ACTIVITY;
import static com.example.mymobileforumbrowser2.MainActivity.mSharedEditor;
import static com.example.mymobileforumbrowser2.MainActivity.makeToast;
import static com.example.mymobileforumbrowser2.MainActivity.serverUrl;

public class LoginActivity extends AppCompatActivity {

    public static TextView serverMessageTxv;
    EditText usernameEditTxv,passwordEditTxv;
    Button loginButton;
    ProgressDialog progress;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        serverMessageTxv = (TextView)findViewById(R.id.server_message);
        usernameEditTxv = (EditText)findViewById(R.id.username_edittextview);
        passwordEditTxv = (EditText)findViewById(R.id.password_edittextview);

        loginButton = (Button)findViewById(R.id.login_button);

        loginButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v) {

                progress = ProgressDialog.show(LoginActivity.this, "LOG IN",
                        "Logging Please Wait ...", true);

                new Thread(new Runnable() { // open new thread gia background processing
                    @Override
                    public void run() {
                        String url = serverUrl + "login.php";
                        //Log.d("EXEC_JSON","CALL JSON");
                        new JsonTaskPost().execute(url,
                                usernameEditTxv.getText().toString(),
                                passwordEditTxv.getText().toString(),
                                LOGIN_ACTIVITY);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                progress.dismiss();
                            }
                        });
                    }
                }).start();
                /*
                String url = serverUrl + "login.php";
                new JsonTaskPost().execute(url,
                        usernameEditTxv.getText().toString(),
                        passwordEditTxv.getText().toString(),
                        LOGIN_ACTIVITY);
                        */
            }
        });

    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu, menu);

        MenuItem topicItem = menu.findItem(R.id.new_topic);
        topicItem.setVisible(false);
        MenuItem postItem = menu.findItem(R.id.new_post);
        postItem.setVisible(false);
        //MenuItem mapItem = menu.findItem(R.id.map);
        //mapItem.setVisible(false);
        MenuItem loginItem = menu.findItem(R.id.login);
        loginItem.setVisible(false);
        invalidateOptionsMenu();

        return true;

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        Intent intent;
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.preferences:
                intent = new Intent(this, PreferencesActivity.class);
                startActivity(intent);
                return true;
            case R.id.logout:
                if(mSharedEditor!= null)
                {
                    mSharedEditor.putString("Username", "");
                    mSharedEditor.putBoolean("LoggedIn", false);
                    mSharedEditor.commit();
                    makeToast(this, "Successfully logged out");
                }
                return true;
            case R.id.register:
                intent = new Intent(this, RegisterActivity.class);
                startActivity(intent);
                finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

}

JsonTaskPost.java

package com.example.mymobileforumbrowser2;

import android.os.AsyncTask;
import android.util.Log;

import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import  static com.example.mymobileforumbrowser2.LoginActivity.serverMessageTxv;
import  static com.example.mymobileforumbrowser2.MainActivity.LOGIN_ACTIVITY;
//import  static com.example.mymobileforumbrowser2.MainActivity.MAPS_ACTIVITY;
import  static com.example.mymobileforumbrowser2.MainActivity.NEWPOST_ACTIVITY;
import  static com.example.mymobileforumbrowser2.MainActivity.NEWTOPIC_ACTIVITY;
import  static com.example.mymobileforumbrowser2.MainActivity.POSTS_ACTIVITY;
import  static com.example.mymobileforumbrowser2.MainActivity.REGISTER_ACTIVITY;
import  static com.example.mymobileforumbrowser2.MainActivity.TOPICS_ACTIVITY;
import  static com.example.mymobileforumbrowser2.MainActivity.mSharedEditor;
import  static com.example.mymobileforumbrowser2.MainActivity.mSharedPrefs;
import  static com.example.mymobileforumbrowser2.MainActivity.removeHtmlChars;
import  static com.example.mymobileforumbrowser2.MainActivity.stringToListView;
import  static com.example.mymobileforumbrowser2.PostsActivity.adapterPosts;
import  static com.example.mymobileforumbrowser2.PostsActivity.postsListItems;
import  static com.example.mymobileforumbrowser2.RegisterActivity.registerServerMessageTxv;
import  static com.example.mymobileforumbrowser2.TopicsActivity.adapterTopics;
import  static com.example.mymobileforumbrowser2.TopicsActivity.topicsListItems;

//post-get class
// fetches topics / posts an ginetai call apo TopicsActivity / PostsActivity
public class JsonTaskPost extends AsyncTask<String, String, String>
{
    String message = null;
    String usernameSharedPrefs;
    String callingActivity;
    JSONObject jsonObject;

    protected void onPreExecute() {
        super.onPreExecute();

    }

    protected String doInBackground(String... params) {


        HttpURLConnection connection = null;
        BufferedReader reader = null;
        OutputStream outStream = null;
        callingActivity = params[3]; // orizetai apo caller
        Log.d("Calling Activity",callingActivity);
        usernameSharedPrefs = params[1]; //string of username if login called, else forum / topic name depending on caller activity
        Log.d("USERNAME",usernameSharedPrefs);

        try {
            URL url = new URL(params[0]); // callers url adress, eg http:localhost/phpbb/fetch_forums.php
            Log.d("CALLERS URL",params[0]);
            jsonObject = new JSONObject();
            message = paramsTojson(params).toString(); // metatrepei periexomena Json array se string , {"key:","value"}
            Log.d("MESSAGE",message);

            connection = (HttpURLConnection) url.openConnection(); //open connection to phpbb database
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setFixedLengthStreamingMode(message.getBytes().length);
            connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");

            outStream = new BufferedOutputStream(connection.getOutputStream());
            outStream.write(message.getBytes());
            outStream.close();

            InputStream stream = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(stream));

            StringBuffer buffer = new StringBuffer();
            String line;

            while ((line = reader.readLine()) != null) {
                buffer.append(line+"\n");
                Log.d("Response: ", "> " + line);
            }
            return buffer.toString();


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally
        {
            if (connection != null){
                connection.disconnect();
            }
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result)
    {
        if(result!=null)
        {
            if(callingActivity.equals(TOPICS_ACTIVITY))
            {
                stringToListView(result,topicsListItems);
                adapterTopics.notifyDataSetChanged(); // prosarmogh periexomenwn listview toy topics activity sta nea periexomena
            }
            else if(callingActivity.equals(POSTS_ACTIVITY))
            {
                stringToListView(result,postsListItems);
                adapterPosts.notifyDataSetChanged();
            }
            else if(callingActivity.equals(REGISTER_ACTIVITY))
            {
                result = removeHtmlChars(result);
                if(result.contains("You are registered"))
                    registerServerMessageTxv.setText(result);
            }
            else if(callingActivity.equals(LOGIN_ACTIVITY))
            {
                result = removeHtmlChars(result);
                serverMessageTxv.setText(result);
                mSharedEditor = mSharedPrefs.edit();
                if (result.contains("You are logged in"))
                {
                    mSharedEditor.putString("Username",usernameSharedPrefs);
                    mSharedEditor.putBoolean("LoggedIn",true);
                    mSharedEditor.commit();
                }
                else // LOGOUT / no user logged in
                {
                    mSharedEditor.putString("Username","");
                    mSharedEditor.putBoolean("LoggedIn",false);
                    mSharedEditor.commit();
                }
            }

        }
        super.onPostExecute(result);
    }
    protected JSONObject paramsTojson(String... params)
    {
        try
        {
            if (params[3].equals(LOGIN_ACTIVITY)) {
                jsonObject.put("username", params[1]);
                jsonObject.put("password", params[2]);
            } else if (params[3].equals(TOPICS_ACTIVITY)) {
                jsonObject.put("forum_name", params[1]);
                jsonObject.put("number_of_topics", params[2]);
            } else if (params[3].equals(POSTS_ACTIVITY)) {
                jsonObject.put("topic_name", params[1]);
                jsonObject.put("number_of_posts", params[2]);
            } else if (params[3].equals(REGISTER_ACTIVITY)) {
                jsonObject.put("username", params[1]);
                jsonObject.put("password", params[2]);
                jsonObject.put("email", params[4]);
            } else if (params[3].equals(NEWTOPIC_ACTIVITY)) {
                jsonObject.put("forum_name", params[1]);
                jsonObject.put("topic_title", params[2]);
                jsonObject.put("username", params[4]);
            } else if (params[3].equals(NEWPOST_ACTIVITY)) {
                jsonObject.put("topic_name", params[1]);
                jsonObject.put("forum_name", params[4]);
                jsonObject.put("username", params[5]);
                jsonObject.put("post_text", params[2]);
            }
            /*
            else if (params[3].equals(MAPS_ACTIVITY)) {
                jsonObject.put("username", params[1]);
                jsonObject.put("timestamp", params[2]);
                jsonObject.put("longitude", params[4]);
                jsonObject.put("latitude", params[5]);
            }
            */
        }
        catch (org.json.JSONException e)
        {
            e.printStackTrace();
        }
        return jsonObject;
    }

}

3 个答案:

答案 0 :(得分:2)

你的代码错了,这就是它发生的原因。您在致电progress.dismiss();后呼叫AsyncTask。这就是progressbar在任务完成之前被解雇的原因。

您已使用JsonTaskPost(AsyncTask),因此无需在此处使用单独的线程。您需要从progress.dismiss(); onPostExecute拨打JsonTaskPost,因为此方法是完成任务的地方。因此,您可以为完成任务创建回调,或将progressBar实例传递给JsonTaskPost,或直接在活动本身中使用AsyncTask

答案 1 :(得分:1)

当您关闭进度对话框创建处理程序并使用postDelayed方法时,它允许您将代码延迟特定时间,如下所示:

runOnUiThread(new Runnable() {
     @Override
     public void run() {
          Handler handler = new Handler();
          handler.postDelayed(new Runnable() {
              @Override
              public void run() {
                  progress.dismiss();
              }
          }, 20000);
     }
});

20000是你的时间,以毫秒为单位,这意味着20秒

但是我认为您需要在任务中的onPostExecute方法中删除对话框

答案 2 :(得分:1)

您不需要为了查看进度条添加20秒,您需要做的是asyntask以在UI中显示进度条并执行一些后台任务。在你的情况下,你可以这样做:

class BackGround extends AsyncTask<String, Void, Boolean> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(myActivity.this);

            pDialog.show();

        }

        @Override
        public Boolean doInBackground(String... urls) {
           //Do something...
            return null;
        }

        public void onPostExecute(Boolean result) {
            pDialog.cancel();

        }
    }

您不需要创建另一个java类来执行asynctask,您可以在登录活动中执行此操作,只需将其命名为:

new BackGround().execute();