I am currently working on an alarm to be included in a bigger project. Everything is working correctly with the datepicker/timepicker. And the alarm does start once the date and time has been reached. The problem i am having is the only way to stop the alarm is by closing the application. I have added a button (stopAlarm) with everything i thought would be needed to stop this pending intent, but it is still not stopping the alarm?
I am probably overlooking something very small but i was wondering if there is anyone who can point me in the right direction?
Thanks!
MainActivity:
package servicealarmdemo.test2;
import java.util.Calendar;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.view.View;
public class MainActivity extends Activity{
DatePicker pickerDate;
TimePicker pickerTime;
Button buttonSetAlarm;
Button buttonStopAlarm;
TextView info;
final static int RQS_1 = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
info = (TextView)findViewById(R.id.info);
pickerDate = (DatePicker)findViewById(R.id.pickerdate);
pickerTime = (TimePicker)findViewById(R.id.pickertime);
Calendar now = Calendar.getInstance();
pickerDate.init(
now.get(Calendar.YEAR),
now.get(Calendar.MONTH),
now.get(Calendar.DAY_OF_MONTH),
null);
pickerTime.setCurrentHour(now.get(Calendar.HOUR_OF_DAY));
pickerTime.setCurrentMinute(now.get(Calendar.MINUTE));
buttonSetAlarm = (Button)findViewById(R.id.setalarm);
buttonSetAlarm.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
Calendar current = Calendar.getInstance();
Calendar cal = Calendar.getInstance();
cal.set(pickerDate.getYear(),
pickerDate.getMonth(),
pickerDate.getDayOfMonth(),
pickerTime.getCurrentHour(),
pickerTime.getCurrentMinute(),
00);
if(cal.compareTo(current) <= 0){
//The set Date/Time already passed
Toast.makeText(getApplicationContext(),
"Date/Time Has Already Passed!",
Toast.LENGTH_LONG).show();
}else {
setAlarm(cal);
}
buttonStopAlarm = (Button)findViewById(R.id.stopalarm);
buttonStopAlarm.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS_1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
}});
}
private void setAlarm(Calendar targetCal){
info.setText("\n\n***\n"
+ "Deadline has now been set: " + targetCal.getTime() + "\n"
+ "***\n");
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS_1, intent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), pendingIntent);
}
}
AlarmReceiver.java:
package servicealarmdemo.test2;
import android.content.Context;
import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.content.WakefulBroadcastReceiver;
public class AlarmReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(final Context context, Intent intent) {
Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
Ringtone ringtone = RingtoneManager.getRingtone(context, uri);
ringtone.play();
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".MainActivity" >
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<DatePicker
android:id="#+id/pickerdate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TimePicker
android:id="#+id/pickertime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:id="#+id/setalarm"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Set Alarm"/>
<Button
android:id="#+id/stopalarm"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="stopAlarm"
android:text="Stop Alarm"/>
<TextView
android:id="#+id/info"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</ScrollView>
You have a different mechanism to connect your methods with the view - setAlarm is with code (onClickListener) and stopAlarm is with XML. It could be a problem with the way the XML is connecting to the view/Activity, or a problem in the stopAlarm method itself. Put some debugging in the stopAlarm method to confirm it is getting called.
Also, according to this post, you may need to use the "CURRENT_UPDATE_FLAG" when getting the pending intent.
public void stopAlarm(View view) {
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS_1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
}
One other thing to try is caching the intent between set and stop alarm. Rather than re-creating the intent.
Related
i create this app but it is not send a notification at the time choosen please can any one help me to solve this problem
xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
android:gravity="center_horizontal"
tools:context=".MainActivity">
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter your task"
android:layout_marginBottom="20dp"/>
<TimePicker
android:id="#+id/timePicker"
android:layout_width="300dp"
android:layout_height="342dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:layout_marginTop="30dp">
<Button
android:id="#+id/setBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="set"
android:layout_marginRight="20dp"/>
<Button
android:id="#+id/cancelBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="cancel"/>
</LinearLayout>
and this is the MainActivity class for app:
package com.examble.alarmlast;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlarmManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
private AlarmManager alarmMgr;
private PendingIntent alarmIntent;
Button setbtn;
TimePicker timePicker;
EditText edt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setbtn = findViewById(R.id.setBtn);
edt=findViewById(R.id.editText);
timePicker=findViewById(R.id.timePicker);
final int hour = timePicker.getCurrentHour();
final int minute = timePicker.getCurrentMinute();
setbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
intent.putExtra("todo", edt.getText().toString());
alarmIntent = PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0);
// Set the alarm to start at 8:30 a.m.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY,hour );
calendar.set(Calendar.MINUTE, minute);
// setRepeating() lets you specify a precise custom interval--in this case,
// 20 minutes.
alarm.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 * 60 * 20,
alarmIntent);
Toast.makeText(MainActivity.this, "Done!", Toast.LENGTH_SHORT).show();
}
});
}
}
and this is the AlarmReceiver class for app:
package com.examble.alarmlast;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import static androidx.core.content.ContextCompat.getSystemService;
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("todo");
// When notification is tapped, call MainActivity.
Intent mainIntent = new Intent(context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, mainIntent, 0);
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O)
{
NotificationChannel notificationChannel = new NotificationChannel("n","n",
NotificationManager.IMPORTANCE_DEFAULT);
NotificationManager myNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
myNotificationManager.createNotificationChannel(notificationChannel);
}
// Prepare notification.
NotificationCompat.Builder builder = new NotificationCompat.Builder(context,"n")
.setContentText(message)
.setContentTitle("It's Time!")
.setSmallIcon(android.R.drawable.ic_dialog_info)
.setAutoCancel(true)
.setContentText(message)
.setWhen(System.currentTimeMillis())
.setContentIntent(contentIntent)
.setPriority(Notification.PRIORITY_MAX)
.setDefaults(Notification.DEFAULT_ALL);
// Notify
NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(context);
notificationManagerCompat.notify(999,builder.build());
}
}
AndroidManifast:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.abeer.alarmlast">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".AlarmReceiver" />
</application>
</manifest>
Receiver doesnt know when to invoke itself.
<receiver android:name=".AlarmReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
You need to specify when to invoke it.
This question already has answers here:
Null pointer Exception - findViewById()
(12 answers)
Closed 2 years ago.
This is my first post so apologies if I get any of the formalities wrong...
Before anyone tells me the question is invalid, every solution I have looked at says I should have:
setContentView(R.layout.whateverViewImCurrentlyTryingToFocus)
before I call a
findViewById()
When I debug my application it is crashing when I set up an onClickListener for my button (R.id.sign_in_button), line 75.
So I decided to check what findViewById() was returning so I run the code
Button button = findViewById(R.id.sign_in_button)
This caused the same error. I think it it returning null but not entirely sure.
Activitylogin.xml is the first layout to be loaded, and then the mainactivity.xml is supposed to launch after a firebase sign-in.
Java code:
LoginActivity.java
package com.styryl.socials.ui.login;
import android.app.Activity;
import androidx.annotation.NonNull;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.appcompat.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.snackbar.Snackbar;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import com.styryl.socials.MainActivity;
import com.styryl.socials.R;
import com.styryl.socials.ui.login.LoginViewModel;
import com.styryl.socials.ui.login.LoginViewModelFactory;
public class LoginActivity extends AppCompatActivity {
private LoginViewModel loginViewModel;
private FirebaseAuth mAuth;
private GoogleSignInClient mGoogleSignInClient;
private final static int RC_SIGN_IN = 1;
private String TAG = "Login Activity";
#Override
protected void onStart() {
super.onStart();
FirebaseUser user = mAuth.getCurrentUser();
if(user != null){
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mAuth = FirebaseAuth.getInstance();
createRequest();
// Button findViewByID returns null
findViewById(R.id.sign_in_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signIn();
}
});
}
private void createRequest() {
// Configure Google Sign In
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
// Build a GoogleSignInClient with the options specified by gso.
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = task.getResult(ApiException.class);
Log.d(TAG, "firebaseAuthWithGoogle:" + account.getId());
firebaseAuthWithGoogle(account.getIdToken());
} catch (ApiException e) {
// Google Sign In failed, update UI appropriately
Log.w(TAG, "Google sign in failed", e);
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
// ...
}
}
}
private void firebaseAuthWithGoogle(String idToken) {
AuthCredential credential = GoogleAuthProvider.getCredential(idToken, null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
FirebaseUser user = mAuth.getCurrentUser();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(LoginActivity.this, "Authentication Failed.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
MainActivity.java
package com.styryl.socials;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.styryl.socials.ui.login.LoginActivity;
import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
public class MainActivity extends AppCompatActivity {
TextView user_username;
TextView user_email;
Button logout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
user_username = findViewById(R.id.user_username);
user_email = findViewById(R.id.user_email);
logout = findViewById(R.id.logout_button);
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_profile)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
NavigationUI.setupWithNavController(navView, navController);
GoogleSignInAccount signInAccount = GoogleSignIn.getLastSignedInAccount(this);
if(signInAccount != null){
user_username.setText(signInAccount.getDisplayName());
user_email.setText(signInAccount.getEmail());
}
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseAuth.getInstance().signOut();
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
}
});
}
}
Layout Files:
LoginActivity.xml
<?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:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".ui.login.LoginActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/status_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
<com.google.android.gms.common.SignInButton
android:id="#+id/sign_in_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:layout_width="110dp"
android:layout_height="wrap_content"
android:text="Sign Out"
android:id="#+id/sign_out_button" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.xml
<?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"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorDarkGrey"
android:paddingTop="?attr/actionBarSize">
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/nav_view"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="#color/colorPrimaryDark"
app:itemIconTint="#drawable/bottom_navigation_selector"
app:itemTextColor="#drawable/bottom_navigation_selector"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="#menu/bottom_nav_menu" />
<fragment
android:id="#+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimaryDark"
app:defaultNavHost="true"
app:layout_constraintBottom_toTopOf="#id/nav_view"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navGraph="#navigation/mobile_navigation" />
</androidx.constraintlayout.widget.ConstraintLayout>
If you need anymore information please let me know and I will provide. I can't wrap my head around this issue and really hope some android studio experts can explain it to me as if I'm a idiot because I would love to learn!
I am attempting to fix this as soon as I wake up, because I never quit!
All,
Thank you for your replies,
I woke up this morning and after looking at the logcat as suggested by #Frank van puffelen, I noticed that the error was a nullPointerException on a textView. This was weird becuase there was no textView in my loginActivity. Upon further inspection, I hadn't created the username and the email textView in my main_activity.xml (Problem with late night coding, I should have spotted that). So this was returning a nullPointerException simply because it didn't exist. I added the username, email and logout button to the xml and it works.
Thanks for the help, not entirely sure how to close this thread (this is my first post), apologies for wasting time but I was a little desperate.
In this code i need to apply jingle when the video is getting downloaded from the server to mobile device
code : This the main activity which is java file where the videos are downloaded from server and getting situated in android device and will be played in video view
MainActivity.java
package ivmshd.mcu.com.demo;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.VideoView;
import java.io.File;
import static android.R.attr.path;
public class MainActivity extends AppCompatActivity {
private long enqueue;
private DownloadManager dm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(enqueue);
Cursor c = dm.query(query);
if (c.moveToFirst()) {
int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
VideoView view= (VideoView) findViewById(R.id.videoView);
enter code here
String uriString = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
view.setVideoURI(Uri.parse(uriString));
}
}
}
}
};
registerReceiver(receiver, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
public void onClick(View view) {
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request request =new DownloadManager.Request(Uri.parse("http://eZeeReview.com/login/pages/examples/video/1.mp4"));
enqueue = dm.enqueue(request);
final VideoView videoView;
videoView = (VideoView) findViewById(R.id.videoView);
Uri video = Uri.parse("http://eZeeReview.com/login/pages/examples/video/1.mp4");
videoView.setVideoURI(video);
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.setLooping(true);
videoView.start();
}
});
}
public void showDownload(View view) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setAction(DownloadManager.ACTION_VIEW_DOWNLOADS);
startActivity(i);
}
}
XML File: In this code the widgets are applied
widgets are like Video view and 2 buttons
where videos are played in video view.This videos are the videos which are fetched from server
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button android:text="Start Download" android:id="#+id/button1"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:onClick="onClick"></Button>
<Button android:text="View Downloads" android:id="#+id/button2"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:onClick="showDownload"></Button>
<VideoView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/videoView" />
</LinearLayout>
Good evening, I'm still a noob with code and i wondered if someone could help:)
I want to put an action bar on an Activity that i've already made, where i also want to add the app icon but I already know how to do that, i just want to know how to put an action bar.
package app.alexdickson.com.workout1;
import android.app.AlarmManager;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TimePicker;
import android.widget.Toast;
import java.util.Calendar;
public class Main2Activity extends AppCompatActivity implements View.OnClickListener{
ImageButton botoFlexio;
ImageButton botoAbdominals;
static final int DIALOG_ID = 0;
int hour_x;
int minute_x;
int hourDefinitivaFlexio;
int minuteDefinitvaFlexio;
int hourDefinitivaAbs;
int minuteDefinitivaAbs;
PendingIntent pending_intent1;
PendingIntent pending_intent2;
Context context;
AlarmManager alarm_manager1;
AlarmManager alarm_manager2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
this.context = this;
botoFlexio = (ImageButton) findViewById(R.id.botoFlexio);
botoAbdominals = (ImageButton) findViewById(R.id.botoAbdominals);
botoFlexio.setOnClickListener(this);
botoAbdominals.setOnClickListener(this);
alarm_manager1 = (AlarmManager) getSystemService(ALARM_SERVICE);
alarm_manager2 = (AlarmManager) getSystemService(ALARM_SERVICE);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.botoFlexio:
botoFlexio.setBackgroundResource(R.drawable.flexioclicat);
showDialog(DIALOG_ID);
hourDefinitivaFlexio = hour_x;
minuteDefinitvaFlexio = minute_x;
final Calendar calendar1 = Calendar.getInstance();
calendar1.set(Calendar.HOUR_OF_DAY,hourDefinitivaFlexio);
calendar1.set(Calendar.MINUTE, minuteDefinitvaFlexio);
final Intent my_intent1 = new Intent(this.context, Alarm_Receiver1.class);
pending_intent1 = PendingIntent.getBroadcast(Main2Activity.this,0,
my_intent1, PendingIntent.FLAG_UPDATE_CURRENT);
//Alarm manager
alarm_manager1.set(AlarmManager.RTC_WAKEUP, calendar1.getTimeInMillis(),
pending_intent1);
break;
case R.id.botoAbdominals:
botoAbdominals.setBackgroundResource(R.drawable.abdominalsclicat);
showDialog(DIALOG_ID);
hourDefinitivaAbs = hour_x;
minuteDefinitivaAbs = minute_x;
final Calendar calendar2 = Calendar.getInstance();
calendar2.set(Calendar.HOUR_OF_DAY,hourDefinitivaAbs);
calendar2.set(Calendar.MINUTE, minuteDefinitivaAbs);
final Intent my_intent2 = new Intent(this.context, Alarm_Receiver2.class);
pending_intent2 = PendingIntent.getBroadcast(Main2Activity.this,0,
my_intent2, PendingIntent.FLAG_UPDATE_CURRENT);
//Alarm manager
alarm_manager2.set(AlarmManager.RTC_WAKEUP, calendar2.getTimeInMillis(),
pending_intent1);
break;
}
}
#Override
protected Dialog onCreateDialog(int id) {
if (id == DIALOG_ID)
return new TimePickerDialog(Main2Activity.this, kTimePickerListener, hour_x, minute_x, true);
return null;
}
protected TimePickerDialog.OnTimeSetListener kTimePickerListener =
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
hour_x = hourOfDay;
minute_x = minute;
Toast.makeText(Main2Activity.this, hour_x + ": " + minute_x, Toast.LENGTH_LONG).show();
}
};
And here's my xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="2"
android:orientation="horizontal"
android:theme="#android:style/Theme.Black.NoTitleBar.Fullscreen" >
<ImageButton
android:layout_width="0dp"
android:layout_height="400dp"
android:layout_weight="1"
android:id="#+id/botoAbdominals"
android:background="#drawable/abdominals"
android:contentDescription="ImatgeAbdominals"
android:layout_marginTop="50dp"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"
/>
<ImageButton
android:layout_width="0dp"
android:layout_height="400dp"
android:layout_weight="1"
android:id="#+id/botoFlexio"
android:layout_gravity="top"
android:layout_marginTop="50dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#drawable/flexio"
android:contentDescription="ImatgeFlexio"
/>
I want to add a button to one of my activities (that displays a news article), so when the user clicks the button the article is opened in their browser. So far I have added the button in my xml and it appears. I'm just having some trouble with the click listener. Below is my code, i'm getting an error for 'setOnClickListener' which is 'Non-static method 'setOnClickListener(android.view.View.onClickListener)' cannot be referenced from a static content.
I'm not sure what this means! maybe i'm not calling the method in the right place or there is just an error with the method itself?
Please could someone take a look, thanks!
import android.content.Intent;
import android.media.Image;
import android.net.Uri;
import android.support.v4.app.ShareCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.ShareActionProvider;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.view.View.OnClickListener;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.NetworkImageView;
import org.json.JSONException;
import org.json.JSONObject;
public class NewsItemActivity extends AppCompatActivity {
//Declare java object for the UI elements
private TextView itemTitle;
private TextView itemDate;
private TextView itemContent;
private NetworkImageView itemImage;
private ShareActionProvider mShareActionProvider;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news_item);
itemTitle = (TextView) findViewById(R.id.itemTitle);
itemDate = (TextView) findViewById(R.id.itemDate);
itemContent = (TextView) findViewById(R.id.itemContent);
itemImage = (NetworkImageView) findViewById(R.id.itemImage);
EDANewsApp app = EDANewsApp.getInstance();
Intent intent = getIntent();
int itemId = intent.getIntExtra("newsItemId", 0);
String url = "http://www.efstratiou.info/projects/newsfeed/getItem.php?id="+itemId;
JsonObjectRequest request = new JsonObjectRequest(url, listener, errorListener);
app.requestQueue.add(request);
Button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = getIntent();
int itemId = intent.getIntExtra("newsItemId", 0);
String shareUrl = "http://www.efstratiou.info/projects/newsfeed/getItem.php?id=" + itemId;
Intent buttonIntent = new Intent();
buttonIntent.setAction(Intent.ACTION_VIEW);
buttonIntent.addCategory(Intent.CATEGORY_BROWSABLE);
buttonIntent.setData(Uri.parse(shareUrl));
startActivity(buttonIntent);
}
});
};
activity_news_item.xml
<RelativeLayout 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"
tools:context=".NewsItemActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/itemTitle"
android:layout_margin="15dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textStyle="bold"
android:textColor="#3183b9"/>
<TextView
android:id="#+id/itemDate"
android:layout_marginLeft="15dp"
android:layout_marginBottom="15dp"
android:textSize="16sp"
android:textStyle="italic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/itemImage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/itemContent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20sp"
android:textSize="16sp"
/>
<Button
android:id="#+id/BrowserButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="View in browser"
android:layout_marginLeft="15dp"
style="#style/BrowserButton"
/>
</LinearLayout>
</ScrollView>
</RelativeLayout>
Change
Button.setOnClickListener(new View.OnClickListener() { ... });
to
Button button = (Button) findViewById(R.id.BrowserButton);
button.setOnClickListener(new View.OnClickListener() { ... });
You need to call the setOnClickListener method on an instance of Button, not on the class itself.
The problem is this :
Button.setOnClickListener(new View.OnClickListener() {
You have to declare it out of onCreate() as you did with your Textviews as :
Button btn;
Why?
Because if you put it on onCreate() you wont be able to use this object out of onCreate() so it's recomendable to put it as a public object.
Then in your onCreate() do this :
btn = (Button)findViewById(R.id.BrowserButton);
Then you do the OnclickListener() as follows :
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = getIntent();
int itemId = intent.getIntExtra("newsItemId", 0);
String shareUrl = "http://www.efstratiou.info/projects/newsfeed/getItem.php?id=" + itemId;
Intent buttonIntent = new Intent();
buttonIntent.setAction(Intent.ACTION_VIEW);
buttonIntent.addCategory(Intent.CATEGORY_BROWSABLE);
buttonIntent.setData(Uri.parse(shareUrl));
startActivity(buttonIntent);
}
});
I'm still getting an error for onClickListener, saying it 'cannot resolve symbol'.
Make sure that you've imported this :
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
You can do it doing this :
Add implements OnClickListener { as follows :
public class NewsItemActivity extends AppCompatActivity implements View.OnClickListener {
Then on your Button you do this :
btn = (Button)findViewById(R.id.BrowserButton);
btn.setOnClickListener(this);
Then add a switch case as follows :
public void onClick(View v) {
switch(v.getId()) {
case R.id.BrowserButton:
Intent intent = getIntent();
int itemId = intent.getIntExtra("newsItemId", 0);
String shareUrl = "http://www.efstratiou.info/projects/newsfeed/getItem.php?id=" + itemId;
Intent buttonIntent = new Intent();
buttonIntent.setAction(Intent.ACTION_VIEW);
buttonIntent.addCategory(Intent.CATEGORY_BROWSABLE);
buttonIntent.setData(Uri.parse(shareUrl));
startActivity(buttonIntent);
}
break;
}
}