Display splashscreen & then AppIntro(First time launch) than mainactivity not working - java

I have made android app in which onLaunch I want to show SplashScreen for 3 second & then AppInro(If First time launch in slide) & then MainActivity launches. Actually I have done made splashscreen activity at the end but I set it up all properly but now After splashScreen MainActivity Starts directly. AppIntro not showing(Even in first time launch as well) Before adding SplashScreen activity AppIntro was working fine.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="info.androidhive.introslider">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".SpashScreen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:label="Order Medicines"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name="info.androidhive.welcomeslider.MainActivity"
//In above line code it shows Can not resolve symbol MainActivity
android:label="#string/title_activity_splash"
android:theme="#style/AppTheme"></activity>
</application>
</manifest>
SplashScreen
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
public class SpashScreen extends Activity {
private PrefManager prefManager;
// Splash screen timer
private static int SPLASH_TIME_OUT = 3000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
new Handler().postDelayed(new Runnable() {
/*
* Showing splash screen with a timer. This will be useful when you
* want to show case your app logo / company
*/
#Override
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
Intent i;
if (prefManager.isFirstTimeLaunch()) {
i = new Intent(SpashScreen.this, WelcomeActivity.class);
prefManager.setFirstTimeLaunch(false);
} else {
i = new Intent(SpashScreen.this, MainActivity.class);
}
startActivity(i);
finish();
}
}, SPLASH_TIME_OUT);
}
}
AppIntro(WelcomeActivity)
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
public class WelcomeActivity extends AppCompatActivity {
private ViewPager viewPager;
private MyViewPagerAdapter myViewPagerAdapter;
private LinearLayout dotsLayout;
private TextView[] dots;
private int[] layouts;
private Button btnSkip, btnNext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Making notification bar transparent
if (Build.VERSION.SDK_INT >= 21) {
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}
setContentView(R.layout.activity_welcome);
viewPager = (ViewPager) findViewById(R.id.view_pager);
dotsLayout = (LinearLayout) findViewById(R.id.layoutDots);
btnSkip = (Button) findViewById(R.id.btn_skip);
btnNext = (Button) findViewById(R.id.btn_next);
// layouts of all welcome sliders
// add few more layouts if you want
layouts = new int[]{
R.layout.welcome_slide1,
R.layout.welcome_slide2,
R.layout.welcome_slide3,
R.layout.welcome_slide4};
// adding bottom dots
addBottomDots(0);
// making notification bar transparent
changeStatusBarColor();
myViewPagerAdapter = new MyViewPagerAdapter();
viewPager.setAdapter(myViewPagerAdapter);
viewPager.addOnPageChangeListener(viewPagerPageChangeListener);
btnSkip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
launchHomeScreen();
}
});
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// checking for last page
// if last page home screen will be launched
int current = getItem(+1);
if (current < layouts.length) {
// move to next screen
viewPager.setCurrentItem(current);
} else {
launchHomeScreen();
}
}
});
}
private void addBottomDots(int currentPage) {
dots = new TextView[layouts.length];
int[] colorsActive = getResources().getIntArray(R.array.array_dot_active);
int[] colorsInactive = getResources().getIntArray(R.array.array_dot_inactive);
dotsLayout.removeAllViews();
for (int i = 0; i < dots.length; i++) {
dots[i] = new TextView(this);
dots[i].setText(Html.fromHtml("•"));
dots[i].setTextSize(35);
dots[i].setTextColor(colorsInactive[currentPage]);
dotsLayout.addView(dots[i]);
}
if (dots.length > 0)
dots[currentPage].setTextColor(colorsActive[currentPage]);
}
private int getItem(int i) {
return viewPager.getCurrentItem() + i;
}
private void launchHomeScreen() {
startActivity(new Intent(WelcomeActivity.this, MainActivity.class));
finish();
}
// viewpager change listener
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
addBottomDots(position);
// changing the next button text 'NEXT' / 'GOT IT'
if (position == layouts.length - 1) {
// last page. make button text to GOT IT
btnNext.setText(getString(R.string.start));
btnSkip.setVisibility(View.GONE);
} else {
// still pages are left
btnNext.setText(getString(R.string.next));
btnSkip.setVisibility(View.VISIBLE);
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
};
/**
* Making notification bar transparent
*/
private void changeStatusBarColor() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
}
}
/**
* View pager adapter
*/
public class MyViewPagerAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
public MyViewPagerAdapter() {
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(layouts[position], container, false);
container.addView(view);
return view;
}
#Override
public int getCount() {
return layouts.length;
}
#Override
public boolean isViewFromObject(View view, Object obj) {
return view == obj;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}
}
}

You are never opening WelcomeActivity - you open MainActivity directly from SplashActivity, so PrefManager is never queried.
What you should do in SplashActivity is:
new Handler().postDelayed(new Runnable() {
/*
* Showing splash screen with a timer. This will be useful when you
* want to show case your app logo / company
*/
#Override
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
Intent i;
if (prefManager.isFirstTimeLaunch()) {
i = new Intent(SpashScreen.this, WelcomeActivity.class);
prefManager.setFirstTimeLaunch(false);
} else {
i = new Intent(SplashScreen.this, MainActivity.class)
}
startActivity(i);
finish();
}
}, SPLASH_TIME_OUT);
And remove all first time launch checking code from WelcomeActivity.

You didn't initialize prefManager, Try initializing it first.
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
public class SpashScreen extends Activity {
private PrefManager prefManager;
// Splash screen timer
private static int SPLASH_TIME_OUT = 3000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
// HERE prefManager INITIALIZED
prefManager = getPreferences(Context.MODE_PRIVATE);
new Handler().postDelayed(new Runnable() {
/*
* Showing splash screen with a timer. This will be useful when you
* want to show case your app logo / company
*/
#Override
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
Intent i;
if (prefManager.isFirstTimeLaunch()) {
i = new Intent(SpashScreen.this, WelcomeActivity.class);
prefManager.setFirstTimeLaunch(false);
} else {
i = new Intent(SpashScreen.this, MainActivity.class);
}
startActivity(i);
finish();
}
}, SPLASH_TIME_OUT);
}
}

You didn't initialize prefManager,this is the right way
this is worked for me.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
try {
int netStatus = NetworkUtil.getConnectivityStatus(getBaseContext());
if (netStatus == 0) {
Intent intent = new Intent(SplashScreen.this,NoInternetActivity.class);
startActivity(intent);
finish();
} else {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
PrefManager prefManager = new PrefManager(getApplicationContext());
// This method will be executed once the timer is over
// Start your app main activity
if(prefManager.isFirstTimeLaunch()){
intent = new Intent(SplashScreen.this, WelcomeActivity.class);
prefManager.setFirstTimeLaunch(true);
}else {
intent = new Intent(SplashScreen.this,MainActivity.class);
}
startActivity(intent);
// close this activity
finish();
}
}, SPLASH_TIME_OUT);
}
}catch (RuntimeException e){
e.printStackTrace();
}
}
#Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
}

Related

How do i modify data on my MainActivity from Settings Activity?

I've tried many other threads and articles but I just can't find the right stuff that I am looking for.
So I have a MainActivity and a SettingsActivity both are java classes. In my main activity there is a button when pressed, increases the count by +1, and shows it on a TextView, it also makes the device vibrate on every increment/Every button press. I want to make a switchpreference in SettingsActivity which if kept off/false, turns off the vibration on button press and if kept on/true, turns on the vibration on button press.
I don't know how to retrieve the state of SwitchPreferenceCompat(ON OR OFF) from SettingsActivity and use it in the MainActivity, so if the user turns the switch off in setting activity, the vibration should stop on button press which is in MainActivity.
I have already used Shared Preferences in MainActivity for saving the current count/number when App is closed and resumes from the same count when reopened.
MainAcitivity
package com.saad.tapcounter;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.preference.PreferenceManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;
public class MainActivity extends AppCompatActivity {
private AdView mAdView ;
int Start;
TextView txt;
Button btnU,btnT,btnR;
Switch sw,sw2;
private ConstraintLayout Clayout;
Vibrator vibe;
Boolean switchPref;
SharedPreferences sharedPreferences;
private static long back_pressed;
private Vibrator Vibrator;
//Double Tap Exit
#Override
public void onBackPressed()
{
if (back_pressed + 2000 > System.currentTimeMillis()) super.onBackPressed();
else Toast.makeText(getBaseContext(), "Press once again to exit!", Toast.LENGTH_SHORT).show();
back_pressed = System.currentTimeMillis();
}
//Inflater for Menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu,menu);
return true;
}
//Menu
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch(item.getItemId()){
case R.id.menui1:
startActivity(new Intent(this, SettingsActivity.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbarid);
setSupportActionBar(toolbar);
MobileAds.initialize(this, "-APPID-");
mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
vibe =(Vibrator)getSystemService(VIBRATOR_SERVICE);
Clayout = findViewById(R.id.MainLayout);
btnT = findViewById(R.id.tapbtn);
btnR = findViewById(R.id.resetbtn);
btnU = findViewById(R.id.undobtn);
sw = findViewById(R.id.swch);
sw2 = findViewById(R.id.darkswch);
txt = findViewById(R.id.txtv);
txt.setTextColor(Color.BLACK);
sharedPreferences = getSharedPreferences("0",MODE_PRIVATE);
loadData();
setData();
incrementbtn();
undobtn();
resetbtn();
switchbtn();
themeswitch();
}
public void loadData(){
sharedPreferences = getSharedPreferences("0",MODE_PRIVATE);
}
private void setData(){
Start = sharedPreferences.getInt("0",0);
if(Start==0){
txt.setText("0");
}
else{
txt.setText(Integer.toString(Start));
}
}
public void incrementbtn(){
btnT.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
incvibe();
if (Start != 0) {
Start = sharedPreferences.getInt("0", 0);
Start += 1;
txt.setText(Integer.toString(Start));
txtresize();
} else {
Start += 1;
txt.setText(Integer.toString(Start));
}
sharedPreferences.edit().putInt("0", Start).apply();
}
});
}
public void undobtn(){
btnU.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
undovibe();
if (Start != 0) {
Start = sharedPreferences.getInt("0", 0);
Start -= 1;
txt.setText(Integer.toString(Start));
}
else{
return;
}
sharedPreferences.edit().putInt("0", Start).apply();
}
});
}
public void resetbtn(){
btnR.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
resetvibe();
Start = 0;
txt.setText(Integer.toString(Start));
sharedPreferences.edit().putInt("0", Start).apply();
}
});
}
public void switchbtn(){
sw.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(sw.isChecked()) {
btnR.setEnabled(false);
btnT.setEnabled(false);
btnU.setEnabled(false);
txt.setTextColor(Color.RED);
}
else{
btnR.setEnabled(true);
btnT.setEnabled(true);
btnU.setEnabled(true);
if(sw2.isChecked()){
txt.setTextColor(Color.WHITE);
}
else{
txt.setTextColor(Color.BLACK);
}
}
}
});
}
public void themeswitch(){
sw2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(sw2.isChecked()){
Clayout.setBackgroundColor(Color.DKGRAY);
if(sw.isChecked()){
txt.setTextColor(Color.RED);
}
else{
txt.setTextColor(Color.WHITE);
}
}
else{
Clayout.setBackgroundColor(Color.WHITE);
if(sw.isChecked()){
txt.setTextColor(Color.RED);
}
else{
txt.setTextColor(Color.BLACK);
}
}
}
});
}
public void txtresize(){
if(Start > 1000 && Start < 10000){
txt.setTextSize(80);
}
else if (Start > 10000 && Start < 100000){
txt.setTextSize(60);
}
else if (Start > 100000){
txt.setTextSize(40);
}
else{
return;
}
}
StringBuilder info = new StringBuilder();
public void undovibe(){
vibe.vibrate(100);
}
public void resetvibe(){
vibe.vibrate(150);
}
public void incvibe(){
vibe.vibrate(40);
}
}//Real one
SettingActivity (created it from NEW > SettingActivity)
I did try some stuff by myself in here but it crashed my app.
package com.saad.tapcounter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Toast;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.PreferenceManager;
public class SettingsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_activity);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.settings, new SettingsFragment())
.commit();
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
public static class SettingsFragment extends PreferenceFragmentCompat {
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.root_preferences, rootKey);
}
}
}
root_preference.xml
<PreferenceScreen xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory app:title="Settings"
app:iconSpaceReserved="false">
<SwitchPreferenceCompat
app:key="Switchsett1"
app:title="Vibration"
app:summaryOff="Turn Vibration On"
app:summaryOn="Turn Vibration Off"
app:iconSpaceReserved="false"
app:defaultValue="true"
/>
<SwitchPreferenceCompat
app:key="Switchset2"
app:iconSpaceReserved="false"
app:summaryOff="#string/attachment_summary_off"
app:summaryOn="#string/attachment_summary_on"
app:title="#string/attachment_title" />
</PreferenceCategory>
</PreferenceScreen>
I don't know how to retrieve the state of switch(ON OR OFF) from SettingsActivity
To get the value of SwitchPreferenceCompat from shared preference, then you need to retrieve it as a Boolean
Now the key of your first SwitchPreferenceCompat is Switchsett1, so to retrieve the value of this:
public class MainActivity extends AppCompatActivity {
Boolean switchPref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
....
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
switchPref = prefs.getBoolean("Switchsett1", false);
Toast.makeText(this, String.valueOf(switchPref), Toast.LENGTH_SHORT).show(); // shows true if the SwitchPreferenceCompat is ON, and false if OFF.
Now the Toast in the above script shows true if the SwitchPreferenceCompat is ON, and false if it's OFF.
You can do the same for Switchset2 SwitchPreferenceCompat

Need a new solution for disabling the home, menu buttons in android

I have searched a lot and tried nearly everything and nothing worked for me .
I just want to disable the home and the menu buttons.
here is the LockScreenActivity.java
import android.app.ActionBar;
import android.app.Activity;
import android.app.KeyguardManager;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.mehuljoisar.lockscreen.utils.LockscreenService;
import com.mehuljoisar.lockscreen.utils.LockscreenUtils;
public class LockScreenActivity extends Activity implements
LockscreenUtils.OnLockStatusChangedListener {
// User-interface
private Button btnUnlock;
private Button button1;
private Button button2;
private Button button3;
private Button button4;
private Button button5;
private Button button6;
private Button button7;
private Button button8;
private Button button9;
private ImageButton button10;
private TextView textView;
private RelativeLayout myView;
// Member variables
private LockscreenUtils mLockscreenUtils;
// Set appropriate flags to make the screen appear over the keyguard
#Override
public void onAttachedToWindow() {
this.getWindow().setType(
WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
this.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN
| WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
);
super.onAttachedToWindow();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_lockscreen);
init();
button1=(Button)findViewById(R.id.button1);
button2=(Button)findViewById(R.id.button2);
button3=(Button)findViewById(R.id.button3);
button4=(Button)findViewById(R.id.button4);
button5=(Button)findViewById(R.id.button5);
button6=(Button)findViewById(R.id.button6);
button7=(Button)findViewById(R.id.button7);
button8=(Button)findViewById(R.id.button8);
button9=(Button)findViewById(R.id.button9);
button10=(ImageButton)findViewById(R.id.button10);
textView=(TextView)findViewById(R.id.textView1);
myView=(RelativeLayout)findViewById(R.id.layout);
// Ask the System Bar to hide
myView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
textView.setText(textView.getText().toString()+"1");
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
textView.setText(textView.getText().toString()+"8");
}
});
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
textView.setText(textView.getText().toString()+"5");
}
});
button4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
textView.setText(textView.getText().toString()+"2");
}
});
button5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
textView.setText(textView.getText().toString()+"7");
}
});
button6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
textView.setText(textView.getText().toString()+"4");
}
});
button7.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
textView.setText(textView.getText().toString()+"9");
}
});
button8.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
textView.setText(textView.getText().toString()+"3");
}
});
button9.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
textView.setText(textView.getText().toString()+"6");
}
});
button10.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(textView.getText().toString().length()>0)
// TODO Auto-generated method stub
textView.setText(textView.getText().toString().substring(0, textView.getText().toString().length()-1));
}
});
// unlock screen in case of app get killed by system
if (getIntent() != null && getIntent().hasExtra("kill")
&& getIntent().getExtras().getInt("kill") == 1) {
enableKeyguard();
unlockHomeButton();
} else {
try {
// disable keyguard
disableKeyguard();
// lock home button
lockHomeButton();
// start service for observing intents
startService(new Intent(this, LockscreenService.class));
// listen the events get fired during the call
StateListener phoneStateListener = new StateListener();
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
telephonyManager.listen(phoneStateListener,
PhoneStateListener.LISTEN_CALL_STATE);
} catch (Exception e) {
}
}
}
private void init() {
mLockscreenUtils = new LockscreenUtils();
btnUnlock = (Button) findViewById(R.id.btnUnlock);
btnUnlock.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// unlock home button and then screen on button press
if(textView.getText().toString().equals("1234"))
unlockHomeButton();
}
});
}
// Handle events of calls and unlock screen if necessary
private class StateListener extends PhoneStateListener {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
super.onCallStateChanged(state, incomingNumber);
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
unlockHomeButton();
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
break;
case TelephonyManager.CALL_STATE_IDLE:
break;
}
}
};
// Don't finish Activity on Back press
#Override
public void onBackPressed() {
return;
}
// Handle button clicks
#Override
public boolean onKeyDown(int keyCode, android.view.KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)
|| (keyCode == KeyEvent.KEYCODE_POWER)
|| (keyCode == KeyEvent.KEYCODE_VOLUME_UP)
|| (keyCode == KeyEvent.KEYCODE_CAMERA)) {
return true;
}
if ((keyCode == KeyEvent.KEYCODE_HOME)) {
return false;
}
return true;
}
// handle the key press events here itself
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP
|| (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_DOWN)
|| (event.getKeyCode() == KeyEvent.KEYCODE_POWER)) {
return false;
}
if ((event.getKeyCode() == KeyEvent.KEYCODE_HOME)) {
return false;
}
return false;
}
// Lock home button
public void lockHomeButton() {
mLockscreenUtils.lock(LockScreenActivity.this);
}
// Unlock home button and wait for its callback
public void unlockHomeButton() {
mLockscreenUtils.unlock();
}
// Simply unlock device when home button is successfully unlocked
#Override
public void onLockStatusChanged(boolean isLocked) {
if (!isLocked) {
unlockDevice();
}
}
#Override
protected void onStop() {
super.onStop();
unlockHomeButton();
}
#SuppressWarnings("deprecation")
private void disableKeyguard() {
KeyguardManager mKM = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
KeyguardManager.KeyguardLock mKL = mKM.newKeyguardLock("IN");
mKL.disableKeyguard();
}
#SuppressWarnings("deprecation")
private void enableKeyguard() {
KeyguardManager mKM = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
KeyguardManager.KeyguardLock mKL = mKM.newKeyguardLock("IN");
mKL.reenableKeyguard();
}
//Simply unlock device by finishing the activity
private void unlockDevice()
{
finish();
}
}
and here is my LockscreenIntentReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.RelativeLayout;
import com.mehuljoisar.lockscreen.LockScreenActivity;
import com.mehuljoisar.lockscreen.R;
public class LockscreenIntentReceiver extends BroadcastReceiver {
// Handle actions and display Lockscreen
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)
|| intent.getAction().equals(Intent.ACTION_SCREEN_ON)
|| intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
start_lockscreen(context);
}
}
// Display lock screen
private void start_lockscreen(Context context) {
Intent mIntent = new Intent(context, LockScreenActivity.class);
mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(mIntent);
}
}
and here is my LockscreenService.java
import android.app.Notification;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.IBinder;
import android.provider.SyncStateContract.Constants;
import android.support.v4.app.NotificationCompat;
import com.mehuljoisar.lockscreen.R;
public class LockscreenService extends Service {
private BroadcastReceiver mReceiver;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
// Register for Lockscreen event intents
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
mReceiver = new LockscreenIntentReceiver();
registerReceiver(mReceiver, filter);
startForeground();
return START_STICKY;
}
// Run service in foreground so it is less likely to be killed by system
private void startForeground() {
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle(getResources().getString(R.string.app_name))
.setTicker(getResources().getString(R.string.app_name))
.setContentText("Running")
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(null)
.setOngoing(true)
.build();
startForeground(9999,notification);
}
// Unregister receiver
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mReceiver);
}
}
and here is my LockscreenUtils.java
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.KeyguardManager;
import android.content.Context;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.RelativeLayout;
import com.mehuljoisar.lockscreen.R;
public class LockscreenUtils {
// Member variables
private OverlayDialog mOverlayDialog;
private OnLockStatusChangedListener mLockStatusChangedListener;
// Interface to communicate with owner activity
public interface OnLockStatusChangedListener
{
public void onLockStatusChanged(boolean isLocked);
}
// Reset the variables
public LockscreenUtils() {
reset();
}
// Display overlay dialog with a view to prevent home button click
public void lock(Activity activity) {
if (mOverlayDialog == null) {
mOverlayDialog = new OverlayDialog(activity);
mOverlayDialog.show();
mLockStatusChangedListener = (OnLockStatusChangedListener) activity;
}
}
// Reset variables
public void reset() {
if (mOverlayDialog != null) {
mOverlayDialog.dismiss();
mOverlayDialog = null;
}
}
// Unlock the home button and give callback to unlock the screen
public void unlock() {
if (mOverlayDialog != null) {
mOverlayDialog.dismiss();
mOverlayDialog = null;
if(mLockStatusChangedListener!=null)
{
mLockStatusChangedListener.onLockStatusChanged(false);
}
}
}
// Create overlay dialog for lockedscreen to disable hardware buttons
private static class OverlayDialog extends AlertDialog {
public OverlayDialog(Activity activity) {
super(activity, R.style.OverlayDialog);
WindowManager.LayoutParams params = getWindow().getAttributes();
getActionBar().setDisplayHomeAsUpEnabled(false);
params.type = LayoutParams.TYPE_SYSTEM_ERROR;
params.dimAmount = 0.0F;
params.width = 0;
params.height = 0;
params.gravity = Gravity.BOTTOM;
getWindow().setAttributes(params);
getWindow().setFlags(LayoutParams.FLAG_SHOW_WHEN_LOCKED | LayoutParams.FLAG_NOT_TOUCH_MODAL,
0xffffff);
setOwnerActivity(activity);
setCancelable(false);
}
// consume touch events
public final boolean dispatchTouchEvent(MotionEvent motionevent) {
return true;
}
}
}
last but not least .. here is my manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mehuljoisar.lockscreen"
android:versionCode="3"
android:versionName="1.2" >
<uses-sdk android:minSdkVersion="11" />
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name="com.mehuljoisar.lockscreen.LockScreenActivity"
android:excludeFromRecents="true"
android:label="#string/app_name"
android:launchMode="singleTask"
android:screenOrientation="portrait"
android:theme="#android:style/Theme.Holo.NoActionBar.Fullscreen" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".utils.LockscreenService" >
</service>
<receiver
android:name=".utils.LockscreenIntentReceiver"
android:enabled="true" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>
Use below method for hiding home/menu button:
getActionBar().setDisplayHomeAsUpEnabled(false)
Or use
getActionBar().setHomeButtonEnabled (false)
to disable interaction with the home/up affordance.

Android fragment app errors

I have this calendar app that I am trying to add into a tabs action bar. But when I join all the code together to try and complete the app i get many errors.
Caused by: android.content.ActivityNotFoundException: Unable to find explicit activity class
It tells me that I should try and add it into the android manifest but as they are fragments surely you cant add fragments to the android manifest, anyway here is my code...
package com.idkstudios.shiftcalculator;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import com.idkstudios.shiftcalculator.tab.TabsPagerAdapter;
public class MainActivity extends AppCompatActivity implements ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter adapter;
private ActionBar actionBar;
/**
* Tab titles
*/
private String[] tabTitles = {"Hours List", "Calendar", "Pay"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getSupportActionBar();
adapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
/**
* For adding tabs
*/
for(String tabs : tabTitles){
actionBar.addTab(actionBar.newTab().setText(tabs).setTabListener(this));
}
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
#Override
public void onTabSelected(ActionBar.Tab tab, android.support.v4.app.FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(ActionBar.Tab tab, android.support.v4.app.FragmentTransaction ft) {
}
#Override
public void onTabUnselected(ActionBar.Tab tab, android.support.v4.app.FragmentTransaction ft) {
}
}
That was my main activity this is the three fragments,
package com.idkstudios.shiftcalculator.fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.TextView;
import com.idkstudios.shiftcalculator.R;
import com.idkstudios.shiftcalculator.calendar.adapter.CalendarAdapter;
import com.idkstudios.shiftcalculator.calendar.util.CalendarCollection;
import java.util.GregorianCalendar;
/**
* Created by Toby on 02/09/2015.
*/
public class CalendarFragment extends Fragment {
/**
* The basic variables that you will need for the calendar
*/
public GregorianCalendar cal_month, cal_month_copy;
private CalendarAdapter cal_adapter;
private TextView tv_month;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/**
* Sets up the basic layout file, we return this later
*/
View rootView = inflater.inflate(R.layout.fragment_calendar, container, false);
cal_month = (GregorianCalendar) GregorianCalendar.getInstance();
cal_month_copy = (GregorianCalendar) cal_month.clone();
cal_adapter = new CalendarAdapter(getActivity(), cal_month, CalendarCollection.date_collection_arr);
tv_month = (TextView) getActivity().findViewById(R.id.tv_month);
tv_month.setText(android.text.format.DateFormat.format("MMMM yyyy", cal_month));
ImageButton previous = (ImageButton) getActivity().findViewById(R.id.ib_prev);
previous.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setPreviousMonth();
refreshCalendar();
}
});
ImageButton next = (ImageButton) getActivity().findViewById(R.id.Ib_next);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setNextMonth();
refreshCalendar();
}
});
GridView gridview = (GridView) getActivity().findViewById(R.id.gv_calendar);
gridview.setAdapter(cal_adapter);
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
((CalendarAdapter) parent.getAdapter()).setSelected(v,position);
String selectedGridDate = CalendarAdapter.day_string
.get(position);
String[] separatedTime = selectedGridDate.split("-");
String gridvalueString = separatedTime[2].replaceFirst("^0*","");
int gridvalue = Integer.parseInt(gridvalueString);
if ((gridvalue > 10) && (position < 8)) {
setPreviousMonth();
refreshCalendar();
} else if ((gridvalue < 7) && (position > 28)) {
setNextMonth();
refreshCalendar();
}
((CalendarAdapter) parent.getAdapter()).setSelected(v,position);
((CalendarAdapter) parent.getAdapter()).getPositionList(selectedGridDate, getActivity());
}
});
return rootView;
}
protected void setNextMonth() {
if (cal_month.get(GregorianCalendar.MONTH) == cal_month
.getActualMaximum(GregorianCalendar.MONTH)) {
cal_month.set((cal_month.get(GregorianCalendar.YEAR) + 1),
cal_month.getActualMinimum(GregorianCalendar.MONTH), 1);
} else {
cal_month.set(GregorianCalendar.MONTH,
cal_month.get(GregorianCalendar.MONTH) + 1);
}
}
protected void setPreviousMonth() {
if (cal_month.get(GregorianCalendar.MONTH) == cal_month
.getActualMinimum(GregorianCalendar.MONTH)) {
cal_month.set((cal_month.get(GregorianCalendar.YEAR) - 1),
cal_month.getActualMaximum(GregorianCalendar.MONTH), 1);
} else {
cal_month.set(GregorianCalendar.MONTH,
cal_month.get(GregorianCalendar.MONTH) - 1);
}
}
public void refreshCalendar() {
cal_adapter.refreshDays();
cal_adapter.notifyDataSetChanged();
tv_month.setText(android.text.format.DateFormat.format("MMMM yyyy", cal_month));
}
}
The second fragment
package com.idkstudios.shiftcalculator.fragments;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import com.idkstudios.shiftcalculator.R;
import com.idkstudios.shiftcalculator.calendar.adapter.AndroidListAdapter;
import com.idkstudios.shiftcalculator.calendar.util.CalendarCollection;
import java.util.ArrayList;
/**
* Created by Toby on 02/09/2015.
*/
public class HoursListFragment extends Fragment implements View.OnClickListener{
private ListView lv_android;
private AndroidListAdapter list_adapter;
private Button btn_calender;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_hours, container, false);
CalendarCollection.date_collection_arr = new ArrayList<CalendarCollection>();
CalendarCollection.date_collection_arr.add(new CalendarCollection("2015-04-01","John Birthday"));
CalendarCollection.date_collection_arr.add(new CalendarCollection("2015-04-04","Client Meeting at 5 p.m."));
CalendarCollection.date_collection_arr.add(new CalendarCollection("2015-04-06","A Small Party at my office"));
CalendarCollection.date_collection_arr.add(new CalendarCollection("2015-05-02","Marriage Anniversary"));
CalendarCollection.date_collection_arr.add(new CalendarCollection("2015-04-11","Live Event and Concert of sonu"));
getWidget();
return rootView;
}
public void getWidget(){
btn_calender = (Button) getActivity().findViewById(R.id.btn_calender);
btn_calender.setOnClickListener(this);
lv_android = (ListView) getActivity().findViewById(R.id.lv_android);
list_adapter = new AndroidListAdapter(getActivity(), R.layout.list_item, CalendarCollection.date_collection_arr);
lv_android.setAdapter(list_adapter);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btn_calender:
startActivity(new Intent(getActivity(), CalendarFragment.class));
break;
default:
break;
}
}
}
And finally the third which I havent actually coded yet,
package com.idkstudios.shiftcalculator.fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.idkstudios.shiftcalculator.R;
/**
* Created by Toby on 02/09/2015.
*/
public class PayFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_pay, container, false);
return rootView;
}
}
Here is the android manifest if you needed it
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.idkstudios.shiftcalculator" >
<application
android:allowBackup="true"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Here is the adapter class for the main activity
package com.idkstudios.shiftcalculator.tab;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.idkstudios.shiftcalculator.fragments.CalendarFragment;
import com.idkstudios.shiftcalculator.fragments.HoursListFragment;
import com.idkstudios.shiftcalculator.fragments.PayFragment;
/**
* Created by Toby on 02/09/2015.
*/
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fragmentManager){
super(fragmentManager);
}
#Override
public Fragment getItem(int index) {
switch(index){
case 0:
return new HoursListFragment();
case 1:
return new CalendarFragment();
case 2:
return new PayFragment();
}
return null;
}
#Override
public int getCount() {
/**
* This value is equal to the number of tabs you have in the bar
*/
return 3;
}
}
I did think about having a second plan. The three fragments all came from a activity class, so i copied and pasted the code from the activity class into the fragment so that might be where the issue is. I thought about having the original acitivty classes and just start a new intent from the fragment class to the activity class. But then what would the point of the fragment class be then. Im not too sure if this idea would work in the first place.
Any help would be much appreicated. And if you need any more code please let me know and I will happily provide it, whether that is some of the adapters or the xml code.
Thanks Toby.
HoursListFragment.onClick() has this buggy statement:
startActivity(new Intent(getActivity(), CalendarFragment.class));
As you already know, a fragment is not an activity. Did you mean to pass MainActivity.class instead of CalendarFragment.class?
i think problem is your viewpager adapter,
and your MainActivity is better to extend FragmentActivity
because you want to use fragments
then define three fields in MainActivity class like this
CalendarFragment calenderFragment = new CalendarFragment ();
HoursListFragment hourListFragment = new HoursListFragment ();
PayFragment payFragment = new PayFragment ();
and one integer as NUMBER_OF_VIEWPAGER_PAGES
or shorter variable name like NUM_PAGE
public static final int NUM_PAGES = 3;
and make an adapter to your view pager , like this
private class MyAdapter extends FragmentStatePagerAdapter {
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return tabTitles[0] ;
case 1:
return tabTitles[1] ;
default:
return tabTitles[2] ;
}
}
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return calenderFragment;
case 1:
return hourListFragment;
case 2:
return payFragment;
default:
return null;
}
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
finally set adapter to your viewPager
viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));

How do make the buttons in a fragment manipulate integer variables in seperate activity?

This is a rudimentary android application that serves as an umpires strike/ball/out counter. There is a settings icon in the action bar of the MainActivity. When this icon is 'clicked on', a new Activity is started consisting of a PreferenceFragment, which consists of a checkboxpreference, and a Fragment that consists of 3 buttons. These buttons reset the stike_count, ball_count and total_outs_count to zero. I have spent a day on this and am having trouble figuring out how to manipulate integer variables in my MainActivity from button clicks in a separate Activity's Fragment. Please point me in the right direction.
MyApplication class
////////////////////////////////////////////////
package edu.umkc.baldwin;
import android.app.Application;
public class MyApplication extends Application {
private int strikes, balls, outs;
#Override
public void onCreate() {
super.onCreate();
strikes = 0;
balls = 0;
outs = 0;
}
public void setStrikeCount(int strike_c){
this.strikes = strike_c;
}
public void setBallCount(int ball_c){
this.balls = ball_c;
}
public void setOutsCount(int out_c){
this.outs = out_c;
}
public int getStrikeCount(){
return strikes;
}
public int getBallCount(){
return balls;
}
public int getOutCount(){
return outs;
}
}
MainActivity
//////////////////////////////////////////////////////////
package edu.umkc.baldwin;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
/*
* MainAcitvity extends the Activity class and provides all the functionality
* of the homescreen (main_page_layout) widgets including the actionbar items and presumably the
* menu button on the bottom left of the device (on most devices).
*/
public class MainActivity extends Activity {
private static final String TAG = "UmpireActivity";
MyApplication app = (MyApplication) getApplication();
TextView strikeCounterTV;
TextView ballCounterTV;
TextView totalOutCounterTV;
private Button strikeCounterButton;
private Button ballCounterButton;
private int strike_count;
private int ball_count;
private int out_count;
/*
* Method to update the TextViews representing balls,
* outs and strikes
*/
public void updateViews(){
strikeCounterTV.setText(String.valueOf(strike_count));
ballCounterTV.setText(String.valueOf(ball_count));
totalOutCounterTV.setText(String.valueOf(out_count));
}
/*
* Method to display a Toast message to the user when
* strikes have reached 3 or balls have reached 4
*/
private void displayToast(boolean x){
int messageId = 0;
if (x == true){
messageId = R.string.strike_toast_view;
} else {
messageId = R.string.ball_toast_view;
}
Toast toast = Toast.makeText(MainActivity.this, messageId, Toast.LENGTH_SHORT);
LinearLayout toastLayout = (LinearLayout) toast.getView();
TextView toastTV = (TextView) toastLayout.getChildAt(0);
toast.setGravity(Gravity.CENTER|Gravity.CENTER, 0, -150);
toastTV.setTextSize(42);
toast.show();
}
/*
* (non-Javadoc)
* #see android.app.Activity#onCreate(android.os.Bundle)
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "OnCreate(Bundle) called");
setContentView(R.layout.main_page_layout);
strikeCounterTV = (TextView) findViewById(R.id.strikeCountTextView);
ballCounterTV = (TextView) findViewById(R.id.ballCountTextView);
totalOutCounterTV = (TextView) findViewById(R.id.totalOutsTextViewCounter);
strikeCounterButton = (Button) findViewById(R.id.strikeCountButton);
ballCounterButton = (Button) findViewById(R.id.ballCountButton);
strikeCounterButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
if (strike_count < 2){
strike_count++;
updateViews();
} else {
// batter has reached strike limit
displayToast(true);
out_count++;
strike_count = 0;
ball_count = 0;
updateViews();
}
}
});
ballCounterButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
if (ball_count < 3){
ball_count++;
updateViews();
} else {
// batter has reached ball limit
displayToast(false);
strike_count = 0;
ball_count = 0;
updateViews();
}
}
});
// http://developer.android.com/training/basics/data-storage/shared-preferences.html
SharedPreferences savedObject = getPreferences(Context.MODE_PRIVATE);
out_count = savedObject.getInt("outs_key", 0);
strike_count = savedObject.getInt("strikes_key", 0);
ball_count = savedObject.getInt("balls_key", 0);
updateViews();
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
Log.d(TAG, "onSaveInstanceState() called");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//Displays actionbar items in app actionbar
getMenuInflater().inflate(R.menu.actionbar_layout, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
super.onOptionsItemSelected(item);
switch (item.getItemId()){
case (R.id.about_menu_option):
Intent i = new Intent(this, About.class);
startActivity(i);
return true;
case (R.id.reset_option):
strike_count = 0;
ball_count = 0;
updateViews();
return true;
case (R.id.settings_menu_option):
Intent j = new Intent(this, SettingsActivity.class);
startActivity(j);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onStart() {
super.onStart();
Log.d(TAG, "onStart() called");
}
#Override
public void onPause() {
super.onPause();
Log.d(TAG, "onPause() called");
app.setStrikeCount(strike_count);
// SHOULD THIS CODE BE IN onPause()
// OR onStop() ??????????????????????????????????????????????????????
// store value of out_count to restore after application exit
// http://developer.android.com/training/basics/data-storage/shared-preferences.html
SharedPreferences out_file = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = out_file.edit();
editor.putInt("outs_key", out_count);
editor.putInt("strikes_key", strike_count);
editor.putInt("balls_key", ball_count);
editor.commit();
}
#Override
public void onResume() {
super.onResume();
Log.d(TAG, "onResume() called");
// Save 'totalOuts' variable through application exit
// http://developer.android.com/training/basics/data-storage/shared-preferences.html
SharedPreferences savedObject = getPreferences(Context.MODE_PRIVATE);
out_count = savedObject.getInt("outs_key", 0);
strike_count = savedObject.getInt("strikes_key", 0);
ball_count = savedObject.getInt("balls_key", 0);
updateViews();
}
#Override
public void onStop() {
super.onStop();
Log.d(TAG, "onStop() called");
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy() called");
}
}
SettingsActivity
/////////////////////////////////////////////////////////////////////
package edu.umkc.baldwin;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
public class SettingsActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_layout);
FragmentManager ttsFragmentManager = getFragmentManager();
FragmentTransaction ttsFragmentTransaction = ttsFragmentManager.beginTransaction();
EnableTTSPreferenceFragment ttsFragment = new EnableTTSPreferenceFragment();
ttsFragmentTransaction.add(R.id.tts_fragment, ttsFragment);
ttsFragmentTransaction.commit();
FragmentManager resetFragmentManager = getFragmentManager();
FragmentTransaction resetFragmentTransaction = resetFragmentManager.beginTransaction();
ResetFragment resetFragment = new ResetFragment();
resetFragmentTransaction.add(R.id.reset_fragment, resetFragment);
resetFragmentTransaction.commit();
}
}
ResetFragment
///////////////////////////////////////////////////////////////
package edu.umkc.baldwin;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class ResetFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View resetFragment = inflater.inflate(R.layout.reset_layout, container, false);
return resetFragment;
}
}
EnableTTSPreferenceFragment
//////////////////////////////////////////////////////////////////////
package edu.umkc.baldwin;
import android.os.Bundle;
import android.preference.PreferenceFragment;
public class EnableTTSPreferenceFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.tts_preference_fragment);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
}
Android manifest file
///////////////////////////////////////////////////////////////////
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="edu.umkc.baldwin"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="#drawable/umpire_buddy_icon"
android:name="edu.umkc.baldwin.MyApplication"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="edu.umkc.baldwin.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="edu.umkc.baldwin.About"
android:parentActivityName="edu.umkc.baldwin.MainActivity"
android:label="#string/about_menu_text" >
</activity>
<activity
android:name="edu.umkc.baldwin.Settings"
android:parentActivityName="edu.umkc.baldwin.MainActivity"
android:label="#string/settings_text" >
</activity>
<activity
android:name="edu.umkc.baldwin.SettingsActivity"
android:parentActivityName="edu.umkc.baldwin.MainActivity"
android:label="#string/settings_text" >
</activity>
</application>
</manifest>
Extend Application object and save the strike count values in that. All the activities have access to it. Update it from settings and the main activity will be able to see the change as well.
When you start the setting activity, do startActivityForResult and make the setting activity return a result, which you can use to update your counts.
AFAIK Fragments are in context of a particular Activity and public methods in the activity can be accessed like getActivity().methodName().
Now If you want to change any data that has to be changed from the fragment then you may go by any of these two approaches :
From your fragment call a public method of you base activity and within that public method you can get the context of MainActivity and change its public variables.
I am not sure about the design or flow of your application but will recommend to create static variables and access and modify them using class names easily
Use Application class to solve this. Here is an example code for this solution:
1. Create the Application Class.
public class MyApplication extends Application {
private int strike_count, ball_count, out_count;
#Override
public void onCreate() {
super.onCreate();
//initialize the variables here
strike_count = 0;
ball_count = 0;
out_count = 0;
}
// create set and get functions
public void setStrikeCount(int strike_count) {
this.strike_count = strike_count;
}
public void setBallCount(int ball_count) {
this.ball_count = ball_count;
}
public void setOutCount(int out_count) {
this.out_count = out_count;
}
public int getStrikeCount() {
return strike_count;
}
public int getBallCount() {
return ball_count;
}
public int getOutCount() {
return out_count;
}
}
2. Mention this Application class in your manifest file.
<application android:name="yourpackagename.MyApplication"/>
3. Access the application object in any activity by using the following code.
MyApplication app = (MyApplication) getApplication();
After you get this done, you can manipulate these variables in any activity by simply using any of the Application's public function such as:
app.setStrikeCount(10);

Transition to a black screen

I believe I have my code set up correctly but when I try to debug it, after it transitions from the splash screen it just goes right to a black screen. I know I imported the layout correctly but it still goes black.
This is the code for the splash screen
package com.example.equate.jones;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.NavUtils;
public class EJ_Splash extends Activity {
protected boolean _active = true;
protected int _splashTime = 3000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ej__splash);
// thread for displaying the SplashScreen
Thread splashTread = new Thread() {
#Override
public void run() {
try {
synchronized(this){
wait(4000);
}
}
catch(InterruptedException e) {
// do nothing
} {
finish();
Intent i = new Intent(getApplicationContext(),EJ_Board.class);
startActivity(i);
}
}
};
splashTread.start();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_ej__splash, menu);
return true;
}
}
This is the code for the screen it is supposed to transition to.
package com.example.equate.jones;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
public class EJ_Board extends Activity {
private ImageView button1;
final MediaPlayer mp = MediaPlayer.create(this, R.raw.warm);
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ej_board);
button1=(ImageView)findViewById(R.id.imageView1);
button1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
mp.start();
}
});
}
}
This is the xml for EJ_Board
<?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="match_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher" />
</LinearLayout>
I think your problem is with the ImageView. You need to add an image to your drawable folder, then change your android:src="#drawable/ic_launcher" to the name of the image you saved. This will give you the image you need for your button. Hope that helps
Edit:
For your splash screen, try something like this:
public class SplashActivity extends Activity {
private long splashDelay = 5000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
TimerTask task = new TimerTask()
{
#Override
public void run() {
finish();
Intent homeIntent = new Intent().setClass(SplashActivity.this, HomeActivity.class);
startActivity(homeIntent);
}
};
Timer timer = new Timer();
timer.schedule(task, splashDelay);
}
}
Then in your home activity you can set your menu:
public class HomeActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.layout.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.locationButton:
Intent locationIntent = new Intent(this, LocationActivity.class);
startActivity(locationIntent);
return true;
case R.id.diningButton:
Intent diningIntent = new Intent(this, DiningActivity.class);
startActivity(diningIntent);
return true;
case R.id.topXXVButton:
Intent topIntent = new Intent(this, DiningActivity.class);
startActivity(topIntent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Try this:
public class SplashActivity extends Activity {
private long splashDelay = 5000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
TimerTask task = new TimerTask()
{
#Override
public void run() {
finish();
Intent mainIntent = new Intent().setClass(EJ_Splash.this, EJ_Board.class);
startActivity(mainIntent);
}
};
Timer timer = new Timer();
timer.schedule(task, splashDelay);
}
}

Categories