Android progressBar setVisibility()가 작동하지 않음 (Android progressBar setVisibility() not working)


문제 설명

Android progressBar setVisibility()가 작동하지 않음 (Android progressBar setVisibility() not working)

누군가 CountDownTimer를 사용할 때 progressBar.setVisibility()가 작동하지만 async 다운로드를 수행할 때는 작동하지 않는 이유를 이해하도록 도와주시겠습니까? 실제로 async 다운로드의 첫 번째 Toast는 두 번째 onPostExecute()가 표시되더라도 표시되지 않습니다. 아래는 작동하거나 작동하지 않는 데모입니다. 감사합니다.

MainActivity:

public class MainActivity extends AppCompatActivity {

    ProgressBar progressBar;

    int[] items = { 12982418, 12998698, 12993549, 12995125, 12987537, 12993021, 12991986, 13008408, 12983417, 12986060, 12998395, 12985644, 13014731, 12986433, 12985074, 12994455, 12994262, 12986759, 13011932, 13005211, 12993521, 12987900, 12992623, 12981736, 12986649, 12991524, 13000035, 12989278, 13013868, 13009417, 13013327, 12981605, 12985768, 13000158, 13015035, 13002596, 13015944, 12997893, 12999767, 13010949, 12996835, 13013517, 13006555, 13013143, 13010016, 13005792, 13016948, 13007235, 12998343, 12987102 };
    int counter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        progressBar.setIndeterminate(true);
        progressBar.setKeepScreenOn(true);
        progressBar.setVisibility(View.INVISIBLE);
    }

    public void actionTimer(View view) {
        Toast.makeText(this, "starting progressBar ‑ CountDownTimer", Toast.LENGTH_SHORT).show();
        progressBar.setVisibility(View.VISIBLE);
        new CountDownTimer(5000, 500) {
            @Override
            public void onTick(long millisUntilFinished) {
            }
            @Override
            public void onFinish() {
                progressBar.setVisibility(View.INVISIBLE);
                Toast.makeText(getApplicationContext(), "timer done", Toast.LENGTH_SHORT).show();
            }
        }.start();
    }

    public void actionJson(View view) {
        Toast.makeText(this, "starting progressBar ‑ json fetch", Toast.LENGTH_SHORT).show();
        progressBar.setVisibility(View.VISIBLE);

        String urlTemplate = "https://hacker‑news.firebaseio.com/v0/item/___ITEM_NUMBER___.json?print=pretty";
        counter = 0;

        for (int i = 0; i < items.length; i++) {
            String url = urlTemplate.replaceAll("___ITEM_NUMBER___", String.valueOf(items[i]));
            //Log.i("thisDoesNotWork", url);

            DownloadJson downloadJson = new DownloadJson();
            try {
                downloadJson.execute(url).get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
    }

    public class DownloadJson extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            Log.i("DownloadJson", "url=" + params[0]);

            URL url;
            HttpURLConnection urlConnection = null;

            try {
                url = new URL(params[0]);
                urlConnection = (HttpURLConnection) url.openConnection();
                InputStream inputStream = urlConnection.getInputStream();

                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuilder resultBuilder = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    resultBuilder.append(line).append("\n");
                }
                //Log.i("DownloadJson", "resultBuilder.length()=" + resultBuilder.length());
                return resultBuilder.toString();

            } catch (Exception e) {
                e.printStackTrace();
                return "{\"status\" : \"Hacker News json download failed\"}";
            }
        }

        @Override
        public void onPostExecute(String s) {
            super.onPostExecute(s);
            counter += 1;
            if (counter == items.length) {
                progressBar.setVisibility(View.INVISIBLE);
                Toast.makeText(getApplicationContext(), "download done", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

XML:

<?xml version="1.0" encoding="utf‑8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.plaudev.progressbar.MainActivity">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical">

        <Button
            android:text="@string/timer"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:id="@+id/buttonTimer"
            android:layout_weight="1"
            android:onClick="actionTimer"
            android:layout_margin="25dp" />

        <Button
            android:text="@string/json"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/buttonJson"
            android:layout_weight="1"
            android:onClick="actionJson"
            android:layout_margin="25dp" />
    </LinearLayout>

    <ProgressBar
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:id="@+id/progressBar" />
</RelativeLayout>

참조 솔루션

방법 1:

The answer is to put the whole for loop in the onClick actionJson() into a worker thread as follows as noted here:

public void actionJson(View view) {
        Toast.makeText(this, "starting progressBar ‑ json fetch", Toast.LENGTH_SHORT).show();
        progressBar.setVisibility(View.VISIBLE);

        final String urlTemplate = "https://hacker‑news.firebaseio.com/v0/item/___ITEM_NUMBER___.json?print=pretty";
        counter = 0;

        // simply put it in a worker thread does the job
        new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i < items.length; i++) {
                    String url = urlTemplate.replaceAll("___ITEM_NUMBER___", String.valueOf(items[i]));
                    //Log.i("actionJson", url);
                    DownloadJson downloadJson = new DownloadJson();
                    try {
                        downloadJson.execute(url).get();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

So even though the for loop as originally defined does spawn a whole bunch of asyncTasks individually, it is still somehow blocking the main thread.

(by rockhammerrockhammer)

참조 문서

  1. Android progressBar setVisibility() not working (CC BY‑SA 2.5/3.0/4.0)

#android-progressbar #android-toast #android-asynctask #countdowntimer #Android






관련 질문

목록 보기 항목의 보기는 화면에서 보기를 스크롤한 후 원래 상태로 돌아갑니다. (listview item's view returns to original state after scroll the view off the screen)

Android의 비동기 클래스에서 FTP 다운로드에 진행률 표시줄을 표시하는 방법은 무엇입니까? (How to show the progress bar in FTP download in async class in Android?)

Android에서 진행률 표시줄의 ListView (ListView of Progress Bars in android)

안드로이드에서 24시간 SeekBar 또는 ProgressBar를 만드는 방법 (How to create 24hour SeekBar or ProgressBar in android)

Android: ProgressBar가 활동에서 이상하게 보입니다. (Android: ProgressBar looks strange in activity)

Android에서 기본 ProgressDialog 원 색상을 변경하는 방법 (How to change default ProgressDialog circle color in android)

Android: 사이에 공백이 있는 맞춤 원 ProgressBar (Android: Custom circle ProgressBar with spaces in between)

정적 수평 진행률 표시줄 Android (Static horizontal progress bar android)

Android progressBar setVisibility()가 작동하지 않음 (Android progressBar setVisibility() not working)

비동기 작업의 게시 진행률 (Publishing progress in async task)

BaseActvity/BaseFragment의 ProgressBar 관리 (ProgressBar management in BaseActvity/BaseFragment)

진행 중인 경고 대화 상자가 닫히거나 취소되지 않음 (Alertdialog running ongoing dosen't dismiss or cancel)







코멘트