【问题标题】:How to loop execution of AsyncTask with an array of params如何使用参数数组循环执行 AsyncTask
【发布时间】:2015-11-01 14:48:07
【问题描述】:

我是 Android 编程新手。 我创建了 Web 对象类,每个类都有 3 个要解析的 RSS URL。我循环这些对象的数组以对AsyncTaskExecuter 中的每个对象进行操作。每次我这样做时都会出现不同的错误,并且 UI 会冻结。我找不到问题所在。然后我使用自定义适配器来显示 UI,但程序甚至无法访问该代码。请帮我找出我的代码有什么问题。我尝试了我想到的一切。

我像这样在主线程中循环它:

public class MainActivity extends Activity 
{   
ArrayList <WebPage> wpObjects;
ListView lv;


int threadIsFinishedcounter=0;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    lv=(ListView)findViewById(R.id.listView1);


    WebPage ynet= new WebPage(R.drawable.ynet,  "http://www.ynet.co.il/Integration/StoryRss2.xml","http://www.ynet.co.il/Integration/StoryRss6.xml","http://www.ynet.co.il/Integration/StoryRss3.xml");
    WebPage walla=new WebPage(R.drawable.walla, "http://rss.walla.co.il/?w=/1/0/12/@rss.e","http://rss.walla.co.il/?w=/2/0/12/@rss.e","http://rss.walla.co.il/?w=/3/0/12/@rss.e");
    WebPage  nrg= new WebPage(R.drawable.nrg,   "http://rss.nrg.co.il/news/","http://rss.nrg.co.il/finance","http://rss.nrg.co.il/sport");

    wpObjects=new ArrayList<WebPage>();

    wpObjects.add(ynet);
    wpObjects.add(walla);
    wpObjects.add(nrg);

    for(WebPage item:wpObjects)
    {

        //new getParseData(wpObjects.indexOf(item)).execute(item.getUrls());
        new getParseData(wpObjects.indexOf(item)).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, item.getUrls());


    }


    if(threadIsFinishedcounter==wpObjects.size())
       {

           MyCostumedAdapter adapter=new MyCostumedAdapter(MainActivity.this, wpObjects); 

           lv.setAdapter(adapter);
           if(threadIsFinishedcounter==wpObjects.size())
       }
}

AsyncTask 类:

 class getParseData extends AsyncTask<String,Void, Collecter>
 {
    int indexofwp;

    public getParseData(int indexofwp) {
        super();
        this.indexofwp = indexofwp;
    }
    protected Collecter doInBackground(String... params) {

        Collecter col = new Collecter() ;

        ArrayList<String> allResult = new ArrayList<String>();
        ArrayList<String> Titles = new ArrayList<String>();

        for (int y = 0; y < params.length; y++) {
            Titles.clear();
            allResult.clear();

                col.yIndex = y;

            String urlString = params[y];
            try {

                URL url = new URL(urlString);
                XmlPullParserFactory factory = XmlPullParserFactory
                        .newInstance();
                XmlPullParser parser = factory.newPullParser();
                InputStream is = url.openStream();
                parser.setInput(is, null);
                boolean inItemTag = false;
                boolean inTitleTag = false;
                String TagName;
                int EventType = parser.getEventType();

                while (EventType != XmlPullParser.END_DOCUMENT) {
                    Log.i("im in while loop of parser", "");
                    if (EventType == XmlPullParser.START_TAG) {
                        TagName = parser.getName();

                        if (inItemTag) {
                            if (TagName.equals("title"))
                                inTitleTag = true;
                        } else// !item
                        {
                            if (TagName.equals("item"))
                                inItemTag = true;
                        }
                    }
                    if (EventType == XmlPullParser.TEXT) {
                        if (inTitleTag) {

                            Titles.add(parser.getText());// AD THE TITLE
                            inTitleTag = false;
                        }

                    }
                    if (EventType == XmlPullParser.END_TAG) {
                        TagName = parser.getName();
                        if (TagName.equals("item"))
                            inItemTag = false;
                    }
                    EventType = parser.next();

                    Log.i("im after parser.next", "");
                }// end while of parsing loop

            } catch (MalformedURLException e) {
                e.printStackTrace();
                Log.i("EXEPTION******************",
                        "MalformedURLException*********");
            } catch (XmlPullParserException e) {
                e.printStackTrace();
                Log.i("EXEPTION******************",
                        "XmlPullParserException*********");
            } catch (IOException s) {
                s.printStackTrace();
                Log.i("IOException***************************", "");

            }

            synchronized (col) {
                if (col.yIndex == 0) {

                    col.news.addAll(Titles);
                    col.rssRsult.add(col.news);
                }

                if (col.yIndex == 1) {

                    col.economy.addAll(Titles);
                    col.economy.size()+"");
                    col.rssRsult.add(col.economy);

                }

                if (col.yIndex == 2) {

                    col.sports.addAll(Titles);
                    col.sports.size()+"");
                    col.rssRsult.add(col.sports);
                }
            }

        }// end of y loop
        return col;
    }


    @Override
    protected void onPreExecute() 
    {
        if(threadIsFinishedcounter==wpObjects.size())
            threadIsFinishedcounter=0;
    }


    @Override
    protected void onPostExecute(Collecter coll) 
    {   
        if(indexofwp<wpObjects.size())
       {

        wpObjects.get(indexofwp).NewsTitles.addAll(coll.rssRsult.get(0));
        wpObjects.get(indexofwp).EconomicsTitles.addAll(coll.rssRsult.get(1))
        wpObjects.get(indexofwp).SportssTitles.addAll(coll.rssRsult.get(2));
        threadIsFinishedcounter++;
        }

我以为我的自定义适配器可能有问题,但没有发现任何问题:

public class MyCostumedAdapter extends BaseAdapter
{
   Context context;
   ArrayList<WebPage> wp;
   public MyCostumedAdapter(Context context , ArrayList<WebPage> wp) 
   {
    super();
    this.context = context;
    this.wp=wp;
   }

@Override
public int getCount() 
{
    return wp.size();
}
@Override
public Object getItem(int position) 
{
    return wp.get(position);
}

@Override
public long getItemId(int position) 
{
    return 0;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) 
{
    View rowView;

    if(convertView==null)
    {
        LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        rowView= inflater.inflate(R.layout.lvlayout, null);
    }
    else
    {
        final WebPage currentwp=wp.get(position);
        rowView=convertView;

        ImageView imag=(ImageView)rowView.findViewById(R.id.imageView1);
        imag.setImageResource(currentwp.getIcon());


        Button newsButton=(Button)rowView.findViewById(R.id.AllnewsButton);
        newsButton.setOnClickListener(new View.OnClickListener() 
        {
            @Override
            public void onClick(View v) 
            {
                Intent intent=new Intent(context,NewHeadlines.class);
                intent.putExtra("newsbutton",currentwp.getNewsTitles());//to pass information to next activity
                context.startActivity(intent);


            }
        });
        Button economicsButton=(Button)rowView.findViewById(R.id.AllEconomicsButton);
        economicsButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) 
            {
                Intent intent=new Intent(context,NewHeadlines.class);
                intent.putExtra("economicbutton",currentwp.getEconomicsTitles());//to pass information to next activity
                context.startActivity(intent);
            }
        });
        Button sportsButton=(Button)rowView.findViewById(R.id.AllSportsButton);
        sportsButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) 
            {
                Intent intent=new Intent(context,NewHeadlines.class);
                intent.putExtra("sportsbutton",currentwp.getSportssTitles());//to pass information to next activity
                context.startActivity(intent);
            }
        });
        TextView firstNewsTitle=(TextView)rowView.findViewById(R.id.firstnewsTitle);
        firstNewsTitle.setText(currentwp.getNewsTitles().get(0));
        TextView firstEconomicsTitle=(TextView)rowView.findViewById(R.id.firsteconomicsTitle);
        firstEconomicsTitle.setText(currentwp.getEconomicsTitles().get(0));
        TextView firstSportsTitle=(TextView)rowView.findViewById(R.id.firstSportsTitle);
        firstSportsTitle.setText(currentwp.getSportssTitles().get(0));      
    }        
    return rowView;
}
}

主要布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="326dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:src="@drawable/ic_launcher" />

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

    <Button
        android:id="@+id/AllnewsButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/News" />

    <TextView
        android:id="@+id/firstnewsTitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="TextView" />
</LinearLayout>

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

    <Button
        android:id="@+id/AllEconomicsButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/Economic" />

    <TextView
        android:id="@+id/firsteconomicsTitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="TextView" />
</LinearLayout>

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

    <Button
        android:id="@+id/AllSportsButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/Sports" />

    <TextView
        android:id="@+id/firstSportsTitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="TextView" />
  </LinearLayout  >
 </LinearLayout   > 

每个ListView 行:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="326dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:src="@drawable/ic_launcher" />

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

    <Button
        android:id="@+id/AllnewsButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/News" />
    <TextView
        android:id="@+id/firstnewsTitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="TextView" />
</LinearLayout>
<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >
    <Button
        android:id="@+id/AllEconomicsButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/Economic" />

    <TextView
        android:id="@+id/firsteconomicsTitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="TextView" />
 </LinearLayout>

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

    <  Button
        android:id="@+id/AllSportsButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/Sports" />
      <  TextView
        android:id="@+id/firstSportsTitle"  
        android:layout_width="match_parent"  
        android:layout_height="wrap_content"  
        android:text="TextView" />
  </LinearLayout>   
</LinearLayout>

【问题讨论】:

  • 您实际上可以将一个字符串数组直接传入 AsyncTask 并在那里处理循环。

标签: android android-asynctask


【解决方案1】:

你应该将你的数组传递给构造函数,然后在那里操作和处理它。我确信您可以将您的数组发送到您的参数中,但是您应该像目前一样使您的 Asynktask 具有不同的 fr 字符串值。所以最简单和最好的方法是:

int indexofwp;
List<String> allResult = new ArrayList<String>()
public getParseData(int    indexofwp, List<String> allResult) 
{
    super();
    this.indexofwp = indexofwp;
    This.allResult=allResult;
}

仅此而已。 问候。

【讨论】:

  • 谢谢,但我需要更好地理解您的意思是传递我创建的 wpobjects 的数组列表?该列表中的每个对象都有 3 个数组列表要从后台解析中的 do 提供,所以我想也许可以在构造函数中传递这 3 个数组列表
  • 您能解释一下我在 asynctask 构造函数中传递的内容和我在执行参数中传递的内容之间的用途吗?
  • 当然。如果你传入 Asynctask 构造函数参数,你可以像现在一样保留 Asynctask,这意味着:AsyncTask,你可以只将数组传递给构造函数。但是如果你想在执行参数中做,你必须将你的 Asynctask 定义更改为: extends AsyncTask, Void, ArrayList>... 如果我是你,那有点复杂,我使用构造函数选项。问候
  • 这个答案可以解释得更好更详细:stackoverflow.com/questions/4195609/…
猜你喜欢
  • 1970-01-01
  • 2018-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-21
  • 1970-01-01
  • 2021-04-07
相关资源
最近更新 更多