Android click button populate textview - android

This is week one of Android for me!
I'm programmatically creating a textview, two labels and a button in the same activity.
The idea is that the textview receives a string from the user.
The user clicks the button and the textview string is passed to a proc which returns a string result, and the string result is assigned to one of the labels.
public void onClick(View view) {
sresults = showPP(ttsymbol.getText().toString().trim());
}
But this doesn't work, because "the final local variable sresults cannot be assigned, since it is defined in an enclosing type"
I think I understand what is going wrong, but is there an alternative way of returning the results so that they can be displayed in the label? Or is it necessary to create a new dialog inside the onClick function to show them?
Thanks!

If you are sure of changing the value of sresults, then there is no point in making it final. final is used for constant values. You should directly set the value to the label view. The label view reference can be final.
public void onClick(View view) {
label.setText(ttsymbol.getText().toString().trim());
}

More code would be helpful here, how is sresults, showPP, etc defined? However, the message suggests you have defined sresults as "final" which means you can't change the value. Probably removing final would solve that problem.

Related

How to get button Id on click?

Currently im making a soundboard like app. Becouse i have around 60 sounds it would take ages to create function for every single one. So I ran into idea, is it possible to detect press of any of these buttons and then get its id? It will be very helpful, becouse the buttons ids are also corresponding music file names. Thanks for any help.
From the question, it was not immediately clear that you are seeking a way to retrieve information encoded in your choice of ID string names rather than to simply use a single handler for all of your buttons, for which getId alone is typically sufficient.
The resource name for a View ID can be extracted from an ID using View.getResources().getResourceName(id). (1)
The result is a reusable listener that obtains the file names by extracting the view ID and looking up the resource name:
View.OnClickListener mSoundClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
String resourceName = view.getResources().getResourceName(view.getId());
mySoundHandler(resourceName);
}
};
You can then attach the handler to each button.
button1.setOnClickListener(mSoundClickListener);
button2.setOnClickListener(mSoundClickListener);
//....

How to retrieve the text entered in an EditText Field from the Listener?

My first android project! I have a Login Activity. Within it there are two EditText fields, "username" and "password". I've made a listener for when the user has completed the field, namely an onEditorActionListener. My motivation behind this is that I need the username and password fields as a String Variable to send to Volley and onto an API. The password Listener is nearly identical to the code below.
final EditText loginEditText_User = (EditText) findViewById(R.id.login_user);
loginEditText_User.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_NEXT){
// TODO Retrieve Username here
Log.d("[userName]", loginEditText_User.getText().toString());
loginEditText_Pass.requestFocus();
}
return true;
}
});
I've tried simply declaring a variable String userName before the listener and setting the value within the block via userName = loginEditText_User.getText().toString();, but this doesn't work because "the variable 'userName' is accessed from within inner class, needs to be declared final". However, but when declared final, I obviously "cannot assign value to final variable".
I've seen related questions such as this and this, but they're not quite the same thing.
Thanks in advance!
You can just define you userName variable as a field of your activity, and then you will have an access to it in your scope:
private String userName;
I just answered someone else's question about the same thing here: Edit text first time to input a letter validation
If you use a TextWatcher interface instead, you can get the updated text every time the user adds or removes a letter. Now, If you don't care about the current text until they hit your login button, then you could just do something like. editText.getText() and that returns the current text. The nice thing about the TextWatcher, is you can enable/disable the login button with valid/invalid text. And, it gets you around that whole 'final' issue you mentioned.
This is a known issue every programmer has to deal with a couple of times, there are some options to work around this problem :
1)Use a set function to change the value of the variable, functions can be called anywhere within an inner class.
2)Assign a new variable, which you initialized inside the inner class, with the value you want and use the new variable

Application with different requests sent to a database (SQL) depending on buttons clicked

I still am a beginner in Android development and will try to make my question as clear as possible with a schema of what I have in my mind.
Purpose of this application:
- I want the user to have the choice between a few buttons and when clicking on any of them, it would open a list view with different content according to the button.
ex : if you click on "Category_1" button, only elements with a fitting id will appear in the listview.
So far, I have :
- defined my "handler" class (extends SQLiteOpenHelper) : name/path of DB, definition of CRUD, .getReadableDatabase, etc.
- define a class for my table, in my case "Restaurants.java" with getters/setters and constructor.
- defined my MainActivity with empty listeners for my button.
- defined my "DatabaseAdapter.java" in which I want to define the methods/sql requests which will communicate with the database and get the information I want from it.
- defined my ListViewActivity with nothing to display so far.
Here is a schema of what I want with the idea of how to make it to try to optimize my application :
To sum up:
- I want a listener for each button setting a variable to a certain value (for example: "if you click on 1 then set the value of A to 1") and opening the ListViewActivity.
- There would be a method defined in "...Adapter.java" sending a request to the database and having the variable A defined earlier as an input.
- And then, when clicking on the button, the ListViewActivity will open and call the method from "..Adapter.java", and finally display the results.
So, here are my questions :
- First of all, is the design optimized enough to allow my application to run fast? I think it should as all the button open only one activity and there is only one method defined for all buttons.
- I have a hard time defining the method in "...Adapter.java" which will be called from my ListViewAcitivity. The input should be the variable obtained when clicking on the button but I don't really know how to get a variable in one activity, open a second activity where to display results by using the variable in a third activity... :s
Is it fine to set a variable to a certain value when we click on a button and use this variable in another class as an input for a method?
public findNameInTable(int A){
string sql = " select NAME from MY_TABLE where CAT1 = " + A;
c = database.rawQuery(sql, null); }
Thanks in advance for any indications, suggestions or links which could help me to make my application come true, and sorry if some questions really sounds newbie, I am starting !
Have a good day !
Part 1: The best way I have found to pass variables to other activities is with a putExtra(String, variable);. Say you change the variable name on a button press, you can then call:
YourNewActivityClassName var = new YourNewActivityClassName();
Intent i = new Intent(context, YourNewActivityClassName.class);
i.putExtra("name", name);
startActivity(i);
Then in the activity you just created, you can call this in the onCreate method:
Intent i = getIntent();
final String name = i.getStringExtra("name");
Of course this is assuming the variable was defined as a String before the putExtra was called.
If you want to use other variable types, there are different get***Extra commands you can call like getIntExtra(int, defaultval) but the putExtra will still be used to send it.
Part 2: For calling a method with a variable assigned in a button click, I have found the best way to do this is with a "holder class" this holder can be defined as a final, and a button press assigns a value to one of it's slots. Here is my holder for Integers:
public class holder {
int to;
public void setTo(int to){
this.to = to;
}
public int getTo(){
return to;
}
}
I instantiate my class as final within my on create final holder hold = new holder();
then call my hold.setTo(int); within a list click listener. When I want to get the data, I simply call hold.getTo(); and I have my integer.
Heres a similar post: Pass value outside of public void onClick
Hope this helps!
Mike

Android: setImgVisibility() error

In my app I have a header with icon hidden, I have a adapter with a listview when I click the listview I go to a login screen using listener, when the login is successful is should come back to listview(adapter) and icon should get visible on header.
In the login activity I have the following code:
public void onClick(View v) {
String password = etPassword.getText().toString();
if(password.equals("guest")){
SearchAdapter.setImgVisibility();
} else {
//-----
}
finish();
}
In my adapter I am calling the setImgVisibility() as follows, but it is not working
public static void setImgVisibility() {
img.setVisibility(View.VISIBLE);
}
I am getting a Nullpointerexception near the line img.setVisibility(View.VISIBLE);
I am stuck here and don't know what I am doing wrong. Any suggestions or help is appreciated
I would imagine that img is null. You need to look at where this value is set and make sure happens before you call the method setImgVisibility.
Show more of your complete code for people to help further.
Additionally, i've just noticed you've used a static reference to your search adapter, you should be really careful using statics, especially where any referencing of images is concerned as images can be bound to the context, as such unless you nullify the static you will end up with a memory leak. (this used to be an old problem, not sure its still valid, but i would still avoid using a static reference).
Without more code we're not likely to be able to properly help you. For example are you switching activities when logging in? If you are, this won't work at all.
[given the comment below] If you switch activities then your activity containing the list view is going to be destroyed and then rebuilt then you navigate back to it. or it will at least go through the activity lifecycle. This means you can set the icon during the instantiation of the header img.
You could store your logged in state as a property of the Application or a preference. Grab this value when you set the header image and set the image accordingly.
your img object is null. Is your img object is same as View v then you can pass v in setImgVisibility() and then set v.setVisibility(View.VISIBLE)

Displaying an array of objects, one at a time through a single dialog... instead of several dialogs

In my application I have a list of questions stored in an ArrayList, and I want to display a dialog that shows one question, and then continues to the next one after the question is answered. The way that I'm currently doing it (iterating through a loop) hasn't been working because it just layers all of the dialogs on top of one another all at once which causes a host of other issues. What I'm looking for is a way to still iterate through the questions, but just change the layout of the dialog each time until it has finished each question in the list. Can anyone give me a good pointer for how to get this going?
You can make a function that takes title and message as parameters and shows a dialog.
showDialog(String title, String message){ // Show dialog code here}
Within that dialog's answer button's listener call another function (showQuestion(currentQuestion)) that iterates the arrayList till it is over
int currentQuestion=0;
ArrayList<QuestionObject> questionList;
showQuestion(int i){
if(i<questionList.size()){
showDialog(questionList.get(i).getTitle,questionList.get(i).getMessage);
currentQuestion++;
}else{
//quiz is over
}
}
I assume you mean that you just want to change 1 single layout(created within XML i.e main.xml). In order to do this, make sure that the class your working on is pointing to that layout. From there (assuming your using an Event listener for when the user submits an answer) you can change do as you want by the following:
TextView txt = (TextView) findViewById(R.id.textView); // references the txt XML element
and in your Event listener, if the answer is correct then change(Have i be a global variable thats initially set to 0).
if(i<arrayList.size()){
txt.setText(arrayList.get(++i));
}else{
txt.setText("You Finished");
}
From there, in the else statement, you can change arrayLists and reset i to 0;
If you are trying to use the positive, neutral, and negative buttons; then you may have problems with multiple dialogs. Try defining a customized layout with your own TextViews, ListViews, and Buttons. You can implement listeners and everything else like a regular layout. Then just pass your customized layout to the dialog through AlertDialog.Builder.setView().
PS If you include code examples of what you are currently doing we can provided answers that are less vague.

Categories

Resources