Unable to access member variable in onOptionsItemSelected in android activity - java

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.

Related

How to "save" string variable from settings menu

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");

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.

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.

Make android app backround change when button is pushed, and is on value true or false

In my android app I have a button named "button1". When you click the button a boolean gets either true or false and displays some text appropriately for either true or false.
What I would like to have it do is along with change the text I would like it to change the background based on whether the value after you click the button is true or false.
I have tried anything and everything I can think of so any suggestions and help would be appreciated.
Below is the code without any modifications to try and make the background change.
public class MainActivity extends Activity {
Random r = new Random();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void calculate(View v){
EditText number1text=(EditText)findViewById(R.id.num1text);
String num1=(number1text.getText().toString());
String ans=num1;
TextView answer=(TextView)findViewById(R.id.answer);
boolean value = r.nextBoolean();
if(value==true){
answer.setTextColor(Color.GREEN);
answer.setText("It is a cause for celebration! So CELEBRATE!");}
if(value==false){
answer.setTextColor(Color.RED);
answer.setText("Exciting, but not a cause for celebration!");}
}
#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;
}
}
If you want to change background of your activity then try this,
View root = findViewById(R.id.main);
root.setBackgroundColor(getResources().getColor(R.color.red));
so your full activity code would look something like this
public class MainActivity extends Activity {
Random r = new Random();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View root = findViewById(R.id.main);
}
public void calculate(View v){
EditText number1text=(EditText)findViewById(R.id.num1text);
String num1=(number1text.getText().toString());
String ans=num1;
TextView answer=(TextView)findViewById(R.id.answer);
boolean value = r.nextBoolean();
if(value==true){
answer.setTextColor(Color.GREEN);
root.setBackgroundColor(getResources().getColor(R.color.red));
answer.setText("It is a cause for celebration! So CELEBRATE!");}
else{
root.setBackgroundColor(getResources().getColor(R.color.green));
answer.setTextColor(Color.RED);
answer.setText("Exciting, but not a cause for celebration!");}
}
#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;
}
}

Display editText and a Button in Another Activity

I am using Linear Layout(Horizontal) for my Android application. I am using two buttons for my screen which I have called as Chat and Draw. I want to display a second activity on clicking on Chat button in which I have an area for editText and a corresponding button called as Enter for entering the text.
In the DisplayMessageActivity class which I am using for Chat button, I have created the layout for editText and Enter button too. But however, on clicking on Chat I am not being able to see the area for editText and the button Enter.
Code in MainActivity.java :
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.appfirst.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void chatMessage(View view) {
Intent intent_chat = new Intent(this, DisplayMessageActivity.class);
startActivity(intent_chat);
}
public void drawing(View view) {
Intent intent_draw = new Intent(this, DisplayMessageActivity.class);
startActivity(intent_draw);
}
}
code in DisplayMessageActivity.java :
public class DisplayMessageActivity extends Activity {
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
What code should I write in the OnCreate function of DisplayMessageActivity class so that I am able to get the desired view ?
Can someone help me with the code. I am totally new to Android Development Framework. Thanks and Regards.
From your post i understand that u have 2 layouts 1 with 2 buttons "Chat" and "Draw".And when clicking chat u have to call another activity with Edittext and Enter button in it.If this is the case you simply call the Intent.
Intent intent=new Intent(this,yourclass.class);
startactivity(intent);
In Oncreate of your DisplayMessage do the following:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.YourXml.Xml);
}
In your second activity you need to put the following line setContentView(R.layout.whatEverYourLayoutIsCalled);, put it right after super.onCreate(...);
public class DisplayMessageActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activityxml);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
For more information look the below example link

Categories