I'm using shuhart's stepview for my android application. I've followed this video. But whenever I try to enter my BookingActivity, the application crashes with the error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.estebeauty/com.example.estebeauty.activities.BookingActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.shuhart.stepview.StepView.setSteps(java.util.List)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
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:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
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:930)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.shuhart.stepview.StepView.setSteps(java.util.List)' on a null object reference
at com.example.estebeauty.activities.BookingActivity.setupStepView(BookingActivity.java:88)
at com.example.estebeauty.activities.BookingActivity.onCreate(BookingActivity.java:38)
at android.app.Activity.performCreate(Activity.java:7802)
at android.app.Activity.performCreate(Activity.java:7791)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
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:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
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:930)
And I don't know how to fix it.
Here is my BookingActivity:
public class BookingActivity extends AppCompatActivity {
#BindView(R.id.step_view)
StepView stepView;
#BindView(R.id.view_pager)
ViewPager viewPager;
#BindView(R.id.btn_previous_step)
Button btn_previous_step;
#BindView(R.id.btn_next_step)
Button btn_next_step;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_booking);
ButterKnife.bind(BookingActivity.this);
setupStepView();
setColorButton();
// View
viewPager.setAdapter(new MyViewPagerAdapter(getSupportFragmentManager(), 1));
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i1) {
}
#Override
public void onPageSelected(int i) {
if (i == 0) {
btn_previous_step.setEnabled(false);
}
else {
btn_previous_step.setEnabled(true);
setColorButton();
}
}
#Override
public void onPageScrollStateChanged(int i) {
}
});
}
private void setColorButton() {
if (btn_next_step.isEnabled()) {
btn_next_step.setBackgroundResource(R.color.colorPrimary);
}
else {
btn_next_step.setBackgroundResource(android.R.color.darker_gray);
}
if (btn_previous_step.isEnabled()) {
btn_previous_step.setBackgroundResource(R.color.colorPrimary);
}
else {
btn_previous_step.setBackgroundResource(android.R.color.darker_gray);
}
}
private void setupStepView() { // It fails here
List<String> stepList = new ArrayList<>();
stepList.add("Treatment");
stepList.add("Date");
stepList.add("Employee");
stepList.add("Confirm");
stepView.setSteps(stepList);
}
}
I've looked at the GitHub, and can't find any related issues to this.
Please help, and thanks in advance
I managed to fix it by editing the way i was declaring my bindings. So i changed it to:
stepView = findViewById(R.id.step_view);
viewPager = findViewById(R.id.view_pager);
btn_previous_step = findViewById(R.id.btn_previous_step);
btn_next_step = findViewById(R.id.btn_next_step);
Related
I'm new to android (and not a veteran at all in java) developpment.
Trying to do a weather app, I'm trying to use TinyDB as my storage for saved cities.
A button on another activity let me add cities to a list (which I want to save).
In my MainActivity's onCreate, I'm setting up my TinyDB. Then add a city stored in extra to my TinyDB if the MainActivity is launched from the addCityActivity. Finally, getting all the cities from TinyDB to print it to screen in a ListView. (user will then be able to click on a city to get weather information for this one)
But then a NullPointerException raises and it seems to come from TinyDB and I have no idea how to resolve it, I'm stuck on it for a day now (doing this on my free time).
Do you guys have any idea please ?
TinyDB is here.
And here's my MainActivity :
public class MainActivity extends AppCompatActivity {
private Context context;
private ListView cityListView;
private CitylistAdapter citylistAdapter;
private List<City> cities = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TinyDB tinydb = new TinyDB(context);
if (getIntent().getExtras() != null) {
String name = getIntent().getStringExtra("City");
ArrayList<String> cityList = tinydb.getListString("Cities");
cityList.add(getIntent().getStringExtra("City"));
tinydb.putListString("Cities", cityList);
}
ArrayList<String> cityList = tinydb.getListString("Cities");
for (int i = 0; i < cityList.size(); i++) {
City city = new City();
city.setName(cityList.get(i));
cities.add(city);
}
this.cityListView = (ListView) findViewById(R.id.cityList);
this.citylistAdapter = new CitylistAdapter(getApplicationContext(), cities);
this.cityListView.setAdapter(citylistAdapter);
FloatingActionButton addCity = (FloatingActionButton) findViewById(R.id.openAddCity);
addCity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startAddCityActivity();
}
});
}
private void startAddCityActivity() {
Intent intent = new Intent(this, AddCityActivity.class);
startActivity(intent);
}
}
And here's the stack trace :
2021-09-23 13:59:38.565 5754-5754/com.example.weather E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.weather, PID: 5754
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.weather/com.example.weather.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
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:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.preference.PreferenceManager.getDefaultSharedPreferencesName(PreferenceManager.java:555)
at android.preference.PreferenceManager.getDefaultSharedPreferences(PreferenceManager.java:545)
at com.example.weather.TinyDB.<init>(TinyDB.java:39)
at com.example.weather.MainActivity.onCreate(MainActivity.java:51)
at android.app.Activity.performCreate(Activity.java:8000)
at android.app.Activity.performCreate(Activity.java:7984)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
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:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
2021-09-23 13:59:38.600 5754-5754/com.example.weather I/Process: Sending signal. PID: 5754 SIG: 9
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);
I am trying to make something that converts the text i write into EditText to speech when i press button01.
It works fine on the virtual machine with Android API 23, but it crashes and makes a NullPointerException and crashes on the virtual machine with Android API 30. Here's the code:
public MainActivity() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
button01 = (Button) findViewById(R.id.button01);
final TextView textView1 = (TextView) findViewById(R.id.text1) ;
textView1.setText("\n");
tts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status != ERROR) {
// 언어를 선택한다.
tts.setLanguage(Locale.ENGLISH);
} else {
textView1.setText("TTS 작업에 오류가 생기거나 지원되지 않는 언어입니다.");
tts.speak("TTS 작업에 오류가 생기거나 지원되지 않는 언어입니다.", TextToSpeech.STOPPED, null);
}
}
});
button01.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// editText에 있는 문장을 읽는다.
tts.speak(editText.getText().toString(), TextToSpeech.QUEUE_FLUSH, null);
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
// TTS 객체가 남아있다면 실행을 중지하고 메모리에서 제거한다.
if(tts != null){
tts.stop();
tts.shutdown();
tts = null;
}
}
}
When i view Logcat, it showes this:
2020-07-09 02:10:56.036 7700-7700/com.example.myapplication2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication2, PID: 7700
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication2/com.example.myapplication2.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.speech.tts.TextToSpeech.speak(java.lang.String, int, java.util.HashMap)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
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:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.speech.tts.TextToSpeech.speak(java.lang.String, int, java.util.HashMap)' on a null object reference
at com.example.myapplication2.MainActivity$1.onInit(MainActivity.java:42)
at android.speech.tts.TextToSpeech.dispatchOnInit(TextToSpeech.java:836)
at android.speech.tts.TextToSpeech.initTts(TextToSpeech.java:814)
at android.speech.tts.TextToSpeech.<init>(TextToSpeech.java:745)
at android.speech.tts.TextToSpeech.<init>(TextToSpeech.java:724)
at android.speech.tts.TextToSpeech.<init>(TextToSpeech.java:708)
at com.example.myapplication2.MainActivity.onCreate(MainActivity.java:34)
at android.app.Activity.performCreate(Activity.java:7995)
at android.app.Activity.performCreate(Activity.java:7979)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
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:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
It's happening in the else part in onInit of your listener. When there was an error in initializing the TextToSpeech instance, onInit will be called with ERROR as input while tts is not yet initialized and is null.
It may happen when your device doesn't support text to speech or the engine is missing necessary data.
Don't call anything on tts in case of an error. (There was an error in initializing text to speech. So, how can it speak your text?!)
Apps targeting Android 11 that use text-to-speech should declare TextToSpeech.Engine.INTENT_ACTION_TTS_SERVICE in the queries elements of their manifest:
<queries>
...
<intent>
<action android:name="android.intent.action.TTS_SERVICE" />
</intent>
</queries>
I am new to Android Studio and learning how to create SharedPreference variables. I'm stuck that,updating the value of the string in SharedPreference raises a NullPointerException when I execute below code. Any help will be much appreciated. Thanks in advance.
This is my SettingPage
#Override //Creating the setting page
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settingpage);
setMinsBar = findViewById(R.id.numMinsBar);
setTimeEnterButton = findViewById(R.id.setTimeButton);
musicYesSwitch = findViewById(R.id.musicSwitch);
soundYesSwitch = findViewById(R.id.soundSwitch);
minsLeftTV = findViewById(R.id.minsLeftTV);
timerEndsTV = findViewById(R.id.timerEndsTV);
varAcrossApp = this.getSharedPreferences(SP, Context.MODE_PRIVATE);
//Setting on click listener for the enter button for the time set
setTimeEnterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
timeInInt = Integer.parseInt(setMinsBar.getText().toString());
saveData();
}
});
}
public void saveData(){ //Declaring method saveData
varEditor = varAcrossApp.edit();
varEditor.putInt(timeInStringSP, timeInInt);
varEditor.putBoolean(musicYesSP, musicYesSwitch.isChecked());
varEditor.putBoolean(soundYesSP, soundYesSwitch.isChecked());
varEditor.apply();
Toast.makeText(getApplicationContext(), "Duration set", Toast.LENGTH_SHORT).show();
}
public void loadData(){ //Declaring method loadData
finalTimeInMins = varAcrossApp.getInt(timeInStringSP, 0);
musicYes = varAcrossApp.getBoolean(musicYesSP, false);
soundYes = varAcrossApp.getBoolean(soundYesSP, false);
}
public void updateView() {
minsLeftTV.setText(finalTimeInMins);
if (musicYes = true) {
timerEndsTV.setText("-Turn off music");
} else if (soundYes = true) {
timerEndsTV.setText("-Change sound profile to 'Sound'");
} else if (musicYes && soundYes) {
timerEndsTV.setText("-Turn off music /n-Change sound profile to 'Sound'");
} else {
timerEndsTV.setText("-Do nothing");
}
}
This is MainActivity
#Override //Creating the app here
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.homepage);
startButton = findViewById(R.id.startButton);
SettingPage settingPage = new SettingPage();
settingPage.loadData();
settingPage.updateView();
}
Error Code and Stack trace given below:
Process: com.example.sleep, PID: 6935
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sleep/com.example.sleep.MainActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'int android.content.SharedPreferences.getInt(java.lang.String, int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3260)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3396)
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:2009)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7319)
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:934)
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'int android.content.SharedPreferences.getInt(java.lang.String, int)' on a null object reference
at com.example.sleep.SettingPage.loadData(SettingPage.java:77)
at com.example.sleep.MainActivity.onCreate(MainActivity.java:25)
at android.app.Activity.performCreate(Activity.java:7783)
at android.app.Activity.performCreate(Activity.java:7772)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3235)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3396)
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:2009)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7319)
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:934)
You should not call varAcrossApp.getInt before varAcrossApp = this.getSharedPreferences(SP, Context.MODE_PRIVATE);
This is how shared preferences should/can be used in android.
class SettingsSpDao { // shared preferences data access object
private static final String SP = "SP";
private static final String MUSIC_YES = "music_yes";
public static boolean isMusicYes(Context context) {
// you can initialize sp beforehand so you don't have to pass in context but I prefer it this way, so I don't have to initialize it before using it
SharedPreferences sp = context.getSharedPreferences(SP, Context.MODE_PRIVATE);
return sp.getBoolean(MUSIC_YES , false);
}
// add your methods here
}
// call it anywhere as long as you can pass a context, such as Activity.
musicYes = SettingsSpDao.isMusicYes(this); // in your case `this` since it's in an Activity
Hi I am trying to parse JSON using Retrofit, save it on Sqlite and display on RecyclerView. However my app crashes when I try to open the activity.
Below is my full codes of related activity. Could you please help me with resolving the issue?
Thank you
public class InventoryProductActivity extends AppCompatActivity implements InventoryProductListAdapter.CustomClickListener {
private static final String TAG = InventoryProductActivity.class.getSimpleName();
private InventoryProductListAdapter mInventoryProductListAdapter;
private RecyclerView mRecyclerView;
private RetrofitClient mRetrofitClient;
LinearLayoutManager mLinearLayoutManager;
private WarehouseDatabase mDatabase;
private ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inventory_product);
configViews();
mRetrofitClient = new RetrofitClient();
mDatabase = new WarehouseDatabase(this);
loadInventoryProductFeed();
}
private void configViews() {
mRecyclerView = findViewById(R.id.recycler_view_inventory_product);
mRecyclerView.setHasFixedSize(true);
mLinearLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLinearLayoutManager);
mInventoryProductListAdapter = new InventoryProductListAdapter(this);
mRecyclerView.setAdapter(mInventoryProductListAdapter);
}
private void loadInventoryProductFeed() {
mProgressDialog = new ProgressDialog(InventoryProductActivity.this);
mProgressDialog.setMessage("Loading Inventory Data...");
mProgressDialog.setCancelable(true);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.setIndeterminate(true);
mProgressDialog.show();
mInventoryProductListAdapter.reset();
if (getNetworkAvailability()) {
getFeed();
} else {
getFeedFromDatabase();
}
}
private void getFeed() {
Call<List<InventoryProductModel>> listCall = mRetrofitClient.getWarehouseServiceInventoryProduct().getAllInventoryProducts();
listCall.enqueue(new Callback<List<InventoryProductModel>>() {
#Override
public void onResponse(Call<List<InventoryProductModel>> call, Response<List<InventoryProductModel>> response) {
if (response.isSuccessful()) {
List<InventoryProductModel> inventoryProductModelList = response.body();
for (int i = 0; i < inventoryProductModelList.size(); i++) {
InventoryProductModel inventoryProductModel = inventoryProductModelList.get(i);
mInventoryProductListAdapter.notifyDataSetChanged();
}
} else {
int sc = response.code();
switch (sc) {
}
}
mProgressDialog.dismiss();
}
#Override
public void onFailure(Call<List<InventoryProductModel>> call, Throwable t) {
mProgressDialog.dismiss();
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void getFeedFromDatabase() {
List<InventoryProductModel> inventoryProductModelList = mDatabase.getInventoryProducts();
for (int i = 0; i < inventoryProductModelList.size(); i++) {
InventoryProductModel inventoryProductModel = inventoryProductModelList.get(i);
Log.d(TAG, inventoryProductModel.getName() + "||" + inventoryProductModel.getCountryId());
}
mProgressDialog.dismiss();
}
private boolean getNetworkAvailability() {
return Utils.isNetworkAvailable(getApplicationContext());
}
#Override
public void onClick(int position) {
}
}
E/WindowManager: android.view.WindowLeaked: Activity
codes.bala.bmsfinal1.activity.MainActivity has leaked window
DecorView#52c3fcd[] that was originally added here
at android.view.ViewRootImpl.(ViewRootImpl.java:418)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:331)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:93)
at android.app.Dialog.show(Dialog.java:322)
at android.app.ProgressDialog.show(ProgressDialog.java:116)
at android.app.ProgressDialog.show(ProgressDialog.java:104)
at codes.bala.bmsfinal1.activity.MainActivity.login(MainActivity.java:61)
at codes.bala.bmsfinal1.activity.MainActivity$1.onClick(MainActivity.java:41)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
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:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
I/ViewConfigCompat: Could not find method getScaledScrollFactor() on
ViewConfiguration D/AndroidRuntime: Shutting down VM
--------- beginning of crash E/AndroidRuntime: FATAL EXCEPTION: main
Process: codes.bala.bmsfinal1, PID: 12077
java.lang.RuntimeException: Unable to start activity ComponentInfo{codes.bala.bmsfinal1/codes.bala.bmsfinal1.activity.InventoryProductActivity}:
java.lang.NullPointerException: Attempt to invoke interface method
'retrofit2.Call
codes.bala.bmsfinal1.iinterface.WarehouseService.getAllInventoryProducts()'
on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.NullPointerException: Attempt to invoke interface
method 'retrofit2.Call
codes.bala.bmsfinal1.iinterface.WarehouseService.getAllInventoryProducts()'
on a null object reference
at codes.bala.bmsfinal1.activity.InventoryProductActivity.getFeed(InventoryProductActivity.java:88)
at codes.bala.bmsfinal1.activity.InventoryProductActivity.loadInventoryProductFeed(InventoryProductActivity.java:70)
at codes.bala.bmsfinal1.activity.InventoryProductActivity.onCreate(InventoryProductActivity.java:46)
at android.app.Activity.performCreate(Activity.java:6679)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Application terminated.
getWarehouseServiceInventoryProduct()
method return null.
You should set breakpoint inside this method and check what happening (or add some logs to this method).