I'm writing a weather app in Android Studio and I've a problem. When the user closes the app, I want to save the last city searched, and I used SharedPreferences for this.
If the user wants to search a new city, I have a "search button" that starts a new activity, where the user can choose another city and with an Intent put the string in the MainActivity.
The problem is to check (at the start of the app) if a SharedPreferences exists(and get old data from this) or intent is != null (and get new data from this).
This is my code in "OnCreate" method. It works on emulator but not on my smartphone:
value = ""; //this is a String
pref = getSharedPreferences("meteo", Context.MODE_PRIVATE);
receive_from_intent = getIntent(); //This intent gets from "SearchActivity".
add_city.setOnClickListener(new View.OnClickListener() { //this is the search button
#Override
public void onClick(View view) {
Intent start_new = new Intent(MainActivity.this, SearchActivity.class);
MainActivity.this.startActivity(start_new);
}
});
if (receive_from_intent.getExtras() != null) {
value = receive_from_intent.getStringExtra("luogo"); //if it's a string you stored.
//luogo means "city"
if (!value.matches("")) {
SharedPreferences.Editor editor = pref.edit();
editor.putString("luogo", value);
editor.apply();
}
url = "https://api.openweathermap.org/data/2.5/weather?q=" + value + ",it&mode=json&lang=it&units=metric&APPID=e8cff7ac36757b1ea60b460f036140df";
url2 = "https://api.openweathermap.org/data/2.5/forecast?q=" + value + ",it&mode=json&lang=it&units=metric&APPID=e8cff7ac36757b1ea60b460f036140df";
CercaLuogo(url, url2);
} else if (pref.contains("luogo")) {
value = pref.getString("luogo", "");
url = "https://api.openweathermap.org/data/2.5/weather?q=" + value + ",it&mode=json&lang=it&units=metric&APPID=e8cff7ac36757b1ea60b460f036140df";
url2 = "https://api.openweathermap.org/data/2.5/forecast?q=" + value + ",it&mode=json&lang=it&units=metric&APPID=e8cff7ac36757b1ea60b460f036140df";
CercaLuogo(url, url2);
} else Toast.makeText(this, "Click on search button and insert new city.", Toast.LENGTH_SHORT).show();
Related
I tried to pass variable from one activity to another. In the main activity I managed to call back the values using Toast message.
MainActivity.java
search = (Button) findViewById(R.id.search);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View w) {
subreg = spinner_subregion.getSelectedItem().toString();
reg = spinner_region.getSelectedItem().toString();
pettype = spinner_pet.getSelectedItem().toString();
petnumber = spinner_num.getSelectedItem().toString();
Intent intent = new Intent(MainActivity, Result.class);
intent.putExtra("subregion", subreg);
intent.putExtra("region", reg);
intent.putExtra("petnum", petnumber);
intent.putExtra("pet", pettype);
startActivity(intent);
}
}
However, when I passed the value to Result.java, it only returns null. I tried searching for solutions and still does not work for me. Anyone knows how can I pass the data?
Result.java
Bundle extras = getIntent().getExtras();
if (extras!=null){
subreg = extras.getString("subreg");
reg = extras.getString("reg");
pettype = extras.getString("pettype");
petnumber = extras.getString("petnumber");
}
Try this
MainActivity.java
Intent myIntent = new Intent(this, NewActivity.class);
intent.putExtra("subregion", subreg);
intent.putExtra("region", reg);
intent.putExtra("petnum", petnumber);
intent.putExtra("pet", pettype);
startActivity(myIntent)
Result.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
Intent intent = getIntent();
if(intent ==null){
........
.......
}else{
String subregion= intent.getStringExtra("subregion");
String region= intent.getStringExtra("region");
String petnum= intent.getStringExtra("petnum");
String pet= intent.getStringExtra("pet");
}
}
This is my code after changing it.
MainActivity.java
search = (Button) findViewById(R.id.search);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View w) {
subreg = spinner_subregion.getSelectedItem().toString();
reg = spinner_region.getSelectedItem().toString();
pettype = spinner_pet.getSelectedItem().toString();
petnumber = spinner_num.getSelectedItem().toString();
Intent intent = new Intent(Pet_sitting.this, Pet_sitting_result.class);
intent.putExtra("subreg", subreg);
intent.putExtra("reg", reg);
intent.putExtra("pettype", pettype);
intent.putExtra("petnumber", petnumber);
startActivity(intent);
}
});
Result.java
Intent intent = getIntent();
if (intent == null){
Toast.makeText(getApplicationContext(),"Null value passed",Toast.LENGTH_SHORT).show();
}
else{
subreg= intent.getStringExtra("subreg");
reg= intent.getStringExtra("reg");
pettype = intent.getStringExtra("pettype");
petnumber = intent.getStringExtra("petnumber");
Toast.makeText(getApplicationContext(),subreg + " " + reg + " " + pettype + " " + petnumber,Toast.LENGTH_SHORT).show();
}
As i can see you are using a Spinner in your code.
So it's Obvious a spinner can give you only one value at a time after Spinning the wheel...
you need to set the Code inside in null value Exception...
like...if it's null don't pass empty value inside intent
maybe it's worked...if it's then reply
MainActivity.java
if(subreg != null){
reg = spinner_region.getSelectedItem().toString();
intent.putExtra("reg", reg);
}
startActivity(intent);
Rsult.java
Intent intent = getIntent();
if (intent == null){
Toast.makeText(getApplicationContext(),"Null value passed",Toast.LENGTH_SHORT).show();
}else{
reg= intent.getStringExtra("reg");
Toast.makeText(getApplicationContext(),reg.toString,Toast.LENGTH_SHORT).show();
}
HActivity.java
pass1 = (EditText) findViewById(R.id.edt1);
pass1c = (EditText) findViewById(R.id.edt2);
confirm = (TextView) findViewById(R.id.tv1);
SharedPreferences pref = getSharedPreferences("Apref", Context.MODE_PRIVATE);
if(pref.getBoolean("act_ex", false)){
String passs11 = pass1.getText().toString();
Intent intent = new Intent(this, LogInAct.class);
intent.putExtra("PASSWW", passs11);
startActivity(intent);
finish();
} else {
SharedPreferences.Editor ed = pref.edit();
ed.putBoolean("act_ex", true);
ed.commit();
}
// Its using java in Android Studio, it passes the password the first time you open the app but the second time you do that it will say wrong password (as I wanted) even if you type the right password (the one you registered with) how can I save it somewhere or do something with it?
LogInAct.java
tv2 = (TextView) findViewById(R.id.tv2);
edt3 = (EditText) findViewById(R.id.edt3);
Button loginbtn = (Button) findViewById(R.id.loginbtn);
loginbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
logpass = edt3.getText().toString();
passs1 = getIntent().getExtras().getString("PASSW");
passs11 = getIntent().getExtras().getString("PASSWW");
if (logpass.equals(passs1) && logpass.equals(passs11)) {
Intent intent = new Intent(getApplicationContext(), Photos.class);
startActivity(intent);
} else {
tv2.setText("wrong password");
}
}
});
So it looks to me like on your "registration" screen, you're capturing the username and password, and then passing them through the intent to the Login Screen? This works great in a single instance, but doesn't persist.
It's hard to tell just from the code, but how are you taking the user to the Login Screen on the next time they open the application? Is it just going to that screen as the launch?
Data passed over in intents is not persisted between sessions. It's most useful when passing data from one screen to another just for that session.
It can be used if you have a list screen and on the next screen is the detail screen. You want to pass the id of which item they clicked for example so you can load the data on that screen. But there is no reason to store it if they closed the app and opened it again.
To persist data between sessions, you want to store and extract from a more permanent storage. Ideally, you'll end up with a database system of some sort. But to answer what you're trying to do, use the shared preferences both for storing and extracting the password.
Registration:
SharedPreferences pref = getSharedPreferences("Apref", Context.MODE_PRIVATE);
Editor editor = pref.edit();
editor.putString("username", username);
editor.putString("password", password");
editor.apply();
Login:
SharedPreferences pref = getSharedPreferences("Apref", Context.MODE_PRIVATE);
passs1 = pref.getString("username");
Again, this is definitely not a good way to store user's credentials, but it answers your question of persistence.
I am doing a project where I have to program a pedometer. The pedometer will work using a button and you have to tell the length of your steps. I made a main activity that let you choose between go anonymous an another one that let you register. The aplication works when I register or when I go anonymous, and the step length is passed well to the third activity, an activity where you can press a button and increase the number of steps done and the meters done. In this activity there is another button to configure the length of your steps and I want to pass all the info to the anonymous activity to change only the length of the steps and I pass all the info. I used the method putExtra() and getIntent().getExtra().getString(), but only works going to the main activity to the registe/anonymous activity and then going to the pedometer activity, but when i want to configure the length of the steps the aplications stops.
This is my code for the anonymous activity:
if(this.getIntent().hasExtra("name")){
names=this.getIntent().getExtras().getString("name");
}else{
names="";
}
if(this.getIntent().hasExtra("user")){
userName=this.getIntent().getExtras().getString("user");
}else{
userName="";
}
if(this.getIntent().hasExtra("pass")){
password=this.getIntent().getExtras().getString("pass");
}else{
password="";
}
if(this.getIntent().hasExtra("feetBefore")){
footBefore=this.getIntent().getExtras().getString("feetBefore");
}else{
footBefore="0";
}
if(this.getIntent().hasExtra("steps")){
stepsDone=this.getIntent().getExtras().getString("steps");
}else{
stepsDone="0";
}
Button continueBtn = findViewById(R.id.continueAnonymous);
foot = findViewById(R.id.lengthFeetAnonymous);
continueBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String footSize = String.valueOf(foot.getText());
if(!footSize.equals("")) {
Intent mainAnonymous = new Intent(getApplicationContext(), Main5Activity.class);
mainAnonymous.putExtra("name", names);
mainAnonymous.putExtra("user", userName);
mainAnonymous.putExtra("pass", password);
mainAnonymous.putExtra("feet", footSize);
mainAnonymous.putExtra("steps", stepsDone);
mainAnonymous.putExtra("feetBefore", footBefore);
startActivity(mainAnonymous);
finish() ;
}else{
Toast.makeText(Main4Activity.this, "You have to complete all the backets.",
Toast.LENGTH_SHORT).show();
}
}
});
This is the code of my pedometer activity:
Bundle parameters = this.getIntent().getExtras();
if(parameters != null){
name = parameters.getString("name");
username = parameters.getString("user");
password = parameters.getString("pass");
String foot = parameters.getString("feet");
String footBefore = parameters.getString("feetBefore");
String stepsDone = parameters.getString("steps");
if(stepsDone!=null) cont = Integer.parseInt(stepsDone);
else cont =0;
if(footBefore!=null)feetBefore = Integer.parseInt(footBefore);
else feetBefore =0;
if(foot !=null)feet = Float.parseFloat(foot)/100;
else feet = (float) 0.43;
cont2 = cont*feetBefore;
}else {
name = "";
username = "";
password = "";
feet = (float) 0.43;
}
increase = findViewById(R.id.increaseStep);
configuration = findViewById(R.id.confBtn);
saveMain = findViewById(R.id.saveBtnMain);
resume = findViewById(R.id.resumBtn);
final TextView steps = findViewById(R.id.stepCounter);
final TextView km = findViewById(R.id.kilometerCounter);
steps.setText(String.format(Locale.ENGLISH,"%d Steps",cont));
String aux =String.format(Locale.ENGLISH,"%.2f Meters", cont2);
km.setText(aux);
increase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cont++;
steps.setText(String.format(Locale.ENGLISH,"%d Steps",cont));
cont2 += feet;
String aux =String.format(Locale.ENGLISH,"%.2f Meters", cont2);
km.setText(aux);
}
});
configuration.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent conf = new Intent(getApplicationContext(), Main4Activity.class);
conf.putExtra("name", name);
conf.putExtra("user", username);
conf.putExtra("pass", password);
String aux2 = String.valueOf(cont);
conf.putExtra("steps", aux2);
float aux4 =feet*100;
String aux3 = String.valueOf(aux4);
conf.putExtra("feetBefore", aux3);
startActivity(conf);
finish() ;
}
});
}
I started to learn android yesterday so I don't know what I am doing wrong. If you can help me I would apreciate it. In addition, I think it's something about the bundle.
Add all data in a bundle and check only if bundle!=null –by Milan Pansuriya
I don't know the difference between using a bundle to pass al the data and putExtra to my intent but this works for me. Thank you Milan Pansuriya.
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
I've created a widget which displays a simple textview, which is editable as an Edittext in a configuration activity. I save the inputted text with shared preferences, so the user can tap the widget to edit the text, and the already inputted text appears in the edittextfield.
My problem is this. I would like the user to be able to add multiple widgets, but when a seccond widget is added, the same text as in the other widget is loaded from shared preferences. And, when on widget is edited so is the other one. Hope i'm being clear. I kinda have an idea it has something to do with appWidgetIds but i cannot figure it out.
Here's my code, a bit simplified.
public class WidgetConfig extends Activity implements OnClickListener, OnItemSelectedListener {
AppWidgetManager awm;
int awID;
Context c;
EditText info;
Button b;
String note;
int styleStart = -1, cursorLoc = 0;
SharedPreferences sp;
Spinner spinner;
String[] paths = { "10", "20", "30" };
File path = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.widgetconfig);
c = WidgetConfig.this;
info = (EditText)findViewById(R.id.etwidgetconfig);
...
b = (Button)findViewById(R.id.bwidgetconfig);
loadPrefs();
b.setOnClickListener(this);
//Getting Info about the widget that launched this activity
Intent i = getIntent();
Bundle extras = i.getExtras();
if (extras != null){
awID = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID );
}
awm = AppWidgetManager.getInstance(c);
}
...
private void loadPrefs(){
sp = PreferenceManager.getDefaultSharedPreferences(this);
note = sp.getString("NOTE", "DEFAULT");
info.setText(note);
}
private void savePrefs(String key, String value){
sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sp.edit();
editor.putString(key, value); // value to store
editor.commit();
}
public void onClick(View v) {
// TODO Auto-generated method stub
savePrefs("NOTE", info.getText().toString());
RemoteViews views = new RemoteViews(c.getPackageName(), R.layout.widget);
views.setTextViewText(R.id.tvConfigInput, info.getText());
ComponentName thisWidget = new ComponentName(this, Widget.class);
AppWidgetManager manager = AppWidgetManager.getInstance(this);
manager.updateAppWidget(thisWidget, views);
Intent in = new Intent(c, WidgetConfig.class);
PendingIntent pi = PendingIntent.getActivity(c, 0, in, PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.B_EditAgain, pi);
awm.updateAppWidget(awID, views);
Intent result = new Intent();
result.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, awID);
setResult(RESULT_OK, result);
finish();
}
}
UPDATE:
So i tried this, but nothings different, still doesn't work.
private void loadPrefs(){
sp = context.getSharedPreferences("widget" + String.valueOf(appWidgetId)
, Context.MODE_PRIVATE);
note = sp.getString("Note", "");
info.setText(note);
}
private void savePrefs(String key, String value){
sp = context.getSharedPreferences("widget" + String.valueOf(appWidgetId)
, Context.MODE_PRIVATE);
Editor editor = sp.edit();
editor.clear();
editor.putString("Note", info.getText().toString());
editor.putString(key, value); // value to store
editor.commit();
}
You probably don't want to use getDefaultSharedPreferences here. All widgets share the same default shared preferences, so they will be constantly overwriting each other.
I had the same situation in my own app, so I used a custom preference file for each widget. You can name the preference file with the widgetID, and then each widget will always get it's own unique set of preferences.
In the configuration PreferenceActivity:
this.getPreferenceManager().setSharedPreferencesName(
"widget" + String.valueOf(mAppWidgetId)
);
This will store all of the PreferenceActivity settings into a preference file named after the widget id.
Then in the widget itself, just retrieve the file corresponding to its id:
preferences = context.getSharedPreferences(
"widget" + String.valueOf(appWidgetId)
, Context.MODE_PRIVATE);
And retrieve preferences like normal.