so I'm trying to make an app..(or more specifically..practicing putting stuffs together to see how they work) which will set an alarm if I click a button...and at the set time..it will change the wallpaper of my phone. the app runs perfectly until the set time comes..n when the app is supposed to change my wallpaper..the app crashes..n throws a null pointer exception.
my MainActivity class code:
package com.example.wp;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.WallpaperManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import java.io.IOException;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
public Button b;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY,14); //i want to change wallpaper at 2:00 .
c.set(Calendar.MINUTE,0);
c.set(Calendar.SECOND,0);
SetAlarm(c);
}
});
}
public void changewp(){
Bitmap bit = BitmapFactory.decodeResource(getResources(),R.drawable.wp);
WallpaperManager wm = WallpaperManager.getInstance(getApplicationContext());
try {
wm.setBitmap(bit);
Toast.makeText(getApplicationContext(),"done",3).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(),"failed",3).show();
}
}
public void SetAlarm(Calendar c){
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, alertrec.class);
PendingIntent pen = PendingIntent.getBroadcast(this, 1,intent,0);
am.setExact(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(),pen);
}
}
my alartrec class code:
package com.example.wp;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class alertrec extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
MainActivity m = new MainActivity();
m.changewp();
}
}
I have also tried to write the code inside changewp() method in the onReceive() method...bt wasn't able to use the parameters correctly. So if you have a better (but not too complex) way to accomplish what I am trying too..plz let me know that. And one more thing...I am not an expert of JAVA..so the mistake I'm making maybe stupid..but I have spend a lot of time finding a solution..and found nothing.
Any kind of help will be greatly appreciated.