How to "save" string variable from settings menu - java

I'm new about coding so i'm sorry for my "basic" questions.
I'm coding an Android app with Android studio; very simple, only webview that show my website but i need to have in settings menu an editText where i can modify my website url.
I made two activitys(Main and Settings) that i post; Could anyone help me to understand how can i store permanently the url that i write in my editText in order to open that url when i came back to main activity?
Hope i submit clearly my question!!
Thanks in advance
Settings.java
private EditText editsite;
private Button button;
public static TextView actSite;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
editsite = findViewById(R.id.editsite);
button = findViewById(R.id.saveButton);
actSite = findViewById(R.id.actSite);
button.setOnClickListener(this);
}
#Override
public void onClick(View view) {
String strData = editsite.getText().toString();
if (strData.length()<=0) {
Toast.makeText(this,"Sito non valido", Toast.LENGTH_SHORT).show();
}else {
actSite.setText(strData);
Main Activity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
WebView vista = (WebView)findViewById(R.id.vista);
vista.getSettings().setJavaScriptEnabled(true);
vista.setWebViewClient(new WebViewClient());
vista.loadUrl("www.google.com"); //examplesite
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent intent = new Intent(MainActivity.this, Settings.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
}

You can use SharedPreferences Here. And everytime the MainActivity starts you load the Shared Preferences and get the String.
Example:
set Shared Preferences
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("URL", "Your url");
editor.apply();
Get the value
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String url= prefs.getString("URL", "String if URL is emtpy");

Related

Unable to access member variable in onOptionsItemSelected in android activity

I am trying to open a certain URL passed from previous activity with the browser. Click on the redirect icon on the right side, open the expected web page.
Here are my codes.
public class DetailedProduct extends AppCompatActivity {
private Menu menu;
private String itemId;
private String itemUrl;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d("DetailedProduct-LifeCycle","------------onCreate------------");
setTheme(R.style.AppTheme);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailed_product);
Intent intent = getIntent();
String itemId = intent.getStringExtra("itemId");
String itemUrl = intent.getStringExtra("itemUrl");
Log.d("itemUrl", itemUrl);
ActionBar actionBar = getSupportActionBar();
// actionBar.setDisplayHomeAsUpEnabled(true);
setTitle(itemId);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
Log.v("Menu","----------menuCreate----------");
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.detail_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.v("Menu", "-----------menuSelect---------");
if(itemUrl==null){
Log.v("Menu", "---------Cannot acquire predefined itemUrl---------");
}
else{
Log.d("itemUrlInner", itemUrl);
}
switch(item.getItemId()){
case R.id.redirect:
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(this.itemUrl));
startActivity(browserIntent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
...
}
The issue is that itemUrl is null in the scope of onOptionsItemSelected.
I have assigned value to itemUrl in onCreate. However, as the log shows, it is null.
Hope for your help. Thanks a lot! :-)
In the onCreate method you are using a local variable.
private String itemUrl;
protected void onCreate(Bundle savedInstanceState) {
....
//String itemUrl = intent.getStringExtra("itemUrl"); //It is a different variable!
itemUrl = intent.getStringExtra("itemUrl");
}
You are assigning value to String itemUrl = intent.getStringExtra("itemUrl"); (local variable that ends its life as soon as its scope is hone) but reading it from this.itemUrl (field of your hosting entity). You need to write to and read from the same place.

How to pass String from One Activity to another Activity and use it in intent for Dialpad and Email

I have two one Adapter and another Activity . Adapter send the String Extra as per position in Firebase Data Structure into Next activity where data is displayed which is passed from Adapter.
It works pretty well. I am ablet to show the data in Textview. But When I user intent to Dial a phone or send Email , Then I'm not able to use Extras I"m receivng with but when I setText in Textview ..they show the exact Data. Please help
Here is the method in Adapter
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
database = FirebaseDatabase.getInstance();
dbreference = database.getReference("gender");
g = bookslist.get(position);
holder.teacher_quali.setText(g.getBqualifications());
holder.profile_details.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), gender_details.class);
intent.putExtra(NEAR_LOCATION, g.getBlocation());
intent.putExtra(AVAILAIBILITY, g.getBavailaile());
intent.putExtra(MOBILE, g.getSellermobile());
intent.putExtra(EMAIL, g.getSelleremail());
v.getContext().startActivity(intent);
}
});
where I have defined MOBILE and EMAIL as
public static final String MOBILE = "other_mobile";
public static final String EMAIL= "other_email";
in same adapter view and my activity is
public class gender_details extends AppCompatActivity {
private TextView tutor_email,tutor_mobile;
private ImageView img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_details);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_details); // get the reference of Toolbar
toolbar.setTitle(getIntent().getStringExtra(KEY_NAME));
toolbar.setLogo(R.drawable.ic_person_black_24dp);
setSupportActionBar(toolbar);
String tutor_email_txt = "";
String tutor_mobile_txt = "";
tutor_email_txt = intent.getStringExtra(EMAIL);
tutor_mobile_txt = intent.getStringExtra(MOBILE);
// Setting values
TextView Email_Txt = (TextView) findViewById(R.id.tutor_email);
Email_Txt.setText(tutor_email_txt);
TextView Contact_Txt = (TextView) findViewById(R.id.tutor_contact);
Contact_Txt.setText(String tutor_mobile_txt);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.toolbar_menu, menu);
return true;
}
// Activity's overrided method used to perform click events on menu items
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
// Display menu item's title by using a Toast.
if (id == R.id.action_call) {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:"+tutor_mobile_txt));
startActivity(intent);
return true;
} else if (id == R.id.action_email) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("plain/text");
intent.putExtra(Intent.EXTRA_EMAIL, tutor_email_txt);
intent.putExtra(Intent.EXTRA_SUBJECT, "subject");
intent.putExtra(Intent.EXTRA_TEXT, "mail body");
startActivity(Intent.createChooser(intent, ""));
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
Intent intent = new Intent(gender_details.this, MainActivity.class);
startActivity(intent);
}
}
As you can see in Textview , information are shown correctl but when I use to Intent Action Dail or send email...I'm not been able to do so.
Please help
Try this:
Declare the variable Globally
public class gender_details extends AppCompatActivity {
private TextView tutor_email,tutor_mobile;
private ImageView img;
String tutor_email_txt;
String tutor_mobile_txt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_details);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_details); // get the reference of Toolbar
toolbar.setTitle(getIntent().getStringExtra(KEY_NAME));
toolbar.setLogo(R.drawable.ic_person_black_24dp);
setSupportActionBar(toolbar);
tutor_email_txt = intent.getStringExtra(EMAIL);
tutor_mobilee_txt = intent.getStringExtra(MOBILE);
// Setting values
TextView Email_Txt = (TextView) findViewById(R.id.tutor_email);
Email_Txt.setText(tutor_email_txt);
TextView Contact_Txt = (TextView) findViewById(R.id.tutor_contact);
Contact_Txt.setText(String tutor_mobile_txt);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.toolbar_menu, menu);
return true;
}
// Activity's overrided method used to perform click events on menu items
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
// Display menu item's title by using a Toast.
if (id == R.id.action_call) {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:"+tutor_mobile_txt));
startActivity(intent);
return true;
} else if (id == R.id.action_email) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("plain/text");
intent.putExtra(Intent.EXTRA_EMAIL, tutor_email_txt);
intent.putExtra(Intent.EXTRA_SUBJECT, "subject");
intent.putExtra(Intent.EXTRA_TEXT, "mail body");
startActivity(Intent.createChooser(intent, ""));
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
Intent intent = new Intent(gender_details.this, MainActivity.class);
startActivity(intent);
}
}
Are You Declare Permission in Manifest If Not Then Declare it :
uses-permission android:name="android.permission.CALL_PHONE"
There are some serious naming problems in your code. First you need to make your tutor_mobile_txt variable global. Secondly inside onCreate your are initializing tutor_mobilee_txt instead of tutor_mobile_txt. Correct the spellings and then check.

Android Up button not working

I am trying to manually implement the actions that must take place when the up button on the actionbar is pressed but for some reason nothing happens when I press it.
here is my code:
public class ActivityOne extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity_one);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar_actionbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Button button = (Button)findViewById(R.id.btn1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openActivityTwo();
}
});
Button button2 = (Button)findViewById(R.id.btn2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openActivityThree();
}
});
}
void openActivityTwo(){
Intent intent = new Intent(this, ActivityTwo.class);
startActivity(intent);
}
void openActivityThree(){
Intent intent = new Intent(this, ActivityThree.class);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_activity_one, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
else if(id == R.id.homeAsUp){
Log.i("","Up is pressed");
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
I understand that I have to explicitly assign a parent activity for the activity I want to implement up navigation on the manifest file, but problem is that this activity has multiple parents so I thought calling the finish() method when the up button is pressed on this activity will be the better approach.
I have already tried both id == R.id.home and id == R.id.homeAsUp and they both do not work. I do not know if it is because I am using AppCompactActivity or what Please help
Here is how you can implement this, try this code
use android.R.id.home instead of R.id.home or R.id.homeAsUp
public boolean onOptionsItemSelected(final MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
//use onBackPressed() OR finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
The correct way to do it is to override public boolean onNavigateUp() just like overriding onBackPressed().
Using android studio 3.6.2 I've found that the Up button is not displayed by default in my apps, but it can be easily added..
Go to AndroidManifest.xml and update each activity that needs an Up button as follows:
<activity
android:name=".yourClassName"
android:parentActivityName=".MainActivity">
<meta-data android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.yourPackageName" />
</activity>
The target destination for the Up button is set by changing parentActivityName. In this example I have set it as '.MainActivity' but you can change that to whatever activity you want the user to navigate to.

what to do if backpressed

i have a code to change the text of textview in a layout according to the value of the edittext (et) in the previous layout >> somethig like this
I cannot comment, so i will help you editing. Use SharedPreferences to store the string from the edittext in order to get persistance. Then get the string from the SharedPreferences and do the same thing that you are doing(pass it through the intent)
there is MorningDrsGeneral :
public class MorningDrsGeneral extends ActionBarActivity {
Button button ;
EditText et;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.morningdrs);
et = (EditText) findViewById(R.id.et);
addListenerOnButton1();
}
public void addListenerOnButton1() {
final Context context = this;
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(context, bookingKamal.class);
intent.putExtra("fn" , et.getText().toString());
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
and there is bookingKamal.java :
public class bookingKamal extends ActionBarActivity {
Button button;
TextView textView3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bookingkamal);
textView3 = (TextView) findViewById(R.id.textView3);
String A = textView3.getText().toString();
String N = " ";
if (A.equals(N)){
Intent intent = getIntent();
String texx = intent.getStringExtra("fn");
textView3.setText(texx);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
So i have to keep the text in the bookingKamal activity .. it means when i go back from this layout and back to it the text should be the same as previous. And in this code it back to null :/ or
You have two options here:
Save the value into the internal file system so it can still will be loaded after the app has been unloaded
Save the value in the Activity which holds the button to this activity and save the text over there in a variable and when the bookingkamal activity starts, it could be read from somewhere (hint: Intent#putExtra("KEY", "VALUE"))
I am not describing how you should do it because there is enough documentation about it out there and that is not the point of this answer. This should give you an idea how to it.
You can do that by using sharedpreferences.
The above link will help you undderstand how to use it.
To add data to SharedPreferences use
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putString("text", mSaved.getText().toString());
editor.putInt("selection-start", mSaved.getSelectionStart());
editor.putInt("selection-end", mSaved.getSelectionEnd());
editor.apply();
And to retrieve
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null)
{
//mSaved.setText(restoredText, TextView.BufferType.EDITABLE);
int selectionStart = prefs.getInt("selection-start", -1);
int selectionEnd = prefs.getInt("selection-end", -1);
/*if (selectionStart != -1 && selectionEnd != -1)
{
mSaved.setSelection(selectionStart, selectionEnd);
}*/
}
Note : that SharedPreferences will save the value such that, even of you close the application and restart it. The values will still remain. So, make sure you clear the data when you done with it. You can read more about it here at the SharedPreferences docs.

How do i make a notification appear at random times throughout the day?

Hi im trying to make a notification appear at random times throughout the day. right now all it does is make the notification appear when i press the a button. I would like the button to start making them appear every hour or so. Here is my MainActivity class.
public class MainActivity extends Activity {
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
NotificationCompat.Builder notification = new NotificationCompat.Builder(MainActivity.this);
notification.setSmallIcon(R.mipmap.ic_launcher);
notification.setTicker("Hey!!!");
notification.setWhen(System.currentTimeMillis());
notification.setContentTitle("You're Awesome");
Uri sound = RingtoneManager.getDefaultUri(Notification.DEFAULT_SOUND);
notification.setContentText("keep being awesome!!!:)");
notification.setSound(sound);
Bitmap picture = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
notification.setLargeIcon(picture);
PendingIntent mypendingintent;
Intent myintent = new Intent();
Context mycontext = getApplicationContext();
myintent.setClass(mycontext, Activity2.class);
myintent.putExtra("ID", 1);
mypendingintent = PendingIntent.getActivity(mycontext, 0, myintent, 0);
notification.setContentIntent(mypendingintent);
Notification n = notification.build();
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify(1,n);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Look over here: https://developer.android.com/training/scheduling/alarms.html
What you need to do is make an alarm, for example which will activate your app code every hour like you want. In this alarm you will make a new notification.
If you need a code example look over here: Alarm Manager Example

Categories