I appreciate your help with a problem with the ratingbar, I want to show the value of the ratingbar in a Toast when pressing a button, therefore each time you press the button, the value of the ratingbar should be displayed, however at the time pressing the button closes the application and debugging I get the following error.
"Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'float android.widget.RatingBar.getRating()' on a null object
reference at
com.org.notas.asembisencuesta.MainActivity.onClick(MainActivity.java:114)
"
#Override
protected void onCreate(Bundle savedInstanceState) {
commentsFra = new ComentariosFragment();
navhost = new HomeFragment();
thanks = new ThanksFragment();
}
public void onClick(View view){
ratingBar = findViewById(R.id.ratingBarOne);
transaction = getSupportFragmentManager().beginTransaction();
switch (view.getId()){
case R.id.fin_encuesta: {
transaction.replace(R.id.nav_host_fragment, thanks);
transaction.addToBackStack(null);
Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override public void run() {
transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.nav_host_fragment, navhost);
transaction.addToBackStack(null); transaction.commit();
}
};
handler.postDelayed(runnable,7000);
comments = findViewById(R.id.comments_dialog);
comments.setText(""); float rating; rating = ratingBar.getRating();
//Linea 114 Toast.makeText(this, ":" + rating, Toast.LENGTH_SHORT).show();
break;
}
transaction.commit();
}
}
This is the error that it generates:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.org.notas.asembisencuesta, PID: 7682
java.lang.IllegalStateException: Could not execute method for android:onClick
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(.java:414)
at android.view.View.performClick(View.java:7146)
at android.view.View.performClickInternal(View.java:7119)
at android.view.View.access$3500(View.java:803)
at android.view.View$(View.java:27533)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7386)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:980)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(.java:409)
at android.view.View.performClick(View.java:7146)
at android.view.View.performClickInternal(View.java:7119)
at android.view.View.access$3500(View.java:803)
at android.view.View$(View.java:27533)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7386)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:980)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'float android.widget.RatingBar.getRating()' on a null object reference
at com.org.notas.asembisencuesta.MainActivity.onClick(MainActivity.java:114)
at java.lang.reflect.Method.invoke(Native Method)
Related
I'm trying to add fragments to the dashboard of my project app. However, I'm getting nullpointerexception
in the .setOnItemSelectedListener in the bottomMenu function, the code is as follows:
Dashboard.java
public class Dashboard extends AppCompatActivity {
ChipNavigationBar chipNavigationBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
chipNavigationBar = findViewById(R.id.bottom_nav_menu);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new DashboardFragment()).commit();
bottomMenu();
}
private void bottomMenu() {
chipNavigationBar.setOnItemSelectedListener(new ChipNavigationBar.OnItemSelectedListener() {
#Override
public void onItemSelected(int i) {
Fragment fragment = null;
switch (i){
case R.id.bottom_nav_dashboard:
fragment = new DashboardFragment();
break;
case R.id.bottom_nav_explore:
fragment = new ExploreFragment();
break;
case R.id.bottom_nav_profile:
fragment = new ProfileFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, fragment).commit();
}
});
}
}
LogCat:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.desikhao, PID: 11751
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.desikhao/com.example.desikhao.LocationOwner.Dashboard}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.ismaeldivita.chipnavigation.ChipNavigationBar.setOnItemSelectedListener(com.ismaeldivita.chipnavigation.ChipNavigationBar$OnItemSelectedListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3308)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3457)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2044)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7562)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.ismaeldivita.chipnavigation.ChipNavigationBar.setOnItemSelectedListener(com.ismaeldivita.chipnavigation.ChipNavigationBar$OnItemSelectedListener)' on a null object reference
at com.example.desikhao.LocationOwner.Dashboard.bottomMenu(Dashboard.java:39)
at com.example.desikhao.LocationOwner.Dashboard.onCreate(Dashboard.java:33)
at android.app.Activity.performCreate(Activity.java:7893)
at android.app.Activity.performCreate(Activity.java:7880)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1307)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3283)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3457)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2044)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7562)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
At first, I thought the problem is because I stored a null value in the fragment, if that is the case then how do I fix it, I'm new to this so please let me know what am I doing wrong here.
Your chipNavigationBar variable is null and therefore the OnItemSelectedListener is instantiated with null, which is not possible.
You try to find your chipNavigationBar in the Dashboard, but you haven't even set setContentView(R.layout.yourLayout);, which means that it is not possible to find the ViewById.
You have to instatiate the variable in your fragment, where you have a valid view.
chipNavigationBar = findViewById(R.id.bottom_nav_menu);
Everytime the application gets to my second activity it crashes, giving the error.
My activity:
public class SecondActivity extends AppCompatActivity {
EditText barcodeText = findViewById(R.id.barcodeText);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
IntentFilter filter = new IntentFilter();
filter.addCategory(Intent.CATEGORY_DEFAULT);
filter.addAction(getResources().getString(R.string.activity_intent_filter_action));
registerReceiver(myBroadcastReceiver, filter);
}
private BroadcastReceiver myBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Bundle b = intent.getExtras();
if (action.equals(getResources().getString(R.string.activity_intent_filter_action))) {
try {
displayScanResult(intent);
} catch (Exception e) {
}
}
}
};
private void displayScanResult(Intent initiatingIntent)
{
String decodedSource = initiatingIntent.getStringExtra(getResources().getString(R.string.datawedge_intent_key_source));
String decodedData = initiatingIntent.getStringExtra(getResources().getString(R.string.datawedge_intent_key_data));
String decodedLabelType = initiatingIntent.getStringExtra(getResources().getString(R.string.datawedge_intent_key_label_type));
barcodeText.setText(decodedData);
}
}
Logcat:
07-01 12:37:03.373 349-349/com.example.provatimer E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.provatimer, PID: 349
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.provatimer/com.example.provatimer.SecondActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2236)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5256)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:149)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:99)
at android.content.Context.obtainStyledAttributes(Context.java:438)
at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:692)
at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:659)
at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:479)
at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:214)
at com.example.provatimer.SecondActivity.<init>(SecondActivity.java:14)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1606)
at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5256)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
I think it may have something to do with the context in the BroadcastReceiver, but I tried to declare it in the onCreate method but nothing changed.
Maybe I don't initialize correctly the intent in which the data should be stored, if so, how can I do it correctly?
All the Strings should be correct int the string.xml file, if the error may come from that I'll write them.
I think the error is happening here:
EditText barcodeText = findViewById(R.id.barcodeText);
You are invoking findViewById() directly in the class member declaration.
You have invoke findViewById() after setContentView()
EditText barcodeText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
barcodeText = findViewById(R.id.barcodeText);
}
everytime I'm trying to start my app it crashes immediately on this part of code.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!isOnline()) {
// textViewTemperature.setText(Data);
Toast.makeText(getApplicationContext(), "Cannot connect to network, data will be restore from file with last downloaded data...", Toast.LENGTH_LONG).show();
} else {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
weather = parser.getWeatherForLocation(editText.getText() + "");
runOnUiThread(new Runnable() {
#Override
public void run() {
editText.setText(weather.getCity() + ", " + weather.getCountry()); }
});
} catch (Exception e) {
e.printStackTrace();
}
}
});
t.start();
}
}
});
This is the full logcat from this error:
12-29 10:06:36.376 3524-3524/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.piotr.pogoda, PID: 3524
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.piotr.pogoda/com.example.piotr.pogoda.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.piotr.pogoda.MainActivity.onCreate(MainActivity.java:136)
at android.app.Activity.performCreate(Activity.java:6662)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
I can see the error but I don't get what does it mean that I'm trying to use a method on a null object reference. The button does not exist or what?
Initialize your button, either by findViewById(R.id.btn) or programatically button = new Button(getApplicationContext())
From your crash log, button view is null. May be your view initialization has some issues. Please check the code.
You need to initialize the button
Button btn = (Button) findViewById()
when the app wants to use this and click the button the run time error occurs and I dont know how to fic this , and this code used in fragment and now I nedd to use this in activity and I think its the problem
post_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkPermissionREAD_EXTERNAL_STORAGE(this);
CharSequence items[] = {"گرفتن تصویر از دوربین","گرفتن ویدیو از دوربین",
"انتخاب تصویر از گالری","انتخاب ویدیو از گالری"};
AlertDialog.Builder ab = new AlertDialog.Builder(NewPost.this);
ab.setTitle("انتخاب از :");
ab.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int position) {
switch (position)
{
case 0 :
take_pic_from_camera();
break;
case 1 :
take_video_from_camera();
break;
case 2 :
pick_pic_from_gallery();
break;
case 3 :
pick_video_from_gallery();
break;
}
}
});
ab.create().show();
}
});
and my error is :
09-18 07:33:07.618 8846-8846/com.irprogram.ted E/AndroidRuntime:
FATAL EXCEPTION: main
Process: com.irprogram.ted, PID: 8846
android.content.res.Resources$NotFoundException: Resource ID #0x0
at android.content.res.ResourcesImpl.getValue(ResourcesImpl.java:190)
at android.content.res.Resources.loadXmlResourceParser(Resources.java:2094)
at android.content.res.Resources.getLayout(Resources.java:1111)
at android.view.LayoutInflater.inflate(LayoutInflater.java:424)
at android.view.LayoutInflater.inflate(LayoutInflater.java:377)
at android.support.v7.app.AlertController$AlertParams.createListView(AlertController.java:880)
at android.support.v7.app.AlertController$AlertParams.apply(AlertController.java:857)
at android.support.v7.app.AlertDialog$Builder.create(AlertDialog.java:899)
at com.irprogram.ted.NewPost$2.onClick(NewPost.java:165)
at android.view.View.performClick(View.java:5610)
at android.view.View$PerformClick.run(View.java:22265)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
You called setItems method before showing it. Just try to make a change in your code so that you call ab.create().show(); before ab.setItems().
The exception may be because it can't set the OnClickListeneter before making it visible in the activity.
Hope it helps.
Please check whats the problem with my code here :
Main Activity :
I'm using Android Studio. Import statements are managed for me. It won't be necessary to write them here
public class MainActivity extends Activity implements View.OnClickListener {
SharedPreferences prefs;
String dataName = "MyData";
String intName = "MyString";
int defaultInt = 0;
public static int highScore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonPlay = (Button) findViewById(R.id.btnPlay);
TextView textHighScore = (TextView) findViewById(R.id.textHighScore);
buttonPlay.setOnClickListener(this);
prefs = getSharedPreferences(dataName, MODE_PRIVATE);
highScore = prefs.getInt(intName, defaultInt);
textHighScore.setText("High Score: " + highScore);
}
#Override
public void onClick(View view) {
Intent intent;
intent = new Intent(this, GameActivity.class);
startActivity(intent);
}
}
When I run this application Main Activity is loaded but when I hit play button application closes. I have checked the play button's ID is O.K. I had the same problem in GameActivity but at last I figured out that the problem was with the ID but this time I think problem is with the this I used in Intent();. Activity fails to load.
Exception :
06-24 01:34:05.196 12826-12826/com.cruzerblade.memorygame E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.cruzerblade.memorygame, PID: 12826
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.cruzerblade.memorygame/com.cruzerblade.memorygame.GameActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.content.ContextWrapper.getResources(ContextWrapper.java:87)
at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:81)
at android.view.animation.AnimationUtils.loadAnimation(AnimationUtils.java:75)
at com.cruzerblade.memorygame.GameActivity.<init>(GameActivity.java:55)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1067)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2317)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Please help me out! It took me too much time still I couldn't figure out the problem.
Quoting from your logcat:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method
'android.content.res.Resources android.content.Context.getResources()'
on a null object reference
at android.content.ContextWrapper.getResources(ContextWrapper.java:87)
at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:81)
at android.view.animation.AnimationUtils.loadAnimation(AnimationUtils.java:75)
at com.cruzerblade.memorygame.GameActivity.<init>(GameActivity.java:55)
This last line is the only line in the trace that is your code:
Look on line 55 of GameActivity.java. It is calling loadAnimation. There is something wrong with the animation it is trying to load (probably a missing resource ID, but it could also be a null or invalid context argument for loadAnimation.)