Android Fragment causes NullPointerException - java

First going to say that I know there are a lot of similar posts to this, and I have seen them, however I am new to android development and am not yet familiar enough with it to modify those other answers to fix my exact problem.
I have a fragment that was created by default with a new project that contains a button and text view, and in my MainActivity.java i've made an onClick function for the button. This function throws the NPE. Here's the LogCat:
03-10 19:26:52.620: D/AndroidRuntime(878): Shutting down VM
03-10 19:26:52.620: W/dalvikvm(878): threadid=1: thread exiting with uncaught exception (group=0xb2af2ba8)
03-10 19:26:52.630: E/AndroidRuntime(878): FATAL EXCEPTION: main
03-10 19:26:52.630: E/AndroidRuntime(878): Process: com.example.main, PID: 878
03-10 19:26:52.630: E/AndroidRuntime(878): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.main/com.example.main.MainActivity}: java.lang.NullPointerException
03-10 19:26:52.630: E/AndroidRuntime(878): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
03-10 19:26:52.630: E/AndroidRuntime(878): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
03-10 19:26:52.630: E/AndroidRuntime(878): at android.app.ActivityThread.access$800(ActivityThread.java:135)
03-10 19:26:52.630: E/AndroidRuntime(878): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
03-10 19:26:52.630: E/AndroidRuntime(878): at android.os.Handler.dispatchMessage(Handler.java:102)
03-10 19:26:52.630: E/AndroidRuntime(878): at android.os.Looper.loop(Looper.java:136)
03-10 19:26:52.630: E/AndroidRuntime(878): at android.app.ActivityThread.main(ActivityThread.java:5017)
03-10 19:26:52.630: E/AndroidRuntime(878): at java.lang.reflect.Method.invokeNative(Native Method)
03-10 19:26:52.630: E/AndroidRuntime(878): at java.lang.reflect.Method.invoke(Method.java:515)
03-10 19:26:52.630: E/AndroidRuntime(878): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-10 19:26:52.630: E/AndroidRuntime(878): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
03-10 19:26:52.630: E/AndroidRuntime(878): at dalvik.system.NativeStart.main(Native Method)
03-10 19:26:52.630: E/AndroidRuntime(878): Caused by: java.lang.NullPointerException
03-10 19:26:52.630: E/AndroidRuntime(878): at com.example.main.MainActivity.onCreate(MainActivity.java:31)
03-10 19:26:52.630: E/AndroidRuntime(878): at android.app.Activity.performCreate(Activity.java:5231)
03-10 19:26:52.630: E/AndroidRuntime(878): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
03-10 19:26:52.630: E/AndroidRuntime(878): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
03-10 19:26:52.630: E/AndroidRuntime(878): ... 11 more
03-10 19:31:54.292: I/Process(878): Sending signal. PID: 878 SIG: 9
The MainActivity.java:
package com.example.main;
import android.support.v7.app.ActionBarActivity;
...
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
final TextView myText = (TextView) findViewById(R.id.text1);
Button myButton = (Button) findViewById(R.id.button1);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myText.setText("Yes!");
}
});
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}

If the TextView and the Button are in the layout's fragment, you need to find their id in the onCreatedView method of the fragment. Then, you should do:
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
final TextView myText = (TextView) rootView.findViewById(R.id.text1);
Button myButton = (Button) rootView.findViewById(R.id.button1);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myText.setText("Yes!");
}
});
return rootView;
}
}

then myButton is null. so findViewById(R.id.button1) is returning null. You should make sure that is the id you have used for the button your layout (R.layout.fragment_main)

I don't see any fetal mistakes in your OnCreate code but here are some hints to solve the problem
1) Make sure that youractivity is initialized in the Manifest.xml file.
2) Try to run the project after commenting the onClickListener part to make sure that your problem is not in the inflation or in the Layout xml file itself.
3) Try to debug yourOnCreate method and monitor all the different variable values by selecting the variable TO find out the problem
4) Make sure that your button and TextView are in the layout that you are inflating
I hope I could help

The myButton.setOnClickListener(new View.OnClickListener() line gives an exception because its done after you started the fragment, I believe. Put that code in the fragment constructor, and you should be good.

Related

Application not working on Android Kitkat

I'm creating my own application. I tested it on Android Lollipop and Marshmallow - everything works great. But whenever I try Android Kitkat, an error occurs. Here's error log:
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.newproject/com.example.newproject.Progi}: java.lang.ClassCastException: java.lang.Object[] cannot be cast to java.math.BigDecimal[][]
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
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:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: java.lang.Object[] cannot be cast to java.math.BigDecimal[][]
at com.example.newproject.Progi.onCreate(Progi.java:62)
at android.app.Activity.performCreate(Activity.java:5008)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084) 
at android.app.ActivityThread.access$600(ActivityThread.java:130) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:4745) 
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:786) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
at dalvik.system.NativeStart.main(Native Method) 
It looks like problem is on line 62 in "progi" class, but - as for me - everything is OK especially that on newer Android versions it works great.
public class Progi extends AppCompatActivity {
Intent intent;
Bundle liczby;
Bundle doble;
BigDecimal tablica [][];
BigDecimal punkty = new BigDecimal(-1);
#Override
public boolean onPrepareOptionsMenu(Menu menu)
{
android.content.SharedPreferences shared = android.preference.PreferenceManager.getDefaultSharedPreferences(this);
boolean warunek = shared.getBoolean("serial", false);
android.view.MenuItem menuitem = menu.getItem(0);
if(warunek)
{
menuitem.setTitle("Oceny pojedynczo");
}
else menuitem.setTitle("Oceny seryjnie");
return true;
}
public boolean onCreateOptionsMenu(Menu menu) {
android.view.MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.firstmenu, menu);
return true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layoutprogi);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setTitle("Progi punktowe");
intent = getIntent();
liczby = intent.getBundleExtra("liczby");
doble = intent.getBundleExtra("doble");
tablica = (BigDecimal[][]) doble.getSerializable("doble"); //here is line 62
if(intent.hasExtra("max")) {
Bundle a = intent.getBundleExtra("max");
punkty = (BigDecimal) a.getSerializable("max");
}
przejscie(true);
if(punkty.compareTo(new BigDecimal(-3))==0)
{
procenty(findViewById(android.R.id.content));
}
else if(punkty.compareTo(new BigDecimal(-1))!=0)
{
liczymy(findViewById(android.R.id.content));
}}
And in case someone asking "what 'tablica' gets from intent?":
BigDecimal[][] tablica = new BigDecimal[16][3];
//here i get data from file and put in inside "tablica"
Bundle doble = new Bundle();
doble.putSerializable("doble", tablica);
Intent intent = new Intent(Starter.this, MyActivity.class);
intent.putExtra("doble", doble);
startActivity(intent);
Any idea what's wrong?
Try switching your array implementation (BigDecimal[] []) to ArrayList.
If you want to pass an Array through an intent on Android versions
prior to Android 5.0.1 (maybe some older versions work aswell, but up
to Android 4.3 it is NOT working) You'll have to work around it. You
could do this by converting your Array to an ArrayList.
Then you would be casting it something like this:
(ArrayList<ArrayList<BigDecimal>>) doble.getSerializable("doble");
Related SO answer

unfortunately App has Stopped- Passing Intent data between two Activites

I am trying to pass String data using intent from Authorites.class to Issues.class . When a radio button is chosen and button is clicked, 1st activity has to show toast as well as pass the Radio button value to next activity.
When i choose the radio-button and press the button in Authorites.class,the app stops and exits. Plz find where have i gone wrong
public class Authorities extends AppCompatActivity {
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
//private GoogleApiClient client;
RadioButton auth_button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_authorities);
final RadioGroup auth_grp = (RadioGroup) findViewById(R.id.rgrp);
Button button1 = (Button) findViewById(R.id.authselect);
button1.setOnClickListener( new View.OnClickListener(){
#Override
public void onClick (View v){
// store the text corresponding to the RadioButton which is clicke
int sa = auth_grp.getCheckedRadioButtonId();
auth_button = (RadioButton) findViewById(sa);
// String auth=auth_button.getText().toString();
Toast.makeText(Authorities.this, auth_button.getText(), Toast.LENGTH_SHORT).show();
Intent i;
i=new Intent(Authorities.this, Issues.class);
// Intent i = new Intent().setClassName("com.example.chethan.wapp.Authorities", "com.example.chethan.wapp.Issues");
// i.putExtra("Auth",auth);
// Starts TargetActivity
// Authorities.this.startActivity(i);
startActivity(i);
}
});
}
Issues.class should recieve the Intent data returned from previous activity
public class Issues extends AppCompatActivity {
CheckBox mws,sl,swc,sws,dr;
Button b2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// mws=(CheckBox)findViewById(R.id.mws);
// sl=(CheckBox)findViewById(R.id.sl);
// swc=(CheckBox)findViewById(R.id.swc);
// sws=(CheckBox)findViewById(R.id.sws);
// dr=(CheckBox)findViewById(R.id.dr);
b2=(Button)findViewById(R.id.nxt);
Bundle extras = getIntent().getExtras();
String value1 = extras.getString("Auth");
Toast.makeText(getApplicationContext(),"Authority you chose is:\n"+value1,Toast.LENGTH_LONG).show();
}
Here's the log cat:
02-29 10:54:00.594 1960-1960/com.example.chethan.wapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.chethan.wapp, PID: 1960
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.chethan.wapp/com.example.chethan.wapp.Issues}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
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:5001)
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:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.chethan.wapp.Issues.onCreate(Issues.java:34)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233) 
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:5001) 
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:785) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601) 
at dalvik.system.NativeStart.main(Native Method) 
Because you are getting string value1 data from getString("Auth") of Intent in Issues class but in Authorities class you are not putting any ("Auth") value in Intent obj.
So uncomment this line...
i.putExtra("Auth",auth);
then run the project...

Fetch data from database SQLite with fragment

This is my fragment activity i am getting error while accessing database my code is :-
public class Test extends Fragment {
View view;
private Cursor c;
private final String DB = "Canary";
private SQLiteDatabase db2;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.test, container, false);
Button b = (Button) view.findViewById(R.id.test_button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(),"Listning",Toast.LENGTH_LONG).show();
}
});
db2 = SQLiteDatabase.openOrCreateDatabase(DB, null);
Log.d("Lee", "working her1");
c=db2.rawQuery("SELECT * FROM business_master", null);
Log.d("Lee", "working here2");
c.moveToFirst();
String id=c.getString(c.getColumnIndex("id"));
Log.d("id", "" + id);
String email=c.getString(c.getColumnIndex("email"));
Log.d("email", email);
String password=c.getString(c.getColumnIndex("password"));
db2.close();
return view;
} }
The error i am getting :-
01-20 11:35:57.168 17081-17081/com.purplefront.canary E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.purplefront.canary, PID: 17081
android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:209)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:193)
at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:804)
at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:789)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:694)
at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:709)
at com.purplefront.canary.Test.onCreateView(Test.java:36)
at android.app.Fragment.performCreateView(Fragment.java:1700)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:890)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
at android.app.BackStackRecord.run(BackStackRecord.java:684)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1447)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:443)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5086)
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:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
If i remove the database access it will work fine as expected but i need database access in fragment only.
Any help would be appreciated.

Why does my App crush?

Can someone point me out the error in this code. I am learning to code and I was trying to run my first app from tutorial I saw, until I found this message "Unfortunately, The New Boston has stopped". This the message I get when every time I tried to open it after installation. I even tried on three different phone and in my Emulator and the same thing happened. I looked at my code and I found no error on any line of code. And then I tried to debug it. Here is the entire code and the logcat report respectively.
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.os.Build;
public class MainActivity extends ActionBarActivity {
int counter;
Button add,sub;
TextView display;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
add = (Button) findViewById(R.id.bAdd);
add = (Button) findViewById(R.id.sSub);
display = (TextView) findViewById(R.id.tvDisplat);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter++;
display.setText("Your total is" + counter);
}
});
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter--;
display.setText("Your total is" + counter);
}
});
}
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
Logcat output
07-18 21:28:21.047: E/AndroidRuntime(10601): FATAL EXCEPTION: main
07-18 21:28:21.047: E/AndroidRuntime(10601): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.thenewbostone/com.thenewbostone.MainActivity}: java.lang.NullPointerException
07-18 21:28:21.047: E/AndroidRuntime(10601): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
07-18 21:28:21.047: E/AndroidRuntime(10601): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
07-18 21:28:21.047: E/AndroidRuntime(10601): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
07-18 21:28:21.047: E/AndroidRuntime(10601): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
07-18 21:28:21.047: E/AndroidRuntime(10601): at android.os.Handler.dispatchMessage(Handler.java:99)
07-18 21:28:21.047: E/AndroidRuntime(10601): at android.os.Looper.loop(Looper.java:123)
07-18 21:28:21.047: E/AndroidRuntime(10601): at android.app.ActivityThread.main(ActivityThread.java:4627)
07-18 21:28:21.047: E/AndroidRuntime(10601): at java.lang.reflect.Method.invokeNative(Native Method)
07-18 21:28:21.047: E/AndroidRuntime(10601): at java.lang.reflect.Method.invoke(Method.java:521)
07-18 21:28:21.047: E/AndroidRuntime(10601): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:871)
07-18 21:28:21.047: E/AndroidRuntime(10601): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
07-18 21:28:21.047: E/AndroidRuntime(10601): at dalvik.system.NativeStart.main(Native Method)
07-18 21:28:21.047: E/AndroidRuntime(10601): Caused by: java.lang.NullPointerException
07-18 21:28:21.047: E/AndroidRuntime(10601): at com.thenewbostone.MainActivity.onCreate(MainActivity.java:34)
07-18 21:28:21.047: E/AndroidRuntime(10601): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
07-18 21:28:21.047: E/AndroidRuntime(10601): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
07-18 21:28:21.047: E/AndroidRuntime(10601): ... 11 more
You just have problem with this, sub should be on the second line, not add.
add = (Button) findViewById(R.id.bAdd);
add = (Button) findViewById(R.id.sSub);
So, it crashes then on this line
sub.setOnClickListener(new View.OnClickListener() {
cause sub wasn't initialized.

Android, Navigation Drawer NullPointerException, No ActionBar

I'm trying to make a Navigation Bar by using the example provided from android.
I've downloaded the code and implemented it into my project. I don't know why it doesn't work, it's a sample.
Here my logcat and my jar.
01-30 13:26:51.958: D/AndroidRuntime(580): Shutting down VM
01-30 13:26:51.958: W/dalvikvm(580): threadid=1: thread exiting with uncaught exception (group=0x409961f8)
01-30 13:26:51.969: E/AndroidRuntime(580): FATAL EXCEPTION: main
01-30 13:26:51.969: E/AndroidRuntime(580): java.lang.RuntimeException: Unable to start activity ComponentInfo{ch.antum.antumapp/ch.antum.antumapp.MainActivity}: java.lang.NullPointerException
01-30 13:26:51.969: E/AndroidRuntime(580): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1955)
01-30 13:26:51.969: E/AndroidRuntime(580): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)
01-30 13:26:51.969: E/AndroidRuntime(580): at android.app.ActivityThread.access$600(ActivityThread.java:122)
01-30 13:26:51.969: E/AndroidRuntime(580): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146)
01-30 13:26:51.969: E/AndroidRuntime(580): at android.os.Handler.dispatchMessage(Handler.java:99)
01-30 13:26:51.969: E/AndroidRuntime(580): at android.os.Looper.loop(Looper.java:137)
01-30 13:26:51.969: E/AndroidRuntime(580): at android.app.ActivityThread.main(ActivityThread.java:4340)
01-30 13:26:51.969: E/AndroidRuntime(580): at java.lang.reflect.Method.invokeNative(Native Method)
01-30 13:26:51.969: E/AndroidRuntime(580): at java.lang.reflect.Method.invoke(Method.java:511)
01-30 13:26:51.969: E/AndroidRuntime(580): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
01-30 13:26:51.969: E/AndroidRuntime(580): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
01-30 13:26:51.969: E/AndroidRuntime(580): at dalvik.system.NativeStart.main(Native Method)
01-30 13:26:51.969: E/AndroidRuntime(580): Caused by: java.lang.NullPointerException
01-30 13:26:51.969: E/AndroidRuntime(580): at ch.antum.antumapp.MainActivity.onCreate(MainActivity.java:93)
01-30 13:26:51.969: E/AndroidRuntime(580): at android.app.Activity.performCreate(Activity.java:4465)
01-30 13:26:51.969: E/AndroidRuntime(580): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
01-30 13:26:51.969: E/AndroidRuntime(580): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1919)
01-30 13:26:51.969: E/AndroidRuntime(580): ... 11 more
MainActivity.java
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mTitle;
private String[] mPlanetTitles;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = getTitle();
mPlanetTitles = getResources().getStringArray(R.array.items);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// set up the drawer's list view with items and click listener
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mPlanetTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
if (savedInstanceState == null) {
selectItem(0);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
/* Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action buttons
switch(item.getItemId()) {
case R.id.action_websearch:
// create intent to perform web search for this planet
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());
// catch event that there's no activity to handle intent
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* The click listner for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
// update the main content by replacing fragments
Fragment fragment = new PlanetFragment();
Bundle args = new Bundle();
args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
fragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mPlanetTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
/**
* Fragment that appears in the "content_frame", shows a planet
*/
public static class PlanetFragment extends Fragment {
public static final String ARG_PLANET_NUMBER = "planet_number";
public PlanetFragment() {
// Empty constructor required for fragment subclasses
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_planet, container, false);
int i = getArguments().getInt(ARG_PLANET_NUMBER);
String planet = getResources().getStringArray(R.array.items)[i];
int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
"drawable", getActivity().getPackageName());
((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
getActivity().setTitle(planet);
return rootView;
}
}
}
I have the right imports and package name.
It is a NullPointerException but I can't find anything missing. Also the logcat doesn't really specify in which file or on which line an error occurred. I had no problem debugging my projects when I wrote java applications. But, with android I can't really use the logcat usefully, any tips?
PS: I'm not using the ActionBar, but the code does, so may this be a problem? I've simply deleted the parts which where commented as ActionBar.
Thank you for your time.

Categories

Resources