2

I'm currently working on an Android app and I get NullPointerException. Here is my AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.locking"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="21" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".LogonActivity"
            android:label="@string/app_name" 
            android:launchMode="singleTop"
            android:windowSoftInputMode="adjustPan">
             <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".RegisterActivity"
            android:label="@string/app_name"
            android:launchMode="singleTop"
            android:windowSoftInputMode="adjustPan" />
        <activity
            android:name=".StatActivity"
            android:label="@string/app_name"
            android:launchMode="singleTop" />
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:launchMode="singleTop"
            android:windowSoftInputMode="adjustPan" />
    </application>
</manifest>

Will post my runtime error. Here is LogCat output:

05-08 01:05:06.261: W/System.err(1609): java.util.concurrent.ExecutionException: java.lang.NullPointerException
05-08 01:05:06.271: W/dalvikvm(1609): threadid=12: thread exiting with uncaught exception (group=0xb2d23b20)
    at java.util.concurrent.FutureTask.report(FutureTask.java:93)
    at java.util.concurrent.FutureTask.get(FutureTask.java:163)
    at android.os.AsyncTask.get(AsyncTask.java:483)
    at com.locking.StatActivity.onCreate(StatActivity.java:79)
    at android.app.Activity.performCreate(Activity.java:5231)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
    at android.app.ActivityThread.access$800(ActivityThread.java:135)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:136)
    at android.app.ActivityThread.main(ActivityThread.java:5017)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
    at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.NullPointerException
    at com.locking.StatActivity$GetStats.doInBackground(StatActivity.java:139)
    at com.locking.StatActivity$GetStats.doInBackground(StatActivity.java:1)
    at android.os.AsyncTask$2.call(AsyncTask.java:288)
    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
    at java.lang.Thread.run(Thread.java:841)
 FATAL EXCEPTION: AsyncTask #2
 Process: com.locking, PID: 1609
 java.lang.RuntimeException: An error occured while executing doInBackground()
    at android.os.AsyncTask$3.done(AsyncTask.java:300)
    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
    at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
    at java.util.concurrent.FutureTask.run(FutureTask.java:242)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
    at java.lang.Thread.run(Thread.java:841)
 Caused by: java.lang.NullPointerException
    at com.locking.StatActivity$GetStats.doInBackground(StatActivity.java:139)
    at com.locking.StatActivity$GetStats.doInBackground(StatActivity.java:1)
    at android.os.AsyncTask$2.call(AsyncTask.java:288)
    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
    ... 4 more
 eglSurfaceAttrib not implemented
 eglSurfaceAttrib not implemented
 android.view.WindowLeaked: Activity com.locking.StatActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{b315c460 V.E..... R......D 0,0-456,144} that was originally added here
    at android.view.ViewRootImpl.<init>(ViewRootImpl.java:348)
    at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
    at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
    at android.app.Dialog.show(Dialog.java:286)
    at com.locking.StatActivity$GetStats.onPreExecute(StatActivity.java:108)
    at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
    at android.os.AsyncTask.execute(AsyncTask.java:535)
    at com.locking.StatActivity.onCreate(StatActivity.java:79)
    at android.app.Activity.performCreate(Activity.java:5231)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
    at android.app.ActivityThread.access$800(ActivityThread.java:135)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:136)
    at android.app.ActivityThread.main(ActivityThread.java:5017)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
    at dalvik.system.NativeStart.main(Native Method)

Here is my code for StatActivity.

public class StatActivity extends Activity {
    int userId;
    int temp;
    int lockset = 0;
    int templock;
    int doorset = 0;
    String lock_op;
    String door_op;

    JSONArray status_user = null;
    TextView lockstat;
    TextView DoorStat;
    TextView DateStat;
    String statdisplay = "Lock is open";
    String statdisplay2 = "Lock is closed";
    String doordisplay = "door is open";
    String doordisplay2 = "door is closed";

    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";
    private static final String TAG_STATUS = "status";
    private static final String TAG_LOCK = "lock_op";
    private static final String TAG_DOOR = "door_op";
    private static final String TAG_DATE = "date_modified";

    private ProgressDialog pDialog;

    LobbyFunctions lobbyFunction = new LobbyFunctions();
    UserFunctions userFunction = new UserFunctions();
    UserFunctions socketConnect = new UserFunctions();
    UserFunctions sktConnect = new UserFunctions();

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent extras = getIntent();
        userId = extras.getIntExtra("userId", 0);
        temp = extras.getIntExtra("temp", 0);

        try {

            // get lobbies from JSON and parse them. Wait until async task is complete before continuing
            new GetStats().execute().get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

    class GetStats extends AsyncTask<String, String, String>{

         @Override
            protected void onPreExecute() {
                    super.onPreExecute();
                    lockstat = (TextView)findViewById(R.id.switchstat);

                    pDialog = new ProgressDialog(StatActivity.this);
                    pDialog.setMessage("Fetching Status..");
                    pDialog.setIndeterminate(false);
                    pDialog.setCancelable(true);
                    pDialog.show();
            }
        @Override
        protected String doInBackground(String... args) {
        JSONObject json3 = lobbyFunction.GetStatus();

        try{
        int success = json3.getInt(TAG_SUCCESS);
         String message = json3.getString(TAG_MESSAGE);
         String status = json3.getString(TAG_STATUS);
            JSONArray status_user = new JSONArray(status);
            JSONObject w = status_user.getJSONObject(0);

            String lock = w.getString(TAG_LOCK);
            String door = w.getString(TAG_DOOR);
            String date = w.getString(TAG_DATE);

            if(lock == "0")
            {
                lock = statdisplay;
            }
            else{
                lock = statdisplay2;
            }
            if( door == "0")
            {
                door = doordisplay;
            }
            else{
                door = doordisplay2;
            }
            lockstat.setText(lock);
            DoorStat.setText(door);

        }catch(JSONException e){
            e.printStackTrace();
        }
        return null;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
     // Inflate the menu; this adds items to the action bar if it is present.
     getMenuInflater().inflate(R.menu.main, menu);
     return true;
    }
}
Ziem
  • 6,579
  • 8
  • 53
  • 86
dk33
  • 23
  • 4
  • where is your onPostExecute method – Preethi Rao May 08 '15 at 05:30
  • 1
    The first thing is that you are updating your layout from `doInBackground` method which is wrong you should update your layout in `onPostExecute` method. These two lines should be in onPostExecute method.`lockstat.setText(lock);DoorStat.setText(door);` – BBdev May 08 '15 at 05:38
  • Oh, you are correct. I need one. So what would I put on my postExecute? is it the textview? – dk33 May 08 '15 at 05:39
  • The result you are getting from your `doInBackground` you can set that result to your `TextViews` – BBdev May 08 '15 at 05:41
  • Initialize your `lockstat` and `DoorStat` in your activity's `onCreate` using id's from activity's layout file and don't use `DoorStat.settext();` in `doInBackground` method. For UI stuff in `AsyncTask` you should override `onPostExecute()`. – hardartcore May 08 '15 at 05:44
  • And i am not sure how you are getting your result its look like you are getting result as a `String` and returning null you should have return an array or an arraylist from your doInbackground method and should update it in onPostExecuteMethod which would be easier otherwise you will not be able to set the text. And also initialize your `TextViews` – BBdev May 08 '15 at 05:46

5 Answers5

3

The problem is:

You have only initialize your textView as

  lockstat = (TextView)findViewById(R.id.switchstat); 

in onPreExecute() method.

This line DoorStat.setText(door); giving you NullPointer exception because you haven't initialize that textView. So just initialize it and also keep in mind that you need to update your textViews in onPostExecute() method instead if doInBackground().

NOTE : Don't use == to compare the strings. Instead of use equals().

Piyush
  • 18,895
  • 5
  • 32
  • 63
  • Wanted to add a point if you use `==` to compare a string it will actually compare the reference not the actual value which hold that reference and `equal(String s)` actually comparing the value hold by that reference. – BBdev May 08 '15 at 05:50
  • I already know all this stuff. Don't worry. But using == is a bad practice. – Piyush May 08 '15 at 05:55
  • @PiyushGupta Deserving +1 – M D May 08 '15 at 06:18
1

You cannot update UI from doInBackground like you are doing, use onPostExecute or use the below code in doInBackground

doInBackground() {
    runOnUiThread(new Runnable() {
                public void run() {
                    lockstat.setText(lock);
                    DoorStat.setText(door);
                }
            });
}

instead of just

 lockstat.setText(lock);
 DoorStat.setText(door);
Exception
  • 2,273
  • 1
  • 24
  • 42
  • Should that put out from my class get status? Or inside the class extend async. Sorry Im not strong at android java. Thanks. – dk33 May 08 '15 at 05:44
  • Inside your doInBackground() method of AsyncTask – Exception May 08 '15 at 05:46
  • Attempted to finish an input event but the input event receiver has already been disposed. When I click on my button to get into that activity to load my status. – dk33 May 08 '15 at 06:22
0

Looks like your TextView DoorStat is not initialised and is null. Please initialised the TextView that should resolve this.

Manish
  • 1,215
  • 10
  • 29
  • Hmm I should set my textview to null? I initialized it up by my JSONArray. – dk33 May 08 '15 at 05:38
  • You are initialising the lockStat like lockstat = (TextView)findViewById(R.id.switchstat); You need to do same for DoorStat or create new TextView in code. DorrStat is null that's why NullPointer is thrown. Also move this code to onPostExecute as you can't modify the UI in doInBackground. – Manish May 08 '15 at 05:39
0

please intialise textview and put it into onPostExecute() method because you can not do UI task in doInBackground,

lockstat.setText(lock);
DoorStat.setText(door);
Jignesh Jain
  • 1,518
  • 12
  • 28
  • Now it does not have exception fault anymore. But Its skipped 208 frames. Application is doing too much work on main thread. – dk33 May 08 '15 at 05:55
0

Ok you are trying to access the GUI via another thread. This, in the main, is not good practice.

The AsyncTask executes everything in doInBackground() inside of another thread, which does not have access to the GUI where your views are.

preExecute() and postExecute() offer you access to GUI before and after the heavy lifting occurs in this new thread, you can even pass the result of the long operation to postExecute() to then show any results of processing.

See these lines where you later your TextView:

lockstat.setText(lock);
DoorStat.setText(door);

put them in PostExecute()

and I assume that you declare DoorStat as TextView but did not initialized anywhere

Abdul Rahman Majeed
  • 1,125
  • 2
  • 10
  • 22
  • So, i should combine the two activities? I have a activity that takes me to the status. And the status activity just displays open or lock for me. On my main activity, when I click on check button. It seems like it goes into the status activity, with the pdailog but then hangs. Shows on logcat a warning "Attempted to finish an input event but the input event receiver has already been disposed." This must mean that it will never go into the status activity, becuase it never finishes the intent transition from the main activity? – dk33 May 08 '15 at 06:33