在片段中填充JSON listview

时间:2015-03-27 19:06:32

标签: java android listview android-fragments android-listview

我是java / android编程的初学者,但是我试图添加不同的教程来创建一个自定义的应用程序来完成我想要的东西,这可能对大多数人来说很容易,但是我在这个问题上陷入困境使用此Navigation Drawer View Pager尝试使用此Custom ListView with Volley填充选项卡一个片段。

我想将自定义列表视图的 MainActivity.java 中的代码传输到导航抽屉中的标签片段,但是我收到了错误。

片段标签

public class TabTwoFragment extends Fragment{

private TextView txtFragmenttwo;

public static TabTwoFragment newInstance() {
    Bundle bundle = new Bundle();

    TabTwoFragment fragment = new TabTwoFragment();
    fragment.setArguments(bundle);

    return fragment;
}   

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.two_fragment, container, false);

    txtFragmenttwo = (TextView) rootView.findViewById(R.id.txtFragmentTwo);
    txtFragmenttwo.setText(R.string.fragment_tab_two);

    rootView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT ));       
    return rootView;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onActivityCreated(savedInstanceState);
    setHasOptionsMenu(true);
}`

MainActivity

public class MainActivity extends Activity {
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();

// Movies json url
private static final String url = "http://api.androidhive.info/json/movies.json";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;

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

    listView = (ListView) findViewById(R.id.list);
    adapter = new CustomListAdapter(this, movieList);
    listView.setAdapter(adapter);

    pDialog = new ProgressDialog(this);
    // Showing progress dialog before making http request
    pDialog.setMessage("Loading...");
    pDialog.show();

    // changing action bar color
    getActionBar().setBackgroundDrawable(
            new ColorDrawable(Color.parseColor("#1b1b1b")));

    // Creating volley request obj
    JsonArrayRequest movieReq = new JsonArrayRequest(url,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    Log.d(TAG, response.toString());
                    hidePDialog();

                    // Parsing json
                    for (int i = 0; i < response.length(); i++) {
                        try {

                            JSONObject obj = response.getJSONObject(i);
                            Movie movie = new Movie();
                            movie.setTitle(obj.getString("title"));
                            movie.setThumbnailUrl(obj.getString("image"));
                            movie.setRating(((Number) obj.get("rating"))
                                    .doubleValue());
                            movie.setYear(obj.getInt("releaseYear"));

                            // Genre is json array
                            JSONArray genreArry = obj.getJSONArray("genre");
                            ArrayList<String> genre = new ArrayList<String>();
                            for (int j = 0; j < genreArry.length(); j++) {
                                genre.add((String) genreArry.get(j));
                            }
                            movie.setGenre(genre);

                            // adding movie to movies array
                            movieList.add(movie);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                    // notifying list adapter about data changes
                    // so that it renders the list view with updated data
                    adapter.notifyDataSetChanged();
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    VolleyLog.d(TAG, "Error: " + error.getMessage());
                    hidePDialog();

                }
            });

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(movieReq);
}

两个代码

public class TabOneFragment extends Fragment{

private static final String TAG = TabOneFragment.class.getSimpleName();

// Movies json url
private static final String url = "http://api.androidhive.info/json/movies.json";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
//private TextView txtFragmentone;

@Override
public void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
}

public static TabOneFragment newInstance() {
    TabOneFragment fragment = new TabOneFragment();
    return fragment;
}   

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.one_fragment, container, false);
    //txtFragmentone = (TextView) rootView.findViewById(R.id.txtFragmentOne);
    //txtFragmentone.setText(R.string.fragment_tab_one);
    rootView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT ));

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

    adapter = new CustomListAdapter(this, movieList);
    listView.setAdapter(adapter);

    pDialog = new ProgressDialog(this);
    // Showing progress dialog before making http request
    pDialog.setMessage("Loading...");
    pDialog.show();

    // changing action bar color
    getActivity().getActionBar().setBackgroundDrawable(
            new ColorDrawable(Color.parseColor("#1b1b1b")));

    // Creating volley request obj
    JsonArrayRequest movieReq = new JsonArrayRequest(url,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    Log.d(TAG, response.toString());
                    hidePDialog();

                    // Parsing json
                    for (int i = 0; i < response.length(); i++) {
                        try {

                            JSONObject obj = response.getJSONObject(i);
                            Movie movie = new Movie();
                            movie.setTitle(obj.getString("title"));
                            movie.setThumbnailUrl(obj.getString("image"));
                            movie.setRating(((Number) obj.get("rating"))
                                    .doubleValue());
                            movie.setYear(obj.getInt("releaseYear"));

                            // Genre is json array
                            JSONArray genreArry = obj.getJSONArray("genre");
                            ArrayList<String> genre = new ArrayList<String>();
                            for (int j = 0; j < genreArry.length(); j++) {
                                genre.add((String) genreArry.get(j));
                            }
                            movie.setGenre(genre);

                            // adding movie to movies array
                            movieList.add(movie);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                    // notifying list adapter about data changes
                    // so that it renders the list view with updated data
                    adapter.notifyDataSetChanged();
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    VolleyLog.d(TAG, "Error: " + error.getMessage());
                    hidePDialog();

                }
            });

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(movieReq);

    return rootView;
}

我在

收到错误
adapter = new CustomListAdapter(this, movieList);

pDialog = new ProgressDialog(this);
  

构造函数未定义

然而他们在他们的例子中都很好地编译。

这是运行代码后得到的logcat:

03-27 22:30:57.085: E/AndroidRuntime(10963): FATAL EXCEPTION: main
03-27 22:30:57.085: E/AndroidRuntime(10963): java.lang.NullPointerException
03-27 22:30:57.085: E/AndroidRuntime(10963):    at info.androidhive.customlistviewvolley.adater.CustomListAdapter.<init>(CustomListAdapter.java:24)
03-27 22:30:57.085: E/AndroidRuntime(10963):    at br.liveo.fragments.TabOneFragment.onCreateView(TabOneFragment.java:75)
03-27 22:30:57.085: E/AndroidRuntime(10963):    at android.support.v4.app.Fragment.performCreateView(Fragment.java:1500)
03-27 22:30:57.085: E/AndroidRuntime(10963):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:938)
03-27 22:30:57.085: E/AndroidRuntime(10963):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1115)
03-27 22:30:57.085: E/AndroidRuntime(10963):    at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
03-27 22:30:57.085: E/AndroidRuntime(10963):    at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1478)
03-27 22:30:57.085: E/AndroidRuntime(10963):    at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:478)
03-27 22:30:57.085: E/AndroidRuntime(10963):    at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
03-27 22:30:57.085: E/AndroidRuntime(10963):    at android.support.v4.view.ViewPager.populate(ViewPager.java:1068)
03-27 22:30:57.085: E/AndroidRuntime(10963):    at android.support.v4.view.ViewPager.populate(ViewPager.java:914)
03-27 22:30:57.085: E/AndroidRuntime(10963):    at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1436)
03-27 22:30:57.085: E/AndroidRuntime(10963):    at android.view.View.measure(View.java:12773)
03-27 22:30:57.085: E/AndroidRuntime(10963):    at android.widget.LinearLayout.measureVertical(LinearLayout.java:815)
03-27 22:30:57.085: E/AndroidRuntime(10963):    at android.widget.LinearLayout.onMeasure(LinearLayout.java:553)
03-27 22:30:57.085: E/AndroidRuntime(10963):    at android.view.View.measure(View.java:12773)
03-27 22:30:57.085: E/AndroidRuntime(10963):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4788)
03-27 22:30:57.085: E/AndroidRuntime(10963):    at android.widget.FrameLayout.onMeasure(FrameLayout.java:293)
03-27 22:30:57.085: E/AndroidRuntime(10963):    at android.view.View.measure(View.java:12773)
03-27 22:30:57.085: E/AndroidRuntime(10963):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4788)
03-27 22:30:57.085: E/AndroidRuntime(10963):    at android.widget.FrameLayout.onMeasure(FrameLayout.java:293)
03-27 22:30:57.085: E/AndroidRuntime(10963):    at android.view.View.measure(View.java:12773)
03-27 22:30:57.085: E/AndroidRuntime(10963):    at android.support.v4.widget.DrawerLayout.onMeasure(DrawerLayout.java:704)

编辑2
CustomAdapterList

public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Movie> movieItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();

public CustomListAdapter(Activity activity, List<Movie> movieItems) {
    this.activity = activity;
    this.movieItems = movieItems;
}

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

@Override
public Object getItem(int location) {
    return movieItems.get(location);
}

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

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

    if (inflater == null)
        inflater = (LayoutInflater) activity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    if (convertView == null)
        convertView = inflater.inflate(R.layout.list_row, null);

    if (imageLoader == null)
        imageLoader = AppController.getInstance().getImageLoader();
    NetworkImageView thumbNail = (NetworkImageView) convertView
            .findViewById(R.id.thumbnail);
    TextView title = (TextView) convertView.findViewById(R.id.title);
    TextView rating = (TextView) convertView.findViewById(R.id.rating);
    TextView genre = (TextView) convertView.findViewById(R.id.genre);
    TextView year = (TextView) convertView.findViewById(R.id.releaseYear);

    // getting movie data for the row
    Movie m = movieItems.get(position);

    // thumbnail image
    thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);

    // title
    title.setText(m.getTitle());

    // rating
    rating.setText("Rating: " + String.valueOf(m.getRating()));

    // genre
    String genreStr = "";
    for (String str : m.getGenre()) {
        genreStr += str + ", ";
    }
    genreStr = genreStr.length() > 0 ? genreStr.substring(0,
            genreStr.length() - 2) : genreStr;
    genre.setText(genreStr);

    // release year
    year.setText(String.valueOf(m.getYear()));

    return convertView;
}

4 个答案:

答案 0 :(得分:1)

Manifest文件中进行此更改:

<application
android:name=".AppController" //this one (your path to AppController file)
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">

在功能TabOneFragment的{​​{1}}文件中,更改此行

onCreateView

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

这将解决您的问题。

答案 1 :(得分:0)

在课堂上TabOneFragment改为:

adapter = new CustomListAdapter(getActivity(), movieList);

pDialog = new ProgressDialog(getActivity());


CustomAdapterList

 public class CustomListAdapter extends BaseAdapter {

        private Activity activity;
        private LayoutInflater inflater;
        private List<Movie> movieItems = new ArrayList<>();
        ImageLoader imageLoader = AppController.getInstance().getImageLoader();

        public CustomListAdapter(Activity activity, List<Movie> movieItems) {
            this.activity = activity;
            this.movieItems = movieItems;
            inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            return movieItems != null ? movieItems.size() : 0;
        }

        @Override
        public Object getItem(int location) {
            return movieItems != null ? movieItems.get(location) : null;
        }

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

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

            if (convertView == null)
                convertView = inflater.inflate(R.layout.list_row, parent, false);

            NetworkImageView thumbNail = (NetworkImageView) convertView.findViewById(R.id.thumbnail);
            TextView title = (TextView) convertView.findViewById(R.id.title);
            TextView rating = (TextView) convertView.findViewById(R.id.rating);
            TextView genre = (TextView) convertView.findViewById(R.id.genre);
            TextView year = (TextView) convertView.findViewById(R.id.releaseYear);

            // getting movie data for the row
            Movie m = movieItems.get(position);
            // thumbnail image
            thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);            
            // title
            title.setText(m.getTitle());            
            // rating
            rating.setText("Rating: " + String.valueOf(m.getRating()));         
            // genre
            String genreStr = "";
            for (String str : m.getGenre()) {
                genreStr += str + ", ";
            }

            genreStr = genreStr.length() > 0 ? genreStr.substring(0,genreStr.length() - 2) : genreStr;
            genre.setText(genreStr);

            // release year
            year.setText(String.valueOf(m.getYear()));

            return convertView;
        }
    }

答案 2 :(得分:0)

在TabOneFragment类更改

adapter = new CustomListAdapter(this, movieList);

adapter = new CustomListAdapter(getActivity(), movieList);

 pDialog = new ProgressDialog(this);

pDialog = new ProgressDialog(getActivity());

两个构造函数都接受Context而不是Fragment,所以在你的片段类中基本上你不能调用它,但是你必须得到getActivity()

答案 3 :(得分:0)

我发现并认为这可能对我失踪的其他人check this question有帮助。android:name=".AppController"在我的清单中

<application
    android:name=".AppController" //this one
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme">