从不调用自定义适配器getView()

时间:2014-08-15 20:36:21

标签: android

我有一个用于listview的自定义ArrayAdapter。当我设置列表适配器时,不会调用getView。我已经从中返回了计数,并且计数是应该的(不是0)。我还记录了不同的项目位置,以确保适配器有数据显示,但仍未调用getview。我在异步任务的postExecute()中设置了列表适配器。好像除了getView之外的所有东西都被调用了。这是代码

private class StableArrayAdapter extends ArrayAdapter<String> {

        private final Context context;
        private List<String> viewString;
        private ImageView image;
        private TextView addToCalendarButton;
        private TextView eventTitle;
        private ImageView eventImage;
        private TextView likesTV;
        private TextView planToAttendTV;

        public StableArrayAdapter(Context context, List<String> strings) {
            super(context, R.layout.post_layout, strings);
            this.context = context;
            this.viewString = strings;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View postLayout = inflater.inflate(R.layout.post_layout, parent, false);

            TextView unameTV = (TextView)postLayout.findViewById(R.id.postUnameTv);
            unameTV.setText(viewString.get(0));

            image = (ImageView)postLayout.findViewById(R.id.postProfPic);
            DisplayImageOptions options = initiateDisplayImageOptions();
            ImageLoader imageloader = ImageLoader.getInstance();
            initImageLoader(getActivity());
            imageloader.displayImage(viewString.get(1), image, options);


            addToCalendarButton = (TextView)postLayout.findViewById(R.id.addToCalendarButton);
            addToCalendarButton.setText(viewString.get(2));

            eventTitle = (TextView)postLayout.findViewById(R.id.postTitleTV);
            eventTitle.setText(viewString.get(3));

            eventImage = (ImageView)postLayout.findViewById(R.id.eventImage);
            imageloader.displayImage(viewString.get(4), eventImage, options);


            likesTV = (TextView)postLayout.findViewById(R.id.likesTV);
            likesTV.setText(""+viewContent.get(5));

            planToAttendTV = (TextView)postLayout.findViewById(R.id.planToAttendTV);
            planToAttendTV.setText(viewString.get(6));

            Log.d("Adapter", ""+viewString.get(6));



            return postLayout;
        }


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

        @Override
        public String getItem(int position) {
            return viewString.get(position);
        }

    }

}`

我不确定这是否是一个原因,但这是我如何在postExecute中设置列表适配器

            getActivity().runOnUiThread(new Runnable() {
            public void run() {


                /**
                 * Updating parsed JSON data into ListView
                 * */

                StableArrayAdapter adapter = new StableArrayAdapter(getActivity(), viewContent);
                // updating listview

                lv.setAdapter(adapter);
                adapter.notifyDataSetChanged();


            }
        });

修改 这是我用来获取数据的异步任务

class LoadAllProducts extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }

    /**
     * getting All products from url
     * */
    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(url_get_events, "GET", params);

        // Check your log cat for JSON reponse
        Log.d("Loading Events: ", "Loading Events...");

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {

                // products found
                // Getting Array of Products
                products = json.getJSONArray(TAG_PRODUCTS);


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

                    JSONObject c = products.getJSONObject(i);

                    // Storing each json item in variable
                    int id = c.getInt("id");
                    String name = c.getString("name");
                    String radius = c.getString("radius");

                    String centerlat = c.getString("centerlat");
                    String centerlng = c.getString("centerlng");

                    String topleftcornerlat = c.getString("topleftcornerlat");
                    String topleftcornerlng = c.getString("topleftcornerlng");

                    String bottomleftcornerlat = c.getString("bottomleftcornerlat");
                    String bottomleftcornerlng = c.getString("bottomleftcornerlng");

                    String bottomrightcornerlat = c.getString("bottomrightcornerlat");
                    String bottomrightcornerlng = c.getString("bottomrightcornerlng");




                    String startmonth = c.getString("startmonth");
                    String endmonth = c.getString("endmonth");

                    String startday= c.getString("startday");
                    String endday = c.getString("endday");

                    String startyear = c.getString("startyear");
                    String endyear = c.getString("endyear");

                    String starthour = c.getString("starthour");
                    String endhour= c.getString("endhour");

                    String startmins = c.getString("startmins");
                    String endmins= c.getString("endmins");




                    String attending_future = c.getString("attending_future");
                    String attending_now = c.getString("attending_now");

                    String likes = c.getString("likes");
                    String image = c.getString("image");

                    String profile = c.getString("profile");

                    String userprofilepic = c.getString("userprofpic");
                    String username = c.getString("username");


                    viewContent.add(username);


                    viewContent.add(userprofilepic);


                    String date = getMonth(Integer.parseInt(startmonth)) + " " + startday + ", " + startyear;

                    viewContent.add(date);


                    viewContent.add(name);


                    viewContent.add(image);
                    viewContent.add(""+likes);


                    viewContent.add(attending_future + " people plan to attend.");



                }
            } else {
                // no products found
                // Launch Add New product Activity
                /*
                Intent i = new Intent(getApplicationContext(),
                        NewProductActivity.class);
                // Closing all previous activities
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);
                */
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        Log.d("Loading Events: ", "Events Loaded");
        // dismiss the dialog after getting all products
        // updating UI from Background Thread


        getActivity().runOnUiThread(new Runnable() {
            public void run() {


                /**
                 * Updating parsed JSON data into ListView
                 * */

                StableArrayAdapter adapter = new StableArrayAdapter(getActivity(), viewContent);
                // updating listview

                lv.setAdapter(adapter);
                adapter.notifyDataSetChanged();


            }
        });

    }

修改

这是整个代码

public class MainFeed extends Fragment {

// Progress Dialog
private ProgressDialog pDialog;

// Creating JSON Parser object
JSONParser jParser = new JSONParser();
static List<String> viewContent = new ArrayList<>();

static Bundle bundle;
ArrayList<HashMap<String, String>> productsList;

// url to get all products list
private static String url_get_events = "http://127.0.0.1/get_events.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";

// products JSONArray
JSONArray products = null;
private ListView lv;

/* (non-Javadoc)
 * @see android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)
 */
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    bundle = savedInstanceState;

    inflater = getLayoutInflater(savedInstanceState);
    View view=inflater.inflate(R.layout.main_feed_layout, null);

    // Loading products in Background Thread
    new LoadAllProducts().execute();

    // Get listview
    lv = (ListView) view.findViewById(R.id.listView);


    // on seleting single product
    // launching Edit Product Screen
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

            /*
            String pid = ((TextView) view.findViewById(R.id.pid)).getText()
                    .toString();

            // Starting new intent
            Intent in = new Intent(getApplicationContext(),
                    EditProductActivity.class);
            // sending pid to next activity
            in.putExtra(TAG_PID, pid);

            // starting new activity and expecting some response back
            startActivityForResult(in, 100);
            */
        }
    });

    ImageLoadingListener progressListener = new ImageLoadingListener() {
        @Override
        public void onLoadingStarted(String s, View view) {
            Log.i("Start", "Start");
        }

        @Override
        public void onLoadingFailed(String s, View view, FailReason failReason) {
            Log.i("Start", "Failed");

        }

        @Override
        public void onLoadingComplete(String s, View view, Bitmap bitmap) {
        }

        @Override
        public void onLoadingCancelled(String s, View view) {
            Log.i("Start", "Cancelled");

        }
    };




    if (container == null) {

        return null;
    }
    return (RelativeLayout) inflater.inflate(R.layout.main_feed_layout, container, false);

}

// Response from Edit Product Activity
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // if result code 100
    if (resultCode == 100) {
        // if result code 100 is received
        // means user edited/deleted product
        // reload this screen again
        Intent intent = data;
        //finish();
        startActivity(intent);
    }

}

class LoadAllProducts extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }

    /**
     * getting All products from url
     * */
    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(url_get_events, "GET", params);

        // Check your log cat for JSON reponse
        Log.d("Loading Events: ", "Loading Events...");

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {

                // products found
                // Getting Array of Products
                products = json.getJSONArray(TAG_PRODUCTS);


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

                    JSONObject c = products.getJSONObject(i);

                    // Storing each json item in variable
                    int id = c.getInt("id");
                    String name = c.getString("name");
                    String radius = c.getString("radius");

                    String centerlat = c.getString("centerlat");
                    String centerlng = c.getString("centerlng");

                    String topleftcornerlat = c.getString("topleftcornerlat");
                    String topleftcornerlng = c.getString("topleftcornerlng");

                    String bottomleftcornerlat = c.getString("bottomleftcornerlat");
                    String bottomleftcornerlng = c.getString("bottomleftcornerlng");

                    String bottomrightcornerlat = c.getString("bottomrightcornerlat");
                    String bottomrightcornerlng = c.getString("bottomrightcornerlng");




                    String startmonth = c.getString("startmonth");
                    String endmonth = c.getString("endmonth");

                    String startday= c.getString("startday");
                    String endday = c.getString("endday");

                    String startyear = c.getString("startyear");
                    String endyear = c.getString("endyear");

                    String starthour = c.getString("starthour");
                    String endhour= c.getString("endhour");

                    String startmins = c.getString("startmins");
                    String endmins= c.getString("endmins");




                    String attending_future = c.getString("attending_future");
                    String attending_now = c.getString("attending_now");

                    String likes = c.getString("likes");
                    String image = c.getString("image");

                    String profile = c.getString("profile");

                    String userprofilepic = c.getString("userprofpic");
                    String username = c.getString("username");


                    viewContent.add(username);


                    viewContent.add(userprofilepic);


                    String date = getMonth(Integer.parseInt(startmonth)) + " " + startday + ", " + startyear;

                    viewContent.add(date);


                    viewContent.add(name);


                    viewContent.add(image);
                    viewContent.add(""+likes);


                    viewContent.add(attending_future + " people plan to attend.");



                }
            } else {
                // no products found
                // Launch Add New product Activity
                /*
                Intent i = new Intent(getApplicationContext(),
                        NewProductActivity.class);
                // Closing all previous activities
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);
                */
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        Log.d("Loading Events: ", "Events Loaded");
        // dismiss the dialog after getting all products
        // updating UI from Background Thread



         /**
          * Updating parsed JSON data into ListView
          * */
         StableArrayAdapter adapter = new StableArrayAdapter(getActivity(), viewContent);
         // updating listview
         lv.setAdapter(adapter);
         adapter.notifyDataSetChanged();




    }








    private class StableArrayAdapter extends ArrayAdapter<String> {

        private final Context context;
        private List<String> viewString;
        private ImageView image;
        private TextView addToCalendarButton;
        private TextView eventTitle;
        private ImageView eventImage;
        private TextView likesTV;
        private TextView planToAttendTV;

        public StableArrayAdapter(Context context, List<String> strings) {
            super(context, R.layout.post_layout, strings);
            this.context = context;
            this.viewString = strings;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View postLayout = inflater.inflate(R.layout.post_layout, parent, false);

            TextView unameTV = (TextView)postLayout.findViewById(R.id.postUnameTv);
            unameTV.setText(viewString.get(0));

            image = (ImageView)postLayout.findViewById(R.id.postProfPic);
            DisplayImageOptions options = initiateDisplayImageOptions();
            ImageLoader imageloader = ImageLoader.getInstance();
            initImageLoader(getActivity());
            imageloader.displayImage(viewString.get(1), image, options);


            addToCalendarButton = (TextView)postLayout.findViewById(R.id.addToCalendarButton);
            addToCalendarButton.setText(viewString.get(2));

            eventTitle = (TextView)postLayout.findViewById(R.id.postTitleTV);
            eventTitle.setText(viewString.get(3));

            eventImage = (ImageView)postLayout.findViewById(R.id.eventImage);
            imageloader.displayImage(viewString.get(4), eventImage, options);


            likesTV = (TextView)postLayout.findViewById(R.id.likesTV);
            likesTV.setText(""+viewContent.get(5));

            planToAttendTV = (TextView)postLayout.findViewById(R.id.planToAttendTV);
            planToAttendTV.setText(viewString.get(6));

            Log.d("Adapter", ""+viewString.get(6));



            return postLayout;
        }


        @Override
        public int getCount()
        {
            Log.d("Adapter", ""+viewString.size());
            return viewString.size();
        }

        @Override
        public String getItem(int position) {
            return viewString.get(position);
        }

    }

}











public DisplayImageOptions initiateDisplayImageOptions()
{
    DisplayImageOptions options = new DisplayImageOptions.Builder()
            .cacheInMemory(true)
            .cacheOnDisc(true)
            .bitmapConfig(Bitmap.Config.RGB_565)
            .build();

    return options;
}


protected void initImageLoader(Context context) {
    // This configuration tuning is custom. You can tune every option, you may tune some of them,
    // or you can create default configuration by
    //  ImageLoaderConfiguration.createDefault(this);
    // method.
    ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
            .threadPriority(Thread.NORM_PRIORITY - 2)
            .denyCacheImageMultipleSizesInMemory()
            .diskCacheFileNameGenerator(new Md5FileNameGenerator())
            .tasksProcessingOrder(QueueProcessingType.LIFO)
            .writeDebugLogs() // Remove for release app
            .build();

    // Initialize ImageLoader with configuration.
    ImageLoader.getInstance().init(config);
}

public String getMonth(int mon)
{
    String month;

    if(mon == 1)
    {
        month = "January";
    }
    else if (mon == 2)
    {
        month = "February";
    }
    else if (mon == 3)
    {
        month = "March";
    }
    else if (mon == 4)
    {
        month = "April";
    }
    else if (mon == 5)
    {
        month = "May";
    }
    else if (mon == 6)
    {
        month = "June";
    }
    else if (mon == 7)
    {
        month = "July";
    }
    else if (mon == 8)
    {
        month = "August";
    }
    else if (mon == 9)
    {
        month = "September";
    }
    else if (mon == 10)
    {
        month = "October";
    }
    else if (mon == 11)
    {
        month = "November";
    }
    else
    {
        month = "December";
    }


    return month;
}

}

4 个答案:

答案 0 :(得分:2)

尝试更改此行

// Get listview
lv = (ListView) view.findViewById(R.id.listView);

lv = (ListView) getActivity().findViewById(R.id.listView);

参见 ListFragment Not Rendering and getView() in Adapter Not Being Called

答案 1 :(得分:1)

我不确定你需要

 getActivity().runOnUiThread(new Runnable() {
            public void run() {

}

在onPostExecute()中。它会自动完成UI线程上的所有操作。请删除它并查看。

答案 2 :(得分:0)

您的 doInBackground()正在填充名为“ viewContent ”的变量,该变量是静态的。由于 doInBackground()在后台线程中发生,并且当您在另一个线程中运行的 onPostExecute()上使用它时,它会因Thread visibility issue而失败,换句话说,一个线程更改的变量是另一个线程不可见的,如果在同步区域中执行,则更改。在同步区域中执行此操作会使您的代码工作,但这不是使用AsyncTask的Android方式。

你应该做的是:删除make doInBackground()返回此列表的副本,并在 onPostExecute()上,您将收到此列表作为参数,然后您可以将其绕过适配器。忘掉这个静态列表viewContent = new ArrayList&lt;&gt;(); 除非你想要缓存结果,但要小心使用它。

解决方案示例如下:

class LoadAllProducts extends AsyncTask<String, String, List<String>> {

  protected List<String> doInBackground(String... args) {
    List<String> allData = ....
    return allData;
  }


  protected void onPostExecute(List<String> allData) {
    Log.d("Loading Events: ", "Events Loaded");

     StableArrayAdapter adapter = new StableArrayAdapter(getActivity(), allData);
     // updating listview
     lv.setAdapter(adapter);
     adapter.notifyDataSetChanged();
   }

}

适配器上的其他相邻问题:

您的适配器有一个字符串列表.OK。但是,适配器设计为列表中的每个项目调用getView()。在您的获取视图中,您调用列表中的所有位置,这会使目的失效。

在你的getView()中你应该调用:

 String currentItem = getItem(position);
 // note that 'position' is one of the given parameters for the getView().

请阅读getView() api,以便更深入地了解每个参数。

答案 3 :(得分:0)

对所有可能面临类似问题的人。从未调用getView()的原因是因为在我的onCreateView()我的片段中,当我返回视图时,我在最后一个新布局。我的问题是我正在修改膨胀布局中的视图然后我返回一个新视图因此getView没有时间被调用,即使它确实如此,它也不会显示任何结果,因为我正在膨胀一个全新的布局。为了解决这个问题,我删除了 return (RelativeLayout)inflater.inflate(R.layout.main_feed_layout, container, false);,而是放了return view;。这立即解决了我的问题。