0

I just start my hands on Eclipse and want to know what cause error in my apps. I wonder if their is a way like Visual Studio.

What I means is I have got Null pointer Exception but even after putting Breakpoint i am confused what cause error happen.

Because I am new most of time I run bad or code which will not work. How I recognize my mistake. Sometime my code is not working and exception are hard to figure out the real issue happen with my code.

Do someone check the code and guide me how to find it. I means how to know where the null pointer exception happen.

public class MainActivity extends Activity {

    Set<String> tasks = new HashSet<String>();
    final String prefName = "andorid";
    SharedPreferences sp = getSharedPreferences(prefName, MODE_PRIVATE);

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

        SetupApp();
    }

    // / Add the task in this function
    private void SetupApp() {

        tasks.add("blah");

        if (!sp.contains("tasks")) {
            Editor edit = sp.edit();

            edit.putStringSet("tasks", tasks);

            edit.commit();
        }

    }

    public void btnClick(View view) {

        EditText etxt = (EditText) findViewById(R.id.txtTask);

        tasks.add(etxt.getText().toString());

    }

    public void UpdateUI(String TaskName) {

        final ListView listview = (ListView) findViewById(R.id.listView1);

        Set<String> tasks = sp.getStringSet("tasks", new HashSet<String>());

        @SuppressWarnings("unchecked")
        ArrayList<String> taskarr = (ArrayList<String>) tasks;

        final ArrayList<String> list = new ArrayList<String>();
        for (int i = 0; i < taskarr.size(); ++i) {
            list.add(taskarr.get(i));
        }
    }

    public void LoadTasks() {

    }

}

class StableArrayAdapter extends ArrayAdapter<String> {

    HashMap<String, Integer> mIdMap = new HashMap<String, Integer>();

    public StableArrayAdapter(Context context, int textViewResourceId,
            List<String> objects) {
        super(context, textViewResourceId, objects);
        for (int i = 0; i < objects.size(); ++i) {
            mIdMap.put(objects.get(i), i);
        }
    }

    @Override
    public long getItemId(int position) {
        String item = getItem(position);
        return mIdMap.get(item);
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

}
user2126670
  • 195
  • 1
  • 5
  • 15
  • Why not look at the logcat output to see where the NPE is? It's kind of tough to just look at code and find out where "the" NPE is other that "it could be here or here or here or..." – Dave Newton May 28 '13 at 01:32
  • Post your logcat and we can help you to know how to read it to find the error – codeMagic May 28 '13 at 01:32
  • logcat is rather horrible if you ask me, but its all you have to work with unless you swap IDE's. When copying from logcat make sure to copy it all to a text file as half of the message are not shown alot of the time, then go through this and figure out where the issue is, also set it to error mode not verbose – Matthew Pigram May 28 '13 at 01:35
  • @MatthewPigram hmmm...I have found logcat very useful and easy to read once you understand it – codeMagic May 28 '13 at 01:36
  • @MatthewPigram How is logcat significantly worse than any other logging? And how is it all you have unless you switch IDEs? You can still debug. – Dave Newton May 28 '13 at 01:41
  • @codeMagic compared to Visual Studio I find it hellish, especially since it doesnt display the entire stack but says ...2 more in the list, very annoying – Matthew Pigram May 28 '13 at 01:41
  • @DaveNewton its not that it makes debugging impossible, its just a little more painful than other IDE's and in my opinion a little less intuitive. – Matthew Pigram May 28 '13 at 01:44
  • 1
    @MatthewPigram So, make a suggestion to the OP as to his/her options, then. I don't know what isn't "intuitive" about looking at log output, or what's particularly painful about the Eclipse debugger: without any elaboration, you're not really helping the OP much. The truncated stack traces are because those parts are almost *never* relevant to the exception. – Dave Newton May 28 '13 at 01:47
  • @DaveNewton almost is the key word there, the actual debugger is fine, its just logcat i'm not a fan of, why wouldn't they design the truncated part to be expandable? Also I would recommend eclipse for an android app since that is what Google supports, I just don't like logcat, plain and simple – Matthew Pigram May 28 '13 at 01:52
  • @MatthewPigram The point Dave was trying to make, I believe, is that your comments on how it is horrible isn't helping the OP solve the issue. Its completely fine if you don't like it but give alternatives, explain how to use it, or something helpful. – codeMagic May 28 '13 at 01:55
  • @MatthewPigram I think you're not really aware of what is being truncated; maybe [the docs](http://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html#printStackTrace%28%29) will help. – Dave Newton May 28 '13 at 01:56
  • @codeMagic true, well an alternative is Netbeans, however im not sure if have has GUI capabilities for android stuff. You can run the AVD by using command line I believe, so you can still emulate, but with a little more effort. – Matthew Pigram May 28 '13 at 03:01

2 Answers2

4

Your problem here is this line

SharedPreferences sp = getSharedPreferences(prefName, MODE_PRIVATE);

getSharedPreferences() uses a Context so you can't call this until onCreate() has run. Try changing your code like this

public class MainActivity extends Activity {

Set<String> tasks = new HashSet<String>();
final String prefName = "andorid";
SharedPreferences sp;  // you can declare it here

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    sp = getSharedPreferences(prefName, MODE_PRIVATE);  // but don't initialize it until at least here

    SetupApp();
}

As far as reading logcat take this example

05-18 18:29:44.160: ERROR/AndroidRuntime(2145): FATAL EXCEPTION: main
05-18 18:29:44.160: ERROR/AndroidRuntime(2145): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.paad.whereami/com.paad.whereami.WhereAmI}: java.lang.NullPointerException
05-18 18:29:44.160: ERROR/AndroidRuntime(2145):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
05-18 18:29:44.160: ERROR/AndroidRuntime(2145):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
05-18 18:29:44.160: ERROR/AndroidRuntime(2145):     at android.app.ActivityThread.access$1500(ActivityThread.java:117)
05-18 18:29:44.160: ERROR/AndroidRuntime(2145):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
05-18 18:29:44.160: ERROR/AndroidRuntime(2145):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-18 18:29:44.160: ERROR/AndroidRuntime(2145):     at android.os.Looper.loop(Looper.java:130)
05-18 18:29:44.160: ERROR/AndroidRuntime(2145):     at android.app.ActivityThread.main(ActivityThread.java:3683)
05-18 18:29:44.160: ERROR/AndroidRuntime(2145):     at java.lang.reflect.Method.invokeNative(Native Method)
05-18 18:29:44.160: ERROR/AndroidRuntime(2145):     at java.lang.reflect.Method.invoke(Method.java:507)
05-18 18:29:44.160: ERROR/AndroidRuntime(2145):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
05-18 18:29:44.160: ERROR/AndroidRuntime(2145):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
05-18 18:29:44.160: ERROR/AndroidRuntime(2145):     at dalvik.system.NativeStart.main(Native Method)
05-18 18:29:44.160: ERROR/AndroidRuntime(2145): Caused by: java.lang.NullPointerException
05-18 18:29:44.160: ERROR/AndroidRuntime(2145):     at com.example.project.MainActivity.updateWithNewLocation(MainActivity.java:290)
05-18 18:29:44.160: ERROR/AndroidRuntime(2145):     at com.example.project.MainActivity.onCreate(MainActivity.java:216)
05-18 18:29:44.160: ERROR/AndroidRuntime(2145):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
05-18 18:29:44.160: ERROR/AndroidRuntime(2145):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)

After you see FatalException look for the first line like Caused by

This tells you what your exception is. In this example, NullPointerException. Then look for the first line that references your project. Here it is at com.example.project.MainActivity.updateWithNewLocation(MainActivity.java:290). This tells us that the exception occurred at line 290 of MainActivity and this is the best place to start. You may have to trace it back from here but this is generally where your problem is.

I grabbed this stacktrace from another question, hope no one minds, but this should give you a general idea of how to debug your app. You still may not understand exactly why or where it happened but this will better prepare you to ask a question so you can post the most relevant code and give it a good go. Hope this helped

codeMagic
  • 44,549
  • 13
  • 77
  • 93
1

The best way to debug android using eclipse is to use breakpoints, catch exceptions, and use the log cat.

Set breakpoints like you have been doing to try and locate the error.

If the breakpoints aren't working then you can view the log cat and it may give you more information such as the line the error occurred on in your code.

Then you could try catching exceptions:

try{
  //do some stuff
}catch(Exception e){
  Log.wtf("A terrible error occured.", e);
}

You could also check this post How to Debug Android application line by line using Eclipse? which tells you about more debugging methods.

Community
  • 1
  • 1
Andrew Cumming
  • 965
  • 6
  • 14