【问题标题】:getview not getting calledgetview 没有被调用
【发布时间】:2013-12-14 23:09:04
【问题描述】:

这是调用列表适配器的主要活动,应用程序每次都会崩溃,因为从未调用过 getview,因此永远不会加载列表。

MainActivity

public class MainActivity extends FragmentActivity {

    ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        // Create the adapter that will return a fragment for each of the three
        // primary sections of the app.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }



/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */

SectionsPagerAdapter

public class SectionsPagerAdapter extends FragmentPagerAdapter {
        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }
        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a DummySectionFragment (defined as a static inner class
            // below) with the page number as its lone argument.
            Fragment fragment = new DummySectionFragment();
            Bundle args = new Bundle();
            args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
            fragment.setArguments(args);
            return fragment;
        }
        @Override
        public int getCount() {
            // Show 3 total pages.
            return 3;
        }
        @Override
        public CharSequence getPageTitle(int position) {
            Locale l = Locale.getDefault();
            switch (position) {
                case 0:
                    return getString(R.string.title_section1).toUpperCase(l);
                case 1:
                    return getString(R.string.title_section2).toUpperCase(l);
                case 2:
                    return getString(R.string.title_section3).toUpperCase(l);
            }
            return null;
        }
    }

/** * 一个代表应用程序部分的虚拟片段,但这只是 * 显示虚拟文本。 */

DummySectionFragment

public static class DummySectionFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    public static final String ARG_SECTION_NUMBER = "section_number";

    public DummySectionFragment() {
    }

    @Override
     public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main_dummy, container, false);
       //itcItems = (ListView)rootView.findViewById(R.id.streamList);
        //itcItems.setAdapter(adapter);




        return rootView;
    }
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        MyAsyncTask task = new MyAsyncTask(getActivity());
        task.execute("http://findaway.in/card/restlist.xml");
        super.onActivityCreated(savedInstanceState);
    }
}


static class MyAsyncTask extends AsyncTask<String, Void, List<Data> > {

    Activity mContext;
    //Response response;
   public  MyAsyncTask(Activity context) {

     this.mContext=context;
    }
    protected List<Data> doInBackground(String... urls) {

        // Debug the task thread name
        Log.d("ITCRssReader", "inside");

        try {
            // Create RSS reader
            RssReader rssReader = new RssReader(urls[0]);
            Log.d("ITCRssReader", "inside1");
            // Parse RSS, get items
            //Log.d("ITCRssReader", rssReader.getItems().get(3).getName());
            return rssReader.getItems();

        } catch (Exception e) {
            Log.e("ITCRssReader", "error");
        }

        return null;
    }
    protected void onPostExecute(List<Data> result) {
        Log.d("RESULT", result.get(3).getName());
        // Get a ListView from main view
       ListView itcItems = (ListView)mContext.findViewById(R.id.streamList);
       ListAdapter la = new ListAdapter(mContext,R.layout.fragment_main_dummy, result);             
        // Create a list adapter
        itcItems.setAdapter(la);
    }
}
}`

这是我的适配器代码 "Log.d("list",obj.getName())" 永远不会被调用 列表适配器

public class ListAdapter extends ArrayAdapter<Data>    {
    Context context;
    // List values
    List<Data> foodList;
    public ListAdapter(Context context, int resource , List<Data> result) {
    super(context, resource, result);
    //Log.d("RESULT2", result.get(3).getName());
    this.context = context;
    this.foodList = result;
    Log.d("RESULT2", foodList.get(3).getName());
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
      //View rowView=convertView;
     // ImageHolder holder = null;

      Data obj = foodList.get(position);
      Log.d("list",obj.getName());

      LayoutInflater inflater = (LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
      View rowView = inflater.inflate(R.layout.fragment_main_dummy,parent,false);
      TextView n = (TextView)rowView.findViewById(R.id.name);
      TextView d = (TextView)rowView.findViewById(R.id.discount);
      TextView l = (TextView)rowView.findViewById(R.id.Type);
      n.setText(obj.getName());
      d.setText(obj.getDiscount());
      l.setText(obj.getLocation());


          return rowView;

       }


}

【问题讨论】:

  • “应用程序崩溃”不是很有帮助。您必须发布 LogCat 错误消息,顺便说一下,这将帮助您了解发生了什么问题。
  • snag.gy/nel1p.jpg 这是 logcat 截图

标签: android android-fragments adapter listadapter


【解决方案1】:

这里有一些不好的做法……但让我指出可能的罪魁祸首:

您的 AsyncTask 不应创建适配器。你的 AsyncTask 应该获取数据并让 Fragment 知道:嘿,这是新数据,你现在可以用它做任何你想做的事情。

另外,就像已经说明的那样,将 AsyncTask 排除在“onActivityCreated”之外。

错误可能在您的 onPostExecute 中:

 Log.d("RESULT", result.get(3).getName());

结果为空或结果列表的第 4 项没有名称。

始终检查 Null。

使用观察者/监听者模式来通知事件。

更新: 因为看起来 null 有点低于…

您正在一个方法 (onPostExecute) 中创建一个适配器,该适配器属于一个很快就会死去的对象 (AsyncTask),并且通过保留该适配器,您将保留您的异步任务,而异步任务又引用了一个 Activity ( Bad Idea),这是内存泄漏。

但是当你的整个 AsyncTask 最终被垃圾回收时,适配器就会死掉。因为就像我说的,你不应该在异步任务中创建适配器。

把这个逻辑移开。

在 OnPostExecute 上让您的片段知道有新数据。

在你的回调中做一些类似的事情......

if ( mListAdapter == null ) {
    mListAdapter = new Adapter…
    mListView.setAdapter(mListAdapter);
}
else {
    mListAdapter.notifyDataSetChanged();
}

【讨论】:

  • result.get(3).getName() 在日志中显示所需的名称意味着结果列表正在生成正常。问题是适配器没有设置,因为它返回 null。
  • 由于我是 android 新手,你能告诉我我需要做的代码修改吗?我明白了你的意思,但不知道如何解决这个问题。
【解决方案2】:

问题是,您在 oncreateview() 方法中调用了异步任务。

  • 因为 oncreateview() 方法为您的片段返回视图,在它为您的片段返回视图之后,只有您的片段视图被加载。

  • 由于您在 oncreateview 中添加了异步任务,因此异步任务在您的片段获取视图之前执行。所以在 onPostExecute() 你的列表视图将不起作用。

  • 解决方案:在片段的 onActivitycreated() 方法中执行异步任务。

【讨论】:

  • 我根据您的建议更新了我的代码,但仍然无法正常工作
【解决方案3】:

尝试在fragment的onAttach方法中执行异步任务。

@Override
public void onAttach(Activity activity) {
    // TODO Auto-generated method stub
    super.onAttach(activity);

    MyAsyncTask task = new MyAsyncTask(activity);
    task.execute("http://findaway.in/card/restlist.xml");
}

将您的 onPostExecute 更改为以下内容:

  protected void onPostExecute(List<Data> result) {
        Log.d("RESULT", result.get(3).getName());
        // Get a ListView from main view
       ListView itcItems = (ListView)DummySectionFragment.this.getView().findViewById(R.id.streamList);
       ListAdapter la = new ListAdapter(mContext,R.layout.fragment_main_dummy, result);             
        // Create a list adapter
        itcItems.setAdapter(la);
    }

您正在使用属于的方法 (onPostExecute) 创建适配器 到一个很快就会死去的对象(AsyncTask),并保持它 适配器你保留你的异步任务,这反过来有一个参考 到一个正在泄漏内存的活动(坏主意)。

我不同意适配器对象不属于 AsyncTask 对象,因为它是在 onPostExecute 内部创建并分配给一个局部变量保持适配器对象不是一个大问题,但事情是每次你得到新的适配器数据不是一个好主意,因为@martin 提到您应该只创建一个适配器并在数据更改时通知该适配器。

【讨论】:

  • 试过了还是不行 :( OnPost 像往常一样给出空指针异常
  • 而不是在活动上调用 findViewById 尝试在片段视图上调用它
  • 还是不行。您可能应该阅读上面的马丁斯评论,然后如果可能的话告诉我我需要进行的代码修改。
  • fragment_main_dummy 中有streamList吗??
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多