I would like to start an activity only if the string I pass with putExtra from another activity equals 'search' like so:
action = intent.getStringExtra("cause");
Button btnBack = findViewById(R.id.btnBack);
btnBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(action == "search") {
Intent intent2 = new Intent(profiloutente.this, ricerca.class);
startActivity(intent2);
}
}
});
But, the condition always seems to be false (so the activity doesn't start) even if the variable containing the get Extra equals "search". I don't understand why this happens. Could someone help me?
The obvious probklem is that you are using == on a String. How do I compare strings in Java?
Another problem is that action is read outside of listener. That may be the intent, but I can't tell in isolation - if it is the surrounding the entire listener in the if statement would make more sense. action will take the value from getStringExtra at the time you run the surrounding code, not when the listener is fired.
There may be other issues.
if(action.equals("search"))
instead
if(action == "search")
Related
Consider you have a Button A and button B both of them when clicked it start Activity1 which contains only one TextView.
Now When I click on Button A it should start Activity1 and setTextView to "The click was from A"
and when clicked on B it should set the text to "The click was from B".
So I figure out that by making a global Boolean variable but I wanted to know is there any other way that is more efficient than making a global Boolean variable(the code become really messy with Boolean)
And this all is just an example in reality I want to add a lot of code instead of just setting the text.
TL;DR
Pass arguments with your Intent object that launches Activity2. Use putExtra methods. That is the default way of passing small pieces of data.
Explained
"making a global Boolean variable" is a bad solution (nothing personal, it just does not fit the given problem) in this situation as anyone has access to that variable and the value can be changed at any point in time making it unreliable.
When you launch activity with Intent you can use putExtra methods on it (example of such method in docs).
For example, there is a putExtra that accepts boolean as a value: link. Using that method you can remove the global variable, but the code still could be messy.
If this boolean variable is simply deciding which label to show you can pass the label itself using these putExtra methods. It would look like this:
// From Activity1 when you click Button A
buttonA.setOnClickListener {
Intent intent = new Intent(Activity1.this, Activity2.class);
intent.putExtra(Activity2.SOME_KEY, "This label is from buttonA.");
startActivity(intent);
}
// From Activity1 when you click Button B
buttonB.setOnClickListener {
Intent intent = new Intent(Activity1.this, Activity2.class);
intent.putExtra(Activity2.SOME_KEY, "This label is from buttonB. A slightly different one.");
startActivity(intent);
}
Activity2.SOME_KEY is some public static variable that you should declare to be sure that you use the same key for setting and getting back the value. You can name it differently. It must be of String type. There is no need to declare it in Activity2 class but since it is the key for passing arguments for Activity2 only I think that is the most fitting place.
And now in you can get that value back in Activity2:
class Activity2 extends Activity {
public static String SOME_KEY = "some string value";
private String labelValue = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
labelValue = getIntent().getStringExtra(SOME_KEY);
// ... other stuff here like setContentView
// use `labelValue` to set text into some TextView.
}
}
How do I get an item id when I click on it without setting an "onClick" event in the xmk file?
I tried that:
private View.OnClickListener globalClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
int clickedPosition = (int) v.getTag();
// do something with position
}
}
But i don't understand how to use it
Hello!
Rebuild the method as follows:
private View.OnClickListener globalClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
}
}
Well, to get the target ID that you click, it is better to first define the attribute android:tag="target_id" in the XML file, and then access it within the called method when the target is clicked, using the v.getTag(). Of course, you can also get the clicked ID via v.getId() without doing so. You can check the ID from:
use if (v.getTag () == R.id.target_id), or parse it as follows:
String viewID = getResources (). GetResourceName (v.getId ())
Your code creates a listener without actually attaching it to anything, so it never receives click events. If you have, for example, a button that you want to respond to clicks, you can register your listener with it like so:
button.setOnClickListener(globalClickListener);
Currently i managed to create the buttons dynamically on a view
Here is the my code to create the buttons;
public void Add_on(View v) {
AlertDialog.Builder mbuilder = new AlertDialog.Builder(Mb.this);
View mview = getLayoutInflater().inflate(R.layout.activity_mb1, null);
EditText number = (EditText) mview.findViewById(R.id.etnum);
Button Create = (Button) mview.findViewById(R.id.etcreate);
Button Cancel = (Button) mview.findViewById(R.id.etcancel);
Create.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
if (!number.getText().toString().isEmpty())
{
Toast.makeText(Mb.this, "Number can be NULL",Toast.LENGTH_SHORT).show();
LinearLayout yenilayout = new LinearLayout(Mb.this);
int n =1;
for(int i=0; i<n; i++)
{
Button yeniButton = new Button(Mb.this);
yenilayout.addView(yeniButton);
yeniButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(Mb.this, "Button is working",Toast.LENGTH_SHORT).show();
}
});
}
altlayout.addView(yenilayout);
} else {
Toast.makeText(Mb.this, "Number cannot be NULL",Toast.LENGTH_SHORT).show();
}
}
});
But whenever i recall the activity, the buttons are no longer exist. So May i know can i place the button there permanently?
Thank you for suggestions
You can use Bundle to save an activity's state and recreate it in the onCreate() method. This works for a particular instance of Activity, so can be used to save data concerning selection, or user input etc., but not data that you need to be persistent across application launches.
To use the Bundle, override the onSaveInstanceState(Bundle) and onRestoreInstanceState(Bundle) methods in the Activity class. You can use methods from Bundle to save whatever data you like in a map, and get it back in onRestoreInstanceState(Bundle), which is called in onStart().
The default implementations already handle most UI stuff though, and I would have thought this would keep track of your buttons for you, so it may be that your question is actually about associating some persistent data with your application. (this also means that if you do override the above methods, you should make sure to call the super methods in the first line of your implementation).
If you need persistent data across application launches, then the quickest and easiest way would be to use SharedPreferences, see this answer for an example.
I'm using Eclipse for windows 7 and I am making an informative application(just text and offline content).
In my app I have about 180 buttons. Each button will lead to another screen. I need to know how to make each button lead to a specific screen?
And also, is there a way to like duplicate the code and not spend hours copying and pasting the code 180 times?
Check my code below for the first two screens:
That's for the MainActivity.java:
public void addListenerOnButton() {
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, MainActivity2.class);
startActivity(intent);
}
});
}
I mean that code is only for one single button. Am I supposed to repeat this for every single button?
and also a question, how many classes should I do? 180 main activities, 180 fragment_main.xml and 180 activity_main.xml?
That's my idea, since your application is just a "informative application" you can create two activities:
Main activity with buttons
"Information page"
To do it i need info about how you get this informations:
In a SQLite Database.
In a string-array
Personally, i prefer a SQLite DB it allows you to improve it without problems in the future.
About the Information activity:
Example: in your layout you have a TextView where will be added the text which this activity should be passed.
To make it dynamic in your case we pass the string to show using Intents, in our onCreate we add something like this:
Intent intent = getIntents();
String stringToDisplay = null;
if (intent != null)
{
stringToDisplay = intent.getStringExtra (EXTRA_STRING_CONTENT);
}
getIntents will get the Intent object which is created and passed to it by our main activity. getStringExtra is a simple method which says to Android: i want to get the string which is saved with the key EXTRA_STRING_CONTENT (it's something like a Map)
EXTRA_STRING_CONTENT is a field which we used to make sure we don't make any error in passing data, since we need to use the same name when we pass it (in MainActivity) and when we read it (InformationActivity)
public static final String EXTRA_STRING_CONTENT = "EXTRA_STRING_CONTENT";
Ok, we are done.
We now only need to set the string to our TextView:
TextView infoTextView = (TextView) findViewById(R.id.infotextview);
infoTextView.setText (stringToDisplay);
Stop it.
Now we should go to our MainActivity code and modify our addListenerOnButton
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, MainActivity2.class);
startActivity(intent);
}
});
Well, i will focus on this two lines
Intent intent = new Intent(context, MainActivity2.class);
startActivity(intent);
We need to pass the string to display here, how?
Before we used getStringExtra now it's similar (note: it's the same Intent class) but now we need the putExtra method, the compiler will select the correct overload for us so we just need to do
String stringToDisplay = "Hello world";
intent.putExtra(InformativeActivity.EXTRA_STRING_CONTENT, stringToDisplay);
(Note: InformativeActivity.EXTRA_STRING_CONTENT)
With the current code we will always sent Hello world to the second activity but we need something of dynamic based on the button... well now this depends on how you get the data.
If it's a string-array, you can save the string-array in an array and then based on the button (if it's the first sent string index 0, etc.).
An example:
int buttonId = 1; // it will be a general variable, if it's button 1 it will be 0, if 2-1 etc.
String[] informations = getResources().getStringArray(R.array.infos); // in a real code you should move it outside the `onClick` code and put it in a static final field.
intent.putExtra(InformativeActivity.EXTRA_STRING_CONTENT, informations[buttonId]); // it's the same of above
If you understand the concept you will know how to adapt the code based on your needs.
There are some cases where you need more info or what you want to sent is something which is better if managed by the second activity (example: in a sqlite database you could sent only the id of the line and read lines in the second activity based on this id)
Some things which you could change:
Avoid to call it MainActivity2, it's not so helpful as name
You don't need really to save Context, you could just use MainActivity.this
Try to make your addListenerOnButton more general, example take as argument a Button and set the listener to it.. don't read it from XML you will end up with 180 methods for every button.
I'm having a very weird situation in my app. I have an activity, on which I have log in button. On button click I'm checking whether user is logged in or not, and simultaneously showing proper message. My code looks like this:
#Override
public void onClick(View v) {
if (loginUserId == null || loginAccessToken == null) {
Intent intent = new Intent();
intent.setClassName("com.example.poc",
"com.example.poc.LoginPromptDialog");
startActivity(intent);
} else {
System.out.println("Else condition here!");
}
}
On else condition I'm printing on the log.
In my case take a scenario that user is not logged in, then Login Prompt Activity will be shown. I have a skip button on my Second Activity, on that button I'm just calling finish() method. And I'm coming back from Second Activity to First Activity. This is confirmed that my onResume() method is called when coming back from Second Activtiy.
Still user is not logged in and when I click again button on the First Activity my else condition is called. Why again my if condition is not called?
I can't figure out why this is happening.
Any kind of help will be appreciated.
I was getting "" values from the other activity. Thanks to the comments I got. Solved.