I am new to Android developement and had recently started on a project to get WiFi SSID, BSSID and MAC address. However, the app crashed unexpectedly immediately after opening it.
The error log in Android Studio says that:
FATAL EXCEPTION: main
Process: com.example.android.wifi, PID: 3875
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.android.wifi/com.example.android.wifi}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2993)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3248)
at ...
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
at
android.app.Activity.findViewById(Activity.java:2277)
at
com.example.android.wifi.MainActivity.<init>(MainActivity.java:16)
at ...
My java file can be found at http://www.yikjin.ga/MainActivity.java
There were no syntax errors recorded by Android Studio.
Thanks in advance!
From your error is seems you are trying to get the View inside the constructor of your class or you are calling findViewById() outside.
com.example.android.wifi.MainActivity.<init>(MainActivity.java:16)
Move those code to onCreate() method after calling setContentView()
Update:
Change
TextView viewWifiSSID = (TextView) findViewById(R.id.network);
TextView viewWifiBSSID = (TextView) findViewById(R.id.bssid);
TextView viewWifiMAC = (TextView) findViewById(R.id.mac);
to
TextView viewWifiSSID;
TextView viewWifiBSSID;
TextView viewWifiMAC;
and add the following to onCreate() after setContentView()
viewWifiSSID = (TextView) findViewById(R.id.network);
viewWifiBSSID = (TextView) findViewById(R.id.bssid);
viewWifiMAC = (TextView) findViewById(R.id.mac);
you are referring object before activity is created ... onCreate() is called when your activity is created so refer object inside onCreate()...
TextView viewWifiSSID, viewWifiBSSID, viewWifiMAC;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewWifiSSID = (TextView) findViewById(R.id.network);
viewWifiBSSID = (TextView) findViewById(R.id.bssid);
viewWifiMAC = (TextView) findViewById(R.id.mac);
getWifi();
}
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
Hi i am new to android studio and I am trying to start a new activity - however, I am having endless issues with getting Context - I have tried a few different methods posted on stack overflow but It just keeps throwing a null pointer please help. See onCreate method and exception below.
AddRoutine.class is just a blank activity
MainActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MainActivity.mContext = this.getApplicationContext();
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Add Routine
FloatingActionButton fab = findViewById(R.id.addRoutine);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, AddRoutine.class));
}
});
generateRoutineListing(getAppContext());
//if returnListing.length > 0
// recyclerView.addItems
//else
// Show Jumbotron/Message board explaining that no routines have been created
}
Exception
E/AndroidRuntime: FATAL EXCEPTION: main
Process: za.co.freelanceweb.routines, PID: 14648
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.content.ComponentName.<init>(ComponentName.java:130)
at android.content.Intent.<init>(Intent.java:5780)
at za.co.freelanceweb.routines.MainActivity$1.onClick(MainActivity.java:38)
at android.view.View.performClick(View.java:6294)
at android.view.View$PerformClick.run(View.java:24774)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6518)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Thanks so Much
Instead of:
MainActivity.mContext = this.getApplicationContext();
Use:
Context mcontext = MainActivity.this; //Also, set mcontext as a global variable.
Also,
Instead of:
generateRoutineListing(getAppContext());
Use:
generateRoutineListing(mcontext);
The problem is probably in this line:
MainActivity.mContext = this.getApplicationContext();
Activity extends Context so you can always use this to refer to the activity's context.
I am not sure what you are trying to do with that but you should not be using the application's context on one activity. The application context lives through out the entire lifetime of the application.
If you want want to start a new activity do this.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, AddRoutineActivity.class);
startActivity(intent);
}
And then register AddRoutineActivity in your AndroidManifest.xml file like so:
<activity android:name=".AddRoutineActivity" />
If you are new to android you may want to check out Kotlin.
When I run the app and go to the user's activity the app crashes showing me that the mUsersList.setHasFixedSize(true); is making the app crash.
this is the message "Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setHasFixedSize(boolean)' on a null object reference"
private RecyclerView mUsersList;
private DatabaseReference mUsersDatabase;
#Override
protected void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.users_single_layout);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mUsersDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
mUsersList = findViewById(R.id.users_list);
mUsersList.setHasFixedSize(true);
mUsersList.setLayoutManager(new LinearLayoutManager(this));
}
The stacktrace tells you everything you need. mUsersList is null, so you can't call any methods on it. You should make sure your layout file R.layout.users_single_layout has a RecyclerView with id of "#+id/users_list" defined in it. Also, you should do a null pointer check:
mUsersList = findViewById(R.id.users_list);
if (mUsersList != null) {
mUsersList.setHasFixedSize(true);
mUsersList.setLayoutManager(new LinearLayoutManager(this));
}
Although this question has been asked several times none of the solutions has worked for me. I keep getting this error suddenly, and I think I might have have a problem different those others.
Here's the class thats responsible:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_car);
}
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance();
PageDownloader PDL = new PageDownloader();
TextView tv1 = findViewById(R.id.textView6);
TextView tv2 = findViewById(R.id.textView5);
TextView tv3 = findViewById(R.id.textView3);
public int Distance;
public int Mileage;
float GasPriceMid;
float GasPricePre;
float GasPriceReg;
public float Toll;
public float Parking;
String StringPriceReg;
String StringPriceMid;
String StringPricePre;
As well as this one:
public class MenuActivity extends AppCompatActivity {
PriceCalculator PC = new PriceCalculator();
//PageDownloader PDL = new PageDownloader();
EditText et1 = findViewById(R.id.et1);
EditText et2 = findViewById(R.id.et2);
EditText et3 = findViewById(R.id.et3);
EditText et4 = findViewById(R.id.et4);
It was simply supposed to create a reference to these objects but its receiving this error:
Process: com.example.ojd.pricecalculatorapp, PID: 5067
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.ojd.pricecalculatorapp/com.example.ojd.pricecalculatorapp.MenuActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3135)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3418)
at android.app.ActivityThread.access$1100(ActivityThread.java:231)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1823)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7422)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
at android.support.v7.app.AppCompatDelegateImpl.<init>(AppCompatDelegateImpl.java:249)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:182)
at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:520)
at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:191)
at com.example.ojd.pricecalculatorapp.PriceCalculator.<init>(PriceCalculator.java:19)
at com.example.ojd.pricecalculatorapp.MenuActivity.<init>(MenuActivity.java:9)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1096)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3125)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3418)
at android.app.ActivityThread.access$1100(ActivityThread.java:231)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1823)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7422)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
It says that the problem was (PriceCalculator.java:19) which is
TextView tv1 = findViewById(R.id.textView6);
and (MenuActivity.java:9)
PriceCalculator PC = new PriceCalculator();
Thanks in advance and I'm hoping the answer won't just be a stupid mistake I made.
It's hard to tell from your code snippet, but PriceCalculator appears to extend from AppCompatActivity. You should never use the new operator with activities. Doing this will cause the activity to not have the proper context set and you won't be able to use methods like findViewById(). I'm not sure why MenuActivity has an instance of another activity inside of it. This is also a bad idea, activities should never have references to each other and should instead communicate through intents. Fixing these two issues should make things work better.
I think TextView tv1 = findViewById(R.id.textView6); should be in the onCreate method...
Try putting those in the onCreate method?
Just put all your identifications inside your Activity onCreate function. Meaning to say,
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_car);
TextView tv1 = findViewById(R.id.textView6);
TextView tv2 = findViewById(R.id.textView5);
TextView tv3 = findViewById(R.id.textView3);
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am trying to create a user profile section in my app. In my Login Activity, I ask for the username from FirebaseAUTH.getCurrentUser().getDisplayName() and save it in a string.
In my xml file for the main activity, I put a textView with a string containing a placeholder.
I tried both in the Login and the Main Activity Java files to .setText .format etc, but the text simply doesnt change..
Any hints on how to solve this?
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private HomeFragment hf;
private WebViewFragment wvf;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
firebaseAuth = FirebaseAuth.getInstance();
if (firebaseAuth.getCurrentUser().getDisplayName() != null) {
String name = firebaseAuth.getCurrentUser().getDisplayName();
final TextView profile = (TextView)findViewById(R.id.profile_section);
profile.setText("Test");
}
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.vreeni.firebaseauthentiction, PID: 6060
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.vreeni.firebaseauthentiction/com.example.vreeni.firebaseauthentication.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2822)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2897)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1598)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:251)
at android.app.ActivityThread.main(ActivityThread.java:6563)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.vreeni.firebaseauthentication.MainActivity.onCreate(MainActivity.java:52)
at android.app.Activity.performCreate(Activity.java:6975)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
You can find a simple example right at the top of this resource.
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView helloTextView = (TextView) findViewById(R.id.text_view_id);
helloTextView.setText(R.string.user_greeting);
}
}
If you still have problems, please provide your code.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
So I have this code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.favourites);
assert getSupportActionBar() != null;
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
SharedPreferences prefs = getSharedPreferences("myFavs", 0);
Map<String, String> m = (Map<String, String>) prefs.getAll();
List<String> list = new ArrayList<>(m.values());
ListView listView = (ListView) findViewById(R.id.favsList);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,R.layout.listlayout, android.R.id.text1, list );
listView.setAdapter(adapter);
And it outputs this error in logcat:
10-08 08:48:44.114 19390-19390/com.example.me1jmo.insult_generator E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.me1jmo.insult_generator, PID: 19390
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:399)
at android.widget.ArrayAdapter.getView(ArrayAdapter.java:369)
at android.widget.AbsListView.obtainView(AbsListView.java:2346)
at android.widget.ListView.measureHeightOfChildren(ListView.java:1280)
at android.widget.ListView.onMeasure(ListView.java:1188)
at android.view.View.measure(View.java:18788)
...
I have read the articles on why this happens but I can't figure out what bit of my code I need to change to get it working.
The issue is coming because you are referring the Textview which is not in your specified layout.
android.R.id.text1
is a Textview of Android OS classes which is inbuilt in OS.
You need to use the id of the Textview which you have specified in the
R.layout.listlayout
Change that and your error will be resolved.
Try changing android.R.id.text1 to R.id.text1. Also, check if your listlayout has a TextView with id text1.
Replace this
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,R.layout.listlayout, android.R.id.text1, list );
With this
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1, android.R.id.text1, list );