0

I got a java.lang.NullPointerException on this line pdao.majPost(c); when I try to grab my posts from my API and trying to insert post my SQLite database.

My JSON Parser Class:

private PostsDAO pdao;

public void data() {

    AsyncHttpClient client = new AsyncHttpClient();
    client.get("http://twitter.192.168.1.38.xip.io/api/v1/posts", new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(String response) {

            JSONObject data;
            JSONArray posts;
            try {
                data = new JSONObject(response);

                // Traitement des posts
                posts = data.getJSONArray("posts");
                for (int i = 0; i < posts.length(); i++) {
                    JSONObject c = posts.getJSONObject(i);
                    pdao.majPost(c);
                }

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    });

}

My PostDAO file

public void majPost(JSONObject c) throws JSONException {
    ContentValues values = new ContentValues();
    values.put("id_post", c.getInt("id_post"));
    values.put("id_user", c.getInt("id_user"));
    values.put("content", c.getString("content"));
    values.put("photo", c.getString("photo"));
    values.put("masked", c.getInt("masked"));
    values.put("deleted", c.getInt("deleted"));
    values.put("created_at", c.getString("created_at"));
    values.put("updated_at", c.getString("updated_at"));
    db.insert("posts", null, values);
}
user3207586
  • 141
  • 4
  • 14

6 Answers6

1

Try this...

PostsDAO pdao = new PostsDAO();
Pragnesh Ghoda シ
  • 8,318
  • 3
  • 25
  • 40
1

You forgot to initialize pdao, that's why its firing Null Pointer, Initialize it:

PostsDAO pdao = new PostsDAO();
Pratik Dasa
  • 7,439
  • 4
  • 30
  • 44
1

To be safe with JSON, use this:

jsonObject.optString("string_key", "fallback");
jsonObject.optInt("int_key", -1);

or just

jsonObject.optString("string_key");
jsonObject.optInt("int_key");

and check for null.

The idea is that opt will not throw an exception, but it will return null if the key doesn't exist or something goes wrong.

Ionut Negru
  • 6,186
  • 4
  • 48
  • 78
1

try this one

private PostsDAO pdao = new PostsDAO();
Ramki Anba
  • 754
  • 1
  • 10
  • 21
1

work with following

PostsDAO pdao = new PostsDAO();

as you have never initialize pdao

 PostsDAO pdao=null;

than initialize

pdao = new PostsDAO();
Jitesh Upadhyay
  • 5,244
  • 2
  • 25
  • 43
0

Just made your method majPost static and call it like this PostDAO.majPost();

Asheesh
  • 565
  • 6
  • 21