如何在android中显示额外20秒的进度条? [英] how to show progressbar for additional 20sec in android?

查看:49
本文介绍了如何在android中显示额外20秒的进度条?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个调用 java 类 (JsonTaskPost) 的活动 (LoginActivity).我想在用户单击按钮时显示一个进度条,同时 java 类执行其任务.我想代码必须运行得太快才能看到进度条.那么如何添加进度条的可见性,例如 20 秒?还是逻辑不对?

I have an activity (LoginActivity) that calls a java class (JsonTaskPost). I want to show a progessbar when the user clicks the button and the java class meanwhile does its task. I guess that the code must run too fast for the progressbar to be seen. So how can i add visibility of progressbar for e.g 20 sec? Or is the logic wrong?

登录活动.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

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;
    }

}

推荐答案

你的代码是错误的,这就是它发生的原因.在调用 AsyncTask 之后,您正在调用 progress.dismiss();.这就是 progressbar 在任务完成之前被关闭的原因.

Your code is wrong that's why it is happening. You are calling progress.dismiss(); just after calling your AsyncTask. This is why the progressbar gets dismissed before the task has been completed.

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

You are already using JsonTaskPost(AsyncTask), so there is no need to use a separate thread here. And you need to call progress.dismiss(); from onPostExecute of JsonTaskPost as this method is where task completion happens. So for this either you can create call back for task completion or pass the progressBar instance to JsonTaskPost or directly use AsyncTask in the activity itself.

这篇关于如何在android中显示额外20秒的进度条?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆