How to get button Id on click? - android

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);
//....

Related

Unable to get the position in a RecyclerView

I am trying to create a dynamic survey app, using a RecyclerView. I have no problem on initializing the primary questions. The issue is when I try to insert a row in the recyclerView.It is not placed where it is expected to be. I wanted the row to be inserted next to the current row. I tried several methods like getAdapterPosition, getLayoutPosition for viewholder but I cant get the selected correct position of the view. Furthermore, the RecyclerView does stores the old location of a view when something is inserted. Could someone help me to figure this out or is there any easier approach. Furthermore, Thank you guys, I'm a newbie programmer.. Here is a snippet of my Adapter where I create and initialize dynamic views.
What i always do and works fine is to use tag.
for example you have a radio button and you have an item ( Question , single choice etc... ) .
before you assign a clicklistener to your view just put that item as tag
MYVIEW.setTag(MyItem);
so in your clicklistener just do this :
new View.OnClickListener() {
#Override
public void onClick(View v) {
ITEM item = (ITEM)v.getTag();
int alwaysTruePosition = items.indexOf(item);
...
}
}
Important note is that you should define equal method in your ITEM class and there should be a unique identifier which helps you to define are two objects the same or not. (for example a unique id or unique name )

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

Pulling data from one Tab Activity to another

Everything I've read about Intents talks about using them to push data, or to start one Activity from another Activity. I want to pull data from an Activity that's already running.
The Tab Layout tutorial at http://developer.android.com/resources/tutorials/views/hello-tabwidget.html illustrates what I want to do. (My app is doing some engineering calculations instead, but the tutorial code provides a good analogy to my app.) The tutorial creates an app with three tabs, and each tab hosts a separate activity.
To expand on the example in the tutorial, suppose I select an artist in the Artists tab/activity. I want to be able to select the Albums tab/activity and have it display all the albums featuring that artist.
It seems to me that I need to use an Intent to do this. All of the tutorials I've found assume that I would create a "See albums" Button in the Artists tab/activity, and that pressing the Button would execute an Intent that starts the Albums activity and passes artistName.
I DO NOT want to create that Button. Real estate on the Artists layout is precious, and I have a perfectly good Albums tab, AND the HelloTabWidget activity already contains an intent to create the Albums tab.
Besides, a user will want to skip back and forth between Album and Artist in order to change artist selections, and the tabs are a perfectly good way to do this. There's no need to complicate the UI with another button.
So how can I have the Albums activity PULL artistName from the Artists activity when the Albums tab is selected (or the Albums layout is displayed), rather than have the Artists activity START Albums and PUSH the artistName?
Equivalents I can think of from other programming worlds:
Global variables. Discouraged in Android devt, right? And if they do exist, what are they called?
A getter, like artistName = Artists.getArtistName(); . I get the feeling that it's not that easy.
Writing to, and reading from, a file - that is, mass storage or non-volatile memory. I don't need the artistName value to be permanent. It will be reset to null every time the user launches the application.
So how is it done in the Android world? Do I use an Intent - and if so, how?
Global variables were the right answer.
I thought Java discouraged their use, but a couple of links that appeared in the "Related" links on the right margin of this window mentioned them directly. One was "Android: How to declare global variables?" and the other was "how to pass value betweeen two tab in android". Both pointed to the Application Class as the place to define global variables and methods. Armed with this new knowledge, I found an article called "Android Application Class" on the Xoriant blog that expanded on the StackOverflow answers.
It's best to review those three links first. I need to add some tips to what those authors have said.
Your Application class has to be in its own separate file. (That might be a "duh" to some people, but not to everybody.) Here's a good framework for an example called Something.java:
public class Something extends Application {
// Put application wide (global) variables here
// Constants are final, so they don't have to be private
// But other variables should be declared private;
// use getters/setters to access them
public final boolean FEET = false;
public final boolean METERS = true;
private boolean units = FEET;
#Override
public void onCreate() {
super.onCreate();
// Put any application wide (global) initialization here
}
// Put application wide (global) methods here
public boolean getUnits() {
return units;
}
public void setUnits(boolean whichOne) {
units = whichOne;
}
}
I'm using Eclipse with the ADT plug-in, in Windows XP. Eclipse doesn't always behave properly if you edit XML code directly, so it's best to open AndroidManifest.xml, then select the Application tab and enter your application name in the Name field. You don't need to put a dot or period in front of the name. Just type in the name of your class, like "Globals" or "MyApplication" or whatever. (Note that this is the default application in your Manifest. You don't have to create a separate <application></application> tag.
This step may not be necessary on an actual Android device, but it was necessary for the emulator: you need to use the getApplicationContext() command in every onCreate() and every method that will be accessing the global variables and methods. I tried to put it outside of onCreate() with the rest of my activity wide variables, and it didn't work. Putting it inside every method seems wasteful, but both the emulator and the Android device work fine with it that way. Here's a sample showing how I used it:
public void fooBar() {
// Access to global variables and methods
final Something s = (Something)getApplicationContext();
// ...
// This next line demonstrates both a global method and a global variable
if (s.getUnits() == s.FEET) {
// do something with feet
} else {
// do something with meters instead
}
// ...
}
Those were the only hiccups I encountered. The three references that I have listed, taken together, are otherwise pretty complete.

Buttons using onClickListener

am new to android
I have seen many examples on creating buttons, but i just can't get what does each line mean :(
take the following piece of code as an ex.
connect = (Button) findViewById(R.id.button_connect)
connect.setOnClickListener(connectListener)
private OnClickListener connectListener = new OnClickListener() {
public void onClick(View v) {
Log.i("CONNECT PRESSED", "press")
// ....
// ....
// ....
};
what i know is that the first line Defines a button, but wht is findViewbyId?
i know the second line
but then when defining the listener, what's the log.i?
nd r "connect pressed" and "press" just labels for the button? f so why there r two for a single button...
You should have an additional Button connect; before those lines.
connect = (Button) findViewById(R.id.button_connect) // findViewById() in layman term it means, finding view by id. Which also means finding the view(button/textview/edittext) by ID(value you stated in your main.xml for the view. e.e. android:id=#+id/"")
connect.setOnClickListener(connectListener) //listens to a click when clicked
private OnClickListener connectListener = new OnClickListener() { //if button of android:id="button_connect" is clicked, Do this method.
public void onClick(View v) {
Log.i("CONNECT PRESSED", "press") //prints message in your logcat
// ....
// ....
// ....
};
If you still don't understand what does findViewById(), just think of it this way. View is man. Id is name. So in the end you are finding the man by name("Whatever this is")
In Android you normally define the layout of an Activity in an XML file. Each View element in a layout that you want to interact with in code needs an id. In you example the layout XML file needs to have a button with the id button_connect.
In the onCreate() method of an Activity you normally call setContentView() and pass it the layout you want to use in this Activity. E.g. setContentView(R.layout.my_layout); where your layout file's name is my_layout.xml.
The setContentView() method builds up the defined layout as objects and with findViewById(R.id.button_connect) you get a reference to a Button object from this layout whose id is button_connect.
Log.i() is simply logs the message "press" under the tag "CONNECT PRESSED" in the log cat.
It seem to be you didn't read basic things about android app development. Android Developers website providing information to learn android app development with good examples and tutorials. You are asking very basic things by just copying the code from tutorials.
Actually its not the right place for this kind of questions. First do practice by reading tutorials around the web.
Coming to your doubts regarding code you posted here, those are very basic things.
findViewById() finds a View by field Id, which is declared in XML layout file as below
Log.i() is LogCat info message displayed in your logcat window when debugging is enabled in your app.
in your example you probably have defined an xml layout file as the style of your activity with setContentView(R.layout.myXMLLayout);
If not, findViewById(R.id.button_connect) will fail.
R.id.button_connect refers to an id created in your xml layout.
There has to be a line android:id="#+id/button_connect" in a < Button > tag.
findViewById finds this Button (which is more genereally a view, which is why you have to cast it to a Button with the (Button) before findViewById(...) ). You then refer to exactly the button you've put in your xml.
Log.i("CONNECT PRESSED","press"); isn't necessary at all. It's just logging the press of the button and displays it in the log cat. It can be removed without any further impact. This is for debugging only and should be removed for any final (public) versions of your code.

Android click button populate textview

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.

Categories

Resources