Safely store/modify/delete a string in Android - java

I'm making a project in which I need to store a specific string in my application. I must be able to Store it, Delete it, and Modify it at any given time AFTER the user authenticates, which is done by using the fingerprint API.
If possible, I would like to make sure that ONLY the selected fingerprint, or ONLY the fingerprints that were in the phone before adding this string, will be able to unlock/reveal this string
pop-up windows in which I would like to have the password check for example is as follows:
package com.gmtechnology.smartalarm;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
public class Check_Pass extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(inflater.inflate(R.layout.check_pass, null))
// Add action buttons
.setPositiveButton(R.string.check, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
//Check if the entered string matches the string stored
DialogFragment next = new Add_Pass();
next.show(getFragmentManager(), "Add_pass");
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Check_Pass.this.getDialog().cancel();
}
});
return builder.create();
}
}
This pop-up has an edit text that I can capture the input from to use for the comparison, adding and removing will follow the same pattern. The point here and how to SAFELY store that string and manage it.

Safely store what?? Look if you want a persistent storage i.e you need to save it even after your application is closed .then you should use Shared Preference .. Its very easy to use and modify . Or if you want to save it only for once at the runtime of your application then just use a singleton class for it ..

As #ADM said use SharedPreference to store your String. You can specify if your data is private or public.
Use 0 or MODE_PRIVATE for the default operation, MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE to control permissions.
Have a look at the docs or this answer here.
In your case, you can make a specific activity (to manipulate your string) only accessible with a Fingerprint authentification.
You should be aware that not all devices are compatible.

Related

Do not show Onboarding activity again on button click [duplicate]

This question already has answers here:
How to run an activity only once like Splash screen
(5 answers)
Closed 1 year ago.
I have a Android App built in Android studio, on this app, I am using a Walkthrough Activity.
How can set this activity in a way that when a button is clicked, this page won't show again.
This is the function "public void onFinishButtonPressed()" and this is the part where I added onlick listener to the button, how should it be done in a way that once this function is called, this activity will not open again.
I have tried to implement a code to show activity only on first time run, but it is still not the desired result, i really want this page to keep showing until using clicks on that button.
Thanks for your help in advance.
My code;
package com.frigate.vpn.view;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
import com.frigate.vpn.R;
import com.shashank.sony.fancywalkthroughlib.FancyWalkthroughActivity;
import com.shashank.sony.fancywalkthroughlib.FancyWalkthroughCard;
import java.util.ArrayList;
import java.util.List;
public class Walkthrough extends FancyWalkthroughActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FancyWalkthroughCard fancywalkthroughCard1 = new FancyWalkthroughCard("Welcome to Frigate Media VPN", "Let me show you why so many people love Frigate Media VPN", R.drawable.find_restaurant1);
FancyWalkthroughCard fancywalkthroughCard2 = new FancyWalkthroughCard("We Protect your Privacy", "Internet access is mind free, we'll keep you safe",R.drawable.pickthebest);
FancyWalkthroughCard fancywalkthroughCard3 = new FancyWalkthroughCard("Fast & Limitless!", "We provide you the fastest servers without limits.",R.drawable.chooseurmeal);
FancyWalkthroughCard fancywalkthroughCard4 = new FancyWalkthroughCard("Frigate Media VPN is 100% Free", "You do not have to worry about paying for expensive VPN, we give you everything for free.",R.drawable.mealisonway);
fancywalkthroughCard1.setBackgroundColor(R.color.white);
fancywalkthroughCard1.setIconLayoutParams(300,300,0,0,0,0);
fancywalkthroughCard2.setBackgroundColor(R.color.white);
fancywalkthroughCard2.setIconLayoutParams(300,300,0,0,0,0);
fancywalkthroughCard3.setBackgroundColor(R.color.white);
fancywalkthroughCard3.setIconLayoutParams(300,300,0,0,0,0);
fancywalkthroughCard4.setBackgroundColor(R.color.white);
fancywalkthroughCard4.setIconLayoutParams(300,300,0,0,0,0);
List<FancyWalkthroughCard> pages = new ArrayList<>();
pages.add(fancywalkthroughCard1);
pages.add(fancywalkthroughCard2);
pages.add(fancywalkthroughCard3);
pages.add(fancywalkthroughCard4);
for (FancyWalkthroughCard page : pages) {
page.setTitleColor(R.color.black);
page.setDescriptionColor(R.color.black);
}
setFinishButtonTitle("Get Started");
showNavigationControls(true);
setColorBackground(R.color.white);
//setImageBackground(R.drawable.restaurant);
setInactiveIndicatorColor(R.color.grey_600);
setActiveIndicatorColor(R.color.colorGreen);
setOnboardPages(pages);
}
#Override
public void onFinishButtonPressed() {
Intent intent = new Intent(Walkthrough.this, MainActivity.class);
startActivity(intent);
finish();
}
}
Why not just use a global boolean variable named "isFinishedButtonPressed" set to false by default and when the button is pressed set it to true, and with the correct conditions it should do what you want, no ?

Dialog showing only 1 button

I made an app and inserted a dialog in it using DialogFragment, by reading the instructions on the officila android developers site. I made a dialog with 3 buttons, each having a different function. However, when I run it, only 1 button is displayed (mxed fraction). Why is that so?
Here's the code:
package com.example.fractionscalculator;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatDialogFragment;
import androidx.fragment.app.DialogFragment;
public class specifyInput extends AppCompatDialogFragment {
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Please specify the type of number you entered.");
builder.setTitle("Set format");
builder.setNeutralButton("Regular Fraction", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((MainActivity)getActivity()).getandsetText1("frac");
}
});
builder.setNeutralButton("Whole Number", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((MainActivity)getActivity()).getandsetText1("whole");
}
});
builder.setNeutralButton("Mixed Fraction", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((MainActivity)getActivity()).getandsetText1("mixed");
}
});
return builder.create();
}
}
I am a beginner in java and android, so if it is a stupid mistake, please go easy on me.
you can use 3 kind of predefined action button like : so you have used setNeutralButton 3 time its override that button and only show 1 time.
dialog.setPositiveButton(..);
dialog.setNegativeButton(..);
dialog.setNeutralButton(..);
as per documentation :
There are three different action buttons you can add:
Positive : You should use this to accept and continue with the action (the "OK" action).
Negative : You should use this to cancel the action.
Neutral : You should use this when the user may not want to proceed with the action, but doesn't necessarily want to cancel. It appears between the positive and negative buttons. For example, the action might be "Remind me later."

Invoking methods from MainActivity within the onClick methods of a DialogFragment

I'm trying to use a DialogFragment to show a Dialog within my MainActivity. Depending on the user's reaction to the dialog I want to invoke methods defined in my MainActivity.java file (e.g. onActivityResult, but ideally also customized methods).
Following a reply by ashishduh on this question, I defined the DialogFragment as follows (in a seperate java file):
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
public class YesNoDialog extends DialogFragment {
public static final String ARG_TITLE = "YesNoDialog.Title";
public static final String ARG_MESSAGE = "YesNoDialog.Message";
public YesNoDialog() {}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{ Bundle args = getArguments();
String title = args.getString(ARG_TITLE);
String message = args.getString(ARG_MESSAGE);
return new AlertDialog.Builder(getActivity())
.setTitle(title)
.setMessage(message)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, null);
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_CANCELED, null);
}
})
.create();
}
}
Correspondingly, I try to start it from the MainActivity like this:
public void openYesNoDialog (View view) {
DialogFragment dialog = new YesNoDialog();
Bundle args = new Bundle();
args.putString(YesNoDialog.ARG_TITLE, "title");
args.putString(YesNoDialog.ARG_MESSAGE, "message");
dialog.setArguments(args);
dialog.setTargetFragment(this, YES_NO_CALL);
dialog.show(getSupportFragmentManager(), "tag");
}
where openYesNoDialog is triggered by a button in the activity_main.xml layout file.
I am facing the problem that setTargetFragment(this, YES_NO_CALL) is not working, since "this" corresponds to my MainActivity, but setTargetFragment is (naturally)
expecting a Fragment and no Activity. The problem is that I do not know what to reference in the first argument instead because apart from the DialogFragment I
am trying to build I have made absolutely no use of Fragments in my code.
So I am wondering which of the following strategies you would encourage to fix my issue (not even sure if all of them might possibly work):
1.) Use a method similar to setTargetFragment which allows setting a target Activity. (sort of a "setTargetActivity" method; this solution sounds easiest to me if such a thing exists, but I haven't found anything similar yet).
2.) Write everything in terms of Fragments and have something like a "MainFragment" instead of a MainActivity. I could then easily reference this "MainFragment" as a reasonable target fragment with "this".
3.) Use a completely different approach (e.g. not putting the methods in the activity but in an interface both activity and fragment implement, but actually I also want to make use of e.g. TextViews of the activity inside of the DialogFragment, so I think this might be a problem)
I am very thankful for any help.
One final comment: Note that I am using the v4 support libraries in my imports to support backward compatibility as suggested in the Android tutorials on Dialogs.
This is for example why I needed to use getSupportFragmentManager() instead of getFragmentManager() to make work what is already working right now. So that's the reason for my slight modifications of the code I have been referring to with the hyperlink.
getTargetFragment and setTargetFragment both we should use for communication between Fragment to Fragment,
For Activity to Fragment communication, you can use 2 ways
You can use interface for communication
You can use Local broadcast
Interface communication
Create one interface in dialog fragment,
public class YesNoDialog extends DialogFragment {
public interface OnDialogActionListener {
public void onClickDialog();
}
private OnDialogActionListener mListener;
#Override
public void onAttach(Context context) {
mListener = (OnDialogActionListener) context;
}
// Your code
#Override
public void onClick(DialogInterface dialog, int which)
{
mListener.onClickDialog();
}
}
And in Your activity you can implement and override the function, you will get callback in your Activty.
You can simply use interface for the same. Just define interface in a separate class and declare method as onClickEvent/onSuccess according to you and override it in your activity and perform your task in your activity in the method. And call this method from your dialog on yes/no click buttons.

When I change the page orientation it come at the beginning of page [duplicate]

This question already has answers here:
When I change the page orientation come at the beginning of page
(2 answers)
Closed 5 years ago.
I am using barteksc-AndroidPdfViewer. I am using this code
package com.epubtest.hxfy.epubtest;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Canvas;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnDrawListener;
import com.github.barteksc.pdfviewer.listener.OnErrorListener;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
import com.github.barteksc.pdfviewer.listener.OnPageScrollListener;
public class PDFReaderActivity2 extends AppCompatActivity implements OnPageChangeListener, OnLoadCompleteListener, OnDrawListener, OnErrorListener, OnPageScrollListener {
private PDFView pdfview;
private SharedPreferences pdfReader;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdfreader2);
pdfReader = this.getSharedPreferences("PDFReader", Context.MODE_PRIVATE);
pdfview = (PDFView) findViewById(R.id.pdfView);
pdfview.fromAsset("test4.pdf")
.defaultPage(pdfReader.getInt("pages",0))
.onPageChange(this)
.swipeHorizontal(false)
.enableAnnotationRendering(true)
.scrollHandle(null)
.onLoad(this)
.onDraw(this)
.enableSwipe(true)
.onError(this)
.enableDoubletap(true)
.onPageScroll(this)
.load();
}
#Override
public void onPageChanged(int page, int pageCount) {
SharedPreferences.Editor edit = pdfReader.edit();
edit.putInt("pages",page);
edit.commit();
}
#Override
public void loadComplete(int nbPages) {
}
#Override
public void onLayerDrawn(Canvas canvas, float pageWidth, float pageHeight, int displayedPage) {
}
#Override
public void onError(Throwable t) {
}
#Override
public void onPageScrolled(int page, float positionOffset) {
}
}
to change the orientation of the page. But if I have to assume if the portrait mode and page number 15 in change page orientation of the page when we started the landscape.
SharedPreferences is not working. It can't keep record last page where we were. Please help me in this regard, Please help me about this.
Don't use SharePreferences for this. When you change screen orientation, system recalls onCreate() method again and it redraws your views. For solution of this problem, you have 2 ways. First one is forcing to save state in manifest file.
<activity name= ".YourActivity" android:configChanges="orientation|screenSize"/>
If you write this parameter no need to handle in Activity , the framework will take care of rest of things. It will retain the state of the screen or layout if orientation is changed.
Another way is recommended by google developers which is better way for handling this problems in orientation changes. You can get more information in thislink. It will be better for reading this article also. It is about lifecycle of activity.
If you want source example, i can share my source with you. Enjoy!
For handling orientation changes, add this few lines to your source.
Configurator.onRender(new OnRenderListener() {
#Override
public void onInitiallyRendered(int pages, float pageWidth, float pageHeight) {
pdfView.fitToWidth(); // optionally pass page number
}
});

How To: Voice Commands into an android application

There are many tutorials online for adding voice recognition to an android app. They are often confusing and the publishers of the coding are never available for questions. I need a basic overview of how to add voice recognition to my app (as an answer, not a link).
If you want to add voice recognition to your group's Android app it is very simple.
Throughout this tutorial you will need to add imports as you paste in the code.
Create an xml file or use an existing one and make sure that you add a button and a listview.
In a java class you need to extend activity and implement OnClickListener
You will get an error that says you have unimplemented methods. Hover over it and add the unimplemented methods. We will add to this later.
Next set up the button and listview in your java.
public ListView mList;
public Button speakButton;
also add:
public static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
Next, make an OnCreate Method and set up the button and listener.
speakButton = (Button) findViewById(R.id.btn_speak);
speakButton.setOnClickListener(this);
also add this method(we will set it up next)
voiceinputbuttons();
Remember to setContentView for the xml you are showing.
Outside of your oncreate make a new method that looks like this.
public void voiceinputbuttons() {
speakButton = (Button) findViewById(R.id.btn_speak);
mList = (ListView) findViewById(R.id.list);
}
Now you will have to set up your voice recognition activity by using the following code.
public void startVoiceRecognitionActivity() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
"Speech recognition demo");
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}
Next, inside your onclick method from step 2 add the activity from step 6.
startVoiceRecognitionActivity();
Next we will have to set up another method. Copy and paste the following code.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
mList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, matches));
matches is the result of voice input. It is a list of what the user possibly said. Using an if statement for the keyword you want to use allows the use of any activity if keywords match it is possible to set up multiple keywords to use the same activity so more than one word will allow the user To use the activity (makes it so the user doesn't have to memorize words from a list) To use an activity from the voice input information simply use the following format;
if (matches.contains("information")) {
informationMenu();
}
NOTE: you can format the code any time by pressing ctrl+shift+F in eclipse.
Now we are going to set up our method used by the code in step 8. This code creates an intent to direct the user to a new menu. You will need another xml and java class for this. Also, remember to add an activity to your manifest.
public void informationMenu() {
startActivity(new Intent("android.intent.action.INFOSCREEN"));
}
Finally you need to set up some code that will let the user know if the mic is operational. Paste this code inside of the OnCreate method at the end.
// Check to see if a recognition activity is present
// if running on AVD virtual device it will give this message. The mic
// required only works on an actual android device
PackageManager pm = getPackageManager();
List activities = pm.queryIntentActivities(new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (activities.size() != 0) {
voiceButton.setOnClickListener(this);
} else {
voiceButton.setEnabled(false);
voiceButton.setText("Recognizer not present");
}
FINAL NOTE: Voice Recognition will not work on a virtual emulator because they can't access the mic on your computer. The voice recognition will only work with an internet connection.
This is approx. what your final code should look like in your java.
package com.example.com.tutorialthread;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.speech.RecognizerIntent;
import android.support.v4.app.NavUtils;
public class main extends Activity implements OnClickListener {
public ListView mList;
public Button speakButton;
public static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
speakButton = (Button) findViewById(R.id.btn_speak);
speakButton.setOnClickListener(this);
voiceinputbuttons();
}
public void informationMenu() {
startActivity(new Intent("android.intent.action.INFOSCREEN"));
}
public void voiceinputbuttons() {
speakButton = (Button) findViewById(R.id.btn_speak);
mList = (ListView) findViewById(R.id.list);
}
public void startVoiceRecognitionActivity() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
"Speech recognition demo");
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}
public void onClick(View v) {
// TODO Auto-generated method stub
startVoiceRecognitionActivity();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
// Fill the list view with the strings the recognizer thought it
// could have heard
ArrayList matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
mList.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, matches));
// matches is the result of voice input. It is a list of what the
// user possibly said.
// Using an if statement for the keyword you want to use allows the
// use of any activity if keywords match
// it is possible to set up multiple keywords to use the same
// activity so more than one word will allow the user
// to use the activity (makes it so the user doesn't have to
// memorize words from a list)
// to use an activity from the voice input information simply use
// the following format;
// if (matches.contains("keyword here") { startActivity(new
// Intent("name.of.manifest.ACTIVITY")
if (matches.contains("information")) {
informationMenu();
}
}
}
Really good tutorial. Well done.
To complete a little bit more :
You need to add permission to your manifest as follow
<uses-permission android:name="android.permission.RECORD_AUDIO" />
Also voice does not work if you have
launchMode="singleInstance" or launchMode="singleTask" it looks like it should be "standard"

Categories

Resources