在片段自定义阵列适配器 [英] Custom Array adapter in fragment

查看:295
本文介绍了在片段自定义阵列适配器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Andriod的非常新。我已经试过很多次,但因为很长一段时间就死在了这个问题。我有一个名为ProductListActivity一个活动,这个活动我有一个片段。现在我想显示列表并为我创造了我自己的自定义阵列适配器。其工作正常,当我不使用时的片段但片段给我NullPointerException异常。调试我的code。请帮我出guys.Thanks审议。
在这里我粘贴我的code。

活动类:

 公共类ProductListActivity扩展活动实现ProductInterface {
公共静态字符串的cookie;
公共静态字符串jsonSettingsResponse;
公共静态的String [] TIDS;
公共静态字符串jsonPorductsCategoryListResponseString;
公共JSONArray jsonPorductsCategoryListResponseArray;
公共静态字符串VID;
公共静态字符串publicPath;
公共静态JSONArray产品列表;
公众的ArrayList<串GT; listItems中;
公众的String [] listProCategory;@覆盖
保护无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.product_category_and_list);
    意向意图= getIntent();
    饼干= intent.getStringExtra(BConstant.WEB_SERVICES_COOKIES);
    产品列表=新JSONArray();
    FetchProductCategories产品=新FetchProductCategories();
    产品列表= products.fetchProducts();
    listProCategory = products.onDisplayProductList(产品列表).toArray(
            新的String [0]);    束束=新包();
    bundle.putString(BConstant.WEB_SERVICES_COOKIES,饼干);
    bundle.putString(BConstant.PUBLIC_PATH,publicPath);
    bundle.putStringArray(BConstant.TAXONOMY_TID,TIDS);
    bundle.putStringArray(BConstant.PRODUCT_C​​ATEGORY_NAMES,listProCategory);
    ProductCategoryFragment productCategoryFragment =新ProductCategoryFragment();
    FragmentManager经理= getFragmentManager();
    productCategoryFragment.setArguments(包);}私有类FetchProductCategories {
    保护JSONArray fetchProducts(字符串... PARAMS){
        jsonSettingsResponse = WebserviceBUtil
                .callWebServicesGetVocabularyList(饼干);
        VID = JSONUtil.parseJSONResponse(jsonSettingsResponse,
                BConstant.TAXONOMY_VID);
        publicPath = JSONUtil.parseJSONResponse(jsonSettingsResponse,
                BConstant.PUBLIC_PATH);
        jsonPorductsCategoryListResponseString = WebserviceBUtil
                .callWebServicesGetProductsList(饼干,VID);
        TIDS = ProductCategoryIds.parseJSONResponseToGetTidsOfProducts(
                jsonPorductsCategoryListResponseString,
                BConstant.TAXONOMY_TID);
        尝试{
            jsonPorductsCategoryListResponseArray =新JSONArray(
                    jsonPorductsCategoryListResponseString);
        }赶上(JSONException E){
            e.printStackTrace();
        }
        返回jsonPorductsCategoryListResponseArray;
    }
    保护的ArrayList<串GT; onDisplayProductList(JSONArray结果){
        时listItems =新的ArrayList<串GT;();
        的for(int i = 0; I< result.length();我++){
            尝试{
                listItems中
                        。新增(result.getJSONObject(I)
                                .getString(BConstant.NAME_CONSTANT)
                                的ToString());
            }赶上(例外前){
                ex.printStackTrace();
            }
        }
        返回时listItems;
    }
}
    @覆盖
    公众的HashMap<整数,位图> DownloadImages(HashMap的<整数,字符串> productCategoryImagePath){
        HashMap的<整数,位图> imgBitmap =新的HashMap<整数,位图>();
        对(INT POS = 0; POS及下; productCategoryImagePath.size(); POS ++){
            位图BVAL = ImageDownloader
                    .getBitmapFromURL(productCategoryImagePath.get(POS));
        imgBitmap.put(POS,BVAL);
        }
        返回imgBitmap;}
}

Fragments类:

 公共类ProductCategoryFragment扩展片段{
ProductInterface productInterface;
私有静态的String [] TIDS;
私有静态HashMap的<整数,字符串> productCategoryImagePath;
私人静态字符串jsonPorductsDetailsImagePathResponse;
私人静态字符串publicPath;
私人静态字符串的cookie;
公众的String [] listProCategory;
公众的ListView listOfProductsCategory;
私有静态HashMap的<整数,位图> imgBitmapUrls;
DisplayProductListArrayAdapter适配器;
@覆盖
公共查看onCreateView(LayoutInflater充气器,容器的ViewGroup,
        捆绑savedInstanceState){
     查看fragProcatView = inflater.inflate(R.layout.product_category_list,集装箱,
                假);
     listOfProductsCategory =(ListView控件)getActivity()findViewById(R.id.productCategorylistView)。
    返回fragProcatView;}@覆盖
公共无效onActivityCreated(捆绑savedInstanceState){
    super.onActivityCreated(savedInstanceState);
    publicPath = getArguments()的getString(BConstant.PUBLIC_PATH)。
    饼干= getArguments()的getString(BConstant.WEB_SERVICES_COOKIES)。
    TIDS = getArguments()getStringArray(BConstant.TAXONOMY_TID)。
    listProCategory = getArguments()。getStringArray(
            BConstant.PRODUCT_C​​ATEGORY_NAMES);
    束B = getActivity()getIntent()getExtras()。
    publicPath = b.getString(BConstant.PUBLIC_PATH);
    饼干= b.getString(BConstant.WEB_SERVICES_COOKIES);
    TIDS = b.getStringArray(BConstant.TAXONOMY_TID);
    listProCategory = b.getStringArray(
            BConstant.PRODUCT_C​​ATEGORY_NAMES);
    productInterface =(ProductInterface)getActivity();
    productCategoryImagePath =新的HashMap<整数,字符串>();
    的for(int i = 0; I< tids.length;我++){
        jsonPorductsDetailsImagePathResponse = WebserviceBUtil
                .callWebServicesGetProductsDetails(饼干,TIDS [I]);
        字符串文件名= ProductCategoryIds
                .parseJSONResponseToGetVidOfProductsFromVocabulary(
                        jsonPorductsDetailsImagePathResponse,
                        BConstant.FILE_NAME);
        字符串completeUrl = publicPath +文件名;
        productCategoryImagePath.put(ⅰ,completeUrl);
    }
    imgBitmapUrls = productInterface
            .DownloadImages(productCategoryImagePath);
     适配器=新DisplayProductListArrayAdapter(
                getActivity(),listProCategory,
                imgBitmapUrls);
    listOfProductsCategory.setAdapter(适配器);
}
/ **
 * ExtendsArrayAdapterClassToDisplayCustomListView
 * /
公共类DisplayProductListArrayAdapter扩展ArrayAdapter<串GT; {    上下文语境;
    HashMap的<整数,位图> prodctImgs;
    的String [] proCategoryNames;
    HashMap的<整数,位图> biturls;
    DisplayProductListArrayAdapter(上下文C,
            的String [] listCategory,HashMap的<整数,位图> imgUrls){
        超(C,
                R.layout.product_category_single_layout,
                R.id.productCategoryName,listCategory);
        this.context = C;
        this.prodctImgs = imgUrls;
        this.proCategoryNames = listCategory;
        this.biturls = imgUrls;
    }    @覆盖
    公共查看getView(INT位置,查看convertView,父母的ViewGroup){
        // LayoutInflater吹气=(LayoutInflater)上下文
    // .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        LayoutInflater充气=((活动)上下文).getLayoutInflater();
查看排= inflater.inflate(R.layout.product_category_single_layout,父母,假);
        ImageView的productCategoryImage =(ImageView的)行
                .findViewById(R.id.productCategoryImageId);
        位图位图= imgBitmapUrls.get(位置);
        // productCategoryImage.setFocusable(假);
        TextView的productCategoryName =(TextView中)一行
                .findViewById(R.id.productCategoryName);
        productCategoryImage.setImageBitmap(位图);
        productCategoryName.setText(proCategoryNames [位置]);
        返回行;
    }
     }
  }


解决方案

修改

  listOfProductsCategory =(ListView控件)getActivity()findViewById(R.id.productCategorylistView)。

  listOfProductsCategory =(ListView控件)fragProcatView .findViewById(R.id.productCategorylistView);

findViewById 查找在当前infalted布局id的视图。因此,使用视图对象来初始化列表视图。

编辑:

您做这样的事情。

 静态ProductCategoryFragment的newInstance(INT NUM){
    ProductCategoryFragment F =新ProductCategoryFragment();    //供应NUM输入作为参数。
    捆绑ARGS =新包();
    args.putInt(民,NUM);
    f.setArguments(参数);    返回F;
}

然后

  int值= getArguments()调用getInt(民);

在活动

  ProductCategoryFragment newFragment = ProductCategoryFragment.newInstance(10);

I am very new in Andriod. i have tried so many times but got stuck on this problem since long time. I have an activity named ProductListActivity and in this activity i have one fragments. now i want to display List and for that i have created my own custom array adapter. its working fine when when i am not using fragments but for fragments giving me NullPointerException. I debug my code. Please help me out guys.Thanks for considering. Here i am pasting my code.

Activity class:

public class ProductListActivity extends Activity implements ProductInterface{
public static String cookie;
public static String jsonSettingsResponse;
public static String[] tids;
public static String jsonPorductsCategoryListResponseString;
public JSONArray jsonPorductsCategoryListResponseArray;
public static String vid;
public static String publicPath;
public static JSONArray productsList;
public ArrayList<String> listItems;
public String[] listProCategory;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.product_category_and_list);
    Intent intent = getIntent();
    cookie = intent.getStringExtra(BConstant.WEB_SERVICES_COOKIES);
    productsList = new JSONArray();
    FetchProductCategories products = new FetchProductCategories();
    productsList = products.fetchProducts();
    listProCategory = products.onDisplayProductList(productsList).toArray(
            new String[0]);

    Bundle bundle = new Bundle();
    bundle.putString(BConstant.WEB_SERVICES_COOKIES, cookie);
    bundle.putString(BConstant.PUBLIC_PATH, publicPath);
    bundle.putStringArray(BConstant.TAXONOMY_TID, tids);
    bundle.putStringArray(BConstant.PRODUCT_CATEGORY_NAMES, listProCategory);
    ProductCategoryFragment productCategoryFragment = new ProductCategoryFragment();
    FragmentManager manager = getFragmentManager();
    productCategoryFragment.setArguments(bundle);

}

private class FetchProductCategories {
    protected JSONArray fetchProducts(String... params) {
        jsonSettingsResponse = WebserviceBUtil
                .callWebServicesGetVocabularyList(cookie);
        vid = JSONUtil.parseJSONResponse(jsonSettingsResponse,
                BConstant.TAXONOMY_VID);
        publicPath = JSONUtil.parseJSONResponse(jsonSettingsResponse,
                BConstant.PUBLIC_PATH);
        jsonPorductsCategoryListResponseString = WebserviceBUtil
                .callWebServicesGetProductsList(cookie, vid);
        tids = ProductCategoryIds.parseJSONResponseToGetTidsOfProducts(
                jsonPorductsCategoryListResponseString,
                BConstant.TAXONOMY_TID);
        try {
            jsonPorductsCategoryListResponseArray = new JSONArray(
                    jsonPorductsCategoryListResponseString);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jsonPorductsCategoryListResponseArray;
    }


    protected ArrayList<String> onDisplayProductList(JSONArray result) {
        listItems = new ArrayList<String>();
        for (int i = 0; i < result.length(); i++) {
            try {
                listItems
                        .add(result.getJSONObject(i)
                                .getString(BConstant.NAME_CONSTANT)
                                .toString());
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return listItems;
    }
}


    @Override
    public HashMap<Integer, Bitmap> DownloadImages(HashMap<Integer, String> productCategoryImagePath) {
        HashMap<Integer, Bitmap> imgBitmap = new HashMap<Integer, Bitmap>();
        for (int pos = 0; pos < productCategoryImagePath.size(); pos++) {
            Bitmap bval = ImageDownloader
                    .getBitmapFromURL(productCategoryImagePath.get(pos));
        imgBitmap.put(pos, bval);
        }
        return imgBitmap;

}
}

Fragments class:

public class ProductCategoryFragment extends Fragment {
ProductInterface productInterface;
private static String[] tids;
private static HashMap<Integer, String> productCategoryImagePath;
private static String jsonPorductsDetailsImagePathResponse;
private static String publicPath;
private static String cookie;
public String[] listProCategory;
public  ListView listOfProductsCategory;
private static HashMap<Integer, Bitmap> imgBitmapUrls;
DisplayProductListArrayAdapter adapter;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
     View fragProcatView = inflater.inflate(R.layout.product_category_list, container,
                false);
     listOfProductsCategory = (ListView) getActivity().findViewById(R.id.productCategorylistView);
    return fragProcatView;

}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    publicPath = getArguments().getString(BConstant.PUBLIC_PATH);
    cookie = getArguments().getString(BConstant.WEB_SERVICES_COOKIES);
    tids = getArguments().getStringArray(BConstant.TAXONOMY_TID);
    listProCategory = getArguments().getStringArray(
            BConstant.PRODUCT_CATEGORY_NAMES);
    Bundle b = getActivity().getIntent().getExtras();
    publicPath = b.getString(BConstant.PUBLIC_PATH);
    cookie = b.getString(BConstant.WEB_SERVICES_COOKIES);
    tids =b.getStringArray(BConstant.TAXONOMY_TID);
    listProCategory =b.getStringArray(
            BConstant.PRODUCT_CATEGORY_NAMES);
    productInterface = (ProductInterface) getActivity();
    productCategoryImagePath = new HashMap<Integer, String>();
    for (int i = 0; i < tids.length; i++) {
        jsonPorductsDetailsImagePathResponse = WebserviceBUtil
                .callWebServicesGetProductsDetails(cookie, tids[i]);
        String filename = ProductCategoryIds
                .parseJSONResponseToGetVidOfProductsFromVocabulary(
                        jsonPorductsDetailsImagePathResponse,
                        BConstant.FILE_NAME);
        String completeUrl = publicPath + filename;
        productCategoryImagePath.put(i, completeUrl);
    }
    imgBitmapUrls = productInterface
            .DownloadImages(productCategoryImagePath);
     adapter = new DisplayProductListArrayAdapter(
                getActivity(), listProCategory,
                imgBitmapUrls);
    listOfProductsCategory.setAdapter(adapter);
}


/**
 * ExtendsArrayAdapterClassToDisplayCustomListView
 */
public class DisplayProductListArrayAdapter extends ArrayAdapter<String> {

    Context context;
    HashMap<Integer, Bitmap> prodctImgs;
    String[] proCategoryNames;
    HashMap<Integer, Bitmap>biturls;
    DisplayProductListArrayAdapter(Context c,
            String[] listCategory, HashMap<Integer, Bitmap> imgUrls) {
        super(c,
                R.layout.product_category_single_layout,
                R.id.productCategoryName, listCategory);
        this.context = c;
        this.prodctImgs = imgUrls;
        this.proCategoryNames = listCategory;
        this.biturls = imgUrls;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        //LayoutInflater inflater = (LayoutInflater) context
    //          .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        LayoutInflater inflater=((Activity)context).getLayoutInflater(); 
View row = inflater.inflate(R.layout.product_category_single_layout,parent,false);
        ImageView productCategoryImage = (ImageView) row
                .findViewById(R.id.productCategoryImageId);
        Bitmap bitmap = imgBitmapUrls.get(position);
        // productCategoryImage.setFocusable(false);
        TextView productCategoryName = (TextView) row
                .findViewById(R.id.productCategoryName);
        productCategoryImage.setImageBitmap(bitmap);
        productCategoryName.setText(proCategoryNames[position]);
        return row;
    }
     }
  }

解决方案

Change

listOfProductsCategory = (ListView) getActivity().findViewById(R.id.productCategorylistView);

to

listOfProductsCategory = (ListView) fragProcatView .findViewById(R.id.productCategorylistView);

findViewById looks for a view with the id in the current infalted layout. So use the view object to initialize your listview.

Edit:

You do something like this

  static ProductCategoryFragment newInstance(int num) {
    ProductCategoryFragment f = new ProductCategoryFragment();

    // Supply num input as an argument.
    Bundle args = new Bundle();
    args.putInt("num", num);
    f.setArguments(args);

    return f;
}

Then

int value = getArguments().getInt("num");

In Activity

 ProductCategoryFragment newFragment = ProductCategoryFragment.newInstance(10);

这篇关于在片段自定义阵列适配器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆