【问题标题】:How to pass multiple ArrayList to BaseAdapter in Android?如何在 Android 中将多个 ArrayList 传递给 BaseAdapter?
【发布时间】:2017-12-06 06:31:14
【问题描述】:

我正在尝试将一些动态数据传递给BaseAdapter 以在listview 上显示它。(使用ArrayList),我当前的代码给了我以下错误:

错误:

error: cannot find symbol variable ArrayList
error: cannot find symbol variable String

指向这部分代码(ArrayList ):

CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), ArrayList<String> NameArrayList, ArrayList<String> IconArrayList);

我检查了 Arraylist 的大小,发现 IconArrayList 和 NameArrayList 不为空,使用 int itemCount = IconArrayList.size();

但是,如果我将以下静态字符串数组传递给 Baseadapter,那么它将在 listview 上显示数据!

String NameArrayList[] = {"USA", "China", "australia", "Portugle", "Norway", "NewZealand"};
String IconArrayList[] = {"http://awebsite.com/icons/usa.png", "http://awebsite.com/icons/china.png", "http://awebsite.com/icons/australia.png", "http://awebsite.com/icons/portugle.png", "http://awebsite.com/icons/norway.png", "http://awebsite.com/icons/new_zealand.png"};

CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), NameArrayList, IconArrayList);

你们能帮我解决上述错误并成功将arraylist传递给baseAdapter以便显示它。提前致谢。

MainActivity.java:

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;

import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;

import android.os.StrictMode;
import android.os.StrictMode.ThreadPolicy.Builder;

import java.io.InputStreamReader;

import java.net.URL;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.io.BufferedReader;

import java.util.ArrayList;

public class MainActivity extends Activity {

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

        sendGetRequest();

     }


public String sendGetRequest() {

         String NEW_ICON = "icon";


        ArrayList<String> IconArrayList =new ArrayList<String>();
        ArrayList<String> NameArrayList =new ArrayList<String>();
        ArrayList<String> UrlArrayList =new ArrayList<String>();


        try {

            StrictMode.setThreadPolicy(new Builder().permitAll().build());

            HttpURLConnection myURLConnection = (HttpURLConnection) new URL("http://awebsite.com/test/test.php").openConnection();


            myURLConnection.setReadTimeout(60000);
            myURLConnection.setConnectTimeout(60000);
            myURLConnection.setRequestMethod("GET");
            myURLConnection.setUseCaches(false);
            myURLConnection.setDoInput(true);
            myURLConnection.setDoOutput(true);
            myURLConnection.setRequestProperty("Content-Type", "html");
            myURLConnection.setRequestProperty("User-Agent", "Dalvik/2.1.0 (Linux; U; Android 6.0;)");

            OutputStream os = myURLConnection.getOutputStream();

            os.close();

            myURLConnection.connect();

            BufferedReader in = new BufferedReader(new InputStreamReader(myURLConnection.getInputStream()));


            StringBuffer sb = new StringBuffer();

            String line;


            while ((line = in.readLine()) != null) {

                sb.append(line);
                sb.append("\\n");
            }
            in.close();



            String linesArray[] = sb.toString().split("#MYLIST:");

            for (int i = 0; i < linesArray.length; i++) {
                String currLine = linesArray[i];


                String[] dataArray = currLine.split(",");

                if (dataArray[0].contains(NEW_ICON)) {

                   String s =dataArray[0];

                    s = s.substring(s.indexOf("(") + 1);
                    s = s.substring(0, s.indexOf(")"));


                    IconArrayList.add(s);



                    if (dataArray[1].contains("http://")) {
                        String[] split = dataArray[1].split("http://");
                        String name = split[0];
                        String url = split[1];
                        url ="http://"+url;

                        //adding name and url to arraylist
                        NameArrayList.add(name);
                        UrlArrayList.add(url);
                      }


                }



            }// end of for loop

            //showing array list total
            int itemCount = IconArrayList.size();
            int itemCount2 = NameArrayList.size();
            int itemCount3 = UrlArrayList.size();


            ListView simpleList;
            simpleList = (ListView) findViewById(R.id.simpleListView);
            CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), ArrayList<String> NameArrayList, ArrayList<String> IconArrayList);
            simpleList.setAdapter(customAdapter);


        } catch (Exception e) {

        }
        return null;

    }

基础适配器:

public class CustomAdapter extends BaseAdapter {
    Context context;
    String countryList[];

    String flags[];

    LayoutInflater inflter;

    public CustomAdapter(Context applicationContext, String[] countryList, String[] flags) {
        this.context = context;
        this.countryList = countryList;
        this.flags = flags;
        inflter = (LayoutInflater.from(applicationContext));
    }

    @Override
    public int getCount() {
        return countryList.length;
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

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

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        view = inflter.inflate(R.layout.activity_listview, null);
        TextView country = (TextView) view.findViewById(R.id.textView);
        ImageView icon = (ImageView) view.findViewById(R.id.icon);
        country.setText(countryList[i]);

        Picasso.with(view.getContext())
                .load(flags[i])
                //.resize(50,50)
                .into(icon);

        return view;
    }
}

【问题讨论】:

    标签: android listview arraylist baseadapter


    【解决方案1】:

    您正在发送 WRONG TYPE

    CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), ArrayList<String> NameArrayList, ArrayList<String> IconArrayList);
    

    会的

     CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(),  NameArrayList,  IconArrayList);
    

    所以,你的 Constructor 将是

    ArrayList<String> countryList;
    ArrayList<String> flags;
    
    public CustomAdapter(Context applicationContext,ArrayList<String> countryListOBJ, ArrayList<String> flagsOBJ) {
            this.context = context;
            this.countryList = countryListOBJ;
            this.flags = flagsOBJ;
            inflter = (LayoutInflater.from(applicationContext));
        }
    

    那么

     @Override
        public int getCount() {
            return countryList.size();
        }
    

    【讨论】:

    • 感谢所有回复。 IntelliJ Amiya 我试过你的帖子,但我得到了 3 个新错误,都指向自定义适配器内的行!错误:找不到符号可变长度错误:需要数组,但找到了 ArrayList 错误:需要数组,但找到了 ArrayList
    • @user1788736 使用countryList.size() 而不是countryList.length
    • @user1788736 打印countryList.size() 。检查结果。
    • 非常感谢您帮助我,我接受了您的回答。现在数据显示在列表视图上:-)
    • 如果我想通过单击 listview 项目来显示 toast 如何引用 simpleList.setOnItemClickListener 中的 listview 行项目?
    【解决方案2】:

    这不是将多个属性传递给任何类的方法。您应该使用 POJO 类来代替它。下面是一个例子。

    class CountryModel{
        public String countryName;
        public String countryFlag;
    
        public CountryModel(String countryName, String countryFlag) {
            this.countryName = countryName;
            this.countryFlag = countryFlag;
        }
    }
    

    然后将你的数据解析成这个模型对象的集合。下面是一个例子。

     ArrayList<CountryModel> countryList=new ArrayList<>();
     countryList.add(new CountryModel("Norway","NorwayflagUrl"));
     countryList.add(new CountryModel("Iceland","IcelandflagUrl"));
     countryList.add(new CountryModel("Denmark","DenmarkflagUrl"));
    

    然后设置适配器。在这种情况下,您需要修改您的适配器。

    ListView simpleList = (ListView) findViewById(R.id.simpleListView);
            CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), countryList);
            simpleList.setAdapter(customAdapter);
    

    您可以如下修改您的适配器。

     public class CustomAdapter extends BaseAdapter {
        Context context;
       ArrayList<CountryModel> countryList;
    
        LayoutInflater inflter;
    
        public CustomAdapter(Context applicationContext, ArrayList<CountryModel> countryList) {
            this.context = context;
            this.countryList = countryList;
            inflter = (LayoutInflater.from(applicationContext));
        }
    
        @Override
        public int getCount() {
            return countryList.size();
        }
    
        @Override
        public Object getItem(int i) {
            return countryList.get(i);
        }
    
        @Override
        public long getItemId(int i) {
            return i;
        }
    
        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            view = inflter.inflate(R.layout.activity_listview, null);
            TextView country = (TextView) view.findViewById(R.id.textView);
            ImageView icon = (ImageView) view.findViewById(R.id.icon);
            country.setText(countryList.get(i).countryName);
    
            Picasso.with(view.getContext())
                    .load(countryList.get(i).countryFlag)
                    //.resize(50,50)
                    .into(icon);
            return view;
        }
    }
    

    【讨论】:

      【解决方案3】:

      1. 您在CustomAdapterconstructor 上使用了字符串数组。但是你从Activity 类中传递了ArrayList&lt;String&gt;。所以在CustomAdapter上制作这些ArrayList-

          private ArrayList<String> NameArrayList;
          private ArrayList<String> IconArrayList;
      
          public CustomAdapter(getApplicationContext(), ArrayList<String> NameArrayList, ArrayList<String> IconArrayList) {
              this.NameArrayList= NameArrayList;
              this.IconArrayList= IconArrayList;
              inflter = (LayoutInflater.from(applicationContext));
          }
      

      2.您正在通过MainThread 上的API 调用从服务器获取数据。尝试将此部分保留在单独的线程上以获得更好的性能(有时您不会从服务器获取任何数据,因为连接速度慢或处理时间长)。并使用 Handler 进行这些线程之间的通信因为您需要检测何时完成 api 调用并成功获取数据。 或者您可以使用任何第三方AndroidNetworking 库进行线程安全网络调用。

      【讨论】:

      • 感谢您的建议。你的意思是我应该使用 AsyncTask 来获取 api 数据?
      • 是的,您也可以使用AsyncTask。但是第三方库对您来说非常容易。
      【解决方案4】:

      1.改变

      CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), ArrayList NameArrayList, ArrayList IconArrayList);

      到这里

      CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(),  NameArrayList,  IconArrayList);
      

      2.改变

       @Override
      public Object getItem(int i) {
          return null;
      }
      
      @Override
      public long getItemId(int i) {
          return 0;
      }
      

      到这里

      public Object getItem(int i) {
          return i;
      }
      
      public long getItemId(int i) {
          return i;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-26
        • 1970-01-01
        • 1970-01-01
        • 2012-06-15
        • 2019-04-20
        • 2013-01-25
        相关资源
        最近更新 更多