CustomList未添加到片段中

时间:2014-10-10 03:42:34

标签: android android-fragments android-asynctask custom-lists

我已经被困在这里很长一段时间了。我使用异步任务来检索事件列表并将它们添加到片段中的列表视图中。但是,它没有显示出来。有人可以告诉我有什么问题吗?这将是一个很好的帮助。

这是片段的代码:

public static class EventsSectionFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    public static final String ARG_SECTION_NUMBER = "section_number";
    SharedPreferences settings = null;
    Editor editor;
    ListView list;
    TextView noEventsTv;

    public EventsSectionFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
    {
        recLifeCycle_with_savedInstanceState(savedInstanceState);
        View rootView = inflater.inflate(R.layout.fragment_events, container, false);

        list = (ListView) rootView.findViewById(R.id.list);
        noEventsTv = (TextView) rootView.findViewById(R.id.norecordsTV);

        new GetEventsAsyncTask((MainActivity) getActivity()).execute();

        settings = PreferenceManager.getDefaultSharedPreferences(getActivity());

        return rootView;
    }

    public void updateEventList(final List<Event> eventList)
    {

        Log.i("updateEventList:eventlist.count", String.valueOf(eventList.size()));

        if (eventList.size() > 0) 
        {

            Log.i("CustomList", "Start customlist inflation");
            CustomList adapter = new CustomList(getActivity(), eventList);

            noEventsTv.setVisibility(View.GONE);
            list.setVisibility(View.VISIBLE);
            list.setAdapter(adapter);
            list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {

                    String eventSel = eventList.get(position).getEvent_id();
                    event_id = eventSel;
                    // direct to event details fragment
                    startEventDetailsFragment();
                }
            });
            adapter.notifyDataSetChanged();
            list.invalidateViews();
        } 
        else 
        {
            noEventsTv.setVisibility(View.VISIBLE);
            list.setVisibility(View.GONE);
        }
    }

这是检索事件的异步任务:

public class GetEventsAsyncTask extends AsyncTask<Void, Integer, Boolean>{

ProgressDialog progressDialog;
MainActivity activityMain;
Boolean ticketValid=false;
List<Event> eventList = new ArrayList<Event>();

public GetEventsAsyncTask(MainActivity parent)
{
    activityMain = parent;
}

 @Override
    protected void onPreExecute() {

        progressDialog = null;

         if (progressDialog == null) 
         {
               progressDialog = new ProgressDialog(activityMain);
               progressDialog.setMessage("download events, please wait...");
               progressDialog.show();
               progressDialog.setCanceledOnTouchOutside(false);
               progressDialog.setCancelable(false);
         }   
    }

      @Override
      protected Boolean doInBackground(Void... params) {
        // TODO Auto-generated method stub
            Boolean error = false;
            try {
                error = postData();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return error;
      }

      protected void onPostExecute(Boolean error){          
             /* if (progressDialog.isShowing()) {
                  progressDialog.dismiss();
                  progressDialog = null;
              } */
              if(error==true)
              {
                  Log.i("GetEvents", "Error at get events");
                  activityMain.errorOccured();
              }
              else
              {
                  Log.i("onPostExecute:eventlist.count",String.valueOf(eventList.size()));
                  MainActivity.myDB.removeAllEvents();
                  for(int i=0;i<eventList.size();i++)
                  {
                      MainActivity.myDB.insertEventEntry(eventList.get(i));
                  }
                  activityMain.downloadEventsSuccess(eventList);

              }

      } 

      protected void onProgressUpdate(Integer... progress){
      }


    public Boolean postData() throws JSONException {

        Boolean error = false;
        HttpClient httpclient = new DefaultHttpClient();
      // specify the URL you want to post to

        try {

            HttpGet httpget = new HttpGet(Constants.HOST_NAME+"/"+Constants.SERVICE_NAME+"/api/event?userId=S6871919D");
            BufferedReader reader;
            StringBuffer sb;
            String line = "";
            String NL="";
            String json;
            HttpResponse response = httpclient.execute(httpget);

            if(response.getStatusLine().getStatusCode()==200)
            {
                reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));

                 sb = new StringBuffer("");
                 line = "";
                 NL = System.getProperty("line.separator");

                while ((line = reader.readLine()) != null)
                {
                    sb.append(line + NL);
                }

                reader.close();
                json = sb.toString();

                Log.i("event json",json);
                try
                {
                    JSONArray jsonArray = new JSONArray(json);   

                    for (int i = 0, length = jsonArray.length(); i < length; i++)
                    {
                        JSONObject attribute = jsonArray.getJSONObject(i);
                        Event eventObj =  new Event(); 
                        eventObj.setEvent_id(attribute.getString("event_id"));
                        eventObj.setEvent_title(attribute.getString("event_title"));
                        eventObj.setEvent_desc(attribute.getString("event_desc"));
                        eventObj.setStart_date(attribute.getString("start_date"));
                        eventObj.setEnd_date(attribute.getString("end_date"));
                        eventObj.setStart_time(attribute.getString("start_time"));
                        eventObj.setEnd_time(attribute.getString("end_time"));
                        eventObj.setLocation(attribute.getString("location"));
                        eventObj.setPicture_path(attribute.getString("picture_path"));
                        eventObj.setSmall_picture_path(attribute.getString("small_picture_path"));

                        eventList.add(eventObj);
                        eventObj = null;
                    }
                }
                catch (JSONException e)
                {
                    e.printStackTrace();
                    error = true;
                }
            }
            else
            {
                error = true;
            }


        } catch (ClientProtocolException e) {
            // process execption
            error = true;
        } catch (IOException e) {
            // process execption
            error = true;
        }
        return error;

    }

这是customList的代码:

private final Activity context;
private final List<Event> eventsList;

public CustomList(Activity context, List<Event> eventsList) {
    super(context, R.layout.list_single);
    this.context = context;
    this.eventsList = eventsList;


}
@Override
public View getView(int position, View view, ViewGroup parent) {

    //set up the inflater...
    LayoutInflater inflater = context.getLayoutInflater();
    View rowView= inflater.inflate(R.layout.list_single, null, true);

    //reference the widgets...
    TextView txtTitle = (TextView) rowView.findViewById(R.id.txt);
    TextView txtDate = (TextView) rowView.findViewById(R.id.txt2);
    ImageView imageView = (ImageView) rowView.findViewById(R.id.img);
    Log.i("CustomList", "Start customList");

    txtTitle.setText(eventsList.get(position).getEvent_title());
    txtDate.setText(eventsList.get(position).getStart_date());
    new GetEventsImageAsyncTask(imageView).execute(Constants.HOST_NAME + "/"+ Constants.CMS_NAME+ "/" +eventsList.get(position).getSmall_picture_path());

    Log.i("CustomList", "End customList");

    return rowView;
}

这是从服务器检索图像的异步任务:

public class GetEventsImageAsyncTask extends AsyncTask<String, Void, Bitmap> {

    ImageView imageView;

    public GetEventsImageAsyncTask(ImageView imageView){
        this.imageView = imageView;
    }

    @Override
    protected Bitmap doInBackground(String... url) {
        // TODO Auto-generated method stub
        String urls = url[0];
        Bitmap icon = null;

        try
        {
            InputStream input = new java.net.URL(urls).openStream();
            icon = BitmapFactory.decodeStream(input);
        }

        catch(Exception e)
        {
            Log.e("GetEventImage", e.getMessage());
            e.printStackTrace();
        }

        return icon;
    }

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

这是自定义列表的xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/list_single"
android:layout_width="match_parent"
android:layout_height="match_parent" 
android:background="@drawable/bg"
android:orientation="horizontal">

    <ImageView
        android:id="@+id/img"
        android:layout_width="50dp"
        android:layout_height="match_parent"
        android:contentDescription="@drawable/ic_launcher"/>

    <TextView
        android:id="@+id/txt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/img"
        android:text="Placeholder" />

    <TextView
        android:id="@+id/txt2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/img"
        android:layout_marginTop="7dp"
        android:layout_below="@+id/txt"
        android:text="Placeholder" />

这是事件片段的xml:

    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/fragment_events"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <LinearLayout
      android:orientation="vertical"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:background="@drawable/bg">

        <ListView
           android:id="@+id/list"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" > 
        </ListView>

        <TextView
                android:id="@+id/norecordsTV"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:text="@string/no_events"
                android:visibility="gone"
                android:gravity="center"/>
    </LinearLayout>
</FrameLayout>

代码甚至没有转到CustomList adapter = new CustomList(getActivity(),eventList);而且我不知道为什么。事件正确检索btw。

编辑:

这里是logcat:

10-10 12:56:44.193: I/updateEventList:eventlist.count(16963): 4
10-10 12:56:56.473: I/MYTAG(16963): FacilitiesSectionFragment.onPause
10-10 12:56:56.473: I/MYTAG(16963): FacilitiesSectionFragment.onStop
10-10 12:56:56.473: I/MYTAG(16963): FacilitiesSectionFragment.onDestroyView
10-10 12:56:56.553: I/dalvikvm(16963): Total arena pages for JIT: 25
10-10 12:56:56.553: I/dalvikvm(16963): Total arena pages for JIT: 26
10-10 12:56:56.553: I/dalvikvm(16963): Total arena pages for JIT: 27
10-10 12:56:56.553: I/dalvikvm(16963): Total arena pages for JIT: 28
10-10 12:56:56.553: I/dalvikvm(16963): Total arena pages for JIT: 29
10-10 12:56:56.553: I/dalvikvm(16963): Total arena pages for JIT: 30
10-10 12:56:56.553: I/dalvikvm(16963): Total arena pages for JIT: 31
10-10 12:56:56.553: I/dalvikvm(16963): Total arena pages for JIT: 32
10-10 12:56:56.563: I/dalvikvm(16963): Total arena pages for JIT: 33
10-10 12:56:56.563: I/dalvikvm(16963): Total arena pages for JIT: 34
10-10 12:56:56.563: I/dalvikvm(16963): Total arena pages for JIT: 35
10-10 12:56:56.563: I/dalvikvm(16963): Total arena pages for JIT: 36
10-10 12:56:56.563: I/dalvikvm(16963): Total arena pages for JIT: 37
10-10 12:56:56.563: I/dalvikvm(16963): Total arena pages for JIT: 38
10-10 12:56:56.563: I/dalvikvm(16963): Total arena pages for JIT: 39
10-10 12:56:56.563: I/dalvikvm(16963): Total arena pages for JIT: 40
10-10 12:56:56.563: I/dalvikvm(16963): Total arena pages for JIT: 41
10-10 12:56:57.333: I/MYTAG(16963): FacilitiesSectionFragment.onCreateView / savedInstanceState == null
10-10 12:56:57.333: I/MYTAG(16963): FacilitiesSectionFragment.onStart
10-10 12:56:57.333: I/MYTAG(16963): FacilitiesSectionFragment.onResume
10-10 12:56:57.383: I/facility json(16963): [{"facility_id":"ITM00000002","facility_name":"Libary","facility_desc":"The Nanyang Polytechnic Library provides a rich and diverse collection of resources to serve the information and research needs of staff and students.","requires_booking":"N","school_code":"ARO","open_hrs":"0900","close_hrs":"2100","open_for_book":null,"picture_path":"Data/Sites/1/uploads/alumniAdmin_Facility_2014-09-22_03-51-30.png","small_picture_path":"Data/Sites/1/uploads/alumniAdmin_Facility_2014-09-22_03-30-54.png","close_from":"0001-01-01T00:00:00","close_to":"0001-01-01T00:00:00","fee":"0.00"},{"facility_id":"ITM00000004","facility_name":"Table Tennis","facility_desc":"Table Tennis for playing  table tennis","requires_booking":"N","school_code":"ARO","open_hrs":"0900","close_hrs":"2100","open_for_book":null,"picture_path":"Data/Sites/1/uploads/alumniAdmin_Facility_2014-09-22_03-31-44.png","small_picture_path":"Data/Sites/1/uploads/alumniAdmin_Facility_2014-09-22_03-31-44.jpg","close_from":"0001-01-01T00:00:00","close_to":"0001-01-01T00:00:00","fee":"3.00"},{"facility_id":"ITM00000009","facility_name":"Badminton Court Pass","facility_desc":"Badminton Court Pass","requires_booking":"N","school_code":"ARO","open_hrs":"0900","close_hrs":"2100","open_for_book":null,"picture_path":"Data/Sites/1/uploads/leowzzaro_Facility_2014-10-08_11-29-05.png","small_picture_path":"Data/Sites/1/uploads/leowzzaro_Facility_2014-10-08_11-29-05.jpg","close_from":"0001-01-01T00:00:00","close_to":"0001-01-01T00:00:00","fee":"0.00"},{"facility_id":"ITM00000014","facility_name":"Badminton Court","facility_desc":"Badminton Court for playing badminton","requires_booking":"Y","school_code":"ARO","open_hrs":"0900","close_hrs":"2100","open_for_book":null,"picture_path":"Data/Sites/1/uploads/leowzzaro_Facility_2014-10-08_11-22-44.png","small_picture_path":"Data/Sites/1/uploads/leowzzaro_Facility_2014-10-08_11-22-44.jpg","close_from":"0001-01-01T00:00:00","close_to":"0001-01-01T00:00:00","fee":"3.00"}]
10-10 12:56:57.393: I/onPostExecute:facilityList.count(16963): 4
10-10 12:56:57.403: W/MY_LOG(16963): Removing Entries from facilities Success
10-10 12:56:57.403: W/MY_LOG(16963): Inserted EntryName=Libary into table facilities
10-10 12:56:57.433: W/MY_LOG(16963): Inserted EntryName=Table Tennis into table facilities
10-10 12:56:57.453: W/MY_LOG(16963): Inserted EntryName=Badminton Court Pass into table facilities
10-10 12:56:57.493: W/MY_LOG(16963): Inserted EntryName=Badminton Court into table facilities
10-10 12:56:57.513: I/updateEventList:eventlist.count(16963): 4
10-10 12:57:06.523: I/MYTAG(16963): EcardSectionFrontFragment.onPause
10-10 12:57:06.523: I/MYTAG(16963): EcardSectionFrontFragment.onStop
10-10 12:57:06.533: I/MYTAG(16963): EcardSectionFrontFragment.onDestroyView
10-10 12:57:06.533: I/MYTAG(16963): TicketSectionFragment.onCreateView / savedInstanceState == null
10-10 12:57:06.543: I/MYTAG(16963): TicketSectionFragment.onStart
10-10 12:57:06.543: I/MYTAG(16963): TicketSectionFragment.onResume
10-10 12:57:14.203: I/MYTAG(16963): EcardSectionFrontFragment.onCreateView / savedInstanceState == null
10-10 12:57:14.203: I/MYTAG(16963): TicketSectionFragment.onPause
10-10 12:57:14.203: I/MYTAG(16963): TicketSectionFragment.onStop
10-10 12:57:14.203: I/MYTAG(16963): TicketSectionFragment.onDestroyView
10-10 12:57:14.203: I/MYTAG(16963): EcardSectionFrontFragment.onStart
10-10 12:57:14.203: I/MYTAG(16963): EcardSectionFrontFragment.onResume

1 个答案:

答案 0 :(得分:3)

您的CustomList Adapter没有列表计数,因此通过添加以下方法可以解决问题..

@Override public int getCount()
{
 if (List.size() <= 0)
 {
  return 0;
  }
 return List.size();
 }

@Override
public Event getItem(int position)
{
    return List.get(position);
}

@Override
public long getItemId(int position)
{
    return position;
}