主详细信息流单击recyclerview时出现空异常

时间:2018-11-14 11:18:11

标签: android android-recyclerview master-detail

嗯,我有recyclerView和一个片段作为Master Detail Flow的示例 现在我从json获取数据,并在recyclerView中完美解析 问题是每当我单击它时,都会得到null异常。

public class ItemDetailFragment extends Fragment {
/**
 * The fragment argument representing the item ID that this fragment
 * represents.
 */
public static final String ARG_ITEM_ID = "item_id";

/**
 * The dummy content this fragment is presenting.
 */
private DummyContent.DummyItem mItem;

/**
 * Mandatory empty constructor for the fragment manager to instantiate the
 * fragment (e.g. upon screen orientation changes).
 */
public ItemDetailFragment() {
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (getArguments().containsKey(ARG_ITEM_ID)) {
        // Load the dummy content specified by the fragment
        // arguments. In a real-world scenario, use a Loader
        // to load content from a content provider.
        mItem = DummyContent.ITEM_MAP.get(getArguments().getString(ARG_ITEM_ID));

        Activity activity = this.getActivity();
        CollapsingToolbarLayout appBarLayout = (CollapsingToolbarLayout) activity.findViewById(R.id.toolbar_layout);
        if (appBarLayout != null) {
            appBarLayout.setTitle(mItem.id);
        }
    }
}

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

    // Show the dummy content as text in a TextView.
    if (mItem != null) {
        ((TextView) rootView.findViewById(R.id.item_detail)).setText("hello");


    }

    return rootView;
}

这是活动

public class ItemDetailActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_item_detail);
    Toolbar toolbar = (Toolbar) findViewById(R.id.detail_toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own detail action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    // Show the Up button in the action bar.
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        actionBar.setDisplayHomeAsUpEnabled(true);
    }

    // savedInstanceState is non-null when there is fragment state
    // saved from previous configurations of this activity
    // (e.g. when rotating the screen from portrait to landscape).
    // In this case, the fragment will automatically be re-added
    // to its container so we don't need to manually add it.
    // For more information, see the Fragments API guide at:
    //
    // http://developer.android.com/guide/components/fragments.html
    //
    if (savedInstanceState == null) {
        // Create the detail fragment and add it to the activity
        // using a fragment transaction.
        Bundle arguments = new Bundle();
        arguments.putString(ItemDetailFragment.ARG_ITEM_ID,
                getIntent().getStringExtra(ItemDetailFragment.ARG_ITEM_ID));
        ItemDetailFragment fragment = new ItemDetailFragment();
        fragment.setArguments(arguments);
        getSupportFragmentManager().beginTransaction()
                .add(R.id.item_detail_container, fragment)
                .commit();
    }
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == android.R.id.home) {
        // This ID represents the Home or Up button. In the case of this
        // activity, the Up button is shown. For
        // more details, see the Navigation pattern on Android Design:
        //
        // http://developer.android.com/design/patterns/navigation.html#up-vs-back
        //
        navigateUpTo(new Intent(this, ItemListActivity.class));
        return true;
    }
    return super.onOptionsItemSelected(item);
}
 }

这是我获取json和ItemlistActivity的地方

public class ItemListActivity extends AppCompatActivity {
View recyclerView;
/**
 * Whether or not the activity is in two-pane mode, i.e. running on a tablet
 * device.
 */
private boolean mTwoPane;
RequestQueue queue;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_item_list);
    queue = Volley.newRequestQueue(this);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    toolbar.setTitle(getTitle());

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

     recyclerView = findViewById(R.id.item_list);
    assert recyclerView != null;

    if (findViewById(R.id.item_detail_container) != null) {
        // The detail container view will be present only in the
        // large-screen layouts (res/values-w900dp).
        // If this view is present, then the
        // activity should be in two-pane mode.
        mTwoPane = true;
    }
    connection();

}

private void setupRecyclerView(@NonNull RecyclerView recyclerView) {
    recyclerView.setAdapter(new SimpleItemRecyclerViewAdapter(DummyContent.ITEMS));
}

public class SimpleItemRecyclerViewAdapter
        extends RecyclerView.Adapter<ViewHolder> {

    private final List<DummyContent.DummyItem> mValues;

    public SimpleItemRecyclerViewAdapter(List<DummyContent.DummyItem> items) {
        mValues = items;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_list_content, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {

        String profilePicUrl = mValues.get(position).profile_pic;
        String full_name = mValues.get(position).full_name;
        String state = mValues.get(position).state;
        String city = mValues.get(position).city;
        String phoneNo =  mValues.get(position).phone_no;

        holder.full_name.setText("Name : " +full_name);
        holder.state.setText("State : " +state);
        holder.city.setText("City : " +city);
        holder.phone_number.setText("Phone Number : " +phoneNo);
        Glide.with(getApplicationContext())
                .load(profilePicUrl)
                .fitCenter()
                .override(500,500)
                .into(holder.profile_pic);




        holder.mView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mTwoPane) {
                    Bundle arguments = new Bundle();
                    arguments.putString(ItemDetailFragment.ARG_ITEM_ID, holder.mItem.id);
                    ItemDetailFragment fragment = new ItemDetailFragment();
                    fragment.setArguments(arguments);
                    getSupportFragmentManager().beginTransaction()
                            .replace(R.id.item_detail_container, fragment)
                            .commit();
                } else {
                    Context context = v.getContext();
                    Intent intent = new Intent(context, ItemDetailActivity.class);
                    Log.e("hello",holder.mItem.full_name);
                    intent.putExtra(ItemDetailFragment.ARG_ITEM_ID, holder.mItem.id);

                    context.startActivity(intent);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return mValues.size();
    }


}

public void connection(){

    final String url = "aaaaa";

    // prepare the Request
    JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, url, null,
            new Response.Listener<JSONObject>()
            {
                @Override
                public void onResponse(JSONObject response) {
                    // display response
                    try {
                        JSONArray jsonArray = response.getJSONArray("results");

                        for (int i = 0; i < jsonArray.length(); i++) {

                            JSONObject test = jsonArray.getJSONObject(i);
                            String gender = test.getString("gender");


                            String full_name = test.getJSONObject("name").getString("title") + " " +
                                    test.getJSONObject("name").getString("first") + " " +
                                    test.getJSONObject("name").getString("last");

                            String state = test.getJSONObject("location").getString("state");
                            String city = test.getJSONObject("location").getString("city");
                            String phone_no = test.getString("phone");
                            String profile_pic = test.getJSONObject("picture").getString("large");
                            String id = test.getJSONObject("id").getString("name");
                            Log.d("test2222", gender + " \n " + full_name + " \n " + state + " \n " + city + " \n " + phone_no + "\n" + profile_pic
                                    + "\n" + id);


                            addItem(new DummyContent.DummyItem(gender,profile_pic, full_name, state, city, phone_no,"hello"));
                        }                            

                        setupRecyclerView((RecyclerView) recyclerView);


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener()
            {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.d("Error.Response", error.toString());
                    Toast.makeText(getApplicationContext(),"check internet connection",Toast.LENGTH_SHORT).show();

                }
            }
    );

    // add it to the RequestQueue

    queue.add(getRequest);
}

最后是虚拟内容

public class DummyContent {

/**
 * An array of sample (dummy) items.
 */
public static final List<DummyItem> ITEMS = new ArrayList<DummyItem>();

/**
 * A map of sample (dummy) items, by ID.
 */
public static final Map<String, DummyItem> ITEM_MAP = new HashMap<String, DummyItem>();

private static final int COUNT = 25;

static {
    // Add some sample items.
}

public static void addItem(DummyItem item) {
    ITEMS.add(item);
    ITEM_MAP.put(item.full_name, item);


}



/**
 * A dummy item representing a piece of content.
 */
public static class DummyItem  {
    public final String id;
    public final String profile_pic;
    public final String full_name;
    public final String state;
    public final String city;
    public final String phone_no;

    public final String data;



    public DummyItem(String id ,String profile_pic, String full_name, String state ,String city,String phone_no,String data) {
        this.id = id;
        this.profile_pic = profile_pic;
        this.full_name = full_name;
        this.state = state;
        this.city = city;
        this.phone_no = phone_no;
        this.data = data;

    }



    @Override
    public String toString() {
        return full_name;
    }
}
 }

现在的问题是我想获取与片段相同的数据(文本或图像) 我的问题是我什至无法显示带有自定义“ hello world”文本视图的片段,每当我单击recyclerview时都会出现异常,因此请向我解释代码中的错误在哪里

这是ViewHolder

public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final ImageView profile_pic;
public final TextView full_name;
public final TextView state;
public final TextView city;
public final TextView phone_number;


public DummyContent.DummyItem mItem;

public ViewHolder(View view) {
    super(view);
    mView = view;
    profile_pic = (ImageView) view.findViewById(R.id.profile_pic);
    full_name = (TextView) view.findViewById(R.id.full_name_txt);
    state = (TextView) view.findViewById(R.id.state_txt);
    city = (TextView) view.findViewById(R.id.city_txt);
    phone_number = (TextView) view.findViewById(R.id.phone_no_txt);


}

@Override
public String toString() {
    return super.toString() + " '" + full_name.getText() + "'";
}

}

1 个答案:

答案 0 :(得分:0)

您将获得空值,因为您正在使用ViewHolder类中的mItem而不进行初始化,该值为null。

尝试一下:

 DummyContent.DummyItem mItem = mValues.get(position);  //initialize here, not in ViewHolder class
holder.mView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mTwoPane) {
                Bundle arguments = new Bundle();
                arguments.putString(ItemDetailFragment.ARG_ITEM_ID, mItem.id); //use without holder
                ItemDetailFragment fragment = new ItemDetailFragment();
                fragment.setArguments(arguments);
                getSupportFragmentManager().beginTransaction()
                        .replace(R.id.item_detail_container, fragment)
                        .commit();
            } else {
                Context context = v.getContext();
                Intent intent = new Intent(context, ItemDetailActivity.class);
                Log.e("hello",holder.mItem.full_name);
                intent.putExtra(ItemDetailFragment.ARG_ITEM_ID, mItem.id); //same here

                context.startActivity(intent);
            }
        }
    });