片段活动中我的Listview适配器上的空指针

时间:2013-12-08 04:28:19

标签: android listview android-fragments parse-platform listadapter

我的问题:

我有一个称为控制台活动的片段活动,它位于h3海盗页面的视图寻呼机中。当我只是查看页面时它会正常加载,但随后我快速浏览页面,我收到了这个错误。

 12-07 20:14:39.851: E/AndroidRuntime(24498): FATAL EXCEPTION: main
12-07 20:14:39.851: E/AndroidRuntime(24498): java.lang.NullPointerException
12-07 20:14:39.851: E/AndroidRuntime(24498):    at trade.ly.tradely.ConsoleActivity$RemoteDataTask.onPostExecute(ConsoleActivity.java:145)
12-07 20:14:39.851: E/AndroidRuntime(24498):    at trade.ly.tradely.ConsoleActivity$RemoteDataTask.onPostExecute(ConsoleActivity.java:1)
12-07 20:14:39.851: E/AndroidRuntime(24498):    at android.os.AsyncTask.finish(AsyncTask.java:631)
12-07 20:14:39.851: E/AndroidRuntime(24498):    at android.os.AsyncTask.access$600(AsyncTask.java:177)
12-07 20:14:39.851: E/AndroidRuntime(24498):    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
12-07 20:14:39.851: E/AndroidRuntime(24498):    at android.os.Handler.dispatchMessage(Handler.java:99)
12-07 20:14:39.851: E/AndroidRuntime(24498):    at android.os.Looper.loop(Looper.java:137)
12-07 20:14:39.851: E/AndroidRuntime(24498):    at android.app.ActivityThread.main(ActivityThread.java:5039)
12-07 20:14:39.851: E/AndroidRuntime(24498):    at java.lang.reflect.Method.invokeNative(Native Method)
12-07 20:14:39.851: E/AndroidRuntime(24498):    at java.lang.reflect.Method.invoke(Method.java:511)
12-07 20:14:39.851: E/AndroidRuntime(24498):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
12-07 20:14:39.851: E/AndroidRuntime(24498):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
12-07 20:14:39.851: E/AndroidRuntime(24498):    at dalvik.system.NativeStart.main(Native Method)

以下是我的控制台活动的代码。

public class ConsoleActivity extends SherlockFragment {

private ProfilePictureView userProfilePictureView;
private TextView userNameView;
private TextView userLocationView;
ListView listview;
List<ParseObject> ob;
ListViewAdapter adapter;
private List<UserPosts> userpostarraylist = null;

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

    userProfilePictureView = (ProfilePictureView) v.findViewById(R.id.userProfilePicture);
    userNameView = (TextView) v.findViewById(R.id.userName);
    userLocationView = (TextView) v.findViewById(R.id.userLocation);

    SlidingLayer slidingLayer = (SlidingLayer) v.findViewById(R.id.slidingLayer1);

    slidingLayer.setShadowWidthRes(R.dimen.shadow_width);
    slidingLayer.setOffsetWidth(70);
    slidingLayer.setShadowDrawable(R.drawable.sidebar_shadow);
    slidingLayer.setStickTo(SlidingLayer.STICK_TO_RIGHT);
    slidingLayer.setCloseOnTapEnabled(true); 

    Button newPage = (Button)v.findViewById(R.id.post_button);
    newPage.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getActivity(), PostActivity.class);
            startActivity(intent);
        }
    });


    Button logoutButton = (Button) v.findViewById(R.id.logout_button);
    logoutButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onLogoutButtonClicked();
        }
    });


 // Fetch Facebook user info if the session is active
        Session session = ParseFacebookUtils.getSession();
        if (session != null && session.isOpened()) {
            makeMeRequest();
        }

        return v;
    }


private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();


    }

    protected Void doInBackground(Void... params) {
        // Create the array
        userpostarraylist = new ArrayList<UserPosts>();
        try {
            ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("testData");

            // Restrict to cases where the author is the current user.
            query.whereEqualTo("author", ParseUser.getCurrentUser());

            query.orderByDescending("createdAt");

            ob = query.find();
            for (ParseObject country : ob) {
                ParseFile image = (ParseFile) country.get("Photo");

                UserPosts upost = new UserPosts();

                upost.setPrice((String) country.get("Price"));
                upost.setDescription((String) country.get("Description"));
                upost.setCategory((String) country.get("MainCat"));
                upost.setSubCategory((String) country.get("SubCat"));
                upost.setEmail((String) country.get("PEmail"));                 
                upost.setName((String) country.get("PName"));
                upost.setPNumber((String) country.get("PPhone"));
                upost.setMeet((String) country.get("PMeet"));
                upost.setPrice((String) country.get("Price"));
                upost.setTitle((String) country.get("Title"));
                upost.setId((String) country.getObjectId());
                upost.setPhone(image.getUrl());

                userpostarraylist.add(upost);
            }
        } catch (ParseException e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {

        listview = (ListView) getActivity().findViewById(R.id.userpostlistview);
        adapter = new ListViewAdapter(getActivity (), userpostarraylist);
        listview.setAdapter(adapter);
    }
}


    @Override
    public void onResume() {
        super.onResume();

        ParseUser currentUser = ParseUser.getCurrentUser();
        if (currentUser != null) {
            // Check if the user is currently logged
            // and show any cached content
            updateViewsWithProfileInfo();
            //try this to kill the errors!!!
            //new RemoteDataTask().execute();

        } else {
            // If the user is not logged in, go to the
            // activity showing the login view.
            startLoginActivity();

        }
    }




    private void makeMeRequest() {
        Request request = Request.newMeRequest(ParseFacebookUtils.getSession(),
                new Request.GraphUserCallback() {
                    @Override
                    public void onCompleted(GraphUser user, Response response) {
                        if (user != null) {
                            // Create a JSON object to hold the profile info
                            JSONObject userProfile = new JSONObject();
                            try {
                                // Populate the JSON object
                                userProfile.put("facebookId", user.getId());
                                userProfile.put("name", user.getName());
                                if (user.getLocation().getProperty("name") != null) {
                                    userProfile.put("location", (String) user
                                            .getLocation().getProperty("name"));
                                }


                                // Save the user profile info in a user property
                                ParseUser currentUser = ParseUser
                                        .getCurrentUser();
                                currentUser.put("profile", userProfile);
                                currentUser.saveInBackground();

                                // Show the user info
                                updateViewsWithProfileInfo();
                            } catch (JSONException e) {
                                Log.d(TradelyApplication.TAG,
                                        "Error parsing returned user data.");
                            }

                        } else if (response.getError() != null) {
                            if ((response.getError().getCategory() == FacebookRequestError.Category.AUTHENTICATION_RETRY)
                                    || (response.getError().getCategory() == FacebookRequestError.Category.AUTHENTICATION_REOPEN_SESSION)) {
                                Log.d(TradelyApplication.TAG,
                                        "The facebook session was invalidated.");
                                onLogoutButtonClicked();
                            } else {
                                Log.d(TradelyApplication.TAG,
                                        "Some other error: "
                                                + response.getError()
                                                        .getErrorMessage());
                            }
                        }
                    }
                });
        request.executeAsync();

    }

    private void updateViewsWithProfileInfo() {
        ParseUser currentUser = ParseUser.getCurrentUser();
        if (currentUser.get("profile") != null) {
            JSONObject userProfile = currentUser.getJSONObject("profile");
            try {
                if (userProfile.getString("facebookId") != null) {
                    String facebookId = userProfile.get("facebookId")
                            .toString();
                    userProfilePictureView.setProfileId(facebookId);
                } else {
                    // Show the default, blank user profile picture
                    userProfilePictureView.setProfileId(null);
                }
                if (userProfile.getString("name") != null) {
                    userNameView.setText(userProfile.getString("name"));
                } else {
                    userNameView.setText("");
                }
                if (userProfile.getString("location") != null) {
                    userLocationView.setText(userProfile.getString("location"));
                } else {
                    userLocationView.setText("");
                }

            } catch (JSONException e) {
                Log.d(TradelyApplication.TAG,
                        "Error parsing saved user data.");
            }
                    // This is where the listView data task is called
            new RemoteDataTask().execute();
        }
    }

    private void onLogoutButtonClicked() {
        // Log the user out
        ParseUser.logOut();

        // Go to the login view
        startLoginActivity();
    }

    private void startLoginActivity() {
        Intent intent = new Intent(getActivity(), MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }


 }  

1 个答案:

答案 0 :(得分:1)

试试这个

Listview

内初始化OnCreate
listview = (ListView) v.findViewById(R.id.userpostlistview);

并尝试..