简体   繁体   English

android:ArrayAdapter 在 AsyncTask 中只执行一次

[英]android: ArrayAdapter executing only one time in AsyncTask

I'm parsing a JSon file which has 5 football teams and each of them have played 4 games.我正在解析一个 JSon 文件,其中有 5 个足球队,每个球队都打了 4 场比赛。
I created a Wrapper class OutputClass to store all the details of each team ie number of games played, won, drawn and lost.我创建了一个 Wrapper 类OutputClass来存储每个团队的所有详细信息,即玩、赢、平和输的游戏数量。
Since there are 5 teams, I created a List of OutputClass .由于有 5 个团队,我创建了一个 List of OutputClass So after passing the value to onPostExecute , I invoke an adapter called FootballAdapter .因此,在将值传递给onPostExecute ,我调用了一个名为FootballAdapter的适配器。 This adapter is executed only one time.这个适配器只执行一次。
Even if I change my position value to 2 or 3 in outputClassList.get(int position) , I get the same result in Toast as you can see in the image below.即使我在outputClassList.get(int position)我的位置值更改为 2 或 3,我在Toast中也会得到相同的结果,如下图所示。
I checked if the outputClassList is empty but its not.我检查了outputClassList是否为空,但不是。 Objects is a list, that is passed from: Objects 是一个列表,从以下位置传递:

FootballAdapter adapter= new FootballAdapter(getApplicationContext(),R.layout.row,result);
        jsonList.setAdapter(adapter);

The above code is in onPostExecute method of AsyncTask .上面的代码在AsyncTask onPostExecute方法中。

public class JSONTask extends AsyncTask<String,String,List<OutputClass>> {

    @Override
    protected List<OutputClass> doInBackground(String... params) {
        HttpURLConnection connection=null;
        BufferedReader r=null;

        try {
            URL url=new URL(params[0]);

            connection=(HttpURLConnection)url.openConnection();
            connection.connect();
            InputStream stream= connection.getInputStream();
            r= new BufferedReader(new InputStreamReader((stream)));
            StringBuffer stringBuffer=new StringBuffer();
            String line="";
            while((line=r.readLine())!=null){
                stringBuffer.append(line);
            }

            String finalJSON=stringBuffer.toString();


            /// read and parse JSON file for desired output.....

            JSONObject parentObject= new JSONObject(finalJSON);

            // gets the name of all the objects namels alpha, bravo charlie etc etc
            JSONArray names=parentObject.names();

            // multiple objets for each team.....
            List<OutputClass> outputClassList =new ArrayList<>();

            String games[]=new String[4];
            int finalScore[]=new int[names.length()];
            int gd[]=new int[names.length()];
            int won[]=new int[names.length()];
            int draw[]=new int[names.length()];
            int lost[]=new int[names.length()];



            JSONObject[] mainObject=new JSONObject[names.length()];
            for(int i=0;i<names.length();i++){

                String teamName=names.getString(i);
                mainObject[i]=parentObject.getJSONObject(teamName);

                //outputClass[i].name=teamName;
                // Gets the game data for each game....

                games[0]=mainObject[i].getString("match_1");
                games[1]=mainObject[i].getString("match_2");
                games[2]=mainObject[i].getString("match_3");
                games[3]=mainObject[i].getString("match_4");

                // Calculates the final score and goal difference for each team.

                for(int j=0;j<4;j++) {
                    String score[] = games[j].split("-");
                    int score1 = Integer.parseInt(score[0]);
                    int score2 = Integer.parseInt(score[1]);

                    if (score1 > score2) {
                        finalScore[i] += 3;
                        won[i]++;
                    }
                    else if (score1 == score2) {
                        finalScore[i] += 1;
                        draw[i]++;
                    }else{
                        lost[i]++;
                    }
                    gd[i]+=score1-score2;

                }



                // Calculating the position based on final score and Goal Difference...

                OutputClass outputClass=new OutputClass();
                outputClass.goalDifference=gd[i];
                outputClass.draw=draw[i];
                outputClass.finalScore=finalScore[i];
                outputClass.lost=lost[i];
                outputClass.won=won[i];
                outputClass.played=4;
                outputClass.name=teamName;

                outputClassList.add(outputClass);


            }
            //Arrays.sort(outputClass,OutputClass.FinalScoreComparator);
            //Arrays.sort(outputClass,new OutputClass().FinalScoreComparator);
            Collections.sort(outputClassList,new OutputClass().FinalScoreComparator);

            Log.i(TAG,"Final Scre: "+outputClassList.get(0).finalScore+" won : "+outputClassList.get(0).won);
            Log.i(TAG,"Final Scre: "+outputClassList.get(1).finalScore+" won : "+outputClassList.get(1).won);
            Log.i(TAG,"Final Scre: "+outputClassList.get(2).finalScore+" won : "+outputClassList.get(2).won);
            Log.i(TAG,"Final Scre: "+outputClassList.get(3).finalScore+" won : "+outputClassList.get(3).won);
            //return stringBuffer.toString();
            return outputClassList;

        } catch (MalformedURLException e) {
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {
            if(connection != null)
                connection.disconnect();
            try {
                if(r!=null)
                    r.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }


    @Override

    protected void onPostExecute(List<OutputClass> result){
        super.onPostExecute(result);

        FootballAdapter adapter= new FootballAdapter(getApplicationContext(),R.layout.row,result);
        jsonList.setAdapter(adapter);

        //to remove the button and text view after clicking them...
        imageButton.setVisibility(View.GONE);
        jsonData.setVisibility(View.GONE);
        //showing the list.....
        setContentView(jsonList);


    }


}

public class FootballAdapter extends ArrayAdapter<OutputClass>{

    private List<OutputClass> outputClassList;
    private int resource;
    private LayoutInflater inflater;

    public FootballAdapter(Context context, int resource, List<OutputClass> objects) {
        super(context, resource, objects);
        outputClassList = objects;
        this.resource=resource;
        inflater =(LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
    }

    @NonNull
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if(convertView== null)
            convertView=inflater.inflate(R.layout.row,null);


        TextView rank;
        TextView played;
        TextView won;
        TextView lost;
        TextView draw;
        TextView gd;

        rank=(TextView)findViewById(R.id.rank);
        played=(TextView)findViewById(R.id.played);
        won=(TextView)findViewById(R.id.won);
        lost=(TextView)findViewById(R.id.lost);
        draw=(TextView)findViewById(R.id.draw);
        gd=(TextView)findViewById(R.id.gd);

        if(rank!=null)
            played.setText("Played: " + outputClassList.get(position).played);
        if(won!=null)
            won.setText("Won: " + outputClassList.get(position).won);
        if(lost!=null)
            lost.setText("Lost: " + outputClassList.get(position).lost);
        if(draw!=null)
            draw.setText("Draw: " + outputClassList.get(position).draw);
        if(gd!=null)
            gd.setText("Goal Diff: " + outputClassList.get(position).goalDifference);


        Toast toast=Toast.makeText(getApplicationContext(),"Played: "+outputClassList.get(4).played+"Won: "+outputClassList.get(4).won,Toast.LENGTH_LONG);
        toast.show();
        return convertView;
    }
}

This is the log file that i created ot check if the outputClassList is empty or not :这是我创建的日志文件,用于检查 outputClassList 是否为空:

I/enpFootball: Final Scre: 8 won : 2
I/enpFootball: Final Scre: 7 won : 2
I/enpFootball: Final Scre: 7 won : 2
I/enpFootball: Final Scre: 5 won : 1

A snipped of ListView can be seen at the image below:在下图中可以看到ListView一个片段:

在此处输入图片说明

The problem is probably in the line问题可能出在线路上

rank=(TextView)findViewById(R.id.rank);

ArrayAdapter does not have findViewById() (see ArrayAdapter Reference ) ArrayAdapter 没有 findViewById()(请参阅ArrayAdapter 参考

Since the above line is working, you probably have your FootballAdapter class defined as a nested class inside a context (eg Activity or Fragment) from which it is using the findViewById() method.由于上述行有效,您可能将 FootballAdapter 类定义为上下文(例如 Activity 或 Fragment)中的嵌套类,从中使用 findViewById() 方法。 In this case, you will be searching for the "first" widget with the specified id in the entire context.在这种情况下,您将在整个上下文中搜索具有指定 id 的“第一个”小部件。 So, your adapter is infact executing for all the items in the list, but each time it is called, it overwrites the first widget (eg the first. R.id.rank, and the first R.id.played, etc.)因此,您的适配器实际上正在为列表中的所有项目执行,但是每次调用它时,它都会覆盖第一个小部件(例如第一个。R.id.rank 和第一个 R.id.played 等)

Try this instead试试这个

rank= (TextView) convertView.findViewById(R.id.rank);

This way you are referring to the TextView inside the List Item that the adapter is supposed to fill and not the first item in the entire context.通过这种方式,您指的是适配器应该填充的列表项内的 TextView,而不是整个上下文中的第一项。 (See View Reference ) (见 查看参考

尝试打印 postexecute() 的结果,看看你在 postupdate 中得到了什么,之后你就会知道问题到底是什么,如果你不能理解,那么再次发布一些关于你的响应和适配器的更多信息班级

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM