0

Currently, I'm trying to download some contents from Web and would like to push it to ListView:

I created a Runnable to do the download content part:

Runnable postTest = new Runnable() {
    @Override
    public void run() {
        try {
            URL u = new URL("192.168.1.1/getList.php");
            ContentValues c = new ContentValues();
            c.put("token", networkCommunication.getToken());
            String k = networkCommunication.downloadContent(u, c);
            getParent().runOnUiThread(
                    new Runnable() {
                        public void run() {
                            Toast.makeText(Main.this, k, Toast.LENGTH_SHORT).show();
                        }
                    });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
};

The code works fine until String k = networkCommunication.downloadContent(u, c);

But then, the "K" variable is not accessable in "Run" method, also, I tried changing the k variable to "Hello world" (i.e. print hello world when it finish downloading the content) but then another exception occurs:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.Activity.runOnUiThread(java.lang.Runnable)' on a null object reference

How to solve this problem?

User2012384
  • 4,769
  • 16
  • 70
  • 106

1 Answers1

1

Because getParent() is NULL. According to the documentation:

public final Activity getParent () Since: API Level 1

Return the parent activity if this view is an embedded child.

You can refer to this similar question : Android Activity.getParent() always returning null

Community
  • 1
  • 1
user3162662
  • 743
  • 1
  • 7
  • 20