populate listview from database error

时间:2016-01-28 09:03:21

标签: java android listview

Hey guys i am getting an error (NullPointerException) and need your help.I cant find my mistake no matter how hard i look.

My general discussion activity wont even open.Thanks in advance.Part of my codes are the following:

GENERALDISCUSSION

public class GeneralDiscussion extends ListActivity {


SQLiteDatabase sqLiteDatabase;
SQLiteHandler sqLiteHandler;
Cursor cursor;
ListView l;
private static final String TAG = GeneralDiscussion.class.getSimpleName();
private Button btnposting;
private Button btnLinkToLogin;
private EditText inputPost;
private EditText inputEmail;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;
private TextView txtName;
private TextView txtPost;



@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_general_discussion);


    ArrayList<HashMap<String, String>> emaillist = db.getMessage();
    if (emaillist.size() != 0) {
        Toast.makeText(getApplicationContext(), "this" + emaillist.get(1), Toast.LENGTH_SHORT).show();

        ListAdapter adapter = new SimpleAdapter(GeneralDiscussion.this, emaillist,
                R.layout.raw_layout,
                new String[]{"user_posted", "post", "posted_at", "post_id"}, new int[]{
                R.id.text_user_name, R.id.text_user_post, R.id.text_user_date, R.id.text_user_number});
        setListAdapter(adapter);
    }

    txtName = (TextView) findViewById(R.id.name);
    inputPost = (EditText) findViewById(R.id.post);
    btnposting = (Button) findViewById(R.id.btnposting);

    // Progress dialog
    pDialog = new ProgressDialog(this);
    pDialog.setCancelable(false);

    // Session manager
    session = new SessionManager(getApplicationContext());

    // SQLite database handler
    db = new SQLiteHandler(getApplicationContext())

    HashMap<String, String> user = db.getUserDetails();
    String name = user.get("name");
    txtName.setText(name);

    // Posting Button Click event
    btnposting.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            String post = inputPost.getText().toString().trim();
            String user_posted = txtName.getText().toString().trim();

            if (!post.isEmpty()) {
                postThreads(post, user_posted)

            } else {
                Toast.makeText(getApplicationContext(),
                        "Please enter your details!", Toast.LENGTH_LONG)
                        .show();
            }
        }
    });
}
private void postThreads(final String post,final String user_posted) {
    // Tag used to cancel the request
    String tag_string_req = "req_posting";
    pDialog.setMessage("Posting ...");
    showDialog();
    StringRequest strReq = new StringRequest(Method.POST,
                AppConfig.URL_POSTING, new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            Log.d(TAG, "Posting Response: " + response.toString());
            hideDialog();
            try {
                JSONObject jObj = new JSONObject(response);
                boolean error = jObj.getBoolean("error");
                if (!error) {
                    // User successfully stored in MySQL
                    // Now store the user in sqlite

                    JSONObject posting = jObj.getJSONObject("posting");
                    String post = posting.getString("post");
                    String user_posted = posting.getString("user_posted");
                    String posted_at = posting
                            .getString("posted_at");

                    // Inserting row in users table
                    db.addPosting(user_posted,post,posted_at);

                    Toast.makeText(getApplicationContext(), "User successfully posted!", Toast.LENGTH_LONG).show();

               } else {

                    // Error occurred in registration. Get the error
                    // message
                    String errorMsg = jObj.getString("error_msg");
                    Toast.makeText(getApplicationContext(),
                            errorMsg, Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
           }

        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e(TAG, "Posting Error: " + error.getMessage());
            Toast.makeText(getApplicationContext(),
                    error.getMessage(), Toast.LENGTH_LONG).show();
            hideDialog();
        }
    }) {
        @Override
        protected Map<String, String> getParams() {
            // Posting params to register url
            Map<String, String> params = new HashMap<String, String>();
            params.put("post", post);
            params.put("user_posted", user_posted);
          return params;
        }
    };

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
    if (!pDialog.isShowing())
        pDialog.show();
}
private void hideDialog() {
    if (pDialog.isShowing())
        pDialog.dismiss();
}

}

ACTIVITY_GENERAL_DISCUSSION

         <?xml version="1.0" encoding="utf-8"?> <LinearLayout   android:id="@+id/main"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent">


    <LinearLayout android:id="@+id/layout"
        android:layout_width="wrap_content"
        android:layout_height="286dp">

        <ListView
            android:id="@android:id/list"
            android:layout_height="251dp"
            android:layout_width="fill_parent">
        </ListView>
    </LinearLayout>




<Button
        android:id="@+id/btnposting"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dip"
        android:background="#0000"
        android:text="Write..."
        android:textColorHighlight="#000000" />

    <EditText
        android:id="@+id/name"
        android:layout_width="203dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dip"
        android:background="#ffffff"
        android:textColor="#000000" />

    <EditText
        android:id="@+id/post"
        android:layout_width="234dp"
        android:layout_height="87dp"
        android:layout_marginBottom="10dp"
        android:padding="10dp"
        android:singleLine="true" />

</LinearLayout>

SQLITEHANDLER

  public ArrayList<HashMap<String, String>> getMessage(){
ArrayList<HashMap<String, String>> message = new ArrayList<HashMap<String, String>>();
String selectQuery = "SELECT  * FROM " + TABLE_USER;

SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row

if ( cursor.moveToFirst()) {
    do {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("post_id", cursor.getString(0));
        map.put("user_posted", cursor.getString(1));
        map.put("post", cursor.getString(2));
        map.put("posted_at", cursor.getString(3));
        message.add(map);
    } while (cursor.moveToNext());
}
// return contact list
return message;

}

RAW_LAYOUT

   <TextView
android:layout_width="100dp"
android:layout_height="wrap_content"
android:id="@+id/text_user_post"
android:text="Post"
android:gravity="center"



    />
<TextView
    android:layout_width="100dp"
    android:layout_height="wrap_content"
    android:id="@+id/text_user_name"
    android:text="Name"
    android:gravity="center"


    />
<TextView
    android:layout_width="100dp"
    android:layout_height="wrap_content"
    android:id="@+id/text_user_number"
    android:text="Number"
    android:gravity="center"


    />

<TextView
    android:layout_width="100dp"
    android:layout_height="wrap_content"
    android:id="@+id/text_user_date"
    android:text="Date"  
   android:gravity="center"

ERROR LOG

  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.tonia/com.tonia.activity.GeneralDiscussion}: java.lang.NullPointerException
                                                         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
                                                         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
                                                         at android.app.ActivityThread.access$600(ActivityThread.java:123)
                                                         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
                                                         at android.os.Handler.dispatchMessage(Handler.java:99)
                                                         at android.os.Looper.loop(Looper.java:137)
                                                         at android.app.ActivityThread.main(ActivityThread.java:4424)
                                                         at java.lang.reflect.Method.invokeNative(Native Method)
                                                         at java.lang.reflect.Method.invoke(Method.java:511)
                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
                                                         at dalvik.system.NativeStart.main(Native Method)
                                                      Caused by: java.lang.NullPointerException
                                                         at com.tonia.activity.GeneralDiscussion.onCreate(GeneralDiscussion.java:86)
                                                         at android.app.Activity.performCreate(Activity.java:4466)
                                                         at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
                                                         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
                                                         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981) 
                                                         at android.app.ActivityThread.access$600(ActivityThread.java:123) 
                                                         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147) 
                                                         at android.os.Handler.dispatchMessage(Handler.java:99) 
                                                         at android.os.Looper.loop(Looper.java:137) 
                                                         at android.app.ActivityThread.main(ActivityThread.java:4424) 
                                                         at java.lang.reflect.Method.invokeNative(Native Method) 
                                                         at java.lang.reflect.Method.invoke(Method.java:511) 
                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 
                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 
                                                         at dalvik.system.NativeStart.main(Native Method) 

1 个答案:

答案 0 :(得分:0)

你在onCreate()方法 -

的这一行得到了NPE
ArrayList<HashMap<String, String>> emaillist = db.getMessage();//db is not instantiated yet. 

您正在访问尚未实例化的db上的方法getMessage()。 在调用方法之前,需要实例化它。