How to save the intent Extras in Shared prefrences - java

Here is my code which request user for their username:
private void request_user_name() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Enter name:");
final EditText input_field = new EditText(this);
input_field.setText(sharedpreferences.getString("username",""));
final SharedPreferences.Editor editor = sharedpreferences.edit();
builder.setCancelable(false);
builder.setView(input_field);
final String savedName = sharedpreferences.getString(username,"");
input_field.setText(savedName);
input_field.setSelection(input_field.getText().length());
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
name = input_field.getText().toString();
if(TextUtils.isEmpty(savedName)) {
input_field.setError("Your message");
builder.setCancelable(false);
}
editor.putString(username, name);
editor.apply();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if(TextUtils.isEmpty(savedName)) {
input_field.setError("Your message");
builder.setCancelable(false);
}
else
{
dialogInterface.cancel();
request_user_name();
}
}
});
builder.show();
}
And this is how I pass he username to next Activity:
intent.putExtra("room_name",((TextView)view).getText().toString() );
intent.putExtra("user_name",name);
intent.putExtra("default_name","anyonymous");
startActivity(intent);
And this is how I receive the Intent Extra in next Activity:
if (getIntent().getExtras() != null
&& getIntent().getExtras().get("user_name")!=null) {
user_name = getIntent().getExtras().get("user_name").toString();
}else{
user_name = getIntent().getExtras().get("default_name").toString();
}
My problem is when users don't enter his name and it returns null then it returns anyonymous but when users enter his name then it pass user name to next activity. But when I restart the app then again it passes anyonymous to next activity instead of usernae the user already entered
So I need suggestion on how to save the entered username in shared prefrences and use the same in future launch of app unless new name is not entered instead of anyonymous
Thanks in advance.

If you are already using SharedPreferences to store the user_name, then you don't need to pass the user_name via Intent. SharedPreferences are global and could be accessed throughout the application. Just do:
sharedpreferences.getString("username","anonymous")
in your target activity.

Related

NullPointerException on Intent between two Activities

I am trying to send an Intent value between two activities, though it appears, having read this, that in my second activity, the received intent is null; having encoutnered an NPE at runtime.
The intended functionality behind this is: 'the user scans a code in Activity A' -> 'a true value received and packed into an intent' -> 'Activity B opens, unpacks the intent and checks that the intent value is true' -> 'if true, the height of an ImageView in the activity is reduced by a set amount'.
I am therefore, not sure why my Intent is received as null in Activity B, as I would like this check to happen so that the height is updated when the activity opens?
Activity A:
//do the handling of the scanned code being true and display
//a dialog message on screen to confirm this
#Override
public void handleResult(Result result) {
final String myResult = result.getText();
Log.d("QRCodeScanner", result.getText());
Log.d("QRCodeScanner", result.getBarcodeFormat().toString());
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Activity Complete!");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
//the user has pressed the OK button
#Override
public void onClick(DialogInterface dialog, int which) {
scannerView.resumeCameraPreview(QRActivity.this);
//pack the intent and open our Activity B
Intent intent = new Intent(QRActivity.this, ActivityTank.class);
intent.putExtra("QRMethod", "readComplete");
startActivity(intent);
}
});
builder.setMessage(result.getText());
AlertDialog alert1 = builder.create();
alert1.show();
}
Activity B:
// in onCreate, I check that the bundled intent is true
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tank);
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if (extras == null) {
//then the extras bundle is null, and nothing needs to be called here
}
else {
String method = extras.getString("QRmethod");
if (method.equals("readComplete")) {
updateTank();
}
}
}
}
//this is the method that is called when the intent check is true
public int tHeight = 350;
public void updateTank() {
ImageView tankH = (ImageView)findViewById(R.id.tankHeight);
ViewGroup.LayoutParams params = tankH.getLayoutParams();
params.height = tHeight - 35;
tankH.setLayoutParams(params);
}
In Activity B you have a typo while pulling QRMethod from the Intent extras. You are using QRmethod while you have set extras with 'QRMethod'.
You can use :
In first activity ( MainActivity page )
Intent i = new Intent(MainActivity.this,SecondActivity.class);
i.putExtra("QRmethod","readComplete" );
then you can get it from your second activity by :
In second activity ( SecondActivity page )
Intent intent = getIntent();
String YourtransferredData = intent.getExtras().getString("QRmethod");
You can get string value by using intent.getStringExtra() method like this in your second activity.
if (getIntent() != null){
getIntent().getStringExtra("QRmethod") //this s your "readComplete" value
}

How to show alert dialog every 10 launches?

I don't know if this question was asked, but I couldn't find it.
I want alert dialog to show every 10 or more times app is launched.
AlertDialog.Builder a_builder = new AlertDialog.Builder(MainActivity.this);
a_builder.setMessage("Please take time and rate our application")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Uri uri = Uri.parse("market://details?id=" + getApplicationContext().getPackageName());
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY |
Intent.FLAG_ACTIVITY_NEW_DOCUMENT |
Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
try {
startActivity(goToMarket);
} catch (ActivityNotFoundException e) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id=" + getApplicationContext().getPackageName())));
}
}
}).setNegativeButton("Not Now",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
}) ;
AlertDialog alert = a_builder.create();
alert.setTitle("Rate Us !");
alert.show();
Set a sharedPreferences and increment the count every time by the value stored in it. When the values reaches the count, Just show alert and reset the sharedpreferences.
You can store an integer value in the shared preference to keep count of how many times your app has been launched.
You can increment the value in OnCreate() method of launch activity or in any other activity that is an entry point to your app(like from notification).
You should reset the value after displaying the dialog every time.
Here's a small piece of code -
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
int appLaunchCount = pref.getInt("appLaunchCount",-1);
if(appLaunchCount==10){
// code to show dialog
// reset
appLaunchCount=0;
} else {
// increment count
appLaunchCount = appLaunchCount+1;
}
SharedPreferences.Editor editor = pref.edit();
editor.putInt("appLaunchCount", appLaunchCount);
editor.apply();
int count=0;
int prefcount;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
count++;
SharedPreferences pref= PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor edit=pref.edit();
edit.putInt("Count",count);
edit.commit();
prefcount=pref.getInt("Count",-1);
if(prefcount>10){
//show dialog
}
}
}
Hope this will help you.
You can store open count in SharedPreferences
add counter on oncreate activity.
restoredCount ++
editor1.putInt("name", restoredCount);
editor1.commit();
// Get Counter Values
SharedPreferences prefs = getSharedPreferences("user_count", MODE_PRIVATE);
SharedPreferences.Editor editor1 = getSharedPreferences("user_count", MODE_PRIVATE).edit();
int restoredCount = prefs.getInt("name", 0);
if (restoredCount == 10) {
editor1.putInt("name", 0);
editor1.commit();
// Here Show Alert Dialog.
}
I Hope this example is help you.

Broadcastreceiver cannot receive when activity not opened

I have a notepad activity that opens up a window dialog version of it where user can go to another app and still type on the notepad
For both notepad to have the same content, I used broadcastReceiver to set the text of the notepad activity to the one in the dialog when the user is done.
Activity's BroadcastReceiver:
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final globalVariable globalVariable = (globalVariable) getApplicationContext();
et_editor.setText(globalVariable.getScriptEditorText());
Toast.makeText(Script_editor.this, "Script Editor have been updated", Toast.LENGTH_SHORT).show();
}
};
Close Button of the Dialog:
btn_Close = (Button) view.findViewById(R.id.button_Close);
btn_Close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog alertDialog = new AlertDialog.Builder(getApplicationContext())
.setTitle("Would you like to update the editor?")
.setNegativeButton("No, discard the changes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(ColorCoordinatePickerService.this, "Changes have been discarded", Toast.LENGTH_SHORT).show();
dialog.dismiss();
stopSelf();
}
})
.setPositiveButton("Yes, update with changes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
final globalVariable globalVariable = (globalVariable) getApplicationContext();
globalVariable.setScriptEditortext(CCEditor.getText().toString());
Intent intent = new Intent(BROADCAST_ACTION);
sendBroadcast(intent);
dialog.dismiss();
stopSelf();
}
})
.create();
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
alertDialog.show();
}
});
It works BUT the user have to go back to the notepad activity (cannot be in another app or activity).
How do I update the notepad's content without having to "open" it up?
Queue the changes in BroadcastReceiver and when NotepadActivity resumes set the changes in the EditText. The queue doesn't need to be an actual queue, you can persist the last broadcast receiver data somewhere.
I am not sure, but it may be clear your global variable on moving from activity to another activity, also you are declaring the instance of global variable so it will set value in instance not in main variable and therefor you will not get it on receiver.
So I think you should set value in intent and then get it on receiver and manage it so it will work.
Check below, first your click event of dialog box method
#Override
public void onClick(DialogInterface dialog, int which) {
final globalVariable globalVariable = (globalVariable) getApplicationContext();
globalVariable.setScriptEditortext(CCEditor.getText().toString());
Intent intent = new Intent(BROADCAST_ACTION);
intent.putExtra("global_variable","" + CCEditor.getText().toString());
sendBroadcast(intent);
dialog.dismiss();
stopSelf();
}
And now get value in receiver as like below.
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final globalVariable globalVariable = (globalVariable) getApplicationContext();
String strData = intent.getExtras().getString("global_variable");
et_editor.setText(strData);
Toast.makeText(Script_editor.this, "Script Editor have been updated", Toast.LENGTH_SHORT).show();
}
};
Hope this will work
without opening acitivity,you want to update data then only one way you can do it.when you receive in receiver set all data into sharepreference.Whenever your notepad activity opens you can set take data from sharepreference and set it into notepad activity.
Use LocalBroadcastManager.
Example: How to use it

Android App storing and calling Username and Passwords

I have an application that I want to create a log in activity. Ive got
1) Login (Button)
2) UserID (EditText)
3) Password (EditText)
I would like to store the username and password on the device's internal storage. How do I create the file from which the SharedPreferences pulls from and encrypt it?
login_Button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
SharedPreferences userDetails = getSharedPreferences("userdetails", MODE_PRIVATE);
SharedPreferences.Editor edit = userDetails.edit();
edit.clear();
if(etUserID.getText().toString().equals("")){
Toast.makeText(getApplicationContext(),"Please enter a User ID", Toast.LENGTH_LONG).show();
}else if (etPassword.getText().toString().equals("")){
Toast.makeText(getApplicationContext(),"Please enter a password", Toast.LENGTH_LONG).show();
}else{
edit.putString("userID", txtUID.getText().toString().trim());
edit.putString("password", txtPass.getText().toString().trim());
edit.commit();
}
}
});
The txtUID and txtPass is showing up as red and when I delete it the system says that the getText is wrong.
This is my first shot at an authenticator. I found something called PasswordAuthentication from the android dev page but I haven't been able to find any tutorials or code of it being used.
SharedPreferences userDetails = getSharedPreferences("userdetails", MODE_PRIVATE);
String UID = userDetails.getString("userID", "");
String pass = userDetails.getString("password", "");
if (userDetails.contains("userID")||userDetails.contains("password")){
startActivity(new Intent(LogOn.this,CrimeMap.class));
}
Sources Ive used for my research:
http://developer.android.com/reference/java/net/PasswordAuthentication.html
how to use getSharedPreferences in android
Update:
Ok, here is my updated code. If I don't enter a User ID or password it sets off my statements. However, the program doesn't go to the next activity when I put in the correct UserID and Password. I'm going to get it running first and then Ill move on to encrypting it.
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log_on);
etUserID = (EditText) findViewById(R.id.etUserID);
etPassword = (EditText) findViewById(R.id.etPassword);
login_Button = (Button) findViewById(R.id.bLogin);
login_Button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
int uid = 1155;
String pass = "pass";
SharedPreferences userDetails = getSharedPreferences(User_File, MODE_PRIVATE);
SharedPreferences.Editor edit = userDetails.edit();
edit.putInt("userID", uid);
edit.putString("password", pass);
edit.commit();
if((etUserID.getText().toString().equals("")) || (etPassword.getText().toString().equals(""))) {
Toast.makeText(getApplicationContext(),"Please enter a User ID", Toast.LENGTH_LONG).show();
}else if (etPassword.getText().toString().equals("")){
Toast.makeText(getApplicationContext(),"Please enter a password", Toast.LENGTH_LONG).show();
}else{
edit.putInt("userID", Integer.parseInt(etUserID.getText().toString()));
edit.putString("password", etPassword.getText().toString());
}
}
});
SharedPreferences userDetails = getSharedPreferences(User_File, MODE_PRIVATE);
if (userDetails.equals(etUserID) && (userDetails.equals(etPassword))){
startActivity(new Intent(LogOn.this,CrimeMap.class));
}
Update:
I finally got it! Thanks for your help! Here is my complete code for this portion of the project. I still haven't encrypted it but I think I'm going to take a break and come back to it later. Thanks for all your help!
#Override
public void onClick(View v) {
int uid = 1155;
String pass = "pass";
SharedPreferences userDetails = getSharedPreferences(User_File, MODE_PRIVATE);
SharedPreferences.Editor edit = userDetails.edit();
edit.putInt("userID", uid);
edit.putString("password", pass);
edit.commit();
if((etUserID.getText().toString().equals(""))){
Toast.makeText(getApplicationContext(),"Please enter a User ID", Toast.LENGTH_LONG).show();
}else if (etPassword.getText().toString().equals("")){
Toast.makeText(getApplicationContext(),"Please enter a password", Toast.LENGTH_LONG).show();
}else{
String user_id = etUserID.getText().toString();
int user_id2 = Integer.parseInt(user_id);
String user_password = etPassword.getText().toString();
int userID = userDetails.getInt("userID", 1);
String password = userDetails.getString("password", "no name");
if (userID == user_id2 && password.equals(user_password)){
startActivity(new Intent(LogOn.this,CrimeMap.class));
}
}
Don't try to access the file. Let android do that, and encrypt the data you store to the shared preferences. I mean:
edit.putString("userID", encrypt(txtUID.getText().toString().trim()));
edit.putString("password", encrypt(txtPass.getText().toString().trim()));
You can use whatever encryption you like, though of course you'll need to decode it this way.
Another option is to store the SHA1 encrypted password, and in the authentication you compare the SHA1 encypted password that was typed in with the stored string. You could use http://mvnrepository.com/artifact/commons-codec/commons-codec for example:
String sha1Password = DigestUtils.sha1Hex(password);
edit.putString("sha1Password", encrypt(sha1Password);
To fix the "red" problem you'll need to declare txtUID, txtPass. They should be added to your layout somehow. Probably via editing the layout xml. But even programmatically you can do, like: Input text dialog Android

AlertDialog is giving an "undefined" error

My code is:
View.OnClickListener menuHandle = new View.OnClickListener() {
public void onClick(View v) {
//inflate menu
final String [] items = new String[] {"Rate This App", "Quit"};
final Integer[] icons = new Integer[] {R.drawable.star, R.drawable.quit};
ListAdapter adapter = new ArrayAdapterWithIcon(MainActivity.this, items, icons);
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.DialogSlideAnim)
.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item ) {
//Toast.makeText(MainActivity.this, "Item Selected: " + item, Toast.LENGTH_SHORT).show();
switch (item) {
case 0:
//Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Intent.ACTION_VIEW);
//Try Google play
intent.setData(Uri.parse("market://details?id=com.test.testing"));
if (MyStartActivity(intent) == false) {
//Market (Google play) app seems not installed, let's try to open a web browser
intent.setData(Uri.parse("https://play.google.com/store/apps/details?com.test.testing"));
if (MyStartActivity(intent) == false) {
//Well if this also fails, we have run out of options, inform the user.
//let the user know nothing was successful
}
}
break;
case 1:
finish();
break;
default:
//do nothing
}
}
});
AlertDialog alert = builder.create();
alert.requestWindowFeature(Window.FEATURE_NO_TITLE);
alert.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
alert.getWindow().setGravity(Gravity.BOTTOM);
alert.show();
}
};
I get the following error:
The constructor AlertDialog.Builder(MainActivity, int) is undefined
What do I have to modify to get rid of the error?
Note: My MainActivity class extends Activity and DialogSlideAnim as been initialized in the res/values/styles.xml file
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.DialogSlideAnim) will work only on API level 11 and above.
If you are targeting all the platforms then use following.
AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(MainActivity.this, R.style.DialogSlideAnim))
try
new AlertDialog.Builder(v.getContext(), R.style.DialogSlideAnim)
instead of
new AlertDialog.Builder(MainActivity.this, R.style.DialogSlideAnim)
I think its because the AlertDialog.Builder is inside a inner class(menuHandle.setOnClickListener), try changing to: new AlertDialog.Builder(TheNameOfYourClass.this,R.style.DialogSlideAnim);
Like this way :
public void onClick(View v) {
new AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.DialogSlideAnim);
^^^
....
}
Try to set the Style in your AlertDialog as below:
new AlertDialog.Builder(
new ContextThemeWrapper(MainActivity.this, R.style.DialogSlideAnim)

Categories

Resources