In my application, there are five activities containing very long text. I want to add find facility to my activity, so that when a user types something to the search bar then if the activity contains that word then the word should scroll to top automatically being highlighted.I am able to call the Search Dialog (as instructed in the Android Developer page). Can you guys help me compare the input in the search dialog with the texts in my activity and scroll it to top?
MainActivity.java
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.search:
onSearchRequested(); //opens the search dialog
break;
return super.onOptionsItemSelected(item);
}
SearchableActivity.java
public class SearchableActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
//Get the intent, verify the action and get the query
Intent intent = getIntent();
if (intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
doMySearch(query);
}
}
private void doMySearch(String query) {
//what to do here???
}
}
Here the searchable activity is a different activity. How do I compare the search input with a text which is in another activity (MainActivity.java)?
What you trying to do is:
Take Certain Input Value from an activity (input in the dialog from MainActivity), then use that value to compare with something else in the another activity (SearchableActivity)
There should be few method to do so, I would suggest a simple method which is:
Store the Value Input to a Global Variable that can be access Global in the whole application.
Then used the store value in the Global Variable to do comparison the any activity you want to.
To store something to Global variable, you can use the SharedPreference Method: Android Shared preferences example
This Method store Specify Value into a Global Variable where all activity can be access and Store Permanently only until you command to delete. Something like a 'Session' of a Website.
In your case, I will make use of the sharedpreference by:
When user enter something in the search dialog, I will store the value in a SharedPreference Variable.
Then when come to the SearchableActivity that need to use the input value of search dialog to do comparison, I will call the SharedPreference Variable to do comparison.
For your information:
Share Preference is very useful to store Value that used for Permanent usage of the application and its Scope is covering all the Activity in your Application. You can have Great Control of it, because you can specify to Store, Rewrite, Delete the value whenever you want, in wherever you want.
Hope This Would Help.
Related
I know there must be douzens of answers to this question out there, but either i cant't find them or I don't understand them.
The Question:
How do I get my app to exactly start as it was left?
F.e. dynamicly added checkBoxes shouldn't dissapear!
There is no "out of the box" way of doing it. You could save the current state of your Activity in some way (More on persistence)
Then you need to be able to rebuild the desired state of the persisted state in your Activity lifecycle
You could save and load with the shared preferences for example:
public void saveState(YourState state) {
SharedPreferences sharedPreferences = app.getSharedPreferences(R.string.preference_file_key, Context.MODE_PRIVATE)
sharedPreferences.edit()
.putString("CustomAtt", state.getCustomAtt())
}
public YourState loadState() {
SharedPreferences sharedPreferences = app.getSharedPreferences(R.string.preference_file_key, Context.MODE_PRIVATE)
String customAtt = sharedPreferences.getString("CustomAtt", "DefaultValue")
return new YoutState(customAtt)
}
And use it like this
#Override
protected void onCreate(Bundle savedInstanceState) {
YourState state = loadState();
// Rebuild your activity based on state
someView.setText(state.getCustomAtt())
}
You can store such values in SharedPreferences.
https://developer.android.com/training/basics/data-storage/shared-preferences.html
It is using key-value approach for saving. So you can save some values and read it from SharedPreferences whenever you want to.
This is the best approach for small data, that can be used on the app launch. So you can quit your app and the data is still present - so can be read on the next app launch.
Or save the condition of your program to a text file, so that the program can "translate" it back into conditions before it stops, or what I do not recommend, it saves every object created with ObjectOutputStream.
I am very new to Java. I am doing a school project at the moment and I have my main activity, then I have a settings activity. I am trying to modify the xml from the main activity with the settings activity. I am able to modify the settings xml file with the settings.java, but I would like to modify the main activity xml with settings.java
public class Settings extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
// Get the Intent that started this activity and extract the string
Switch switchButton;
final RelativeLayout mRelativeLayout = (RelativeLayout) findViewById(R.id.activity_settings);
final RelativeLayout mRelativeLayoutMain = (RelativeLayout) findViewById(R.id.activity_main);
switchButton = (Switch) findViewById(R.id.switch1);
switchButton.setChecked(true);
switchButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean bChecked) {
if (bChecked) {
mRelativeLayoutMain.setBackgroundColor(Color.GRAY);
mRelativeLayout.setBackgroundColor(Color.GRAY);
} else {
mRelativeLayoutMain.setBackgroundColor(Color.WHITE);
mRelativeLayout.setBackgroundColor(Color.WHITE);
}
}
});
if (switchButton.isChecked()) {
mRelativeLayoutMain.setBackgroundColor(Color.GRAY);
mRelativeLayout.setBackgroundColor(Color.GRAY);
} else {
mRelativeLayoutMain.setBackgroundColor(Color.WHITE);
mRelativeLayout.setBackgroundColor(Color.WHITE);
}}
public void toast1(View view) {
android.widget.Toast.makeText(this, "Created by Cody Walls and Tommy Serfas", android.widget.Toast.LENGTH_LONG).show();
}
/*public void switch1(View view) {
ScrollView mScrollView = (ScrollView) findViewById(R.id.scrollView);
mScrollView.setBackgroundColor(Color.GRAY);
}*/
}
In the Code I am trying to change the background of the main activity xml with :
mRelativeLayoutMain.setBackgroundColor(Color.GRAY);
and when I run the app and click the intent it will crash with the error:
"java.lang.NullPointerException: Attempt to invoke virtual method
'void android.widget.RelativeLayout.setBackgroundColor(int)' on a null
object reference"
I think the easiest way is to create an PreferenceManager.SharedPreferences, in which I recommend you to store current app data. This will help you not to loose any changes in app after you exit the it. Here is short instructions:
Create button in settings activity which will change something in main activity.
Create onClickListener for your button.
Use .SharedPreferences to store was you button clicked or not. (I recommend storing boolean variables, this way you can store was button clicked or not.)
I both of your activities in onCreate method call .getSharedPreferences to read saved app values. (I mean to read was the button clicked or not.)
Use app values you got from 4. to change any element in activity. (For example if you stored that button was clicked, then change some TextView text or etc.)
I hope you understood the idea.
Link to the Android developer tutorial about App key values storing & saving
Link to the StackOverflow much easier explanation & examples
There are a couple of ways of doing this (Some of which depends on how you are switching back and forth from each activity). It also depends on what things you are changing.
From your settings page, as you are changing different settings, you'll save this content within Preferences. (You can see more how to use Preferences here: https://examples.javacodegeeks.com/android/core/ui/settings/android-settings-example/ or by just Googling it).
On you main activity, depending on how you come back to it (onStart most likely), you can setup the things you need to programmatically.
So, you may need to do a little research on the Android lifecycle and how each cycle works (https://developer.android.com/guide/components/activities/activity-lifecycle.html), how to program the UI programmatically through Java (http://startandroid.ru/en/lessons/220-lesson-16-creating-layout-programmatically-layoutparams.html), and the Preferences Android library to save certain settings.
The xml isn't meant to be "altered". You can change the UI programmatically. It's possible to build an Android app without any xml. When Android was first built, it didn't use the xml to create the UI. It was all done through Java. It was then added to use xml to create your activities or fragments or any UI component. This made things easier for more static activities or activities with very little dynamic content.
I searched a lot but i did not find my answer. I have developed an android application where on the very first lunch user will be shown a welcome screen made of viewpager. The problem is i don't know which place is the best to put the welcome activity code in my application.
The simplest way it could be that in the main activity at the very fist line even before super.onCreate(), inside onCreate method where i try to get the shared preference value and then evaluate whether it is fist lunch. If it is, then i start the welcome activity as shown below
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean welcome = sharedPreferences.getBoolean(getString(R.string.key_welcome), true);
if (welcome) {
// go and start welcoming activity
Intent intent = new Intent(this, WelcomeSlideActivity.class);
startActivity(intent);
}
super.onCreate();
}
}
But i found another approach to deal with it. It is Application class. Since Application class is the first one, which runs even before any other codes in my application. So i thought, i would be nice to do it there as shown below
public class App extends Application {
#Override
public void onCreate() {
super.onCreate();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean welcome = sharedPreferences.getBoolean(getString(R.string.key_welcome), true);
if (welcome) {
// go and start welcoming activity
Intent intent = new Intent(this, WelcomeSlideActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
}
So i am in dilemma, which one would be the best option to choose. And i am even not sure if i am doing it in the right way since there is no such documentation in android developer website or anywhere.
Have a look at how to create splash screens the correct way. https://www.bignerdranch.com/blog/splash-screens-the-right-way/
As for using the Application class - this is primarily used for Application-wide configuration for maintaining a global application state. Hence starting an activity from here does not make much sense as it's purpose has changed into becoming an entry point into the application rather than providing state for the app as a whole.
Furthermore, why not make the WelcomeSlideActivity the first 'launcher' activity? Then in there, you can create the logic of whether to launch the next activity without history or whether to show the current view.
Ideally, you should create a splash screen activity, which determines whether to show the WelcomeSlideActivity Or the MainActivity. The advantage of this is that while he app determines which Activity to launch, the user is presented with a splash screen that informs the user that the app has started
totally n00b in android programming with an embarrassing question, here it goes. For example, I have an onClick function with a view parameter like this:
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radio_pirates:
if (checked)
// Pirates are the best
break;
case R.id.radio_ninjas:
if (checked)
// Ninjas rule
break;
}
}
If I have to call this function in an another class in the same activity for example an AsyncTask class or whatever. How would I successfully do that? I have confusion with the parameter. Should I do it like:
View view; //local variable
onRadioButtonClicked(view); // it gives an error of being uninitialized
Or should I initialize it with a null value like:
View view = null;
//local variable onRadioButtonClicked(view); //this gives a null pointer exception
How do I call this function successfully without having a problem with the parameters?
Generally you wouldn't call your onRadioButtonClicked() method yourself. The way you should use this in android is to set the onClick attribute in your xml like so onClick:onRadioButtonClicked. This way the android operating system will call the method for you when the user clicks the button.
The way android handles events like button presses is to use a callback method. Your callback for the radio button can be set programatically by calling radioButton.setOnClickListener() and passing in a radioButtonOnClickListener that you would create yourself. It can also be set in the xml as stated above. If you have a method like that in your class you should declare the onclick in the xml.
Read this for onclick for views in general
http://martin.cubeactive.com/android-onclicklitener-tutorial/
and here is some example radioButtonCode so you can see one in action
https://github.com/asabbarwal/SimpleRadioButton
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
I know that when the user presses back button the saveoninstance is not supposed to be called.
I have a layout with many edittexts added dynamically by user, and then the user can enter text. I managed to save these when the user rotates screen using saveoninstance etc.
However, I also want to save these when the user exits app using the back button so when the app is opened again a "continue" button should be available for the user to continue (meaning adding all the text boxes again). I kind of know how to save and retrieve them, but which method should I use? Should i write a file for a example? Thanks.
When the user pressed back button application is closed. When he open app again it start as new instance and don't remember what user done before.
If u have to save data, then u can save them (eg. to Preferences or database) in onPasue or onDestroy
If you know how to save and retrieve them, why dont you just override the Back button and write save functionality there.
e.g.
public boolean onKey(View v, int keyCode, KeyEvent event)
{
// TODO Auto-generated method stub
return false;
}
#Override
public void onBackPressed()
{
/*Your functione here to what should be done on Back Button Press event*/
}
What you have to do is, you have override the below method in your Activity,
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
}
And save the state of your activity in SharedPrefrence, and next time when you enter your Activity get the value from the Sharedpreference and set the state accordingly.
Example,
private void SavePreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("state", "true");
editor.commit();
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
Boolean state = sharedPreferences.getBoolean("state", false);
button.setEnabled(state);
}
#Override
public void onBackPressed() {
SavePreferences();
super.onBackPressed();
}
onCreate(Bundle savedInstanceState)
{
//just a rough sketch of where you should load the data
LoadPreferences();
}
Basically shared preference in android are used to save the state of an activity or to save the important data within the scope of an application means data will remain saved till the application is installed in the devices. Shared Preference also works as Sessions which are used for the automatic login process.
see this Documentation.
And here is an Example.
Well its pretty simple. All you need to do is:
Use shared preferences and bundle.
Save everything in the onSavedInstanceState(Bundle outState)
Now how you do is:
Overwrite the function onSavedInstanceStae(Bundle outState)
and inside it
Save everything in Shared Preferences and then bundle them ,and this bundle is then sent automatically as a parameter in your onCreate(Bundle bundle)
Thus in your onCreate check if the bundle==null; if not retrieve sharedPreferences and load the data just like you saved it.