【问题标题】:Show external Image using async task使用异步任务显示外部图像
【发布时间】:2015-04-17 17:20:27
【问题描述】:

我想调用外部图片并将其显示在列表视图中。 我的代码工作一秒钟并崩溃并给出空指针错误。代码逻辑是这样的 1.我已经调用了第一个异步任务来从外部获取 Json 对象。 然后创建了一个自定义适配器以在自定义布局中设置该对象。 2.second async task获取其中一个对象(包含图片的url)并返回Bitmap图片。

你能找出我做错了什么吗?

Eroor:尝试在空对象引用上调用虚拟方法“void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)”

我的片段类

public class NewsFragment extends Fragment{

    private ProgressDialog pDialog;// Progress Dialog
    String my_url;
    ListView newsList;
    ArrayList<HashMap<String, String>> postList; //Declare Array
    private static String url = "http://wangeltmg.com/GKN_ADMIN/GET_POSTS/get_news.php";
    GetNews.CustomAdapter CA;
    View ImageView;

    // JSON Node names
    private static final String TAG_ID = "id";
    private static final String POST_ALLPOSTS = "posts";
    private static final String POST_ID = "ID";
    private static final String POST_TITLE = "post_title";
    private static final String POST_CONTENT = "post_content";
    private static final String GUID = "guid";


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.news, container, false);
        newsList = (ListView) view.findViewById(R.id.newsListView);
        TextView topic = (TextView) view.findViewById(R.id.topic);
        postList = new ArrayList<HashMap<String, String>>();
        //Get arguments
        Bundle args = getArguments();
        String mytopic = args.getString("Topic");
        //Set topic
        topic.setText(mytopic.toUpperCase());
        //Execute getContacts
        new GetNews().execute();
        newsList.setOnItemClickListener(new newsListClick());


        return view;
    }

    public class newsListClick implements ListView.OnItemClickListener{

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Log.d("News List","Clicked " + id);
            android.support.v4.app.FragmentManager fragmentManager = getFragmentManager();
            android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            SinglePost singleFrag = new SinglePost();
            fragmentTransaction.replace(R.id.content_frame, singleFrag);
            fragmentTransaction.commit();
        }
    }


    //Async Task
    private class GetNews extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(getActivity());
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

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

            // Creating service handler class instance
            ServiceHandler sh = new ServiceHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
            Log.d("Strings","Checking Json");
            Log.d("Response: ", "> " + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);
                    // contacts JSONArray
                    JSONArray posts = null;
                    // Getting JSON Array node
                    posts = jsonObj.getJSONArray(POST_ALLPOSTS);

                    // looping through All Contacts
                    for (int i = 0; i < posts.length(); i++) {

                        JSONObject c = posts.getJSONObject(i);
                        Log.d("Post->",posts.getJSONObject(i).toString());

                        String id = c.getString(POST_ID);

                        Log.d("Post->ID",id);
                        String post_title = c.getString(POST_TITLE);
                        String post_content = c.getString(POST_CONTENT);
                        String guid = c.getString(GUID);
                        Log.d("GUID->",guid);
                        //String gender = c.getString(TAG_GENDER);

                        // tmp hashmap for single post
                        HashMap<String, String> post = new HashMap<String, String>();
                        int count = 1;

                        // adding each child node to HashMap key => value
                        post.put(POST_ID, id);
                        post.put(POST_TITLE, post_title);
                        post.put(POST_CONTENT, post_content);
                        post.put(GUID, guid);
                        post.put("ListCount",String.valueOf(i));

                        // adding contact to contact list
                        postList.add(post);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }

            //get the bitmap url


            return null;
        }

        @Override
        public void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();

             // Updating parsed JSON data into ListView
            /*
            ListAdapter adapter = new SimpleAdapter(getActivity(), postList, R.layout.list_item,
                    new String[] { POST_TITLE,POST_CONTENT, GUID },
                    new int[] {R.id.email, R.id.mobile, R.id.guid });
            */

            CA = new CustomAdapter( getActivity(), R.layout.list_item, postList);
            newsList.setAdapter(CA);
        }

        public class CustomAdapter extends ArrayAdapter<HashMap<String, String>>{

            private final ArrayList<HashMap<String, String>> objects;

            public CustomAdapter(Context context, int resource, ArrayList<HashMap<String, String>> objects) {
                //something is wrong with super
                super(context, resource, objects);

                this.objects = objects;
            }
            public View getView(int position, View convertView, ViewGroup Parent){
                //convertView = new ImageView();
                if(convertView == null){
                    LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    convertView = inflater.inflate(R.layout.list_item,null);

                }
                TextView thisview = (TextView) convertView.findViewById(R.id.email);
                int getListPos = newsList.getFirstVisiblePosition();
                //i set the count starting 0 and saved in the hashmap array
                //to compare the first result with the first position of listview
                int count = Integer.parseInt(objects.get(position).get("ListCount"));

                if(getListPos == count) {
                    LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    convertView = inflater.inflate(R.layout.list_item_header,null);
                    TextView HeaderText = (TextView) convertView.findViewById(R.id.headertext);
                    TextView HeaderContent = (TextView) convertView.findViewById(R.id.headercontent);
                    HeaderText.setText(objects.get(position).get(POST_TITLE).toUpperCase());
                    HeaderContent.setText(objects.get(position).get(POST_CONTENT));

                }else{
                    thisview.setText("Normal line");
                }
                my_url = objects.get(position).get(GUID);
                new DownloadImageTask((ImageView) convertView.findViewById(R.id.img)).execute(my_url);

                return convertView;
            }


        }//



    }// end async task

    private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
        ImageView bmImage;

        public DownloadImageTask(ImageView bmImage) {
            this.bmImage = bmImage;
        }

        protected Bitmap doInBackground(String... urls) {
            String urldisplay = urls[0];
            Bitmap mIcon11 = null;
            try {
                InputStream in = new java.net.URL(urldisplay).openStream();
                mIcon11 = BitmapFactory.decodeStream(in);
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return mIcon11;
        }

        protected void onPostExecute(Bitmap result) {
            bmImage.setImageBitmap(result);
        }
    }//
}

自定义布局:

?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#444444"
    android:padding="10dp">
    <ImageView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/img"/>

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text"
        android:id="@+id/headertext"
        android:layout_gravity="center_horizontal"
        android:textColor="#FFFFFF"
        android:textStyle="bold"
        android:textSize="20dp"
        android:fontFamily="http://fonts.googleapis.com/css?family=Roboto:700"/>

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="New Text"
        android:id="@+id/headercontent"
        android:layout_gravity="center_horizontal"
        android:textColor="#ffffff"
        android:maxLines="2"/>
</LinearLayout>

【问题讨论】:

  • 您能更好地解释崩溃是如何发生的吗?比如:应用启动、加载数据和?
  • 是的,它显示图像并停止工作。
  • java.lang.NullPointerException:尝试在 edu.gannon.gannonknightnews.NewsFragment$ 的空对象引用上调用虚拟方法 'void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)'在 edu.gannon.gannonknightnews.NewsFragment 下载ImageTask.onPostExecute(NewsFragment.java:266)$DownloadImageTask.onPostExecute(NewsFragment.java:245)

标签: android bitmap android-asynctask


【解决方案1】:

我可以假设以下问题:您有 2 种不同的自定义布局:

  1. R.layout.list_item_header
  2. R.layout.list_item

而且,根据您的代码,您正在调用它们:

  new DownloadImageTask((ImageView) convertView.findViewById(R.id.img)).execute(my_url);

如果ImageView R.id.img 不在这两种布局中,您的应用将崩溃。如果我是对的,您只需要修复您的 if/else 并仅在需要时调用 DownloadImageTask

【讨论】:

  • 太棒了!我对此也有疑问……好吧,我会发布我所做的。非常感谢
【解决方案2】:

Eroor:尝试在空对象引用上调用虚拟方法“void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)”清楚地表明您在构造函数中传递的 ImageView 参数为 NULL。
您正在运行时初始化此图形单元。为什么不一开始就初始化呢

Variable_name = (ImageView) convertView.findViewById(R.id.img)

在 OnCreateView..

并将创建的对象传递到您当前使用它的位置。这可能会解决您的错误。

【讨论】:

    【解决方案3】:

    对条件进行一些调整 - 并且有效。这是我想要设置的视图的冲突。

      if(getListPos == count) {
                            LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                            convertView = inflater.inflate(R.layout.list_item_header,null);
                            TextView HeaderText = (TextView) convertView.findViewById(R.id.headertext);
                            TextView HeaderContent = (TextView) convertView.findViewById(R.id.headercontent);
                            HeaderText.setText(objects.get(position).get(POST_TITLE).toUpperCase());
                            HeaderContent.setText(objects.get(position).get(POST_CONTENT));
                            new DownloadImageTask((ImageView) convertView.findViewById(R.id.img)).execute(my_url);
                        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-29
      相关资源
      最近更新 更多