Notifications wont show android studio - android-studio

Im trying to get a notification when pressing a button, but it is not showing up. I have followed a lot of tutorials and i think it has something ti do with the version of android. Something with channels. I just dont know how to implement it.
package com.example.root.savetheworldv2;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent =new Intent();
PendingIntent pIntent =
PendingIntent.getActivity(MainActivity.this,0,intent,0);
Notification noti = new
Notification.Builder(MainActivity.this)
.setTicker("TickerTitle")
.setContentTitle("Content Title")
.setContentText("Content Text")
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentIntent(pIntent).getNotification();
noti.flags = Notification.FLAG_AUTO_CANCEL;
NotificationManager nm =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify(0,noti);

Related

Open new activity by Clicking button in a Fragment

I'm currently working on a mobile app as a final project for my course. I have these two fragments inside a ViewPager2 controlled by a TabLayout. There are buttons inside of these fragments.
The first frag contains 2 buttons. The other frag has only one button. I want them to open an activity but the problem is when I run the app, these buttons won't work. They didn't open the other activity.
Login Fragment
package com.example.biowit;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.blogspot.atifsoftwares.animatoolib.Animatoo;
public class LoginTabFragment extends Fragment {
EditText email, password;
Button btn_login, btn_forpass;
TextView textView;
float v=0;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.login_fragment, container, false);
email = root.findViewById(R.id.input_LI_email);
password = root.findViewById(R.id.input_LI_pass);
btn_forpass = root.findViewById(R.id.btn_FPass);
btn_login = root.findViewById(R.id.btn_LIn);
email.setTranslationX(800);
password.setTranslationX(800);
btn_forpass.setTranslationX(800);
btn_login.setTranslationX(800);
email.setAlpha(v);
password.setAlpha(v);
btn_forpass.setAlpha(v);
btn_login.setAlpha(v);
email.animate().translationX(0).alpha(1).setDuration(800).setStartDelay(300).start();
password.animate().translationX(0).alpha(1).setDuration(800).setStartDelay(300).start();
btn_forpass.animate().translationX(0).alpha(1).setDuration(800).setStartDelay(300).start();
btn_login.animate().translationX(0).alpha(1).setDuration(800).setStartDelay(300).start();
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), HomeScreen.class);
startActivity(intent);
Animatoo.animateFade(getActivity());
getActivity().finish();
}
});
return root;
}
}
LoginScreen (where the fragment locates)
package com.example.biowit;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import androidx.viewpager2.widget.ViewPager2;
import android.os.Bundle;
import com.google.android.material.tabs.TabItem;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
public class
LoginScreen extends AppCompatActivity {
TabLayout tabLayout;
ViewPager2 viewPager;
float v=1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_screen);
tabLayout = findViewById(R.id.tab_layout);
viewPager = findViewById(R.id.view_pager);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
LoginAdapter login_adapter = new LoginAdapter(this);
viewPager.setAdapter(login_adapter);
new TabLayoutMediator(tabLayout, viewPager,
new TabLayoutMediator.TabConfigurationStrategy() {
#Override
public void onConfigureTab(#NonNull TabLayout.Tab tab, int position) {
switch (position){
case 0:
tab.setText("LOGIN");
break;
case 1:
tab.setText("SIGNUP");
break;
}
}
}).attach();
tabLayout.setAlpha(v);
}
}
Here's the error log(?)
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.biowit, PID: 18551
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.biowit/com.example.biowit.HomeScreen}: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.hide()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3754)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3912)
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:2319)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:239)
at android.app.ActivityThread.main(ActivityThread.java:8212)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:626)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1016)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.hide()' on a null object reference
at com.example.biowit.HomeScreen.onCreate(HomeScreen.java:22)
at android.app.Activity.performCreate(Activity.java:8119)
at android.app.Activity.performCreate(Activity.java:8103)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1359)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3727)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3912) 
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:2319) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:239) 
at android.app.ActivityThread.main(ActivityThread.java:8212) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:626) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1016) 
HomeScreen (Activity that supposedly open when clicking the button)
package com.example.biowit;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
public class HomeScreen extends AppCompatActivity {
Button Chap1_btn, Achieve_btn, HowToPlay_btn, LogOut_btn, Settings_btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
getSupportActionBar().hide(); // hides the action bar.
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
Chap1_btn = findViewById(R.id.btn_Chap1);
Achieve_btn = findViewById(R.id.btn_Achievements);
HowToPlay_btn = findViewById(R.id.btn_HowToPlay);
LogOut_btn = findViewById(R.id.btn_Logout);
Settings_btn = findViewById(R.id.btn_Settings);
Chap1_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent open_Chap1 = new Intent(getApplicationContext(), LessonScreen.class);
startActivity(open_Chap1);
}
});
Achieve_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Intent open_Achievements = new Intent(getApplicationContext(), Achievements.class);
}
});
HowToPlay_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Intent open_HowToPlay = new Intent(getApplicationContext().HowToPlay.class);
}
});
LogOut_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
Settings_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent open_Settings = new Intent(getApplicationContext(), Settings.class);
startActivity(open_Settings);
}
});
}
}
getSupportActionBar().hide(); is what's causing the error. You have added it before
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
So it's trying to execute it before the activity is initialised.
Add it after the above 2 lines and it should work.

Alarm notification is not working for API>=26 android emulators

I am trying to send a notification that appears under the top navigation bar as follows:
My codes work for android emulator with API < 26, but they do not work for android emulator with API >= 26. I found that it is because I need to add channel, so I did. However, although the codes compile well and go through all loops, and there is no error in logcat. Still, the notification does not appear on the screen.
Any help will be greatly appreciated. FYI, here is my FragmentAlarm.java:
package com.example.dailybible3;
import android.app.AlarmManager;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;
import java.util.Calendar;
public class FragmentAlarm extends Fragment {
private View view;
private CheckBox box_sun, box_mon, box_tue, box_wed, box_thu, box_fri, box_sat;
private CheckBox order_history, order_bible;
private CheckBox ninety_days, one_year;
private Button btn_save;
public static FragmentAlarm newInstance() {
FragmentAlarm fragmentAlarm = new FragmentAlarm();
return fragmentAlarm;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_alarm, container, false);
/* start of set notification */
createNotificationChannel();
/* end of set notification */
//save button
btn_save = (Button) view.findViewById(R.id.save_button);
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String message = "This is a notificaiton example";
NotificationCompat.Builder builder = new NotificationCompat.Builder(
getContext(), "notifyBibleVerse"
)
.setSmallIcon(R.drawable.ic_bible_english)
.setContentTitle("Today's Verse")
.setContentText("Genesis 1 - 3")
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
/* start of setting notification */
Intent intent = new Intent(getActivity(), MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("message", message);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
NotificationManager notiifcationManager = (NotificationManager) getActivity().getSystemService(
Context.NOTIFICATION_SERVICE
);
notiifcationManager.notify(0, builder.build());
toastMessage("Alarm is set!");
}
});
return view;
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "DailyBibleChannel";
String description = "Channel for Bible Verse Reminder";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel("notifyBibleVerse", name, importance);
channel.setDescription(description);
}
}
private void toastMessage(String message){
Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
}
}
I am still not sure how to solve the above problem, but I found the working code from here: https://codinginflow.com/tutorials/android/alarmmanager. The major difference I see is that the working code has AlarmManager. Hope this help someone who is having troubles to set a notification.

How to use 2 public classes, protected void on creat functions in the same fragments?

How to put more than one class,overview,void in MainActivity java of Android Studio? I need to have both the button and a code to make the map of google have some restricions in the same page. What names of the classes should be changed for it to work. The codes work when put independently but not together.How to make them work good together?
package com.example.maps;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.MarkerOptions;
public class FirstFragment extends AppCompatActivity {
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFoodFragment();
}
});
}
public void openFoodFragment(){
Intent intent = new Intent(this, FoodFragment.class);
startActivity(intent);
}
}
public class MainACTIVITY extends FragmentActivity implements OnMapReadyCallback {
GoogleMap mapAPI;
SupportMapFragment mapFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mapFragment =(SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.mapAPI);
mapFragment.getMapAsync(this);
}
public void openFoodFragment(){
Intent intent = new Intent(this, FoodFragment.class);
startActivity(intent);
}
#Override
public void onMapReady(GoogleMap googleMap){
mapAPI = googleMap ;
LatLng one = new LatLng(-21.754812, -48.219451);
LatLng two = new LatLng(-21.787443, -48.113332);
LatLngBounds.Builder builder = new LatLngBounds.Builder();
//add them to builder
builder.include(one);
builder.include(two);
LatLngBounds bounds = builder.build();
//get width and height to current display screen
int width = getResources().getDisplayMetrics().widthPixels;
int height = getResources().getDisplayMetrics().heightPixels;
int padding = (int) (width * 0.20);
mapAPI.setLatLngBoundsForCameraTarget(bounds);
mapAPI.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, width, height, padding));
//set zoom to level to current so that you won't be able to zoom out viz. move outside bounds
mapAPI.setMinZoomPreference(mapAPI.getCameraPosition().zoom);
LatLng Kampai = new LatLng(-21.780985, -48.186859);
mapAPI.addMarker(new MarkerOptions().position(Kampai).title("Kampai"));
mapAPI.moveCamera(CameraUpdateFactory.newLatLng(Kampai));
}
}
Yes the can be in the same file but you have your mainACTIVITY inside your FirstFragment which cannot happen you need to remove the bottom most bracket and place it right above the start of your mainACTIVITY class, your FirstFragment's brackets need to close before you paste another class into the file.

Opening a new fragment from within a ViewPager in Android Studio

I have a question about opening a new fragment from within a ViewPager.
I setup FragmentA, FragmentB and FragmentC to be fragments of a viewpager and then proceeded to setup Fragment1 and Fragment2 as fragments of another viewpager which resides in FragmentB.
So Fragment1 and Fragment2 are in a viewpager which is essentially nested in another viewpager. I'm playing around with UI styles etc and this is is similar to that found in the Flickr app.
The problem I'm having is that once I get into the fragment1 or fragment2 (the nested fragment) I want to be able to click on something and enter a full screen fragment bypassing the toolbar I set up in FragmentB.
Below is the the code I have for FragmentB with the toolbar, tablayout and viewpager.
package com.app.fragmentdemo;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.viewpager.widget.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.material.tabs.TabLayout;
public class FragmentB extends Fragment {
public FragmentB() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_b,container,false);
Toolbar toolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
TabLayout tabLayout = (TabLayout) rootView.findViewById(R.id.tabs);
ViewPager viewPager = (ViewPager) rootView.findViewById(R.id.viewPagerFragmentB);
ViewPagerAdapter adapter = new ViewPagerAdapter(((FragmentActivity) getContext()).getSupportFragmentManager());
adapter.addFragment(new Fragment1(),"Fragment 1");
adapter.addFragment(new Fragment2(),"Fragment 2");
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
// Inflate the layout for this fragment
return rootView;
}
}
Here is the code I've put together for fragment2 which contains a button I would like to take to take me to another fragment.
package com.app.fragmentdemo;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
public class Fragment2 extends Fragment {
public Fragment2() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_2,container,false);
Button button = (Button) rootView.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment fragment = new FragmentFull();
FragmentManager fm = ((FragmentActivity) getContext()).getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.fragmentFullContainer,fragment);
ft.commit();
Toast.makeText(getActivity(), "Button Clicked", Toast.LENGTH_SHORT).show();
}
});
// Inflate the layout for this fragment
return rootView;
}
}
Upon clicking the button the app crashes. I get the error:
No view found for id 0x7f080084 (com.app.fragmentdemo:id/fragmentFullContainer) for fragment FragmentFull
If I change the id of the fragment container to the id I assigned to the Fragment2 layout file, it works fine. However, this is still contained in the nested viewpager and doesn't allow me to enter a new layout.
I really appreciate your help.
Thanks.
In the following line
ft.add(R.id.fragmentFullContainer,fragment);
fragmentFullContainer should be a view in your R.layout.fragment_2
You are getting the crash because the OS cannot find fragmentFullContainer in R.layout.fragment_2
UPDATE
replace getSupportFragmentManager with getChildFragmentManager
If you want full screen , you have to manually hide Activity View elements.
Most probably, you have toolbar from activity, you can remove it like that.
((AppCompatActivity)getActivity()).getSupportActionBar().hide();

Can't get custom sound on toggle button

Trying to get my toggle buttons to make custom sounds but I just can't get it, I'm very new to eclipse and I managed to get it on the splash screen but can't get it for the buttons.
package org.iimed.www;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ToggleButton;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
public class vpbox extends Activity {
private ImageButton home;
public void onCreate(Bundle vpbox_activity) {
super.onCreate(vpbox_activity);
setContentView(R.layout.vpbox_activity);
tuetoggle = (ToggleButton) findViewById(R.id.tuetoggle);
home = (ImageButton) findViewById(R.id.home);
home.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
startActivity(new Intent(vpbox.this, MainActivity.class));
ToggleButton sb = (ToggleButton) findViewById(R.id.suntoggle);
sb.setText(null);
sb.setTextOn(null);
sb.setTextOff(null);
sb.setBackgroundResource(R.drawable.vpbuttons);
ToggleButton mt= (ToggleButton)findViewById (R.id.montoggle);
mt.setText(null);
mt.setTextOn(null);
mt.setTextOff(null);
mt.setBackgroundResource(R.drawable.vpmonday);
ToggleButton wt = (ToggleButton) findViewById(R.id.wedtoggle);
wt.setText(null);
wt.setTextOff(null);
wt.setTextOn(null);
wt.setBackgroundResource(R.drawable.vpwed);
ToggleButton ft = (ToggleButton) findViewById(R.id.fritoggle);
ft.setText(null);
ft.setTextOn(null);
ft.setTextOff(null);
ft.setBackgroundResource(R.drawable.vpfri);
The test button with the sound:
ToggleButton thb = (ToggleButton) findViewById(R.id.thutoggle);
thb.setText(null);
thb.setTextOn(null);
thb.setTextOff(null);
thb.setBackgroundResource(R.drawable.vpthu);
MediaPlayer mp= MediaPlayer.create(getBaseContext(), R.raw.splashsound);
mp.start();

Resources