首页 \ 问答 \ AsyncTask检测是否完成(AsyncTask detecting if done)

AsyncTask检测是否完成(AsyncTask detecting if done)

我创建了一个AsyncTask,当我执行它时从网站加载数据。 目前,我得到一个空指针异常,我认为是因为我想太早填充UI,所以我希望创建一些if语句,说如果AsyncTask没有完成显示加载图形和填充数据的时间。 但我不确定如何去做这件事,是否有人知道我该如何实现这一目标,或者至少让我朝正确的方向发展。

这是我的代码到目前为止

public void checkPreferences(){

    SharedPreferences preferences = getSharedPreferences("prefs", Context.MODE_PRIVATE);
    ChosenMethod = preferences.getString("ChosenMethod", ChosenMethod);
    ChosenLeagueID = preferences.getString("ChosenLeagueId", ChosenLeagueID);
    ChosenTeamId = preferences.getString("ChosenTeamId", ChosenTeamId);

    Log.v("lc", "newsurl" + newsFeedURL);


    Log.v("myapp", "ChosenMethod Home = " + ChosenMethod);
    Log.v("myapp", "ChosenLeagueID Home = " + ChosenLeagueID);
    Log.v("myapp", "ChosenTeamID Home = " + ChosenTeamId);

    if (ChosenMethod.equals("Team")) {
        setContentView(R.layout.homeactteam2);
        newsAmount = 5;

    } else {
        newsAmount = 10;
        setContentView(R.layout.homeactteam);
    }

}


@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    //Check Preferences which sets UI

    checkPreferences();
   PostTask posttask;
   posttask = new PostTask();
   posttask.execute();

   FillData();


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

    //Listening to button event
    backbtn.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {
            //Starting a new Intent
            Intent previousScreen = new Intent(getApplicationContext(), ChooseTeamActivity.class);
            ChosenMethod = "null";
            SharedPreferences preferences = getSharedPreferences("prefs", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = preferences.edit();
            editor.putString("ChosenMethod", ChosenMethod);            
            editor.commit();
            previousScreen.putExtra("FullData", fulldata);
            startActivity(previousScreen);


        }
    });

//((PullToRefreshListView) getListView()).setOnRefreshListener(new OnRefreshListener() {
//   
//    public void onRefresh() {
//        // Do work to refresh the list here.
//        loadData();
//    }
//});
//


}



public void loadNewsFeed(){

     newsFeedRequest = "website/" + chosenLeagueId + "/news?timestamp=" + unixTimeStamp;
     newsFeedURL = "https://www.website.com" + newsFeedRequest; 

        String myhash = buildHmacSignature(apiKey, newsFeedURL);
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(newsFeedURL);

        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("requestToken", myhash));
        pairs.add(new BasicNameValuePair("apiUser", apiUser));

            try {
                post.setEntity (new UrlEncodedFormEntity(pairs));
                HttpResponse response = client.execute(post);
                BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
                String json = reader.readLine();
                fulldata = String.valueOf(json);
                Log.v("myApp","newsdata" + fulldata);

                newsList = new ArrayList<String>();
                newsList2 = new ArrayList<String>();
                newsList3 = new ArrayList<String>();
                imageList = new ArrayList<String>();


                JSONObject obj = new JSONObject(json);    
                JSONObject objData = obj.getJSONObject("data");
                JSONArray jArray = objData.getJSONArray("news");
                Log.v("lc","newsAmount= " + newsAmount);

                   for(int t = 0; t < newsAmount; t++){
                       JSONObject newsTitleDict = jArray.getJSONObject(t);
                       imageList.add(newsTitleDict.getString("image_small"));
                     newsList3.add(newsTitleDict.getString("title"));

                   }

                   for(int t = 0; t < 1; t++){
                       JSONObject newsTitleDict = jArray.getJSONObject(t);

                 newsList.add(newsTitleDict.getString("title"));
            //       newsList2.add(newsTitleDict.getString("title"));

                   }



    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


}           


public void loadResultsFeed(){


    resultsFeedRequest = "website/" + chosenLeagueId + "/results?&team_id=" + ChosenTeamId + "&limit=31&timestamp=" + unixTimeStamp;
    resultsFeedURL = "https://www.website.com" + resultsFeedRequest;    

    String myhash = buildHmacSignature(apiKey, resultsFeedURL);

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(resultsFeedURL);

    List<NameValuePair> pairs = new ArrayList<NameValuePair>();
    pairs.add(new BasicNameValuePair("requestToken", myhash));
    pairs.add(new BasicNameValuePair("apiUser", apiUser));

    try {
        post.setEntity (new UrlEncodedFormEntity(pairs));
        HttpResponse response = client.execute(post);
        BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
        String json = reader.readLine();
        fulldata = String.valueOf(json);
        Log.v("myApp","resultsdata" + fulldata);

        newsList = new ArrayList<String>();
        newsList2 = new ArrayList<String>();
        newsList3 = new ArrayList<String>();
        imageList = new ArrayList<String>();


        JSONObject obj = new JSONObject(json);    
        JSONObject objData = obj.getJSONObject("data");
        JSONArray jArray = objData.getJSONArray("results");


        if(jArray.length() < 1) loadLastResults();



    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }   


}


public void loadLastResults(){

    resultsFeedRequest = "website/" + chosenLeagueId + "/results?month=04&team_id=" + ChosenTeamId + "&limit=31&timestamp=" + unixTimeStamp;
    resultsFeedURL = "https://www.website.com" + resultsFeedRequest;    

     String myhash = buildHmacSignature(apiKey, resultsFeedURL);

    Date anotherCurDate = new Date();  
    SimpleDateFormat formatter = new SimpleDateFormat("MM");  
    String CurMonth = formatter.format(anotherCurDate);  

    int Int = Integer.parseInt(CurMonth);

    int MonthInt = Int -1;


    CurMonth = (String) (String.valueOf(MonthInt));



    if (CurMonth.equals("1")){

        lastMonth = "12";

    }    
     else {
        if(CurMonth.length() < 2){
            lastMonth = "0" + CurMonth;
        } else {
            lastMonth = CurMonth;
        }
    }

    Log.v("lc","month= " + CurMonth);
    Log.v("lc","LastMonth= " + lastMonth);


        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(resultsFeedURL);

        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("requestToken", myhash));
        pairs.add(new BasicNameValuePair("apiUser", apiUser));

        try {
            post.setEntity (new UrlEncodedFormEntity(pairs));
            HttpResponse response = client.execute(post);
            BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
            String json = reader.readLine();
            fulldata = String.valueOf(json);
            Log.v("myApp","resultsdata" + fulldata);

            newsList = new ArrayList<String>();
            newsList2 = new ArrayList<String>();
            newsList3 = new ArrayList<String>();
            imageList = new ArrayList&t;String>();


            JSONObject obj = new JSONObject(json);    
            JSONObject objData = obj.getJSONObject("data");
            JSONArray jArray = objData.getJSONArray("results");


               for(int t = 0; t < 1; t++){

                   resultsDict = jArray.getJSONObject(t);
                  HomeTeam = resultsDict.getString("hometeam");
                  AwayTeam = resultsDict.getString("awayteam");
                  HomeScore = resultsDict.getString("homescore");
                  AwayScore = resultsDict.getString("awayscore");
                  Attendance = resultsDict.getString("attendance");
                  Division = resultsDict.getString("division");

                  Log.v("lc","hometeam" + HomeTeam);
                  Log.v("lc","awayteam" + AwayTeam);


               }


        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }   


public class PostTask extends AsyncTask<Void, String, Boolean> {

    @Override
    protected Boolean doInBackground(Void... params) {
        boolean result = false;
        loadNewsFeed();
        loadResultsFeed();
        loadLastResults();
        publishProgress("progress");
        return result;
    }

    protected void onProgressUpdate(String... progress) {
        StringBuilder str = new StringBuilder();
            for (int i = 1; i < progress.length; i++) {
                str.append(progress[i] + " ");
            }
    }

}

public void FillData(){ 


     if (ChosenMethod.equals("Team")) {


         resultsView = LayoutInflater.from(getBaseContext()).inflate(R.layout.resultscell,
                 null);

       TextView homeTeam = (TextView) resultsView.findViewById(R.id.HomeTeam);
       homeTeam.setText(HomeTeam);

       TextView awayTeam = (TextView) resultsView.findViewById(R.id.AwayTeam);
       awayTeam.setText(AwayTeam);

       TextView homeScore = (TextView) resultsView.findViewById(R.id.HomeScore);
       homeScore.setText(HomeScore);

       TextView awayScore = (TextView) resultsView.findViewById(R.id.AwayScore);
       awayScore.setText(AwayScore);

       TextView attendance = (TextView) resultsView.findViewById(R.id.Attendence);
       attendance.setText("Att:" + Attendance);

       TextView division = (TextView) resultsView.findViewById(R.id.Division);
       division.setText(Division);

        arrayAdapter = new ArrayAdapter<String>(this, R.layout.single_item, newsList);

         String[] mStrings = (String[]) imageList.toArray(new String[imageList.size()]);
         String[] news = (String[]) newsList3.toArray(new String[newsList3.size()]);

         arrayAdapter3 = new LazyAdapter(this, mStrings, news);


            ListView list = getListView();
               list.setTextFilterEnabled(true);

               LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE );
                View header = inflater.inflate( R.layout.homeheader, list, false);
                View header2 = inflater.inflate( R.layout.homeheader2, list, false);
                View header3 = inflater.inflate( R.layout.homeheader3, list, false);


        //setListAdapter (arrayAdapter);


            adapter = new MergeAdapter();
            adapter.addView(header);
            adapter.addAdapter(arrayAdapter);
            adapter.addView(header2);
            adapter.addView(resultsView);
            adapter.addView(header3);
            adapter.addAdapter(arrayAdapter3);
            setListAdapter(adapter);



     } else {

         arrayAdapter = new ArrayAdapter<String>(this, R.layout.single_item, newsList);
            arrayAdapter2 = new ArrayAdapter<String>(this, R.layout.single_item, newsList2);
            //arrayAdapter3 = new ArrayAdapter(this, R.layout.complex_item, newsList3);

             String[] mStrings = (String[]) imageList.toArray(new String[imageList.size()]);
             String[] news = (String[]) newsList3.toArray(new String[newsList3.size()]);


             arrayAdapter3 = new LazyAdapter(this, mStrings, news);


                ListView list = getListView();
                   list.setTextFilterEnabled(true);

                   LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE );
                    View header3 = inflater.inflate( R.layout.homeheader3, list, false);


            //setListAdapter (arrayAdapter);


                adapter = new MergeAdapter();
                adapter.addView(header3);
                adapter.addAdapter(arrayAdapter3);
                setListAdapter(adapter);
         } 
}

I have created an AsyncTask that loads data from a website then when I execute it. At the moment I'm getting a null pointer exception which I think is caused because I'm trying to fill the UI too early so I'm hoping to create some kind of if statement that says if AsyncTask isn't complete show a loading graphic and when it is fill the data. But I'm not sure how to go about doing this does anyone know how I could achieve this or at least point me in the right direction.

Here's my code so far

public void checkPreferences(){

    SharedPreferences preferences = getSharedPreferences("prefs", Context.MODE_PRIVATE);
    ChosenMethod = preferences.getString("ChosenMethod", ChosenMethod);
    ChosenLeagueID = preferences.getString("ChosenLeagueId", ChosenLeagueID);
    ChosenTeamId = preferences.getString("ChosenTeamId", ChosenTeamId);

    Log.v("lc", "newsurl" + newsFeedURL);


    Log.v("myapp", "ChosenMethod Home = " + ChosenMethod);
    Log.v("myapp", "ChosenLeagueID Home = " + ChosenLeagueID);
    Log.v("myapp", "ChosenTeamID Home = " + ChosenTeamId);

    if (ChosenMethod.equals("Team")) {
        setContentView(R.layout.homeactteam2);
        newsAmount = 5;

    } else {
        newsAmount = 10;
        setContentView(R.layout.homeactteam);
    }

}


@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    //Check Preferences which sets UI

    checkPreferences();
   PostTask posttask;
   posttask = new PostTask();
   posttask.execute();

   FillData();


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

    //Listening to button event
    backbtn.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {
            //Starting a new Intent
            Intent previousScreen = new Intent(getApplicationContext(), ChooseTeamActivity.class);
            ChosenMethod = "null";
            SharedPreferences preferences = getSharedPreferences("prefs", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = preferences.edit();
            editor.putString("ChosenMethod", ChosenMethod);            
            editor.commit();
            previousScreen.putExtra("FullData", fulldata);
            startActivity(previousScreen);


        }
    });

//((PullToRefreshListView) getListView()).setOnRefreshListener(new OnRefreshListener() {
//   
//    public void onRefresh() {
//        // Do work to refresh the list here.
//        loadData();
//    }
//});
//


}



public void loadNewsFeed(){

     newsFeedRequest = "website/" + chosenLeagueId + "/news?timestamp=" + unixTimeStamp;
     newsFeedURL = "https://www.website.com" + newsFeedRequest; 

        String myhash = buildHmacSignature(apiKey, newsFeedURL);
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(newsFeedURL);

        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("requestToken", myhash));
        pairs.add(new BasicNameValuePair("apiUser", apiUser));

            try {
                post.setEntity (new UrlEncodedFormEntity(pairs));
                HttpResponse response = client.execute(post);
                BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
                String json = reader.readLine();
                fulldata = String.valueOf(json);
                Log.v("myApp","newsdata" + fulldata);

                newsList = new ArrayList<String>();
                newsList2 = new ArrayList<String>();
                newsList3 = new ArrayList<String>();
                imageList = new ArrayList<String>();


                JSONObject obj = new JSONObject(json);    
                JSONObject objData = obj.getJSONObject("data");
                JSONArray jArray = objData.getJSONArray("news");
                Log.v("lc","newsAmount= " + newsAmount);

                   for(int t = 0; t < newsAmount; t++){
                       JSONObject newsTitleDict = jArray.getJSONObject(t);
                       imageList.add(newsTitleDict.getString("image_small"));
                     newsList3.add(newsTitleDict.getString("title"));

                   }

                   for(int t = 0; t < 1; t++){
                       JSONObject newsTitleDict = jArray.getJSONObject(t);

                 newsList.add(newsTitleDict.getString("title"));
            //       newsList2.add(newsTitleDict.getString("title"));

                   }



    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


}           


public void loadResultsFeed(){


    resultsFeedRequest = "website/" + chosenLeagueId + "/results?&team_id=" + ChosenTeamId + "&limit=31&timestamp=" + unixTimeStamp;
    resultsFeedURL = "https://www.website.com" + resultsFeedRequest;    

    String myhash = buildHmacSignature(apiKey, resultsFeedURL);

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(resultsFeedURL);

    List<NameValuePair> pairs = new ArrayList<NameValuePair>();
    pairs.add(new BasicNameValuePair("requestToken", myhash));
    pairs.add(new BasicNameValuePair("apiUser", apiUser));

    try {
        post.setEntity (new UrlEncodedFormEntity(pairs));
        HttpResponse response = client.execute(post);
        BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
        String json = reader.readLine();
        fulldata = String.valueOf(json);
        Log.v("myApp","resultsdata" + fulldata);

        newsList = new ArrayList<String>();
        newsList2 = new ArrayList<String>();
        newsList3 = new ArrayList<String>();
        imageList = new ArrayList<String>();


        JSONObject obj = new JSONObject(json);    
        JSONObject objData = obj.getJSONObject("data");
        JSONArray jArray = objData.getJSONArray("results");


        if(jArray.length() < 1) loadLastResults();



    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }   


}


public void loadLastResults(){

    resultsFeedRequest = "website/" + chosenLeagueId + "/results?month=04&team_id=" + ChosenTeamId + "&limit=31&timestamp=" + unixTimeStamp;
    resultsFeedURL = "https://www.website.com" + resultsFeedRequest;    

     String myhash = buildHmacSignature(apiKey, resultsFeedURL);

    Date anotherCurDate = new Date();  
    SimpleDateFormat formatter = new SimpleDateFormat("MM");  
    String CurMonth = formatter.format(anotherCurDate);  

    int Int = Integer.parseInt(CurMonth);

    int MonthInt = Int -1;


    CurMonth = (String) (String.valueOf(MonthInt));



    if (CurMonth.equals("1")){

        lastMonth = "12";

    }    
     else {
        if(CurMonth.length() < 2){
            lastMonth = "0" + CurMonth;
        } else {
            lastMonth = CurMonth;
        }
    }

    Log.v("lc","month= " + CurMonth);
    Log.v("lc","LastMonth= " + lastMonth);


        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(resultsFeedURL);

        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("requestToken", myhash));
        pairs.add(new BasicNameValuePair("apiUser", apiUser));

        try {
            post.setEntity (new UrlEncodedFormEntity(pairs));
            HttpResponse response = client.execute(post);
            BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
            String json = reader.readLine();
            fulldata = String.valueOf(json);
            Log.v("myApp","resultsdata" + fulldata);

            newsList = new ArrayList<String>();
            newsList2 = new ArrayList<String>();
            newsList3 = new ArrayList<String>();
            imageList = new ArrayList<String>();


            JSONObject obj = new JSONObject(json);    
            JSONObject objData = obj.getJSONObject("data");
            JSONArray jArray = objData.getJSONArray("results");


               for(int t = 0; t < 1; t++){

                   resultsDict = jArray.getJSONObject(t);
                  HomeTeam = resultsDict.getString("hometeam");
                  AwayTeam = resultsDict.getString("awayteam");
                  HomeScore = resultsDict.getString("homescore");
                  AwayScore = resultsDict.getString("awayscore");
                  Attendance = resultsDict.getString("attendance");
                  Division = resultsDict.getString("division");

                  Log.v("lc","hometeam" + HomeTeam);
                  Log.v("lc","awayteam" + AwayTeam);


               }


        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }   


public class PostTask extends AsyncTask<Void, String, Boolean> {

    @Override
    protected Boolean doInBackground(Void... params) {
        boolean result = false;
        loadNewsFeed();
        loadResultsFeed();
        loadLastResults();
        publishProgress("progress");
        return result;
    }

    protected void onProgressUpdate(String... progress) {
        StringBuilder str = new StringBuilder();
            for (int i = 1; i < progress.length; i++) {
                str.append(progress[i] + " ");
            }
    }

}

public void FillData(){ 


     if (ChosenMethod.equals("Team")) {


         resultsView = LayoutInflater.from(getBaseContext()).inflate(R.layout.resultscell,
                 null);

       TextView homeTeam = (TextView) resultsView.findViewById(R.id.HomeTeam);
       homeTeam.setText(HomeTeam);

       TextView awayTeam = (TextView) resultsView.findViewById(R.id.AwayTeam);
       awayTeam.setText(AwayTeam);

       TextView homeScore = (TextView) resultsView.findViewById(R.id.HomeScore);
       homeScore.setText(HomeScore);

       TextView awayScore = (TextView) resultsView.findViewById(R.id.AwayScore);
       awayScore.setText(AwayScore);

       TextView attendance = (TextView) resultsView.findViewById(R.id.Attendence);
       attendance.setText("Att:" + Attendance);

       TextView division = (TextView) resultsView.findViewById(R.id.Division);
       division.setText(Division);

        arrayAdapter = new ArrayAdapter<String>(this, R.layout.single_item, newsList);

         String[] mStrings = (String[]) imageList.toArray(new String[imageList.size()]);
         String[] news = (String[]) newsList3.toArray(new String[newsList3.size()]);

         arrayAdapter3 = new LazyAdapter(this, mStrings, news);


            ListView list = getListView();
               list.setTextFilterEnabled(true);

               LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE );
                View header = inflater.inflate( R.layout.homeheader, list, false);
                View header2 = inflater.inflate( R.layout.homeheader2, list, false);
                View header3 = inflater.inflate( R.layout.homeheader3, list, false);


        //setListAdapter (arrayAdapter);


            adapter = new MergeAdapter();
            adapter.addView(header);
            adapter.addAdapter(arrayAdapter);
            adapter.addView(header2);
            adapter.addView(resultsView);
            adapter.addView(header3);
            adapter.addAdapter(arrayAdapter3);
            setListAdapter(adapter);



     } else {

         arrayAdapter = new ArrayAdapter<String>(this, R.layout.single_item, newsList);
            arrayAdapter2 = new ArrayAdapter<String>(this, R.layout.single_item, newsList2);
            //arrayAdapter3 = new ArrayAdapter(this, R.layout.complex_item, newsList3);

             String[] mStrings = (String[]) imageList.toArray(new String[imageList.size()]);
             String[] news = (String[]) newsList3.toArray(new String[newsList3.size()]);


             arrayAdapter3 = new LazyAdapter(this, mStrings, news);


                ListView list = getListView();
                   list.setTextFilterEnabled(true);

                   LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE );
                    View header3 = inflater.inflate( R.layout.homeheader3, list, false);


            //setListAdapter (arrayAdapter);


                adapter = new MergeAdapter();
                adapter.addView(header3);
                adapter.addAdapter(arrayAdapter3);
                setListAdapter(adapter);
         } 
}

原文:https://stackoverflow.com/questions/10946499
更新时间:2021-12-23 11:12

最满意答案

好的,我自己找到了解决方案。 这里的问题是关于竞争条件 - 一个事件试图停止计数(这意味着引发另一个事件)然后再次启动它(这是有问题的,因为我的功能(我猜)已经混乱了第一个,可能是第二个事件甚至没有添加到事件检测队列中)。 如果我的解释错了,我会感激一些批评;)

这是两个修改过的函数,它们正确地解决了线程管理。 关键是让其他事件完成他们的工作,直到我得到理想的状态。

当我想关闭计数时,我让应用程序从队列中执行事件,直到两个线程都不忙('while'循环):

private: void turnOffAcquisition() {

    if (counting_paused)
        return;

    if (plot_bgworker->IsBusy)
        plot_bgworker->CancelAsync();
    if (data_bgworker->IsBusy)
        data_bgworker->CancelAsync();

    while((plot_bgworker->IsBusy) || (data_bgworker->IsBusy))   // Continue to process events until both workers stop working
        Application::DoEvents();                                // Then, you can process another thread requests! :)

    label_timer->Enabled = false;
    counting_paused = true;
 }

类似地,当我想重新开始计数时,我让应用程序执行事件,直到我检查两个线程都忙(再次,'while'循环):

private: void turnOnAcquisition() {
    if (!counting_paused)
        return;

    if (!plot_bgworker->IsBusy)
        plot_bgworker->RunWorkerAsync();
    if (!data_bgworker->IsBusy)
        data_bgworker->RunWorkerAsync();

    while((!plot_bgworker->IsBusy) || (!data_bgworker->IsBusy)) // Continue to process events until both workers start working
        Application::DoEvents();                                // Then, you can process another thread requests! :)

    label_timer->Enabled = true;
    counting_paused = false;
}

Ok, I found the solution by myself. The problem here was about the race condition - one event tried to stop counting (which meant raising another event) and then starting it again (which was problematic, as my function (I guess) was already cluttered with the first one and probably the second event wasn't even added to the event detected queue). If I am wrong with the explanation, I would appreciate some criticism down there ;)

Here are two modified functions, which solved thread management correctly. The key was to let the other events do their work until I get desired state.

When I want to turn off counting, I let the applications do the events from the queue until both threads will not be busy (the 'while' loop):

private: void turnOffAcquisition() {

    if (counting_paused)
        return;

    if (plot_bgworker->IsBusy)
        plot_bgworker->CancelAsync();
    if (data_bgworker->IsBusy)
        data_bgworker->CancelAsync();

    while((plot_bgworker->IsBusy) || (data_bgworker->IsBusy))   // Continue to process events until both workers stop working
        Application::DoEvents();                                // Then, you can process another thread requests! :)

    label_timer->Enabled = false;
    counting_paused = true;
 }

Similarily, when I want to restart counting, I let the application do the events until I check that both threads are busy (again, the 'while' loop):

private: void turnOnAcquisition() {
    if (!counting_paused)
        return;

    if (!plot_bgworker->IsBusy)
        plot_bgworker->RunWorkerAsync();
    if (!data_bgworker->IsBusy)
        data_bgworker->RunWorkerAsync();

    while((!plot_bgworker->IsBusy) || (!data_bgworker->IsBusy)) // Continue to process events until both workers start working
        Application::DoEvents();                                // Then, you can process another thread requests! :)

    label_timer->Enabled = true;
    counting_paused = false;
}

相关问答

更多
  • 是的,.so文件需要安装到PKGLIBDIR中。 你可以通过运行“pg_config”找出PKGLIBDIR是什么。 例如,在带有PostgreSQL 9.4的Ubuntu系统上,pg_config将返回: PKGLIBDIR = /usr/lib/postgresql/9.4/lib 此外,worker_spi - 1.0.sql应安装到SHAREDIR / extension中。 在带有PostgreSQL 9.4的Ubuntu系统上,从pg_config返回的SHAREDIR是: SHAREDIR = ...
  • 1.添加以下使用方法: using System.ComponentModel; 背景工作者 : private readonly BackgroundWorker worker = new BackgroundWorker(); 3.订阅事件: worker.DoWork += worker_DoWork; worker.RunWorkerCompleted += worker_RunWorkerCompleted; 实现两种方法: private void worker_DoWork(object ...
  • 在进度页面中执行背景 如果您需要传递(并返回)一个对象,请在Progress ctor中执行此操作 private void click(object sender, RoutedEventArgs e) { Progress progressDialog = new Progress(); progressDialog.Show(); if (progressDialog != null) progressDialog = null; } namespace BackGround ...
  • 您无法在非UI线程上更新GUI控件,因此您必须在循环期间尝试“报告”调查结果。 在这里,我只使用ListBox中的字符串副本启动线程: bgw.RunWorkerAsync(ListBox1.Items.Cast(Of String)) 我们需要一个简单的类来报告信息: Public Class UserStatus Property Name As String Property Kind As Integer End Class 然后在DoWork方法中 Private Sub bgw_Do ...
  • 好的,我自己找到了解决方案。 这里的问题是关于竞争条件 - 一个事件试图停止计数(这意味着引发另一个事件)然后再次启动它(这是有问题的,因为我的功能(我猜)已经混乱了第一个,可能是第二个事件甚至没有添加到事件检测队列中)。 如果我的解释错了,我会感激一些批评;) 这是两个修改过的函数,它们正确地解决了线程管理。 关键是让其他事件完成他们的工作,直到我得到理想的状态。 当我想关闭计数时,我让应用程序从队列中执行事件,直到两个线程都不忙('while'循环): private: void turnOffAcqu ...
  • 您遇到的问题是经典的生产者 - 消费者问题。 请查看http://en.wikipedia.org/wiki/Producer-consumer_problem 一个简单的解释是你将有两个线程。 一个是生产者(GUID生成者),另一个是消费者。 您将通过使用信号量使这些线程保持同步。 信号量将负责在队列满时停止生产者,并在消费者为空时停止消费者。 这个过程在维基百科的文章中得到了很好的解释,我打赌你可以在互联网上找到c#中Producer-Consumer的基本实现。 The problem you hav ...
  • 我认为你得到错误,因为在USP_Select_Registration内部你试图从表单控件中读取值。 这是由另一个线程创建的。 RunWorkComleted在创建Backgroundworker的同一个线程中执行,这就是代码P_Panel.Visible = False将正常执行的原因。 但是DoWork在另一个线程上执行。 当您尝试访问某些表单控件以读取值时 TXT_Search.Text - 它引发错误 您可以将搜索参数传递给BackgroundWorker ,但需要向USP_Select_Regis ...
  • 在DoWork()我调用AutoResetEvent.WaitOne() 。 这是否会在调用AutoResetEvent.Set()之前停止当前线程? 例如,如果从不调用AutoResetEvent.Set() , Background Worker只是暂停而不执行任何操作? 从MSDN WaitHandle.WaitOne Method引用的答案是肯定的: 阻止当前线程,直到当前WaitHandle收到信号。 编辑 :对于您添加的代码,while循环将等待Set() within DoWork() I c ...
  • 要扩展@ LarsTech的注释,您当前的进度计算甚至不依赖于j因此将ReportProgress调用移到内部循环之外。 这将通过减少调用次数来帮助响应,甚至不会改变ProgressBar的行为。 for (int i = 0; i < x; ++i) //Parallel.For(0, x, i => { bw.ReportProgress((int)(((double)i / (double)y + (double)1 / (double)x) * 100)); ...
  • 如果您不希望在等待长进程时挂起UI,则必须使用线程。 BackgroundWorker是一个很好的实现,它提供了用于报告进度的钩子,允许用户中止进程等。 关于Stack Overflow的BackgroundWorker有很多问题,或者查看MSDN文档 。 If you don't want your UI to hang while waiting for long processes you have to use a thread. BackgroundWorker is a good impleme ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)