java - 评估匿名类的 toString() 时出现 NullPointerException

标签 java android json gson

尝试使用 Gson 库将 JSON 数组转换为对象列表。

代码:

TypeToken<List<Comment>> token = new TypeToken<List<Comment>>() {}; //this line throws the following exception

public class Comment implements Serializable{

@SerializedName("id")
private int mID;

@SerializedName("content")
private String mContent;

@SerializedName("author")
private String mAuthor;

@SerializedName("author_id")
private int mAuthorID;

@SerializedName("author_email")
private String mAuthorEmail;

@SerializedName("date")
private String mDate;

@SerializedName("name")
private String mName;

@SerializedName("image")
private String mImage;

public int getmID() {
    return mID;
}

public void setmID(int mID) {
    this.mID = mID;
}

public String getmContent() {
    return mContent;
}

public void setmContent(String mContent) {
    this.mContent = mContent;
}

public String getmAuthor() {
    return mAuthor;
}

public void setmAuthor(String mAuthor) {
    this.mAuthor = mAuthor;
}

public int getmAuthorID() {
    return mAuthorID;
}

public void setmAuthorID(int mAuthorID) {
    this.mAuthorID = mAuthorID;
}

public String getmAuthorEmail() {
    return mAuthorEmail;
}

public void setmAuthorEmail(String mAuthorEmail) {
    this.mAuthorEmail = mAuthorEmail;
}

public String getmDate() {
    return mDate;
}

public void setmDate(String mDate) {
    this.mDate = mDate;
}

public String getmName() {
    return mName;
}

public void setmName(String mName) {
    this.mName = mName;
}

public String getmImage() {
    return mImage;
}

public void setmImage(String mImage) {
    this.mImage = mImage;
}

}

public class CommentListingActivity extends BaseActivity implements View.OnClickListener {

private static final String TAG = "CommentListingActivity";
private ListView mListViewComments;
private CommentAdapter mCommentAdapter;
private ArrayList<Comment> mCommentList = new ArrayList<Comment>();

private ProgressBar mProgressBar;
private TextView mTextViewErrorMessage;
private Button mButtonRefresh;
private LinearLayout mLinearLayoutError;
private int mPostID;
private boolean isCommentListLoading = true;
private EditText mEditTextComment;
private ImageView mImageViewSend;
private InputMethodManager mInputMethodManager;
private SwipeRefreshLayout mSwipeRefreshLayout;
private boolean mIsRefreshing = false;
private int mOffset = 0;
private View mProgressBarView;

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

    mPostID = getIntent().getIntExtra("postID",0);

    setToolbar();
    setToolBarTitle(getString(R.string.commentsLabel));
    setToolbarHomeAsUpEnabled(true);

    mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
    mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            mSwipeRefreshLayout.setRefreshing(false);
            mIsRefreshing = true;
            mOffset = 0;
            fetchComments();
        }
    });

    mListViewComments = (ListView) findViewById(R.id.listViewComments);
    mCommentAdapter = new CommentAdapter(this, mCommentList,mImageLoader);
    mListViewComments.setAdapter(mCommentAdapter);
    mProgressBarView = getLayoutInflater().inflate(R.layout.recyclerview_loading_item,null);
    mListViewComments.addFooterView(mProgressBarView);

    // set the custom dialog components - text, image and button
    mEditTextComment = (EditText) findViewById(R.id.editTextComment);

    mImageViewSend = (ImageView) findViewById(R.id.imageViewSend);
    mImageViewSend.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            postComment();
        }
    });

    mEditTextComment.requestFocus();

    mInputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    mInputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);

    initProgressBar();

    initErrorView();

    mListViewComments.setOnScrollListener(new EndlessScrollListener() {
        @Override
        public boolean onLoadMore(int page, int totalItemsCount) {
            mOffset = mOffset + LIST_LIMIT;
            mListViewComments.addFooterView(mProgressBarView);
            fetchComments();

            return true;
        }
    });

    fetchComments();
}

private void fetchComments(){
    if (!mIsRefreshing && mCommentAdapter.getCount()==0)
    showProgressBar();

    HashMap<String,String> parameters = new HashMap<String, String>();
    parameters.put("post",String.valueOf(mPostID));
    parameters.put("offset",String.valueOf(mOffset));
    NetworkUtility.getJSONRquest(this, APIURLs.LIST_COMMENTS, parameters, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            //Remove loading item
            if(mCommentList.size()>0) {
              mListViewComments.removeFooterView(mProgressBarView);
            }
            try {
                if(response.getString(API_KEY_STATUS).equalsIgnoreCase(API_RESPONSE_SUCCESS)){
                    JSONArray jsonArrayComments = response.getJSONArray(API_KEY_DATA);
                    if(jsonArrayComments.length()>0) {
                        if (mIsRefreshing) {
                            mCommentList.clear();
                            mCommentAdapter.notifyDataSetChanged();
                        }
                        TypeToken<List<Comment>> token = new TypeToken<List<Comment>>() {};
                        mCommentList.addAll((Collection<? extends Comment>) GsonUtility.convertJSONStringToObject(jsonArrayComments.toString(), token));
                        mCommentAdapter.notifyDataSetChanged();
                    }

                    mIsRefreshing = false;
                    if(mCommentAdapter.getCount()>0) {
                        showContent();
                    } else {

                        if (mOffset == 0)
                            showError("No comments found.");
                    }
                } else {
                    mProgressBarView.setVisibility(View.GONE);
                    if(mCommentAdapter.getCount()>0){
                        AlertDialogUtility.showErrorMessage(CommentListingActivity.this,getString(R.string.errorLabel),response.getString(API_KEY_MESSAGE),getString(R.string.okLabel),null,null,null);
                    } else
                    showError(response.getString(API_KEY_MESSAGE));
                }
            } catch (JSONException e) {
                e.printStackTrace();
                mProgressBarView.setVisibility(View.GONE);
                if(mCommentAdapter.getCount()>0){
                    AlertDialogUtility.showErrorMessage(CommentListingActivity.this,getString(R.string.errorLabel),getString(R.string.volleyErrorMessage),getString(R.string.okLabel),null,null,null);
                } else {
                    showError(getString(R.string.volleyErrorMessage));
                }
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            mProgressBarView.setVisibility(View.GONE);
            if(mCommentAdapter.getCount()>0){
                AlertDialogUtility.showErrorMessage(CommentListingActivity.this,getString(R.string.errorLabel),getString(R.string.volleyErrorMessage),getString(R.string.okLabel),null,null,null);
            } else {
                showError(error.getCause().getMessage());
            }
            error.printStackTrace();
        }
    },null,TAG);
}

private void postComment() {
    final AppProgressDialog appProgressDialog = new AppProgressDialog(this);
    appProgressDialog.setProgressDialogTitle("Posting Comment");
    appProgressDialog.setProgressDialogMessage("Please Wait...");
    appProgressDialog.showProgressDialog();

    try {
        final String comment = mEditTextComment.getText().toString();

        if (!ValidatorUtility.isBlank(comment) && mPostID!=0) {

            JSONObject jsonData = new JSONObject();

            jsonData.put("content",comment);
            jsonData.put("post",mPostID);

            NetworkUtility.postRquestWithBasicAuth(this, APIURLs.POST_COMMENT, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    try {
                        if(response.has("id") && response.getInt("id")>0){
                            AppToast.toastLong(mContext,"Comment Added");
                            Comment objComment = new Comment();
                            if (response.has("author_name"))
                            objComment.setmAuthor(response.getString("author_name"));
                            if (response.has("author_email"))
                            objComment.setmAuthorEmail(response.getString("author_email"));
                            if (response.has("author"))
                            objComment.setmAuthorID(response.getInt("author"));
                            objComment.setmContent(comment);
                            if (response.has("date"))
                            objComment.setmDate(response.getString("date"));
                            if (response.has("id"))
                            objComment.setmID(response.getInt("id"));
                            objComment.setmImage(mUser.getImage());
                            objComment.setmName(mUser.getName());
                            mCommentList.add(0,objComment);
                            mCommentAdapter.notifyDataSetChanged();
                            mEditTextComment.setText(null);
                            mEditTextComment.clearFocus();
                            mInputMethodManager.hideSoftInputFromWindow(mEditTextComment.getWindowToken(),0);
                            showContent();
                        } else {
                            AlertDialogUtility.showErrorMessage(CommentListingActivity.this,getString(R.string.errorLabel),"Failed to add comment. Please try again later.",getString(R.string.okLabel),null,null,null);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    } finally {
                        appProgressDialog.dismissProgressDialog();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    appProgressDialog.dismissProgressDialog();
                    AlertDialogUtility.showErrorMessage(CommentListingActivity.this,getString(R.string.errorLabel),error.getCause().getMessage(),getString(R.string.okLabel),null,null,null);
                }
            }, jsonData, TAG);
        } else {
            appProgressDialog.dismissProgressDialog();
        }
    } catch (Exception e){
        e.printStackTrace();
        appProgressDialog.dismissProgressDialog();
    }
}

private void initProgressBar(){
    mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
}

private void initErrorView(){
    mLinearLayoutError = (LinearLayout) findViewById(R.id.linearLayoutError);
    mTextViewErrorMessage = (TextView) findViewById(R.id.textViewErrorMessage);
    mButtonRefresh = (Button) findViewById(R.id.buttonRefresh);
    mButtonRefresh.setOnClickListener(this);
}

private void showProgressBar(){
    mProgressBar.setVisibility(View.VISIBLE);
    mLinearLayoutError.setVisibility(View.GONE);
    mSwipeRefreshLayout.setVisibility(View.GONE);
}

private void showContent(){
    mProgressBar.setVisibility(View.GONE);
    mLinearLayoutError.setVisibility(View.GONE);
    mSwipeRefreshLayout.setVisibility(View.VISIBLE);
}

private void showError(String message){
    mProgressBar.setVisibility(View.GONE);
    mLinearLayoutError.setVisibility(View.VISIBLE);
    mSwipeRefreshLayout.setVisibility(View.GONE);
    mTextViewErrorMessage.setText(message);
}

@Override
public void onClick(View view) {
    if(view == mButtonRefresh){
        fetchComments();
    }
}

@Override
protected void onDestroy() {
    super.onDestroy();

    KeyboardUtility.closeKeyboard(this,mEditTextComment);
}

}

异常(exception):

Method threw 'java.lang.NullPointerException' exception. Cannot evaluate app.govindaconnect.mangaltaraproductions.com.views.CommentListingActivity$4$1.toString()

仅转换 1 个 JSON 对象并将其添加到列表中。

什么可能导致异常?因为其他类不会发生这种情况。

最佳答案

你可以试试这个 替换这一行

TypeToken<List<Comment>> token = new TypeToken<List<Comment>>() {};

用这个试试

Type  token = new TypeToken<List<Comment>>() {}.getType();
List<Comment> commentsList = gson.fromJson(String.valueOf(resultArray), type);

关于java - 评估匿名类的 toString() 时出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42993835/

相关文章:

java - org.apache.activemq.broker.TransportConnection serviceTransportException 警告 : java. io.EOFException

java - 在包 'qihoo' 中找不到属性 'android' 的资源标识符

sql - 将 JSON 数据转换为单独的列

c# - .Net 4.0 上的 ServiceStack.Text JSON 解析

c# - 将多行 JSON 反序列化为 C# 对象

java - 为什么 WebView -> onPause 只在第一次工作?

java - 我可以执行类似语言命令的字符串吗?

android - 保留apk到底是做什么的

java - Android列表(ArrayList、List等): addAll() vs redefining reference

android - 数据库的 SQLiteConnection 对象被泄露