How initialize correctly static variable in PreferenceActivity - java

I have Preference class extent PreferenceActivity.
I create public static String quality; in Preference.class i add in onCreate
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref);
quality = "QUALITY_HIGH";//initialize
}
and add in Preference.class this method
public void getQuality() {
if (keyquality.equals("480p")) {
quality = "QUALITY_LOW";
//
}
if (keyquality.equals("720p")) {
//
quality = "QUALITY_720P";
}
if (keyquality.equals("1080p")) {
//
quality = "QUALITY_HIGH";
}
}
in another class i create method to get my variable and set settings
private void getqualityvideo() {
/*if (Prefernce.quality == null) {
preferencecamrecoder = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
} else {*/
if (Prefernce.quality.equals("QUALITY_LOW")) {
preferencecamrecoder = CamcorderProfile.get(CamcorderProfile.QUALITY_LOW);
}
if (Prefernce.quality.equals("QUALITY_720P")) {
preferencecamrecoder = CamcorderProfile.get(CamcorderProfile.QUALITY_720P);
}
if (Prefernce.quality.equals("QUALITY_HIGH")) {
preferencecamrecoder = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
}
// }
}
Problem:
when start application
private void startServes() {
btnStart = (ImageView) findViewById(R.id.StartService);
btnStart.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
v.startAnimation(mAnimationImage);
Intent intent = new Intent(MainActivity.this, RecorderService.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startService(intent);
changeCamera
.setEnabled(false);
btnStart.setEnabled(false);
setings.setEnabled(false);
moveTaskToBack(false);
}
});
}
in another class in method
getqualityvideo() error NullPointerException
error in this first line
if (Prefernce.quality.equals("QUALITY_LOW"))
why the quality variable is empty?

The reason is that you're setting Preference.quality in the onCreate method in your Preference class. So what's probably happening is that when you start your application in your other class, Preference.quality is going to be null because it was never initialized to anything. The reason is that the other class has no way to access the onCreate method in your Preference class as of now. onCreate is executed when an activity starts, but that doesn't seem to happen anywhere in your code. A solution could be to initialize public static String quality outside of your onCreate method but still within the Preference class,
public static String quality = "QUALITY_HIGH";
#Override
public void onCreate(Bundle savedInstanceState) {
//insert code here
}
The problem was merely a scope issue.

Related

setOnClickListener not responding when button is clicked

I am fairly new to java but in this case, the button is not responding at all when it is clicked, no errors in the logcat are showing up, the ID of the button is correct and no other posts on here helped solve the issue, this is not all the code but hopefully, this will be enough.
public class activity_main extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_layout);
getSupportActionBar().hide();
}
int error_count;
public void on_click() {
Button page_2 = findViewById(R.id.page_2);
page_2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
int mother_edu_input = Integer.parseInt(((EditText) findViewById(R.id.mother_edu_input)).getText().toString());
error_writer("Text_View_Warning_1", mother_edu_input, 4);
if (error_count > 0) {
throw new NullPointerException();
} else {
Intent page_1_button = new Intent(activity_main.this, revision_time.class);
startActivity(page_1_button);
}
} catch (NullPointerException npe) {
}
}
});
}
You set your listener inside a method called on_click() and it doesn't appear like you call this method anywhere.
You should probably call on_click() inside your onCreate() to set the listener when creating your activity.

Set Receive Intent back to Default Value in Android using Java

FirstActivity.java
startActivity(new Intent(FirstActivity.this, SecondActivity.class)
.putExtra("passed_value", true));
SecondActivity.java
#Override
public void onPageFinished(final WebView view, String url) {
if(getIntent().getBooleanExtra("passed_value", false)){
}
}
After receiving intent value from FirstActivity.java every reload it runs the if block . But i need this intent to run only in onPageFinished method.
So how to run if block only when it comes from FirstActivity.java. Is there any way so that i can make this intent value back to default value after if block executed?
In your SecondActivity create a class level variable as boolean passed_value = false;
Then in your onCreate(), change its value like - passed_value = getIntent().getBooleanExtra("passed_value", false);
Finally you can use it like -
#Override
public void onPageFinished(final WebView view, String url) {
if(passed_value){
}
}
A fairly straight forward method would be to have a Boolean passedValue variable that you instantiate with the intent extra in onCreate, and then set as false in the if block. Something along the following lines should work,
public class SecondActivity extends AppCompatActivity {
Boolean passedValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
passedValue = getIntent().getBooleanExtra("passed_value", false);
//Other code things
}
#Override
public void onPageFinished(final WebView view, String url) {
if(passedValue){
//Do what you need to do
passedValue = false
}
}
}

Attempt to read from null array android

I have been trying to implement a passcodeView library in my project for easier login instead of the default login feature. I have followed all the steps but I keep getting an error I have been unable to resolve. Please I need solutions.
The array keeps returning null and crashing my app but it is not null.
link
public class QuickLoginActivity extends AppCompatActivity {
private static final String ARG_CURRENT_PIN = "current_pin";
private PinView mPinView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quick_login);
//Set the correct pin code.
//REQUIRED
mPinView = findViewById(R.id.pattern_view);
final int[] correctPattern = new int[]{1, 2, 3, 4};
mPinView.setPinAuthenticator(new PasscodeViewPinAuthenticator(correctPattern));
//Build the desired key shape and pass the theme parameters.
//REQUIRED
mPinView.setKey(new RoundKey.Builder(mPinView)
.setKeyPadding(R.dimen.key_padding)
.setKeyStrokeColorResource(R.color.colorAccent)
.setKeyStrokeWidth(R.dimen.key_stroke_width)
.setKeyTextColorResource(R.color.colorAccent)
.setKeyTextSize(R.dimen.key_text_size));
//Build the desired indicator shape and pass the theme attributes.
//REQUIRED
mPinView.setIndicator(new CircleIndicator.Builder(mPinView)
.setIndicatorRadius(R.dimen.indicator_radius)
.setIndicatorFilledColorResource(R.color.colorAccent)
.setIndicatorStrokeColorResource(R.color.colorAccent)
.setIndicatorStrokeWidth(R.dimen.indicator_stroke_width));
mPinView.setPinLength(4);
mPinView.setTitle("Enter the PIN");
mPinView.setAuthenticationListener(new AuthenticationListener() {
#Override
public void onAuthenticationSuccessful() {
//User authenticated successfully.
//Navigate to secure screens.
startActivity(new Intent(QuickLoginActivity.this, MainActivity.class));
finish();
}
#Override
public void onAuthenticationFailed() {
//Calls whenever authentication is failed or user is unauthorized.
//Do something
}
});
}
private void sendToLogin() {
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putIntArray(ARG_CURRENT_PIN, mPinView.getCurrentTypedPin());
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mPinView.setCurrentTypedPin(savedInstanceState.getIntArray(ARG_CURRENT_PIN));
}
}
StackTrace
E/UncaughtException: java.lang.NullPointerException: Attempt to read from null array
at com.kevalpatel.passcodeview.internal.BoxKeypad.measureView(BoxKeypad.java:181)
at com.kevalpatel.passcodeview.PinView.measureView(PinView.java:182)
at com.kevalpatel.passcodeview.internal.BasePasscodeView.onMeasure(BasePasscodeView.java:212)
at android.view.View.measure(View.java:20665)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:825)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:511)
at android.view.View.measure(View.java:20665)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6320)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:214)
at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLay
It happens because you don't set key names. You should add:
mPinView.setKeyNames(new KeyNamesBuilder());

How do I call one method of an activity from another class

This is a part of my activity class,
public class StatusActivity extends AppCompatActivity {
private boolean cFlag = false;
public boolean getFlag() { return cFlag; }
public void setFlag(boolean cFlag) {
this.cFlag = cFlag;
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,
android.R.id.text1, messages);
ListView listView = findViewById(android.R.id.list);
listView.setAdapter(adapter);
adapters.add(adapter);
Button btn = findViewById(R.id.btnCustomerCheckIn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setFlag(true);
cFlag = getFlag();
Intent intent = new Intent(StatusActivity.this, MainActivity.class);
Toast.makeText(StatusActivity.this, "customer checked in",
Toast.LENGTH_LONG).show();
startActivity(intent);
}
});
}
this is a part of another class named as position
public class Position {
StatusActivity statusactivity = new StatusActivity();
public boolean ccflag = statusactivity.getFlag();
statusactivity.setFlag(false);
}
when i am calling
statusactivity.setFlag(false);
it is showing an error. couldn't recognize that what is the error that i am getting. but
statusactivity.getFlag();
is working properly. any help is appreciated
StatusActivity statusactivity = new StatusActivity();
This is totally wrong because you are trying to create a new Instance of activity.
If you want to use "setFlag" method from other activity then you must create a static method inside StatusActivity so you can access using directly StatusActivity.
And If you want to call from any fragment of this activity then please get an instance of this activity by the cast from "getActivity()" to StatusActivity and use that instance for call "setFlag" or "getFlag" method.
You can implement like below in Activity.
private static boolean cFlag = false;
public static boolean getFlag() {
return cFlag;
}
public static void setFlag(boolean cFlag) {
StatusActivity.cFlag = cFlag;
}
and call from position class like below
public class Position {
public boolean ccflag = StatusActivity.getFlag();
StatusActivity.setFlag(false);
}
you can not instantiate Activity class. if you want to call a method from activity, fist you should check that activity already running and not destroyed then by having the context of your class you just cast it like below then use its method
StatusActivity statusactivity= (StatusActivity )context;
statusactivity.setFlag(false);

show app lock pattern dialog when unlocking the phone

I have MainActivity and on its onResume method I call pattern lock to create and confirm user identity. User visits and leave this MainActivity back and forth while active on the app as well as when phone is in sleep mode and user unlocks it. These both scenarios will call onRestart, onStart and onResume methods, but I only want to revoke the pattern in unlock scenario.
handlePattern() method needs a proper distinguishing to be called.
How to distinguish this when I call the handlePattern method ?
MainActivity.class
onCreate(){}
onResume(){
//help needed to know that user is just visiting activity in app back and forth
or came back after unlocking the screen.
if(isPatternCallRequired){
handlePattern()
}
}
In your onStop() method call you can check if the player is in sleep mode and cache the boolean.
PowerManager pm = (PowerManager)
_context.getSystemService(Context.POWER_SERVICE);
boolean isInSleepMode = !pm.isScreenOn();
Check for the build version
if( Build.VERSION.SDK_INT >= 20)
// use isInteractive()
else
// use isScreenOn()
in onRestart which will get called when you resume from sleep - based on the cached value you can show the pattern to unlock.
You may need to reset the cached value once you are done using it.
onResume may not be a right API for the call as it will be called even when your activity loads.
Edited answer based on your comment
You can try ActivityLifecycleCallbacks too like this,
First, Register your Application in your Application class.
public class StackApp extends Application {
private static final String TAG = StackApp.class.getSimpleName();
public static final String INTENT_ACTION_APP_STATE_CHANGE = "intent_action_app_state_change";
public static final String INTENT_DATA_IS_IN_BACKGROUND = "intent_data_is_in_background";
private static int mNumRunningActivities = 0;
private static AtomicBoolean mIsAppInForeground = new AtomicBoolean();
#Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT >= 14) {
// registerActivityLifecycleCallbacks is supported only from the SDK version 14.
registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
#Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
#Override
public void onActivityStarted(Activity activity) {
mNumRunningActivities++;
if (mNumRunningActivities == 1) {
notifyAppState(false);
Log.i(TAG, "APP IN FOREGROUND");
}
}
#Override
public void onActivityResumed(Activity activity) {
}
#Override
public void onActivityPaused(Activity activity) {
}
#Override
public void onActivityStopped(Activity activity) {
mNumRunningActivities--;
if (mNumRunningActivities == 0) {
notifyAppState(true);
}
}
#Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
#Override
public void onActivityDestroyed(Activity activity) {
}
});
}
}
/**
* To notify App state whether its in ForeGround or in Background
*
* #param isInBackground
*/
private void notifyAppState(boolean isInBackground) {
if (isInBackground) {
mIsAppInForeground.set(false);
} else {
mIsAppInForeground.set(true);
}
sendAppStateChangeBroadcast(isInBackground);
}
public static boolean isInForeground() {
return mIsAppInForeground.get();
}
private void sendAppStateChangeBroadcast(boolean isInBackground) {
Log.i(TAG, "sendAppStateChangeBroadcast - isInBackground : " + isInBackground);
Intent intent = new Intent();
intent.setAction(INTENT_ACTION_APP_STATE_CHANGE);
intent.putExtra(INTENT_DATA_IS_IN_BACKGROUND, isInBackground);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
}
And register the broadcast and listen whether the App is going background or foreground like this Sample Activity example
public class SampleMyActivity extends AppCompatActivity {
private OnAppStateReceiver mAppStateReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample_my);
mAppStateReceiver = new OnAppStateReceiver();
IntentFilter filter = new IntentFilter(StackApp.INTENT_ACTION_APP_STATE_CHANGE);
LocalBroadcastManager.getInstance(this).registerReceiver(mAppStateReceiver, filter);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mAppStateReceiver != null) {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mAppStateReceiver);
}
}
private class OnAppStateReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (!TextUtils.isEmpty(action) && StackApp.INTENT_ACTION_APP_STATE_CHANGE.equalsIgnoreCase(action)) {
boolean isGoingBackground = intent.getBooleanExtra(StackApp.INTENT_DATA_IS_IN_BACKGROUND, false);
if (isGoingBackground) {
//Your app is not vissible to the use
} else {
// App is visible to the user.
}
}
}
}
}
Note: If you want to listen in Multiple Activity you can create a base
class and add the listener there and you can do the operation, In that
case you can reduce a lot of code.

Categories

Resources