线程进度条片段

Thread progresse bar fragment

我正在尝试开发一个小应用程序来分析目录号码。我的应用程序由一个重定向片段的菜单组成。我创建了一个显示加载条的线程。当我使用 Thread.Join 时出现问题。事实上,加载栏不再出现。如果我不 Thread.Join 使用主线程继续执行并且我不会在末尾列表中填充... 我该如何解决这个问题? 提前致谢!

package app.devloots.com.contactproject;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;


public class SurtaxedFragment extends Fragment implements Runnable{

    private ProgressDialog mprogressDialog;
    private ArrayList values = new ArrayList<String>();
    ListView listView;
    String currentContact;

    public SurtaxedFragment(){}

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            int i = msg.what;
            switch (i) {
                case 0:
                    mprogressDialog.setMessage("Analyse des contacts en cours...");
                    mprogressDialog.setMessage("Analyse en cours ... : " +currentContact); break;
                default: mprogressDialog.dismiss();
            }
        }
    };

    public void run(){
        ContentResolver cr = getActivity().getContentResolver();
        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
                null, null, null, null);
        if (cur.getCount() > 0) {
            while (cur.moveToNext()) {
                String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                if (Integer.parseInt(cur.getString(
                        cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                    Cursor pCur = cr.query(
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                            null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                            new String[]{id}, null);
                    while (pCur.moveToNext()) {
                        String phoneNo = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        currentContact=name;
                        handler.sendEmptyMessage(0);
                        if(isSurtaxed(phoneNo)){
                            values.add(name + " : " + phoneNo);
                        }
                    }
                    pCur.close();
                }
            }
        }
        if(values.isEmpty()){
            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction()
                    .replace(R.id.frame_container, new No_SurtaxedFragment()).commit();
        }
            handler.sendEmptyMessage(1);
    }
/*
Creéation du fragment
 */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_surtaxed, container, false);
        listView = (ListView) rootView.findViewById(R.id.list);
        mprogressDialog = new ProgressDialog(getActivity());
        mprogressDialog.setTitle("Analyse");
        mprogressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        mprogressDialog.show();

        Thread thread = new Thread(this);
        thread.start();
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_list_item_1, android.R.id.text1, values);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                int itemPosition = position;
                String itemValue = (String) listView.getItemAtPosition(position);

                deleteContact(itemValue);

                //Refresh current fragment
                FragmentManager fragmentManager = getFragmentManager();
                fragmentManager.beginTransaction()
                        .replace(R.id.frame_container, new SurtaxedFragment()).commit();
            }
        });

        return rootView;
    }

    /*
    *   Methode static qui permet de savoir si un numéro est surtxé ou non
    *   Renvoie true si le numéro est surtxé. Renvoie False sinon.
    */
    private boolean isSurtaxed(String phone){
        if (phone.startsWith("08") || phone.startsWith("0 8") || phone.startsWith("3") || phone.startsWith("+338") || phone.startsWith("+331")){
            return true;
        }
        return false;
    }


    /*
    *   Méthode qui permet de supprimer un contact du repertoire
     */
    private void deleteContact(String s) {
        String f [] = s.split (" : ") ;
        String name = f[0];
        ContentResolver cr = getActivity().getContentResolver();
        String where = ContactsContract.Data.DISPLAY_NAME + " = ? ";
        String[] params = new String[]{name};
        ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
        ops.add(ContentProviderOperation.newDelete(ContactsContract.RawContacts.CONTENT_URI)
                .withSelection(where, params)
                .build());
        try {
            cr.applyBatch(ContactsContract.AUTHORITY, ops);
        } catch (RemoteException e) {
            e.printStackTrace();
        } catch (OperationApplicationException e) {
            e.printStackTrace();
        }
    }
}

你不必使用.join()让线程先run.You可以先初始化listview。当线程完成时,适配器 .notifyDataSetChanged() 刷新 listview.

我删除了 Thread.Join 并在我的 运行 () 中添加了 adapter.notifyDataSetChanged () 方法,但是当我测试应用程序时,它停止了。

我认为是列表在创建视图后自行更新,但我不知道如何解决问题...

您应该在主线程中调用 .notifyDataSetChanged()。使用处理程序 .sendMessage() 通知主线程调用 .notifyDataSetChanged() 更新列表视图。