I have a Preference activity where I get this error when it changes orientation:
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.material.floatingactionbutton.FloatingActionButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
Here is where the crash occurs specifically:
public class SomeActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
.
.
.
}
public static class SettingsFragment extends PreferenceFragmentCompat {
setPreferencesFromResource(R.xml.some_preferences, rootKey);
.
.
final FloatingActionButton brightnessFloatingActionButton = getActivity().findViewById(R.id.brightnessFloatingActionButton);
brightnessFloatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveData(sharedPreferences, gson, brightness_level_preference, packageName);
getActivity().finish();
}
});
.
.
}
}
If I remove the setOnCLickListener statement the orientation crash no longer occurs. What's the problem here?
Add below line in manifest
android:configChanges="orientation|screenSize"
Related
I want my update_activity to display a back arrow button but this code gives me this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
at this line:
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
What do you suggest?
public class UpdateActivity extends AppCompatActivity {
TextView textView;
AppBarLayout appbar;
private static Socket s;
private static PrintWriter pw;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Button button = findViewById(R.id.UpdateButton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
connect();
}
});
}
when I substitute that command with
Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
it returns me this other error (which I think is the same):
Unable to start activity
ComponentInfo{io.anycopy.googleplusdemo/io.anycopy.googleplusdemo.UpdateActivity}: java.lang.NullPointerException
Most likely you are using NoActionBar themes, in which case getSupportActionBar () return null and you must either change the theme or use getActionBar ()
I searched everywhere for a solution to my problem, but couldn't get one.So, the problem is I want to launch another activity called FifthActivity from my MainActivity via the button but my activity keeps crashing. I checked the logcat and found this -
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.india.chemistry/com.example.india.chemistry.FifthActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
Below is my mainActivity java file.
package com.example.india.chemistry;
public class MainActivity extends AppCompatActivity {
private static boolean isRunning = false;
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(!isRunning)
{
isRunning = true;
startActivity(new Intent(this, Intro.class));//Play your video here
}
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void part_a( View View){
Intent intent1 = new Intent("com.example.india.chemistry.Second_Activity");
startActivity(intent1);
}
public void part_b( View View) {
Intent intent2 = new Intent("com.example.india.chemistry.ThirdActivity");
startActivity(intent2);
}
public void formulas( View View) {
Intent intent4 = new Intent(this,FifthActivity.class);
startActivity(intent4);
}
}
Below is my FifthActivity.java file.
package com.example.india.chemistry;
public class FifthActivity extends ActionBarActivity {
final Animation shake = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.shake);
final Animation bounce = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.bounce);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fifth);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_fifth, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void nernst(View View) {
Intent intentf1 = new Intent("com.example.india.chemistry.nernst_activity");
startActivity(intentf1);
}
public void waterhardness(View View) {
Intent intentf2 = new Intent("com.example.india.chemistry.WaterHardness");
startActivity(intentf2);
}
public void determinationOfCao(View view) {
Intent intentf3 = new Intent("com.example.india.chemistry.CementCao");
startActivity(intentf3);
}
public void COD_waste_water(View view) {
Intent intentf4 = new Intent("com.example.india.chemistry.COD");
startActivity(intentf4);
}
public void C_in_B(View view) {
Intent intentf5 = new Intent("com.example.india.chemistry.Copper_in_Brass");
startActivity(intentf5);
}
public void alkalinity(View view) {
Intent intentf6 = new Intent("com.example.india.chemistry.Alkalinity");
startActivity(intentf6);
}
public void haematite_ore(View view) {
Intent intentf7 = new Intent("com.example.india.chemistry.HaemetiteOre");
startActivity(intentf7);
}
public void colourimetry_copper(View view) {
Intent intentf8 = new Intent("com.example.india.chemistry.Colourimetric_Copper");
startActivity(intentf8);
}
public void potentiometry_fas(View view) {
Intent intentf9 = new Intent("com.example.india.chemistry.Potentiometry_fas");
startActivity(intentf9);
}
public void conductometry(View view) {
Intent intentf10 = new Intent("com.example.india.chemistry.Conductometry");
startActivity(intentf10);
}
public void pka(View view) {
Intent intentf11 = new Intent("com.example.india.chemistry.pka");
startActivity(intentf11);
}
}
Below is the logcat.
10-14 17:13:58.145 15430-15430/com.example.india.chemistry E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.india.chemistry, PID: 15430 java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.india.chemistry/com.example.india.chemistry.FifthActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2420)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2569)
at android.app.ActivityThread.access$900(ActivityThread.java:150)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1399)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:168)
at android.app.ActivityThread.main(ActivityThread.java:5885)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:107)
at com.example.india.chemistry.FifthActivity.<init>(FifthActivity.java:21)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1085)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2410)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2569)
at android.app.ActivityThread.access$900(ActivityThread.java:150)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1399)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:168)
at android.app.ActivityThread.main(ActivityThread.java:5885)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)
Please help me.
You can't call getApplicationContext(result in null) before oncreate because activity has not been created properly yet so you need to call this once your oncreate has been executed or after the super call .
The super call of onCreate fetches the application context for your activity.
Solution :
So either put your code inside oncreate or create a function and call it from inside oncreate after the super call.
Note : you will have to avoid final to make your identifiers global because the lazy initialization with final only works with constructors but don't worry , onCreate gets executed once when your activity is created or recreated.
Try this and let me know if problem solved or not.....
Animation shake,bounce;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fifth);
shake = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.shake);
bounce = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.bounce);
}
You need to add the activity in your manifest file, under application. Whenever you create a new activity add it to manifest file.
<application
...
<activity
android:name=". FifthActivity"
android:label="Fifth" />
...
</application>
Hope this helps.
try this:
public class FifthActivity extends ActionBarActivity {
Animation shake,bounce;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fifth);
shake = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.shake);
bounce = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.bounce);
}
Your view has not yet been created, move :
shake = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.shake);
bounce = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.bounce);
To your oncreate method.
stack trace's first line gives Detailed information : getApplicationContext()' on a null object reference.Means Activity was not created,it's return null Context. You make a both animation's Object Globally. try to edit your code this way.
public class FifthActivity extends ActionBarActivity {
Animation shake,bounce;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fifth);
shake = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.shake);
bounce = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.bounce);
}
}
i am creating two java file 1st main activity.java file 2nd fragment.java file create button on fragment.java how to click listener written on activity.java help me
fragment.java
public class fragment extends fragment{
Button btn;
// some code
btn = (Button)layout.findviewbyid(R.id.btn1);
}
}
activity.java
public class activity extends Activity
{
// how to access the click action btn here
btn.setOnclicklistner(new View.OnClickLisitner(){
public OnClick(){
}
To use the button in activity from the fragment, you have to use getActivity()
In your fragment,
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_item_select, container, false);
btn = (Button) getActivity().findViewById(R.id.btn);
}
btn is the button in activity
getActivity() in a Fragment returns the Activity the Fragment is currently associated with. (see http://developer.android.com/reference/android/app/Fragment.html#getActivity()).
You can define custom clickListener class and create it's instance in fragment and set listener instance there. Now you can write code in that class. Hope it will help you.
public class MyCustomListener implements OnClickListener{
#override
public void onClick(View v){
// you stuff
}
}
then in your fragment call this
MyCustomListener listener=new MyCustomListener();
btn.setOnClickListener(listener);
Here is my take on the issue, both in Java and Kotlin.
Java:
public final class YourActivity extends AppCompatActivity {
/***/
public final void yourMethod() {
printIn("Printing from yourMethod!")
}
}
public final class YourFragment extends Fragment {
/***/
#Override
public void onViewCreated(View v, Bundle savedInstanceState) {
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
YourActivity yourActivity = (YourActivity) getActivity();
yourActivity.yourMethod();
}
}));
}
}
Kotlin:
class YourActivity : AppCompatActivity() {
/***/
fun yourMethod() {
print("Printing from yourMethod!")
}
}
class YourFragment: Fragment() {
/***/
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
button.setOnClickListener {
val yourActivity = activity as YourActivity
yourActivity.yourMethod()
}
}
}
I hope it helps someone out there =)
If I understand your problem correctly, you want to delegate a button click inside a fragment back to its parent activity.
Keep a reference to the parent activity inside your fragment. Then set the listener to your button in your fragment like this:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
parentActivity.doStuff();
}
};
In your parent Activity, define method doStuff():
public void doStuff() {
// handle button click event here
}
Starting to learn about creating the settings page, but my app crashes when I select 'settings' from the action bar, and I get this error in logcat:
Caused by: java.lang.ClassCastException: com.myexamlpe.thing.Preference cannot be cast to android.app.Activity
Here's how I call it from my main class:
public class RCs extends FragmentActivity implements
rcfrequency.ToolbarListener, RCButtons.ToolbarListener {
.
.
.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Intent myIntent = new Intent(this, Preference.class);
startActivity(myIntent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Here's my Preference class:
public class Preference extends PreferenceFragment implements OnSharedPreferenceChangeListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
The error happens because you are trying to open a PreferenceFragment as a PreferenceActivity
public class Preference extends PreferenceFragment implements OnSharedPreferenceChangeListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
The error is cast, because its Preference class inherits from PreferenceFragment soon there may not be opened as an Activity
Caused by: java.lang.ClassCastException: com.myexamlpe.thing.Preference cannot be cast to android.app.Activity
change to :
public class Preference extends PreferenceActivity implements OnSharedPreferenceChangeListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
See a example here, how to use PreferenceFragment:
http://www.cs.dartmouth.edu/~campbell/cs65/lecture12/lecture12.html
The problem is that you declare class Preference extends PreferenceFragment but try to start it with an Intent. As Andre stated, you can fix this by extending PreferenceActivity. Alternatively, you can use a the FragmentManager to display your Preference. This requires learning a little about fragments and how they interact with activities. This is what was meant by the suggestion that you should use PreferenceFragment over PreferenceActivity.
Why is mainB_news allways null? (in the method onBackPressed())
In onCreate I set a value to the button!!! :(
PS: with findViewById() I get the same error...
public class MainActivity extends Activity {
private Button mainB_news;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mainB_news = (Button) findViewById(R.id.mainB_news);
mainB_news.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
setContentView(R.layout.news);
}
});
}
#Override
public void onBackPressed() {
// check if page 2 is open
if (mainB_news != null && mainB_news.isShown()){
setContentView(R.layout.main); // open main view again
return;
}else
super.onBackPressed(); // allows standard use of backbutton for page 1
}
}
THANKS a lot!
Because you change contentView on button click. mainB_news doesn't exist after contentView changing. You shouldn't use setContentView() in this manner. Consider using another activity for showing news.
Because it is not defined in res/layout/main.xml ?