Android:无法正确显示RecyclerView

huangapple go评论75阅读模式
英文:

Android: Fails to display RecyclerView correctly

问题

public class RecipeSearch extends MainActivity {

    EditText searchText;
    Spinner typeSpinner;
    List<com.stu54259.plan2cook.Model.Category> searchList = new ArrayList<>();
    SQLiteDatabase db;
    Cursor c;
    String searchType;
    RecyclerView listSearch;
    RecipeSearchAdapter adapterRecipe;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recipe_search);
        Button Search = (Button)findViewById(R.id.btnSearch);

        Search.setOnClickListener(view -> RecipeSearch());
        adapterRecipe = new RecipeSearchAdapter(this, searchList);
        listSearch = findViewById(R.id.listSearch);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this,
                LinearLayoutManager.VERTICAL, false);
        listSearch.setLayoutManager(mLayoutManager);
        listSearch.setItemAnimator(new DefaultItemAnimator());
        listSearch.setAdapter(adapterRecipe);

    }
    public void RecipeSearch() {
        searchList.clear();
        searchText = findViewById(R.id.editSearch);
        typeSpinner = (Spinner) findViewById(R.id.typeSpinner);
        searchType = typeSpinner.getSelectedItem().toString();
        db = (new DatabaseManager(this).getWritableDatabase());
        String RECIPE_SEARCH = " SELECT A.recipe_name, A.image, A.image2, A.category, A.preparation_time, A.cost, B.ingredient " +
                "FROM " + DatabaseManager.TABLE_RECIPE + " AS A JOIN " + DatabaseManager.TABLE_QUANTITY + " AS B ON A.recipe_name = B.recipe";
        String selectQuery = "";
        selectQuery = RECIPE_SEARCH + " WHERE " + searchType + " LIKE ?";
        c = db.rawQuery(selectQuery, new String[]{"%" + searchText + "%"});
        if (c.moveToFirst()) {
            do {
                com.stu54259.plan2cook.Model.Category category = new com.stu54259.plan2cook.Model.Category();
                category.setRecipe_name(c.getString(c.getColumnIndex("recipe_name")));
                category.setImage(c.getInt(c.getColumnIndex("image")));
                category.setImage2(c.getString(c.getColumnIndex("image2")));
                category.setCategory_name(c.getString(c.getColumnIndex("category")));
                searchList.add(category);
            } while (c.moveToNext());
            c.close();
        }

    }

}

public class RecipeSearchAdapter extends RecyclerView.Adapter<RecipeSearchAdapter.ViewHolder> {

    private List<Category> searchList;
    private LayoutInflater mInflater;
    private com.stu54259.plan2cook.RecipeCategoryAdapter.ItemClickListener mClickListener;

    RecipeSearchAdapter(Context context, List<Category> data) {
        this.mInflater = LayoutInflater.from(context);
        this.searchList = data;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.cardview_recipe, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.myTextView1.setText(searchList.get(position).getRecipe_name());
        holder.myTextView2.setText(searchList.get(position).getCategory_name());
        String image2 = searchList.get(position).getImage2();
        Bitmap myBitmap = BitmapFactory.decodeFile(image2);
        if (myBitmap != null)
            holder.imgImage.setImageBitmap(myBitmap);
        else
            holder.imgImage.setImageResource(searchList.get(position).getImage());
    }

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

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        TextView myTextView1;
        TextView myTextView2;
        ImageView imgImage;

        ViewHolder(View itemView) {
            super(itemView);
            myTextView1 = itemView.findViewById(R.id.txtName);
            myTextView2 = itemView.findViewById(R.id.txtCategory);
            imgImage = itemView.findViewById(R.id.imgImage);
            itemView.setOnClickListener(this);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(view.getContext(), Recipe.class);
                    intent.putExtra("NAME", myTextView1.getText().toString());
                    view.getContext().startActivity(intent);
                }
            });
        }

        @Override
        public void onClick(View v) {

        }
    }

    void setClickListener(RecipeCategoryAdapter.ItemClickListener itemClickListener) {
        this.mClickListener = itemClickListener;
    }

    public interface ItemClickListener {
        void onItemClick(View view, int position);
    }
}

请注意,代码中有一些变量和类的引用,这些可能需要根据您的项目结构进行适当的更改。

英文:

I am attempting to view the results of the sql search then display the results in a recyclerview, however when I press the button nothing happens. Debugging shows button press is acknowledged but does nothing.

Main class

public class RecipeSearch extends MainActivity {
EditText searchText;
Spinner typeSpinner;
List&lt;com.stu54259.plan2cook.Model.Category&gt; searchList = new ArrayList&lt;&gt;();
SQLiteDatabase db;
Cursor c;
String searchType;
RecyclerView listSearch;
RecipeSearchAdapter adapterRecipe;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recipe_search);
Button Search = (Button)findViewById(R.id.btnSearch);
Search.setOnClickListener(view -&gt; RecipeSearch());
adapterRecipe = new RecipeSearchAdapter(this, searchList);
listSearch = findViewById(R.id.listSearch);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this,
LinearLayoutManager.VERTICAL, false);
listSearch.setLayoutManager(mLayoutManager);
listSearch.setItemAnimator(new DefaultItemAnimator());
listSearch.setAdapter(adapterRecipe);
}
public void RecipeSearch() {
searchList.clear();
searchText = findViewById(R.id.editSearch);
typeSpinner = (Spinner) findViewById(R.id.typeSpinner);
searchType = typeSpinner.getSelectedItem().toString();
db = (new DatabaseManager(this).getWritableDatabase());
String RECIPE_SEARCH = &quot; SELECT A.recipe_name, A.image, A.image2, A.category, A.preparation_time, A.cost, B.ingredient &quot; +
&quot;FROM &quot; + DatabaseManager.TABLE_RECIPE + &quot; AS A JOIN &quot; + DatabaseManager.TABLE_QUANTITY + &quot; AS B ON A.recipe_name = B.recipe&quot;;
String selectQuery = &quot;&quot;;
selectQuery = RECIPE_SEARCH + &quot; WHERE &quot; + searchType + &quot; LIKE ?&quot;;
c = db.rawQuery(selectQuery, new String[]{&quot;%&quot; + searchText + &quot;%&quot;});
if (c.moveToFirst()) {
do {
com.stu54259.plan2cook.Model.Category category = new com.stu54259.plan2cook.Model.Category();
category.setRecipe_name(c.getString(c.getColumnIndex(&quot;recipe_name&quot;)));
category.setImage(c.getInt(c.getColumnIndex(&quot;image&quot;)));
category.setImage2(c.getString(c.getColumnIndex(&quot;image2&quot;)));
category.setCategory_name(c.getString(c.getColumnIndex(&quot;category&quot;)));
searchList.add(category);
} while (c.moveToNext());
c.close();
}
}

}

Recycler adapter

public class RecipeSearchAdapter extends RecyclerView.Adapter<RecipeSearchAdapter.ViewHolder> {

private List&lt;Category&gt; searchList;
private LayoutInflater mInflater;
private com.stu54259.plan2cook.RecipeCategoryAdapter.ItemClickListener mClickListener;
// data is passed into the constructor
RecipeSearchAdapter(Context context, List&lt;Category&gt; data) {
this.mInflater = LayoutInflater.from(context);
this.searchList = data;
}
// inflates the row layout from xml when needed
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.cardview_recipe, parent, false);
return new ViewHolder(view);
}
/**
* Called by RecyclerView to display the data at the specified position. This method should
* update the contents of the {@link ViewHolder#itemView} to reflect the item at the given
* position.
* &lt;p&gt;
* Note that unlike {@link ListView}, RecyclerView will not call this method
* again if the position of the item changes in the data set unless the item itself is
* invalidated or the new position cannot be determined. For this reason, you should only
* use the &lt;code&gt;position&lt;/code&gt; parameter while acquiring the related data item inside
* this method and should not keep a copy of it. If you need the position of an item later
* on (e.g. in a click listener), use {@link ViewHolder#getAdapterPosition()} which will
* have the updated adapter position.
* &lt;p&gt;
* Override {@link #onBindViewHolder(ViewHolder, int, List)} instead if Adapter can
* handle efficient partial bind.
*
* @param holder   The ViewHolder which should be updated to represent the contents of the
*                 item at the given position in the data set.
* @param position The position of the item within the adapter&#39;s data set.
*/
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
holder.myTextView1.setText(searchList.get(position).getRecipe_name());
holder.myTextView2.setText(searchList.get(position).getCategory_name());
String image2 = searchList.get(position).getImage2();
Bitmap myBitmap = BitmapFactory.decodeFile(image2);
if (myBitmap != null)
holder.imgImage.setImageBitmap(myBitmap);
else
holder.imgImage.setImageResource(searchList.get(position).getImage());
}
// total number of rows
@Override
public int getItemCount() {
return searchList.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView myTextView1;
TextView myTextView2;
ImageView imgImage;
ViewHolder(View itemView) {
super(itemView);
myTextView1 = itemView.findViewById(R.id.txtName);
myTextView2 = itemView.findViewById(R.id.txtCategory);
imgImage = itemView.findViewById(R.id.imgImage);
itemView.setOnClickListener(this);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(),Recipe.class);
intent.putExtra(&quot;NAME&quot;, myTextView1.getText().toString()); //you used recipe name with this id (myTextView1) so.
view.getContext().startActivity(intent);
}
});
}
/**
* Called when a view has been clicked.
*
* @param v The view that was clicked.
*/
@Override
public void onClick(View v) {
}
}
// allows clicks events to be caught
void setClickListener(RecipeCategoryAdapter.ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}

}

答案1

得分: 1

更改按钮的监听器:

Search.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        RecipeSearch();
        adapterRecipe.notifyDataSetChanged();
    }
});

以便通知RecyclerView的适配器列表已更改,必须进行刷新。

还要更改此行:

c = db.rawQuery(selectQuery, new String[]{"%" + searchText + "%"});

为:

c = db.rawQuery(selectQuery, new String[]{"%" + searchText.getText().toString() + "%"});

因为searchText是一个EditText,您必须获取其文本以传递给查询。

英文:

Change the button's listener:

Search.setOnClickListener(view -&gt; RecipeSearch());

to:

Search.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
RecipeSearch();
adapterRecipe.notifyDataSetChanged();
}
});

so that the RecyclerView's adapter is notified that the list has changed and it must refresh.<br/>

Also change this line:

c = db.rawQuery(selectQuery, new String[]{&quot;%&quot; + searchText + &quot;%&quot;});

to:

c = db.rawQuery(selectQuery, new String[]{&quot;%&quot; + searchText.getText().toString() + &quot;%&quot;});

because searchText is an EditText and you must get its text to pass to the query.

huangapple
  • 本文由 发表于 2020年9月24日 02:11:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/64033942.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定