将RecyclerView和CardAdapter连接到数据库的问题

时间:2018-02-10 20:00:06

标签: java android android-recyclerview

所以我的问题出现在库片段中的上下文。我收到以下错误。

  

CardAdapter(Android.content.Context,位于ArrayList<Card>中   CardAdapter无法应用于资源库ArrayList<Card>

我很幸运地从朋友那里得到了一些代码,但我们似乎无法弄清楚其中的差异/错误。

Library.java

public class Library extends Fragment {

    // Private variables
    private RecyclerView recyclerView;
    private CardAdapter cardAdapter;
    private ArrayList<Card> cardArrayList;
    private ArrayList<Card> tempList;

    public Library() {}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate view
        View view = inflater.inflate(R.layout.library, container, false);

        // Find recyclerView
        recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);

        // Initialize cardArrayList
        cardArrayList = new ArrayList<>();

        // Initialize cardAdapter
        cardAdapter = new CardAdapter(this.getContext(), cardArrayList);

        // Initialize recyclerView
        RecyclerView.LayoutManager layoutManager = new GridLayoutManager(this.getContext(), 1);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(cardAdapter);

        // Populate cardArrayList with test Cards
        testCards();

        // Return inflated view
        return view;
    }

    public URL createURL(String constraint) {
        try {
            StringBuilder urlString = new StringBuilder();
            //System.out.print(constraint);
            if (constraint.length() > 0) {
                urlString.append("https://camerondewey.000webhostapp.com/android_podcast_connect.php");
                urlString.append(constraint);
                System.out.print(urlString.toString());
            }
            String muhURL = urlString.toString();
            //System.out.print(muhURL);
            URL myURL = new URL(muhURL);
            System.out.print(myURL);
            return myURL;
            //return new URL(muhURL);
        } catch (Exception e) {
            System.out.print("Failed to return url");
        }
        return null;
    }

    public class GetCardTask extends AsyncTask<URL, Void, JSONArray> {

        @Override
        protected JSONArray doInBackground(URL... params) {
            //System.out.print("Params: " + params[0]);
            HttpURLConnection connection = null;
            StringBuilder result = new StringBuilder();
            try {
                connection = (HttpURLConnection) params[0].openConnection();
                //System.out.println(connection.getResponseCode());
                if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(connection.getInputStream()));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }
                    try {
                        //System.out.print("SUCCESS");
                        return new JSONArray(result.toString());
                    } catch (JSONException je) {
                        //System.out.print("FAILURE2");
                        JSONArray jArray = new JSONArray();
                        jArray.put(new JSONObject(result.toString()));
                        return jArray;
                    }
                } else {
                    throw new Exception();
                }
            } catch (Exception e) {
                System.out.print("FAILURE1");
                e.printStackTrace();
            } finally {
                connection.disconnect();
            }
            return null;
        }

        @Override
        protected void onPostExecute(JSONArray article) {
            if (article != null) {
                convertJSONtoArrayList(article);
                Library.this.updateDisplay();
            } else {
                System.out.print("failure to execute json conversion");
            }
        }
    }

    private void convertJSONtoArrayList(JSONArray articles) {
        cardArrayList = new ArrayList<Card>(); // clear old player data
        tempList = new ArrayList<Card>();
        try {
            for (int i = 0; i < articles.length(); i++) {
                JSONObject currentArticle = articles.getJSONObject(i);
                cardArrayList.add(new Card(
                        currentArticle.has("name") ? currentArticle.getString("name") : "No Headline",
                        currentArticle.has("description") ? currentArticle.getString("description") : "No Name"
                        ));
                tempList.add(new Card(
                        currentArticle.has("name") ? currentArticle.getString("name") : "No Headline",
                        currentArticle.has("description") ? currentArticle.getString("description") : "No Name"
                ));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void updateDisplay() {
        if (cardArrayList == null) {
            System.out.print("Display failed to update");
        }
        ArrayList<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();
        for (Card item : cardArrayList) {
            HashMap<String, String> map = new HashMap<String, String>();
            map.put("name", item.getCardName());
            map.put("description", item.getDescription());
            data.add(map);
        }

        int resource = R.layout.card;
        String[] from = {"name", "description"};
        int[] to = {R.id.card_name, R.id.podcast_desc};
//The error happens here.
        CardAdapter cardAdapter = new CardAdapter(this, cardArrayList);
        recyclerView.setAdapter(cardAdapter);

        cardAdapter.notifyDataSetChanged();
    }

CardAdapter.java

public class CardAdapter extends RecyclerView.Adapter<CardAdapter.CardViewHolder> implements Filterable {

    // Private variables
    private Context cardContext;
    ArrayList<Card> cardList, filteredList;

    public class CardViewHolder extends RecyclerView.ViewHolder{
        public View view;
        public TextView cardName;
        public Card currentItem;

        public CardViewHolder(View v) {
            // Invoke super on view
            super(v);
            view = v;
            this.cardName = (TextView) v.findViewById(R.id.card_name);
            v.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View v){
                    Intent i = new Intent(v.getContext(),PodcastPage.class);
                    //item clicked
                    v.getContext().startActivity(i);
                }
            });
            // Find cardText
            cardName = (TextView) view.findViewById(R.id.card_name);
        }
    }

    public CardAdapter(Context c, ArrayList<Card> l) {
        this.cardContext = c;
        this.cardList = l;
        this.filteredList = l;
    }

    @Override
    public CardViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card, null);
        return new CardViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final CardViewHolder holder, int position) {
        Card card = cardList.get(position);
        holder.currentItem = cardList.get(position);
        holder.cardName.setText(card.getCardName());
    }

    @Override
    public int getItemCount() {
        return filteredList.size();
    }

    @Override
    public Filter getFilter() {
        return new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence query) {
                FilterResults results = new FilterResults();
                if (query != null && query.length() > 0) {
                    query = query.toString().toUpperCase();
                    ArrayList<Card> searchResults = new ArrayList<Card>();
                    for (int i = 0; i < filteredList.size(); i++) {
                        if (filteredList.get(i).getCardName().toUpperCase().contains(query)) {
                            searchResults.add(filteredList.get(i));
                        }
                        else if (filteredList.get(i).getDescription().toUpperCase().contains(query)) {
                            searchResults.add(filteredList.get(i));
                        }
                    }
                    results.count = searchResults.size();
                    results.values = searchResults;
                }
                else {
                    results.count = filteredList.size();
                    results.values = filteredList;
                }
                return results;
            }

            @Override
            protected void publishResults(CharSequence query, FilterResults results) {
                filteredList = (ArrayList<Card>) results.values;
                notifyDataSetChanged();
                System.out.println(filteredList);
            }
        };
    }
}

1 个答案:

答案 0 :(得分:1)

CardAdapter cardAdapter = new CardAdapter(this, cardArrayList); this行中的代码不是Context,而是Fragment。将行更改为:

CardAdapter cardAdapter = new CardAdapter(getActivity(), cardArrayList);