0

我正在使用诸如slidingMenu、pullToRefreshListViews 和android Aquery 之类的片段和库。在我的应用程序中,我想使用从 JSON 解析的数据使用自定义适配器填充我的 ListView。

这是粗略的代码

public class MyFragment extends Fragment {

public MyFragment() {
    // Empty constructor required for fragment subclasses
}
    //initialize some variables here....
    PullToRefreshListView   list;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
final View rootView = inflater.inflate(//my layout xml, container, false);
aq = new AQuery(getActivity(),rootView);
list = (PullToRefreshListView) rootView.findViewById(R.id.list);
asyncJson(); // this method fetches,parses json and sets adapter to the listview
return rootView;
    }
}

asyncJson() 方法是这样的。

public void asyncJson(){
    aq.ajax(url, JSONArray.class, expire, new AjaxCallback<JSONArray>() {

        @Override
        public void callback(String url, JSONArray json, AjaxStatus status) {
    try{
           // fetch and parse json store data in array<List>
        }
      if(adapter == null){
                adapter = new MyAdapter(getView().getContext(),//array<list> variables);
                list.setAdapter(adapter);

                }
                else if(adapter != null){

                    adapter.notifyDataSetChanged();

                }
    }
 });
}

Logcat 在 list.setAdapter(adapter);这一行给了我空指针异常。我没有语法错误。这是因为我传递给适配器的上下文我只是尝试了 getActivity() 但这不起作用是列表 null 还是适配器?:0 我做错了什么?

谢谢!日志猫图像

应用项目文件:https ://www.dropbox.com/s/9sa1l8wm4rnmnew/stackoverflow.zip

4

2 回答 2

0

主要是你Context给你的NullPointerException

尝试通过Context构造函数将 a 传递给您的片段并在适配器中使用它。

private Context ctx;

  public MyFragment(Context ctx) {
    this.ctx = ctx;
}

并像这样初始化适配器:

adapter = new MyAdapter(ctx, array<list> variables);
于 2013-06-27T17:32:19.647 回答
0

我猜你正在使用这个库......

https://github.com/chrisbanes/Android-PullToRefresh

下载它,您需要导入以下内容并将其添加为我们项目的依赖项。

PullToRefreshListFragment 库

我修改了从您的评论链接下载的项目。你可以在这里下载:

https://dl.dropboxusercontent.com/u/33565803/StackOverFlowExamples/chrisbanes%20-%20Android-PullToRefresh-master-plusHeader.zip

我也要编写代码,所以我们不依赖这个链接的这个答案;)。所以我们只有一个从 FragmentActivity 扩展的名为 MainActivity 的类。

public class MainActivity extends FragmentActivity implements PullToRefreshBase.OnRefreshListener<ListView> {

FragmentManager fm = getSupportFragmentManager();
private PullToRefreshListFragment mPullRefreshListFragment;

private PullToRefreshListView mPullRefreshListView;
private ListView mActualListView;

private String[] mStrings = {"Abbaye de Belloc", "Abbaye du Mont des Cats", "Abertam", "Abondance", "Ackawi",
        "Acorn", "Adelost", "Affidelice au Chablis", "Afuega'l Pitu", "Airag", "Airedale", "Aisy Cendre",
        "Allgauer Emmentaler", "Abbaye de Belloc", "Abbaye du Mont des Cats", "Abertam", "Abondance", "Ackawi",
        "Acorn", "Adelost", "Affidelice au Chablis", "Afuega'l Pitu", "Airag", "Airedale", "Aisy Cendre",
        "Allgauer Emmentaler"};

private LinkedList<String> mListItems;
private ArrayAdapter<String> mAdapter;


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

    // sliding menu implementation
    /*final SlidingMenu menu = new SlidingMenu(this);
    menu.setMode(SlidingMenu.LEFT);
    menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
    menu.setShadowWidthRes(R.dimen.shadow_width);
    menu.setShadowDrawable(R.drawable.shadow);
    menu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
    menu.setFadeDegree(0.35f);
    menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
    menu.setMenu(R.layout.menu);*/

    // event handlers come after slidingmenu

    mPullRefreshListFragment = (PullToRefreshListFragment) getSupportFragmentManager().findFragmentById(R.id.frag_ptr_list);

    //aq = new AQuery(getActivity(),mPullToRefreshListFragment.getView());

    /*mPullRefreshListView.setOnScrollListener(new EndlessScrollListener();*/


    mPullRefreshListView = mPullRefreshListFragment.getPullToRefreshListView();

    // Set a listener to be invoked when the list should be refreshed.
    mPullRefreshListView.setOnRefreshListener(this);


    // You can also just use mPullRefreshListFragment.getListView()
    mActualListView = mPullRefreshListView.getRefreshableView();


    mListItems = new LinkedList<String>();
    mListItems.addAll(Arrays.asList(mStrings));
    mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mListItems);

    View headerView = getLayoutInflater().inflate(R.layout.list_header, null);
    mActualListView.addHeaderView(headerView);
    mActualListView.setAdapter(mAdapter);

    mPullRefreshListFragment.setListShown(true);
    /*asyncJson(1,expire);*/

}

public void asyncJson(int page, final long expire) {
    // GET JSON FROM THE WEB AND PARSE IT
    // ALSO STORE DATA IN ARRAY LIST VARIABLES

    if (expire == -1) {
        mPullRefreshListView.onRefreshComplete();
    }

    //if(pg == 1 && expire !=-1){

        //If you wanna add a header at this point, do it like this
        View headerView = getLayoutInflater().inflate(R.layout.list_header, null);
        mActualListView.addHeaderView(headerView);
        // DO SOMETHING
    //}

    //Just notify the changes because the adapter do exist
    mAdapter.notifyDataSetChanged();
}

@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;
}

@Override
public void onRefresh(PullToRefreshBase<ListView> refreshView) {
    // Do work to refresh the list here.
    new GetDataTask().execute();
}


private class GetDataTask extends AsyncTask<Void, Void, String[]> {

    @Override
    protected String[] doInBackground(Void... params) {
        // Simulates a background job.
        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
        }
        return mStrings;
    }

    @Override
    protected void onPostExecute(String[] result) {
        mListItems.addFirst("Added after refresh...");
        mAdapter.notifyDataSetChanged();

        // Call onRefreshComplete when the list has been refreshed.
        mPullRefreshListView.onRefreshComplete();

        super.onPostExecute(result);
    }
  }
}

这是我们的布局:

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >


     <fragment
             android:id="@+id/frag_ptr_list"
             android:name="com.handmark.pulltorefresh.extras.listfragment.PullToRefreshListFragment"
             android:layout_width="match_parent"
             android:layout_height="match_parent" />


</RelativeLayout>

list_row.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

<TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</RelativeLayout>

list_header.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#4a2">

<TextView
        android:id="@+id/text"
        android:gravity="center"
        android:text="My Header"
        android:textColor="#fff"
        android:layout_width="match_parent"
        android:layout_height="40dp"/>
</RelativeLayout>
于 2013-06-28T09:39:03.793 回答