简体   繁体   English

适配器无法在Android上从JSON加载图像

[英]Adapter Can't Load Image from JSON on Android

i have some problem with my JSON code. 我的JSON代码有问题。 I want to display a list that contain text and image. 我想显示一个包含文本和图像的列表。 The text and image stored on my online database, i using JSON for taking them down to my android app. 文本和图像存储在我的在线数据库中,我使用JSON将其带到我的android应用程序中。

The JSON doesn't display any error, the text are displayed but the image are not appear. JSON不显示任何错误,显示文本但不显示图像。

I check the logcat and there's no error for this process. 我检查了logcat,此过程没有错误。 I using viewAdapter for displaying the image on the list. 我使用viewAdapter在列表上显示图像。

Please master help me, can you gimme some simple explanation how to solve this?? 请高手帮帮我,您能给我一些简单的解释如何解决这个问题吗?

Thanks... 谢谢...

NB. NB。 This is my code for HomeFragment.java (where i doing the JSON). 这是我的HomeFragment.java代码(我在其中执行JSON)。

public class HomeFragment extends Fragment implements InternetConnectionListener, ApiHandler.ApiHandlerListener {

private static final String ARG_SECTION_NUMBER = "section_number";
private final int CATEGORY_ACTION = 1;
private CategorySelectionCallbacks mCallbacks;
private ArrayList<Category> categoryList;
private ListView categoryListView;
private String Error = null;
private InternetConnectionListener internetConnectionListener;

public HomeFragment() {

}

public static HomeFragment newInstance(int sectionNumber) {
    HomeFragment fragment = new HomeFragment();
    Bundle args = new Bundle();
    args.putInt(ARG_SECTION_NUMBER, sectionNumber);
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    ((HomeActivity) activity).onSectionAttached(getArguments().getInt(ARG_SECTION_NUMBER));
    try {
        mCallbacks = (CategorySelectionCallbacks) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException("Activity must implement CategorySelectionCallbacks.");
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_home, container, false);
    categoryListView = (ListView) rootView.findViewById(R.id.categoryListView);
    return rootView;
}

@Override
public void onResume() {
    super.onResume();
    if (UtilMethods.isConnectedToInternet(getActivity())) {
        initCategoryList();
    } else {
        internetConnectionListener = (InternetConnectionListener) HomeFragment.this;
        showNoInternetDialog(getActivity(), internetConnectionListener,
                getResources().getString(R.string.no_internet),
                getResources().getString(R.string.no_internet_text),
                getResources().getString(R.string.retry_string),
                getResources().getString(R.string.exit_string), CATEGORY_ACTION);
    }

}

public class getCategList extends AsyncTask<Void, Void, Void>{

    @Override
    protected Void doInBackground(Void... params) {

        /**
         * json is populating from text file. To make api call use ApiHandler class
         *
         *  <CODE>ApiHandler apiHandler = new ApiHandler(this, URL_GET_CATEGORY);</CODE> <BR>
         *  <CODE>apiHandler.doApiRequest(ApiHandler.REQUEST_GET);</CODE> <BR>
         *
         * You will get the response in onSuccessResponse(String tag, String jsonString) method
         * if successful api call has done. Do the parsing as the following.
         */
        URL hp = null;
        try {
            hp = new URL(
                    getString(R.string.liveurl) + "foodcategory.php");

            Log.d("URL", "" + hp);
            URLConnection hpCon = hp.openConnection();
            hpCon.connect();
            InputStream input = hpCon.getInputStream();

            BufferedReader r = new BufferedReader(new InputStreamReader(input));

            String x = "";
            x = r.readLine();
            String total = "";

            while (x != null) {
                total += x;
                x = r.readLine();
            }
            Log.d("UR1L", "" + total);

            JSONArray j = new JSONArray(total);

            Log.d("URL1", "" + j.length());



            categoryList = new ArrayList<Category>();

            for (int i = 0; i < j.length(); i++) {
                Category category = new Category();// buat variabel category
                JSONObject Obj;
                Obj = j.getJSONObject(i); //sama sperti yang lama, cman ini lebih mempersingkat karena getJSONObject cm d tulis sekali aja disini

                category.setId(Obj.getString(JF_ID));
                category.setTitle(Obj.getString(JF_TITLE));
                category.setIconUrl(Obj.getString(JF_ICON));

                if (!TextUtils.isEmpty(Obj.getString(JF_BACKGROUND_IMAGE))) {
                    category.setImageUrl(Obj.getString(JF_BACKGROUND_IMAGE));
                }
                Log.d("URL1",""+Obj.getString(JF_TITLE));
                categoryList.add(category);
            }

            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    categoryListView.setAdapter(new CategoryAdapter(getActivity(), mCallbacks, categoryList));
                }
            });



        }catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Error = e.getMessage();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Error = e.getMessage();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            Error = e.getMessage();
            e.printStackTrace();
        } catch (NullPointerException e) {
            // TODO: handle exception
            Error = e.getMessage();
        }
        return null;
    }
}



//! function for populate category list
private void initCategoryList() {
        new getCategList().execute();
}

@Override
public void onConnectionEstablished(int code) {
    if (code == CATEGORY_ACTION) {
        initCategoryList();
    }
}

@Override
public void onUserCanceled(int code) {
    if (code == CATEGORY_ACTION) {
        getActivity().finish();
    }
}

//! catch json response from here
@Override
public void onSuccessResponse(String tag, String jsonString) {
    //! do same parsing as done in initCategoryList()
}

//! detect response error here
@Override
public void onFailureResponse(String tag) {

}

//! callback interface listen by HomeActivity to detect user click on category
public static interface CategorySelectionCallbacks {
    void onCategorySelected(String catID, String title);
}

} }

This code for categoryAdapter.java (where i put the result of JSON to the list) 该代码用于categoryAdapter.java(我将JSON结果放入列表中)

public class CategoryAdapter extends ArrayAdapter<Category> implements View.OnClickListener {

private final LayoutInflater inflater;
private final ArrayList<Category> categoryList;
private Activity activity;
private HomeFragment.CategorySelectionCallbacks mCallbacks;
private String dummyUrl = "http://www.howiwork.org";
AbsListView.LayoutParams params;


public CategoryAdapter(Activity activity, HomeFragment.CategorySelectionCallbacks mCallbacks, ArrayList<Category> categoryList) {
    super(activity, R.layout.layout_category_list);
    this.activity = activity;
    this.inflater = LayoutInflater.from(activity.getApplicationContext());
    this.categoryList = categoryList;
    this.mCallbacks = mCallbacks;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder row;
    if (convertView == null) {
        convertView = inflater.inflate(R.layout.layout_category_list, null);
        row = new ViewHolder();
        row.bannerImage = (ImageView) convertView.findViewById(R.id.catBannerImageView);
        row.categoryImage = (ImageView) convertView.findViewById(R.id.catImageView);
        row.categoryName = (TextView) convertView.findViewById(R.id.catNameTV);








    } else {
        row = (ViewHolder) convertView.getTag();

    }

    Category category = categoryList.get(position);
    Picasso.with(activity).load(UtilMethods
            .getDrawableFromFileName(activity,category.getIconUrl()))
            .tag(category.getIconUrl())
            .into(row.categoryImage);
    row.categoryName.setText(category.getTitle());

    Picasso.with(activity)
            .load(UtilMethods.getDrawableFromFileName(activity,category.getImageUrl()))
            .placeholder(R.drawable.img_banner_placeholder)
            .tag(category.getIconUrl())
            .fit()
            .into(row.bannerImage);


    row.bannerImage.setOnClickListener(this);
    row.categoryImage.setTag(position);
    row.categoryName.setTag(position);
    row.bannerImage.setTag(position);
    return convertView;
}

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

@Override
public void onClick(View v) {
    int position = Integer.parseInt(v.getTag().toString());
    mCallbacks.onCategorySelected(categoryList.get(position).getId(),
            categoryList.get(position).getTitle());
}

private static class ViewHolder {
    public ImageView bannerImage;
    public TextView categoryName;
    public ImageView categoryImage;
}

} }

Try this. 尝试这个。

Picasso.with(activity).load(category.getIconUrl())
        .into(row.categoryImage);

If it worked !. 如果有效! You Check the UtilMethods.getDrawableFromFileName() !!! 您检查UtilMethods.getDrawableFromFileName()!!!

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

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