ViewModel with PreferenceFragmentCompat - android

I have a PreferenceFragmentCompat that I would like to use together with a corresponding ViewModel class. Is it doable?
The fragment is currently attached to an androidx AppCompatActivity and it works as intended. However, I would like to display the values of my Preferences under their summaries. Traditionally I would do all data manipulation inside the PreferenceFragment but I was made aware that google is suggesting the MVP architectural pattern.
This question might sound quite noob but I am still trying to get my head around the Jetpack after being away from android development for the past 3 years
The classes/files that I have are the following:
app_preference.xml
<PreferenceScreen xmlns:app="http://schemas.android.com/apk/res-auto">
<PreferenceCategory app:title="#string/your_account">
<Preference
app:key="email"
app:title="#string/title_email" />
</PreferenceCategory>
<PreferenceCategory
app:key="help"
app:title="#string/help_desk">
<Preference
app:key="feedback"
app:summary="#string/get_help_summary"
app:title="#string/get_help" />
</PreferenceCategory>
<Preference
app:key="terms"
app:title="#string/terms_of_service" />
<Preference
app:key="app_version"
app:title="#string/app_version_label" />
</PreferenceScreen>
MainActivity
package mypackage;
import android.os.Bundle;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import mypackage.databinding.ActivityMainBinding;
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
BottomNavigationView navView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_settings, R.id.test_settings)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_activity_main);
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
NavigationUI.setupWithNavController(binding.navView, navController);
}
}
Preference Fragment
package mypackage.ui.testFrag.settings;
import android.os.Bundle;
import androidx.preference.PreferenceFragmentCompat;
import mypackage.R;
public class TestSettingsFragment extends PreferenceFragmentCompat {
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.app_preference, rootKey);
}
}

Related

Up Arrow disabled on implementing App Bar with overflow menu

I am developing a sport timer app and new to android programming. I have implemented overflow menu. I am facing two issues:
Facing disappearing Up Arrow that is needed for navigation up in the hierarchy. Up arrow disappears as soon as one of the overflow menus is selected.
As up arrow is missing, I pressed back button, but the screen turns empty showing just the title in App Bar.
I just checked various postings on this missing up arrow in SO and outside. But was not able to get any clue to fix this. I could not see any difference between the code that I have and the solutions given. And for empty screen no clue available anywhere at all.
I frequently come to SO for help and indeed got many. Requesting SOians to help me here. Thanks.
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="visible"
tools:context=".MainActivity">
<TextView
android:id="#+id/textView"
android:layout_width="215dp"
android:layout_height="48dp"
android:background="#color/teal_200"
android:text="#string/app_name"
android:textAlignment="center"
android:textAllCaps="true"
android:textColor="#color/black"
android:textSize="48sp"
android:textStyle="bold"
android:visibility="visible"
app:layout_anchor="#+id/toolbar"
app:layout_anchorGravity="center" />
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="69dp"
android:background="#color/white"
app:popupTheme="#style/Theme.PTimer.PopupOverlay" />
<include
android:id="#+id/include"
layout="#layout/content_main"
android:layout_height="match_parent"
app:layout_anchor="#+id/include"
app:layout_anchorGravity="center" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
The java code of main activity is below
package com.example.ptimer;
import android.content.Intent;
import android.os.Bundle;
import com.google.android.material.snackbar.Snackbar;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.fragment.NavHostFragment;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.example.ptimer.databinding.ActivityMainBinding;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.Toast;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration appBarConfiguration;
private ActivityMainBinding binding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setSupportActionBar(binding.toolbar);
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
appBarConfiguration = new AppBarConfiguration.Builder(navController.getGraph()).build();
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getMenuInflater().inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
FragmentManager fragmentManager = this.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
switch (id) {
case R.id.action_settings:
Fragment fragmentS = new SettingsFragment();
fragmentTransaction.replace(R.id.nav_host_fragment_content_main, fragmentS);
fragmentTransaction.setReorderingAllowed(true);
fragmentTransaction.addToBackStack(null);
break;
case R.id.action_kyc:
Fragment fragmentK = new KnowYourCapacity_Fragment();
fragmentTransaction.replace(R.id.nav_host_fragment_content_main, fragmentK);
break;
case R.id.action_about:
Fragment fragmentA = new HelpFragment();
Bundle bundle = new Bundle();
bundle.putString("help_desc", getResources().getString(R.string.pBasics_desc));
bundle.putString("help_image","basic");
fragmentA.setArguments(bundle);
fragmentTransaction.replace(R.id.nav_host_fragment_content_main, fragmentA);
break;
default:
break;
}
fragmentTransaction.commit();
return super.onOptionsItemSelected(item);
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
onBackPressed();
return NavigationUI.navigateUp(navController, appBarConfiguration)
|| super.onSupportNavigateUp();
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
Blank screen and missing up arrow image of the emulator is given as a link below (not allowed to post the image as such by SO)
Edit 1: After moving getSupportActionBar().setDisplayHomeAsUpEnabled(true); statement to onCreateOptionsMenu UP arrow is being displayed. But clicking UP arrow button shows blank screen. My issue #2 still remains. Need help here. Thanks.
I found solution for
issue 1: Adding getSupportActionBar().setDisplayHomeAsUpEnabled(true); in onCreateOptionsMenu
issue 2:
I came across a solution in https://medium.com/mobile-app-development-publication/learn-android-navigation-component-through-coding-79dc47b240b3 It worked perfectly well and solved white screen issue and also not using explicit method using fragment manager for traversing to another fragment. It was about linking menu items to navigation graph.

I want to replace hamburger icon with back icon in GalleryFragment

I want to how to change hamburger icon to back icon. Below i have provide GalleryFragment.java
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import com.thechamp.myapplication.R;
public class GalleryFragment extends Fragment {
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_gallery, container, false);
final TextView textView = root.findViewById(R.id.text_gallery);
return root;
}
}
and here i am providing MainActivity.java
I have tried various ways but every time i got error. I want back icon in Fragment's Action bar, so that user can get back from that fragment to HomeFragment.
import android.os.Bundle;
import android.view.View;
import android.view.Menu;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.navigation.NavigationView;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
}
Here is all coding of my project. Please help me to change icon
As per the AppBarConfiguration documentation, the IDs you pass into the AppBarConfiguration.Builder are the 'top-level destinations':
Top-level destinations do not display an Up button in the top app bar because there is no higher level destination. By default, the start destination of your app is the only top-level destination. When the user is at a top-level destination, the Navigation button becomes a drawer icon if the destination uses a DrawerLayout.
So by adding R.id.nav_gallery to that list, you are specifically opting in that destination to show the hamburger icon on that destination. This is indeed the expected way to handle different destinations in your NavigationView - they are sibling screens that are not hierarchically related to each other and perfect candidates for being top level destinations (you should not expect destinations in your NavigationView to show an up arrow, despite the system back button taking you back to the start destination of your graph).
But if you really do want to show the Up arrow, just remove the R.id.nav_gallery from your AppBarConfiguration.Builder:
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_slideshow)
.setDrawerLayout(drawer)
.build();

Not being able to switch the toolbar for a different activity [Fixed]

I am working with two activities here and I want to switch the action bar from the default MainActivity to the one that I want to have in this particular activity that just has a + symbol to add stuff to what will be a notepad, but I can't catch the error, the logcat is empty and I am just trying to figure out how to change the action bar from the one that is currently showing to the one I want.
Here is my activity in which I am trying to get the different action bar to work:
package com.example.projetolinguagensprogramacao1;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import androidx.appcompat.widget.Toolbar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
public class Notepad extends AppCompatActivity {
RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notepad);
Toolbar toolbar2 = findViewById(R.id.toolbar2);
setSupportActionBar(toolbar2);
recyclerView = findViewById(R.id.listOfnotes);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.add_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
if(item.getItemId() == R.id.add_note){
Toast.makeText(this, "It's Working!", Toast.LENGTH_SHORT).show();
}
return super.onOptionsItemSelected(item);
}
}
Here is the .xml of it:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="com.example.projetolinguagensprogramacao1.Notepad">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar2"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:background="#color/colorPrimary" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/listOfnotes"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/toolbar2" />
</androidx.constraintlayout.widget.ConstraintLayout>
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import android.view.MenuItem;
import android.view.Menu;
import com.google.android.material.navigation.NavigationView;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private AppBarConfiguration mAppBarConfiguration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setNavigationViewListener();
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_lembrete, R.id.nav_listacompra, R.id.nav_poupanca, R.id.nav_login, R.id.nav_notepad)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_login: {
startActivity(new Intent(this, Login.class));
break;
}
case R.id.nav_notepad: {
startActivity(new Intent(this, Notepad.class));
break;
}
}
return true;
}
private void setNavigationViewListener() {
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
}
And the .xml file for the + (plus) symbol that I want to show up on the action bar:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/add_note"
android:icon="#drawable/ic_add_symb"
android:title="Adicionar"
app:showAsAction="ifRoom" />
</menu>
Edit 1:
So instead of looking something like this:
It looks like this:
Edit 2: I tried using the same action bar in the main activity and it worked, so it just adds to my confusion as to why it isn't working in the Notepad activity.
Edit 3: Added Main Activity Code, I tried seeing if switching stuff on the onNavigationItemSelected() method and it still goes to image number 2. Maybe the problem is here I just can't find it.
Edit 4: I fixed it, I'm so sorry I am an idiot and didn't notice the blatant mistake I had, but thank you to all of you that answered and helped me.
you should create two menu file.xml
menu1(with its items) for MainActivity and menu2(with its items) for OtherActivity
then in each activity in onCreateOptionsMenu() method inflate its own menu.xml
check this code for short answer
check this for a mini project

Define NavigationDrawer behavior

I'm currently trying to understand how does the AndroidX artifacts implements the Navigation Drawer. I've created a new Activity using the Android Studio template for the Navigation Drawer Activity, and in the MainActivity class I can't find the setNavigationItemSelectedListener method.
I need to know where to define which fragment is showed when I select some item in the Navigation menu.
I'm currently using Android Studio 3.5.1
My MainActivity class looks like:
package cu.me.cuantotengo;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import android.view.View;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.google.android.material.navigation.NavigationView;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.Menu;
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow,
R.id.nav_tools, R.id.nav_share, R.id.nav_send)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
#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 onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
}
but you can try it by starting the template of Android Studio.
As per the NavigationUI documentation, the android:id of the menu item in your menu is matched with the android:id of a destination in the navigation graph in the res/navigation directory.
Therefore if you want to change what Fragment is loaded when you select a menu item, you should change your navigation graph file and replace the android:name on the destination with the name of the Fragment class you want.

My app is crashing when I add Bluetooth button [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 1 year ago.
I'm new in Android studio
I want to send data from Arduino to the android via Bluetooth HC-06
I begin my code from the template(Navigation Drawer Activity) of AndroidStudio.
At first everything was okay, but nightmares begin when I wanted to add Bluetooth button with the help SetOnClickListener to my code.
1. Its appearance changed from thisenter image description here
to this enter image description here. For clarity: Navigation bar and other tools disappeared, instead only home fragment is appeared.
2. When push the Bluetooth button on this fragment, my app closed.
I try to follow logcat , but can't fix the problem.
Please, help me with advice
Best Regard
p.s. Below is my MainActivity.java file
package com.example.myecg2;
import android.content.Intent;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.google.android.material.navigation.NavigationView;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.Menu;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Set;
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
private TextView Tekst;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Savollaringiz bo\'lsa Xat yozing", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow,
R.id.nav_tools, R.id.nav_share, R.id.nav_send)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
final int REQUEST_ENABLE_BT = 1;
setContentView(R.layout.fragment_home);
final BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
Button button =findViewById(R.id.button6);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (btAdapter == null) {
Tekst.setText("Bluetooth NOT support");
return;
} else {
if (btAdapter.isEnabled()) {
Tekst.setText("Bluetooth is currently in device discovery process.");
Tekst.append("\nPaired Devices are:");
Set<BluetoothDevice> devices = btAdapter.getBondedDevices();
for (BluetoothDevice device : devices) {
Tekst.append("\nDevice" + device.getName() + "," + device);
}
} else {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
}
}
);}
#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 onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
}
And the content_main.xml file from the res/layout
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/text_home"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:textAlignment="center"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/textView8"
android:layout_width="394dp"
android:layout_height="218dp"
android:text="#string/matn"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf="#+id/button6" />
<Button
android:id="#+id/button6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="116dp"
android:text="#string/LeadI"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf="#+id/text_home"/>
</androidx.constraintlayout.widget.ConstraintLayout>
and errors given in LogCat
2019-11-30 02:09:01.342 13088-13088/com.example.myecg2 D/AndroidRuntime: Shutting down VM
2019-11-30 02:09:01.343 13088-13088/com.example.myecg2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myecg2, PID: 13088
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.myecg2.MainActivity$2.onClick(MainActivity.java:75)
at android.view.View.performClick(View.java:6256)
at android.view.View$PerformClick.run(View.java:24701)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
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)
Tekst is null, i.e. you never instantiate that variable.
Your log says it right here:
java.lang.NullPointerException:
Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.myecg2.MainActivity$2.onClick(MainActivity.java:75)
at ...
It even says the class the error is happening in, MainActivity, the method name its happening in onClick and the line of the error :75.
You are missing doing findViewById to instantiate your Tekst variable, in the onCreate before you attempt to access it (i.e access on line 75).
Sidenotes:
you call setContentView twice. You should not do that. Delete the second one.
Variable names in Java & Kotlin should start with a lowercase, to help you differentiate them from other things. Rename Tekst to tekst. Is that also a typo? perhaps it should be test and a better name to help you debug would be testTextView.

Categories

Resources