简体   繁体   English

将图像和文本添加到android gridview

[英]Adding Images and text to android gridview

I am getting the exception when running my app. 运行我的应用程序时出现异常。 I have tried the answers given on similar question without any success as I am using a fragment 我尝试了类似问题的答案,但没有成功,因为我正在使用片段

Here is my Gridview Adapter code 这是我的Gridview适配器代码

      public class FoodGridviewAdapter extends BaseAdapter {
Context f;
ArrayList<Food> foods;

public FoodGridviewAdapter(Context f, ArrayList<Food> foods){
    this.f = f;
    this.foods = foods;
}
@Override
public int getCount() {
    return foods.size();
}
@Override
public Object getItem(int position) {
    return foods.get(position);
}
@Override
public long getItemId(int position) {
    return position;
}
@Override
public View getView(int position, View view, ViewGroup viewGroup) {
    if(view==null){
        view = LayoutInflater.from(f).inflate(R.layout.food_layout,viewGroup,false);
    }
    TextView name = view.findViewById(R.id.name);
    TextView cost = view.findViewById(R.id.cost);
    ImageView image = view.findViewById(R.id.image);
    final Food food = (Food) this.getItem(position);
    name.setText(food.getTitle());
    cost.setText(food.getCost());
    //check if there is an image returned
    if(food.getImage()!= null && food.getImage().length()>0){
        Picasso.get().load(food.getImage()).placeholder(R.drawable.foodfuzzlogo).into(image);
    }else{
        Picasso.get().load(R.drawable.foodfuzzlogo).into(image);

    }
    view.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(f, food.getTitle(),Toast.LENGTH_SHORT).show();
        }
    });

    return view;
}
}

The purpose is to pass the items to the grid view adapter and inflate it with the items 目的是将项目传递到网格视图适配器,并使用项目对其进行充气

here is my code for retrieving the items from mysql database with a php RESTful api 这是我的代码,用于使用php RESTful API从mysql数据库中检索项目

    public class DataRetriever {
private static final String URL_FOOD = "http://192.168.100.250:8082/foodfuzzbackend/auth/login.php";
private final Context f;
private FoodGridviewAdapter foodGridviewAdapter;

public DataRetriever(Context f) {
    this.f = f;
}
public void retrieveFood(final GridView gridView, final ProgressBar myprogressbar){
    final ArrayList <Food> foods = new ArrayList<>();
    myprogressbar.setIndeterminate(true);
    myprogressbar.setVisibility(View.VISIBLE);
    AndroidNetworking.get(URL_FOOD).setPriority(Priority.MEDIUM).build().getAsJSONArray(new JSONArrayRequestListener() {
        @Override
        public void onResponse(JSONArray response) {
            JSONObject jsonObject;
            Food food;
            try{
                for(int i=0; i<response.length();i++){
                    jsonObject = response.getJSONObject(i);
                    int id = jsonObject.getInt("id");
                    String name = jsonObject.getString("name");
                    String cost = jsonObject.getString("cost");
                    String image = jsonObject.getString("image");
                    food = new Food(URL_FOOD+"../images/"+ image, name, cost);
                    foods.add(food);
                }
                foodGridviewAdapter = new FoodGridviewAdapter(f,foods);
                myprogressbar.setVisibility(View.GONE);

            }catch (JSONException e){
                myprogressbar.setVisibility(View.GONE);
                e.printStackTrace();
            }
        }

        @Override
        public void onError(ANError anError) {
            myprogressbar.setVisibility(View.GONE);
            anError.printStackTrace();
        }
    });
}
}

I then have my fragment code like this 然后我有这样的片段代码

     public class Food extends Fragment {
private static final String TAG = "Food";
GridView food;
ProgressBar myprogressbar;
public Food() {

}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
   View view = inflater.inflate(R.layout.fragment_food, container, false);
    food = view.findViewById(R.id.FoodContainer);
   myprogressbar = view.findViewById(R.id.foodProgressBar);
    new DataRetriever(getActivity()).retrieveFood(food,myprogressbar);

    return view;
}
   }

Finally this is the layout of the gridview xml adapter 最后,这是gridview xml适配器的布局

    <ImageView
        android:id="@+id/image"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:padding="@dimen/margin_xsmall"
        android:src="@drawable/foodfuzzlogo"
        tools:scaleType="fitXY"
        android:contentDescription="@string/food_fuzz_logo" />

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/food"
        android:layout_below="@+id/image"
        android:maxLines="3"
        android:padding="@dimen/margin_xsmall"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:textAppearance="?android:attr/textAppearanceSmall"/>

    <TextView
        android:id="@+id/cost"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/ksh_000_00"
        android:layout_below="@+id/name"
        android:padding="@dimen/margin_xsmall"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:typeface="serif"/>

</RelativeLayout>

What could I be doing wrong and how can I correct it or who has any link that can help me achieve to pull images and text from mysql db and pass them to a gridview using php and java? 我可能在做错什么,如何纠正它,或者谁有任何链接可以帮助我实现从mysql db拉取图像和文本并将其传递给使用php和java的gridview的问题?

This is the error I get 这是我得到的错误

    android.view.InflateException: Binary XML file line #18: addView(View, LayoutParams) is not supported in AdapterView
Caused by: java.lang.UnsupportedOperationException: addView(View, LayoutParams) is not supported in AdapterView
    at android.widget.AdapterView.addView(AdapterView.java:495)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:862)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:861)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
    at com.otemainc.foodfuzzapp.fragment.Food.onCreateView(Food.java:33)
    at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2439)
    at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManager.java:1460)
    at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1784)
    at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManager.java:1852)
    at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:802)
    at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManager.java:2625)
    at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2411)
    at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2366)
    at androidx.fragment.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:2243)
    at androidx.fragment.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:654)
    at androidx.fragment.app.FragmentStatePagerAdapter.finishUpdate(FragmentStatePagerAdapter.java:168)
    at androidx.viewpager.widget.ViewPager.populate(ViewPager.java:1244)
    at androidx.viewpager.widget.ViewPager.populate(ViewPager.java:1092)
    at androidx.viewpager.widget.ViewPager.onMeasure(ViewPager.java:1622)
    at android.view.View.measure(View.java:20009)
    at androidx.constraintlayout.widget.ConstraintLayout.internalMeasureChildren(ConstraintLayout.java:1227)
    at androidx.constraintlayout.widget.ConstraintLayout.onMeasure(ConstraintLayout.java:1572)
    at android.view.View.measure(View.java:20009)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
    at androidx.coordinatorlayout.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:733)
    at com.google.android.material.appbar.HeaderScrollingViewBehavior.onMeasureChild(HeaderScrollingViewBehavior.java:95)
    at com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior.onMeasureChild(AppBarLayout.java:1556)
    at androidx.coordinatorlayout.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:803)
    at android.view.View.measure(View.java:20009)
    at androidx.drawerlayout.widget.DrawerLayout.onMeasure(DrawerLayout.java:1119)
    at android.view.View.measure(View.java:20009)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
    at androidx.appcompat.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:143)
    at android.view.View.measure(View.java:20009)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
    at android.widget.LinearLayout.measureVertical(LinearLayout.java:758)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:640)
    at android.view.View.measure(View.java:20009)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
    at android.view.View.measure(View.java:20009)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
    at android.widget.LinearLayout.measureVertical(LinearLayout.java:758)

Based on original Post : 根据原始帖子

For others who have this problem and have inflated a layout in ArrayAdapter 's getView , set the parent parameter to null , as in view = inflater.inflate(R.layout.mylayout, null); 对于其他有此问题并在ArrayAdaptergetView扩大了布局的其他人,请将parent参数设置为null ,例如在view = inflater.inflate(R.layout.mylayout, null);

除了@Zima所说的之外,我还注意到gridview adpater从未添加到适配器中,因此我将此行添加到了dataretriever类中

     gridView.setAdapter(foodGridviewAdapter);

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

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