-1

I am working on a project where data from a mysql database is loaded from my server and displayed in the form of a ListView. However, I am experiencing some hurdles in achieving this where the application ends up force closing whenever I open the ContentActivity. From my logcat, I get two sets of errors:

First I get errors on lines 196 (class LoadAllContent extends AsyncTask<String, String, String> {) and line 221 (Log.d("All Posts: ", json.toString());). The complete error for this segment is:

10-13 13:42:58.978  20090-20315/? W/System.err? at com.app.appname.ContentActivity$LoadAllContent.doInBackground(ContentActivity.java:221)
10-13 13:42:58.978  20090-20315/? W/System.err? at com.app.appname.ContentActivity$LoadAllContent.doInBackground(ContentActivity.java:196)
10-13 13:42:58.980  20090-20315/? E/AndroidRuntime? FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
        at android.os.AsyncTask$3.done(AsyncTask.java:299)
        at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
        at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
        at java.util.concurrent.FutureTask.run(FutureTask.java:239)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
        at java.lang.Thread.run(Thread.java:838)
 Caused by: java.lang.NullPointerException
        at com.app.appname.ContentActivity$LoadAllContent.doInBackground(ContentActivity.java:221)
        at com.app.appname.ContentActivity$LoadAllContent.doInBackground(ContentActivity.java:196)
        at android.os.AsyncTask$2.call(AsyncTask.java:287)
        at java.util.concurrent.FutureTask.run(FutureTask.java:234)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
        at java.lang.Thread.run(Thread.java:838)
10-13 13:42:59.007     553-3073/? W/ActivityManager? Force finishing activity com.app.appname/.ContentActivity

The Second set of errors are at lines 85 (new LoadAllContent().execute();) and line 208 (pDialog.show();)

10-13 13:42:59.856  20090-20090/? E/WindowManager? Activity com.app.appname.ContentActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41ec1f80 V.E..... R......D 0,0-480,96} that was originally added here
android.view.WindowLeaked: Activity com.app.appname.ContentActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41ec1f80 V.E..... R......D 0,0-480,96} that was originally added here
        at android.view.ViewRootImpl.<init>(ViewRootImpl.java:424)
        at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:218)
        at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
        at android.app.Dialog.show(Dialog.java:281)
        at com.app.appname.ContentActivity$LoadAllContent.onPreExecute(ContentActivity.java:208)
        at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
        at android.os.AsyncTask.execute(AsyncTask.java:534)
        at com.app.appname.ContentActivity.onCreate(ContentActivity.java:85)
        at android.app.Activity.performCreate(Activity.java:5122)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1150)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2315)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2403)
        at android.app.ActivityThread.access$600(ActivityThread.java:165)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1373)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:194)
        at android.app.ActivityThread.main(ActivityThread.java:5370)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:525)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
        at dalvik.system.NativeStart.main(Native Method)

What I am not sure of is whether these two errors are related. My ContentActivity.java and index.php files are as below.

ContentActivity.java

public class ContentActivity extends ListActivity implements ISideNavigationCallback {

Utils util;

final Context context = this;

// Progress Dialog
private ProgressDialog pDialog;

// Creating JSON Parser object
JSONParser jParser = new JSONParser();

ArrayList<HashMap<String, String>> contentList;

// url to get all content
private static String getContent = "http://192.168.43.87/app/index.php?act=getContent";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_POSTS = "posts";
private static final String TAG_PID = "id";
private static final String TAG_TITLE = "title";

// products JSONArray
JSONArray posts = null;

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

    util = new Utils(this);

    TextView appTit = (TextView) findViewById(R.id.appTitle);
    String pageTitle = "MySql Database Content";
    appTit.setText((CharSequence)pageTitle);

    // Hashmap for ListView
    contentList = new ArrayList<HashMap<String, String>>();

    new LoadAllContent().execute();

    // Get listview
    ListView lv = getListView();

    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {
            // getting values from selected ListItem
            String postId = ((TextView) view.findViewById(R.id.postId)).getText()
                    .toString();

            // Starting new intent
            Intent in = new Intent(getApplicationContext(), ContentViewActivity.class);
            // sending pid to next activity
            in.putExtra(TAG_PID, postId);

            // starting new activity and expecting some response back
            startActivityForResult(in, 100);
        }
    });
}

/**
 * Background Async Task to Load all content by making HTTP Request
 * */
class LoadAllContent extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(ContentActivity.this);
        pDialog.setMessage("Loading blog. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * getting All content from url
     * */
    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();

        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(getContent, "GET", params);

        // Check your log cat for JSON reponse
        Log.d("All Posts: ", json.toString());

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // products found
                // Getting Array of Products
                posts = json.getJSONArray(TAG_POSTS);

                // looping through All Products
                for (int i = 0; i < posts.length(); i++) {
                    JSONObject c = posts.getJSONObject(i);

                    // Storing each json item in variable
                    String id = c.getString(TAG_PID);
                    String title = c.getString(TAG_TITLE);

                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    map.put(TAG_PID, id);
                    map.put(TAG_TITLE, title);

                    // adding HashList to ArrayList
                    contentList.add(map);
                }
            } else {
                // no content found
                // Launch Add New product Activity
                Intent i = new Intent(getApplicationContext(),
                        NoPostActivity.class);
                // Closing all previous activities
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all products
        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */
                ListAdapter adapter = new SimpleAdapter(
                        ContentActivity.this, contentList,
                        R.layout.list_item, new String[] { TAG_PID,
                        TAG_TITLE},
                        new int[] { R.id.postId, R.id.title });
                // updating listview
                setListAdapter(adapter);
            }
        });
    }

}
}

index.php

<?php
$action = $_GET['act'];

if ($action == 'getallposts') {
$posts = get_posts('numberposts=10&order=DESC&orderby=post_desc_gmt');
$numPosts = count($posts);
if ($numPosts > 0) {

    $response["posts"] = array();

    foreach ($posts as $postr) : setup_postdata( $post );
        // temp user array
        $post = array();
        $post['id'] = $postr->ID;
        $post["title"] = $postr->post_title;
        $post["desc"] = substr($postr->post_content,0,50).'...';
        $post['comments'] = $postr->comment_count;
        $post["created"] = $postr->post_date_gmt;
        array_push($response["posts"], $post);
    endforeach; 

    // success
    $response["success"] = 1;

    // echoing JSON response
    echo json_encode($response);
} else {
    // no products found
    $response["success"] = 0;

    echo json_encode($response);
}
} 
?>

I would really appreciate any pointers to sort out this issue as all the research I have done has not borne any fruit.

Biko
  • 332
  • 3
  • 15
  • I hate to repeat myself but: **androidhive is a bad tutorial source** ... – Selvin Oct 13 '15 at 11:24
  • 1
    ... but still, possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – Selvin Oct 13 '15 at 11:25
  • try setting `new ProgressDialog(getApplicationContext());` check your `pDialog` is `null` – Rustam Oct 13 '15 at 11:27
  • `json=jParser.makeHttpRequest(getContent, "GET", params);` is `null` in your `doInBackground` – Rustam Oct 13 '15 at 11:36
  • @Rastum, when I run the link on a browser it returns the json formated data. How do I check whether pDialog is null? – Biko Oct 13 '15 at 11:39
  • @selvin, none of the solutions provided fit my situation...there can I find a more reliable tutorial? – Biko Oct 13 '15 at 14:57

1 Answers1

0

Just few comments:

  1. Move Log.d("All Posts: ", json.toString()); to the try .. catch block and catch for NullPointerException too.

  2. You dont need to use runOnUiThread on the postExecute as postExecute always runs on the UI thread ( main thread)

  3. Dont start activity from doInBackground ( It might be possible but dont do it); do this from postExecute rather, like this:

    if(success != 1){

        Intent i = new
    Intent(getApplicationContext(),NoPostActivity.class);
    
          // Closing all previous activities
           i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
           startActivity(i);
    
    }
    
dsharew
  • 10,377
  • 6
  • 49
  • 75