How to fill the progress bar in the background while changing activities - java

I have 3 page application, in which the activities change every 10 secs (i.e., Activity1 -> Activity2 -> Activity3 -> Activity1 .......).
I have a progressbar in Activity2 which updates every 1 sec. The problem is, whenever the Activity2 is changing to Activity3 and then coming back to Activity 2 the progressbar is resetting and starting all over from zero.
I would like the progressbar to update continuously for the set time without interruptions. I tried using the services but the result is still the same.
I hope the code below helps in idenfying the issue and would really appreciate if anyone helps me out.
Activity1.java
package com.ossus.SC20;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
public class frame_6_activity extends Activity {
Timer timer;
private View _bg__frame_6;
private ImageView background_1;
private TextView text_view_date;
private ImageView logo_2_1;
private TextView H2Value;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.frame_6);
startService(new Intent(frame_6_activity.this, service.class));
Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler(this));
if (getIntent().getBooleanExtra("crash", false)) {
Toast.makeText(this, "App restarted after crash", Toast.LENGTH_SHORT).show();
}
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run(){
Intent intent = new Intent(frame_6_activity.this, frame_2_activity.class);
startActivity(intent);
finish();
}
}, 10000);
Calendar calendar = Calendar.getInstance();
String currentDate = DateFormat.getDateInstance(DateFormat.FULL).format(calendar.getTime());
TextView textViewDate = findViewById(R.id.text_view_date);
textViewDate.setText(currentDate);
_bg__frame_6 = (View) findViewById(R.id._bg__frame_6);
background_1 = (ImageView) findViewById(R.id.background_1);
text_view_date = (TextView) findViewById(R.id.text_view_date);
logo_2_1 = (ImageView) findViewById(R.id.logo_2_1);
H2Value = (TextView) findViewById(R.id.H2Value);
}
}
Activity2.java
package com.ossus.SC20;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import org.w3c.dom.Text;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
public class frame_2_activity extends Activity {
private ProgressBar mProgressBar;
private TextView mLoadingText;
private int mProgressStatus = 0;
// private Handler mHandler = new Handler();
Handler handler = new Handler();
Timer timer;
private View _bg__frame_2;
private ImageView background_1;
private TextView text_view_date;
private ImageView logo_2_1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.frame_2_new);
startService(new Intent(frame_2_activity.this, service.class));
mProgressBar = (ProgressBar) findViewById(R.id.progressbar);
mLoadingText = (TextView) findViewById(R.id.LoadingCompleteTextView);
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
startProgress();
}
});
thread.start();
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run(){
Intent intent = new Intent(frame_2_activity.this, frame_3_activity.class);
startActivity(intent);
finish();
}
}, 10000);
Calendar calendar = Calendar.getInstance();
String currentDate = DateFormat.getDateInstance(DateFormat.FULL).format(calendar.getTime());
TextView textViewDate = findViewById(R.id.text_view_date);
textViewDate.setText(currentDate);
_bg__frame_2 = (View) findViewById(R.id._bg__frame_2);
background_1 = (ImageView) findViewById(R.id.background_1);
text_view_date = (TextView) findViewById(R.id.text_view_date);
logo_2_1 = (ImageView) findViewById(R.id.logo_2_1);
//custom code goes here
}
public void startProgress(){
for (mProgressStatus = 0; mProgressStatus < 100; mProgressStatus = mProgressStatus + 1){
try{
Thread.sleep(1000);
mProgressBar.setProgress(mProgressStatus);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
#Override
public void run() {
mLoadingText.setText(String.valueOf(mProgressStatus + "% Completed"));
}
});
}
}
}
Service.java
package com.ossus.SC20;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class service extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service started by user.", Toast.LENGTH_LONG).show();
return START_STICKY;
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.ossus.SC20">
<application
android:allowBackup="true"
android:dataExtractionRules="#xml/data_extraction_rules"
android:fullBackupContent="#xml/backup_rules"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.SC20"
tools:targetApi="31">
<activity
android:name=".frame_3_activity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="#string/app_name"
android:screenOrientation="landscape"
android:exported="true" >
</activity>
<activity
android:name=".frame_2_activity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="#string/app_name"
android:screenOrientation="landscape"
android:exported="true" >
</activity>
<activity
android:name=".frame_6_activity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="#string/app_name"
android:screenOrientation="landscape"
android:exported="true" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="preloaded_fonts"
android:resource="#array/preloaded_fonts" />
<service android:name = ".service"/>
</application>
</manifest>

Related

Unable to add view to a window with TYPE_PHONE params android

I am trying to create a floating view which should appear on top of everything but notification panel and settings app hide my view
I tried to use WindowManager.LayoutParams.TYPE_PHONE but its deprecated after oreo and app crashes if I try to add a view to that window with params set to WindowManager.LayoutParams.TYPE_PHONE
here is my java code
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.opengl.Visibility;
import android.os.IBinder;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;
public class FloatingMouseService extends Service {
private WindowManager mWindowManager;
private View floatingMouse;
public FloatingMouseService() {
}
#Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate() {
super.onCreate();
LayoutInflater layoutInflater = (LayoutInflater) FloatingMouseService.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
floatingMouse = layoutInflater.inflate(R.layout.layoutmouse, null);
final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.TOP | Gravity.LEFT;
params.x = 0;
params.y = 100;
mWindowManager = (WindowManager) FloatingMouseService.this.getSystemService(WINDOW_SERVICE);
mWindowManager.addView(floatingMouse, params);
}
}
here is MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final int CODE_DRAW_OVER_OTHER_APP_PERMISSION = 2084;
TextView serMess = findViewById(R.id.serMess);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, CODE_DRAW_OVER_OTHER_APP_PERMISSION);
} else {
initializeView();
}
}
private void initializeView() {
Button connect = findViewById(R.id.connect);
findViewById(R.id.connect).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startService(new Intent(MainActivity.this, FloatingMouseService.class));
new Thread(new ClientServerReq()).start();
Toast.makeText(MainActivity.this, "Connected Successfully", Toast.LENGTH_SHORT).show();
connect.setText("Connected");
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
final int CODE_DRAW_OVER_OTHER_APP_PERMISSION = 2084;
if (requestCode == CODE_DRAW_OVER_OTHER_APP_PERMISSION) {
if (resultCode == RESULT_OK) {
initializeView();
} else { //Permission is not available
Toast.makeText(this,
"Draw over other app permission not available. Closing the application",
Toast.LENGTH_SHORT).show();
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
#Override
protected void onResume() {
super.onResume();
}
}
here is my Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.MFB.project.sharekey">
<uses-permission android:name="android.permission.INTERNET" ></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" ></uses-permission>
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<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/Theme.AppCompat.DayNight.DarkActionBar">
<activity
android:name="com.MFB.project.sharekey.MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name="com.MFB.project.sharekey.FloatingMouseService"
android:enabled="true" />
</application>
</manifest>

I can't start activity from service while app is hidden

I have two activities: MainActivity and ActivityTwo. When starting application, I start service serviceApp, which after some events should start ActivityTwo. For the test, I made the launch after 10 seconds and AsyncTask, but if the application is hidden, activity does not start
How do I launch activity even if the app is hidden?
MainActivity
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SwitchCompat;
import android.app.ActivityManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import java.security.Provider;
import java.util.List;
public class MainActivity extends AppCompatActivity {
SharedPreferences setting;
#Override
protected void onCreate(Bundle savedInstanceState) {
Intent service = new Intent(this, serviceApp.class);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setting = getSharedPreferences("settings", MODE_PRIVATE);
SwitchCompat switchCompat = findViewById(R.id.switchBLock);
switchCompat.setOnCheckedChangeListener((view, bool) -> {
SharedPreferences.Editor editor = setting.edit();
editor.putBoolean("block", bool);
editor.apply();
if(bool){
startService(service);
}else{
stopService(service);
}
});
if(setting.getBoolean("block", false)){
switchCompat.setChecked(true);
}
}
}
ActivityTwo
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
public class ActivityTwo extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_two);
}
}
serviceApp
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.IBinder;
public class serviceApp extends Service {
Context context;
public serviceApp() {
context = this;
}
#Override
public void onCreate() {
super.onCreate();
new Async().execute();
}
class Async extends AsyncTask<Void, Void, Void>{
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Intent startMain = new Intent();
startMain.setClass(context, ActivityTwo.class);
startMain.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
}
#Override
protected Void doInBackground(Void... voids) {
for(int i = 0; i < 2; i++) {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
AndroidManifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.test">
<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/Theme.AppCompat.NoActionBar">
<activity android:name="com.example.test.ActivityTwo"></activity>
<service
android:name=".serviceApp"/>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I found an easy way to fix this ailment, you need to give the application the SYSTEM_ALERT_WINDOW permission
https://developer.android.com/guide/components/activities/background-starts
AndroidManifest.xml
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
MainActivity
Intent myIntent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
startActivity(myIntent);

Playback position resets to zero after orientation change

Below is the code for my music player. I use Videoview to play a local list of selective songs.
I want to store and resume the playback position when orientation changes (portrait/landscape).
I have used onSaveInstanceState and onRestoreInstanceState methods. No errors on build, but still the songs reset every time.
I couldn't figure out what's wrong.
package io.automaton.android.morningbinge;
import androidx.appcompat.app.AlertDialog;
import android.app.Activity;
import android.content.DialogInterface;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Toast;
import android.widget.VideoView;
import android.widget.MediaController;
import java.util.ArrayList;
public class MainActivity extends Activity
implements MediaPlayer.OnCompletionListener {
VideoView vw;
ArrayList<Integer> videolist = new ArrayList<>();
int currvideo = 0;
int mPositionWhenPaused=0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vw = (VideoView)findViewById(R.id.videoView);
vw.setMediaController(new MediaController(this));
vw.setOnCompletionListener(this);
// video name should be in lower case alphabet.
videolist.add(R.raw.onbadhu_kolum);
videolist.add(R.raw.kala_bhairava_ashtakam);
videolist.add(R.raw.panchamukh_hanumath_kavacham);
videolist.add(R.raw.kandha_shashti_kavasam);
setVideo(videolist.get(0));
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
//we use onSaveInstanceState in order to store the video playback position for orientation change
savedInstanceState.putInt("Position", vw.getCurrentPosition());
vw.pause();
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
//we use onRestoreInstanceState in order to play the video playback from the stored position
mPositionWhenPaused = savedInstanceState.getInt("Position");
vw.seekTo(mPositionWhenPaused);
}
public void setVideo(int id)
{
String uriPath
= "android.resource://"
+ getPackageName() + "/" + id;
Uri uri = Uri.parse(uriPath);
vw.setVideoURI(uri);
vw.start();
}
public void onCompletion(MediaPlayer mediapalyer)
{
AlertDialog.Builder obj = new AlertDialog.Builder(this);
obj.setTitle("Playback Finished!");
obj.setIcon(R.mipmap.ic_launcher);
MyListener m = new MyListener();
obj.setPositiveButton("Replay", m);
obj.setNegativeButton("Next", m);
obj.setMessage("Want to replay or play next video?");
obj.show();
}
class MyListener implements DialogInterface.OnClickListener {
public void onClick(DialogInterface dialog, int which)
{
if (which == -1) {
vw.seekTo(0);
vw.start();
}
else {
++currvideo;
if (currvideo == videolist.size())
currvideo = 0;
setVideo(videolist.get(currvideo));
}
}
}
}
I sorted out the issue. I changed the way the list is being called to play with the setOnPreparedListener, seeking to last played position.
...
Main Activity
package io.automaton.android.morningbinge;
import androidx.appcompat.app.AlertDialog;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import android.widget.VideoView;
import android.widget.MediaController;
import android.media.MediaPlayer.OnPreparedListener;
import java.util.ArrayList;
public class MainActivity extends Activity
implements MediaPlayer.OnCompletionListener {
VideoView vw;
ArrayList<Integer> videolist = new ArrayList<>();
int currvideo = 0;
int mPositionWhenPaused=0;
private static final String TAG = "MyActivity";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vw = (VideoView)findViewById(R.id.videoView);
vw.setMediaController(new MediaController(this));
vw.setOnCompletionListener(this);
videolist.add(R.raw.onbadhu_kolum);
videolist.add(R.raw.kala_bhairava_ashtakam);
videolist.add(R.raw.panchamukh_hanumath_kavacham);
videolist.add(R.raw.kandha_shashti_kavasam);
try {
//set the uri of the video to be played
vw.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + videolist.get(0)));
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
View decorView = getWindow().getDecorView();
int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);
vw.requestFocus();
vw.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mediaPlayer) {
vw.seekTo(mPositionWhenPaused);
if (mPositionWhenPaused == 0) {
vw.start();
} else {
vw.pause();
}
}
});
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt("Position", vw.getCurrentPosition());
Log.i("Orientation Change", "Warn-orientation change and saved");
vw.pause();
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mPositionWhenPaused = savedInstanceState.getInt("Position");
vw.seekTo(mPositionWhenPaused);
Log.i("restored", "restored after orientation change");
}
public void onCompletion(MediaPlayer mediapalyer)
{
++currvideo;
if (currvideo == videolist.size())
currvideo = 0;
setVideo(videolist.get(currvideo));
}
}
...
android manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="io.automaton.android.morningbinge">
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.INTERNET" />
<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"
android:configChanges="orientation|screenSize|screenLayout|keyboardHidden">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
...

Notifications won't appear

When I launch my app, I set the time in my activity and I wait for the notification, it doesn't appear, it doesn't work.
Here's my activity, if you find the error tell me please.. Thanks for your help :)
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.ActionBar;
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 pendingIntent1;
PendingIntent pendingIntent2;
Context context;
AlarmManager alarmManager1;
AlarmManager alarmManager2;
#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);
alarmManager1 = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager2 = (AlarmManager) getSystemService(ALARM_SERVICE);
}
private void alarmMethod1(){
Intent myIntent1 = new Intent(this, NotifyService1.class);
AlarmManager alarmManager1 = (AlarmManager)getSystemService(ALARM_SERVICE);
pendingIntent1 =PendingIntent.getService(this,0,myIntent1,0);
Calendar calendari1 = Calendar.getInstance();
calendari1.set(Calendar.MINUTE, minute_x);
calendari1.set(Calendar.HOUR,hour_x);
alarmManager1.setRepeating(AlarmManager.RTC_WAKEUP,calendari1.getTimeInMillis(),
1000 * 60 * 60 * 24, pendingIntent1);
}
private void alarmMethod2(){
Intent myIntent2 = new Intent(this, NotifyService2.class);
AlarmManager alarmManager2 = (AlarmManager)getSystemService(ALARM_SERVICE);
pendingIntent2 =PendingIntent.getService(this,0,myIntent2,0);
Calendar calendari2 = Calendar.getInstance();
calendari2.set(Calendar.MINUTE,minute_x);
calendari2.set(Calendar.HOUR, hour_x);
alarmManager2.setRepeating(AlarmManager.RTC_WAKEUP,calendari2.getTimeInMillis(),
1000 * 60 * 60 * 24, pendingIntent2);
}
#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;
alarmMethod1();
break;
case R.id.botoAbdominals:
botoAbdominals.setBackgroundResource(R.drawable.abdominalsclicat);
showDialog(DIALOG_ID);
hourDefinitivaAbs = hour_x;
minuteDefinitivaAbs = minute_x;
alarmMethod2();
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();
}
};
}
Here's where the intent goes: (There are two of them but they are the same, it only changes the numbers)
package app.alexdickson.com.workout1;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.IBinder;
public class NotifyService1 extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onCreate(){
Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationManager nNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Intent intent1 = new Intent(this.getApplicationContext(),Main3Activity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent1, 0);
Notification mNotify = new Notification.Builder(this)
.setContentTitle("Hora d'entrenar!")
.setContentText("Clica per començar entrenament de pit i braços")
.setSmallIcon(R.mipmap.logo)
.setContentIntent(pIntent)
.setSound(sound)
.build();
nNM.notify(1,mNotify);
}
}
And here's my manifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<application
android:allowBackup="true"
android:icon="#mipmap/logo"
android:label="#string/app_name"
android:theme="#style/MyTheme">
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Main2Activity"
android:label="#string/title_activity_main2">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity android:name=".Main3Activity" />
<activity android:name=".Main4Activity"></activity>
</application>
You have to register NotifyService1 and NotifyService2 in AndroidManifest.xml.

Android Json Project application crashes

I am having a little trouble with my android development project. I have created an application which allows the user to insert/read/update and delete records from a MySQL database. This is using JSON. The application keeps crashing with a fatal exception main? Not too sure what it is as none of the pages created are showing any errors. I also have used php to connect to the database and query it. There are 5 java files and 4 xml layout files. Not sure if you would like me to put them all on here as it might get to be too much so for now I will add them in my public folder of dropbox, if I need to put all of the pages here I will edit the question. https://www.dropbox.com/s/iakgmx7aci78b65/AndroidAssignment.zip?dl=0
UPDATE:
I managed to get rid of most errors but its sending a error saying unable to find explicit activity class ViewAllEmployee for the onClick method;
Process: com.example.assignment.androidassignment, PID: 2211 android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.assignment.androidassignment/com.example.assignment.androidassignment.ViewAllEmployee}; have you declared this activity in your AndroidManifest.xml?
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1628)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1424)
at android.app.Activity.startActivityForResult(Activity.java:3424)
at android.app.Activity.startActivityForResult(Activity.java:3385)
at android.app.Activity.startActivity(Activity.java:3627)
at android.app.Activity.startActivity(Activity.java:3595)
at com.example.assignment.androidassignment.MainActivity.onClick(MainActivity.java:93)
MainActivity.java
package com.example.assignment.androidassignment;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.HashMap;
public class MainActivity extends Activity implements View.OnClickListener{
//Defining views
private EditText editTextLatitude;
private EditText editTextLongitude;
private EditText editTextTimeInserted;
private Button buttonAdd;
private Button buttonView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initializing views
editTextLatitude = (EditText) findViewById(R.id.editTextLat);
editTextLongitude = (EditText) findViewById(R.id.editTextLon);
editTextTimeInserted = (EditText) findViewById(R.id.editTextTimeInserted);
buttonAdd = (Button) findViewById(R.id.buttonAdd);
buttonView = (Button) findViewById(R.id.buttonView);
//Setting listeners to button
buttonAdd.setOnClickListener(this);
buttonView.setOnClickListener(this);
}
//Adding an employee
private void addEmployee(){
final String lat = editTextLatitude.getText().toString().trim();
final String lon = editTextLongitude.getText().toString().trim();
final String timeInserted = editTextTimeInserted.getText().toString().trim();
class AddEmployee extends AsyncTask<Void,Void,String>{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this,"Adding...","Wait...",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(MainActivity.this,s,Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(Void... v) {
HashMap<String,String> params = new HashMap<>();
params.put(Config.KEY_LAT,lat);
params.put(Config.KEY_LON,lon);
params.put(Config.KEY_TIMEINSERTED,timeInserted);
RequestHandler rh = new RequestHandler();
String res = rh.sendPostRequest(Config.URL_ADD, params);
return res;
}
}
AddEmployee ae = new AddEmployee();
ae.execute();
}
#Override
public void onClick(View v) {
if(v == buttonAdd){
addEmployee();
}
if(v == buttonView){
Intent intent = new Intent(MainActivity.this,ViewAllEmployee.class);
startActivity(intent);
startActivity(new Intent(this,com.example.assignment.androidassignment.ViewAllEmployee.class));
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.assignment.androidassignment"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-sdk
android:minSdkVersion="18"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:label="#string/app_name" >
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#android:style/Theme.Holo.Dialog" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
UPDATE: ViewAllEmployee.java
package com.example.assignment.assignment;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class ViewAllEmployee extends Activity implements ListView.OnItemClickListener {
private ListView listView;
private String JSON_STRING;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_all_employee);
listView = (ListView) findViewById(R.id.listView);
listView.setOnItemClickListener(this);
getJSON();
}
private void showEmployee() {
JSONObject jsonObject = null;
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
try {
jsonObject = new JSONObject(JSON_STRING);
JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);
for (int i = 0; i < result.length(); i++) {
JSONObject jo = result.getJSONObject(i);
String UserID = jo.getString(Config.TAG_ID);
String Lat = jo.getString(Config.TAG_LAT);
HashMap<String, String> employees = new HashMap<>();
employees.put(Config.TAG_ID, UserID);
employees.put(Config.TAG_LAT, Lat);
list.add(employees);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(
ViewAllEmployee.this, list, R.layout.list_item,
new String[]{Config.TAG_ID, Config.TAG_LAT},
new int[]{R.id.id, R.id.name});
listView.setAdapter(adapter);
}
private void getJSON() {
class GetJSON extends AsyncTask<Void, Void, String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(ViewAllEmployee.this, "Fetching Data", "Wait...", false, false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
JSON_STRING = s;
showEmployee();
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequest(Config.URL_GET_ALL);
return s;
}
}
GetJSON gj = new GetJSON();
gj.execute();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(this, ViewEmployee.class);
HashMap<String, String> map = (HashMap) parent.getItemAtPosition(position);
String UserID = map.get(Config.TAG_ID).toString();
intent.putExtra(Config.EMP_ID, UserID);
startActivity(intent);
}
}
You need to add the activity ViewAllEmployee to your manifest between the Application tags
<application ...>
<activity
android:name=".ViewAllEmployee" />
</application>

Categories