I am new to Android Studio and just trying to learn new ways to code and I'm stuck right now. I would like to use a String in a findViewById for example.
public void BDate0(String BId, String BHistoryClass) {
bdatum0 = (Button) findViewById(R.id.BId);
bdatum0.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent BDatum0 = new Intent(bethistory.this, BHistoryClass.class);
startActivity(BDatum0);
}
});
}
and I would like to call the BDate0 with the strings for example,
BDate0(BId1, BHistory1);
I have 10 buttons and the activity they start would be different every day.
Sorry for bad englihs it's not my native language and thank you for help in advance.
You can use this code to replace the findViewById(..). This should make it possible to use a string as identifier:
String BId = "button1"; // for example
int id = getResources().getIdentifier(BId, "id", getPackageName());
// finds R.id.button1
bdatum0 = (Button) findViewById(id);
Related
I'm new to android programming with very little experience, I'll try ask the correct question but I apologize if some of my understanding isn't quite up to scratch.
I'm building a basic calculator app with buttons 0 to 9. The user can use these to input that specific number into a text field.
I have the same piece of code (below) to do my button action for all 0 to 9 buttons. Just where to see the number 1 it's replaced with that buttons relevant number.
Button button1 = (Button) findViewById(R.id.button_calc_1);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String number_1 = ("1");
TextView Insert_Number_1 = (TextView ) findViewById(R.id.editTextoutput);
TextView Insert_Number_1_view = (TextView) findViewById(R.id.CurrentDisplay);
Insert_Number_1.append(number_1);
Insert_Number_1_view.append(number_1);
}
});
So i'm writing a subroutine of the same code that I can then call upon for the relevant button.
public String numberbuttons(String value){
Button button1 = (Button) findViewById(R.id.button_calc_1);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String number_1 = ("1");
TextView Insert_Number_1 = (TextView ) findViewById(R.id.editTextoutput);
TextView Insert_Number_1_view = (TextView) findViewById(R.id.CurrentDisplay);
Insert_Number_1.append(number_1);
Insert_Number_1_view.append(number_1);
}
});
}
Bear in mind this is a work in progress.
My question is basically how do I add the variable numberbuttons to the button_calc_(insert numberbuttons here)
EDIT:
Okay so from the second block of code. I want to use the numberbuttons variable within the findViewById(R.id.button_calc_1).
So in my head I picture it like this.
findViewById(R.id.button_calc_+(numberbuttons);
The same for when I call a textview. I picture it like this.
TextView Insert_Number_+(numberbuttons) = (TextView ) findViewById(R.id.editTextoutput);
The findViewById() method requires an integer, not a String, so you cannot just pass in a String with the name of the button that you are trying to use. When you use R.id.xxx you are passing a reference to the resource, which is actually just an int.
To accomplish what you want I suggest using a list of some type to store the buttons, and then looping through this. Please see an example below.
ArrayList<Button> buttons = new ArrayList<>();
buttons.add((Button) findViewById(R.id.button1)); //Do this for all the buttons.
for(Button b : buttons){
b.setText("1"); //Do whatever you need to each button in here.
}
If you wanted to use a method to manage all your buttons, you can do this too!
changeButton((Button) findViewById(R.id.button1));
private void changeButton(Button b){
//Change the button
}
EDIT:
To be more relevant to your question if I understand correctly, to add an event handler to each.
ArrayList<Button> buttons = new ArrayList<>();
buttons.add((Button) findViewById(R.id.button1)); //Do this for all the buttons.
for(int i = 0; i < buttons.size(); i++){
Button b = buttons.get(i);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String number = String.valueOf(i);
TextView Insert_Number_1 = (TextView ) findViewById(R.id.editTextoutput);
TextView Insert_Number_1_view = (TextView) findViewById(R.id.CurrentDisplay);
Insert_Number_1.append(number_1);
Insert_Number_1_view.append(number_1);
}
});
}
I am making a simple mobile app. For now I am just testing the app and trying to pass some values in between java files and put them in empty TextViews. I get values from a previous activity via Intent and then trying to pass them on to another activity called ConsultActivity.java:
String username = getIntent().getStringExtra("Identifiant");
final TextView tv = (TextView)findViewById(R.id.TVUsername);
if(username.equals("marcel123")){
tv.setText("M Dupond");
}
else if(username.equals("tommy1")){
tv.setText("M Thompson");
}
else if(username.equals("emma89")){
tv.setText("Mme Sinieux");
}
consult = (ImageView)findViewById(R.id.consult);
consult.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(MainActivity.this,ConsultActivity.class);
i.putExtra("Username", tv.getText().toString());
startActivity(i);
}
});
However in my ConsultActivity, when I am doing basically the same thing, my equals are highlighted and say "Cannot resolve symbol equals"
String name = getIntent().getStringExtra("Username");
final TextView textV = (TextView)findViewById(R.id.TVUsername2);
if(name.equals("M Dupond")){
textV.setText("M Dupond");
}
else if(name.equals("M Thompson")){
textV.setText("M Thompson");
}
else if(name.equals("Mme Sinieux")){
textV.setText("Mme Sinieux");
}
Probably its just a Synchronization problem try with: Sych project with gradle files
I have set myself up an array with questions and answers as follows:
static String[][] question= new String[20][5];
{
question[0][0] = "what is my name?";
question[0][1] = "Mark";
question[0][2] = "Steven";
question[0][3] = "Alan";
question[0][4] = "Bob";
question[1][0] = "what is my age?";
question[1][1] = "30";
question[1][2] = "31";
question[1][3] = "32";
question[1][4] = "33";
}
first square brackets indicates the question number and the second number gives the answer number, all correct answers are in 4th answer.my intention is to build a general app of questions that randomize and to pass to the next screen. I have used this code to generate a random number for the question number. so for e.g. 1st attempt Q5 will come up, attempt 2 Q3 could come up, attempt 3 Q1 could come up etc.
This next block of code is used by the android:onClick="goToQuestions"
public void goToQuestions (View v)
{
Intent intent = new Intent (this, Questions.class);
startActivity(intent);
}
using the above code will successfully move from current activity to questions activity. If i use this code below:
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_questions);
final TextView textView1 = (TextView) findViewById(R.id.textView1);
final Button button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
int randomArray = (int) (Math.random() *4);
textView1.setText(question[randomArray][0]);
}
});
}
it will allow me to generate a random number from the array of questions and print it to my text view when it is in the same activity. I have tried this code below to try to pass the information to the questions screen from the home screen:
public void goToQuestions (View v1)
{
final TextView textView1 = (TextView) findViewById(R.id.textView1);
int randomArray = (int) (Math.random() * 4);
textView1.setText(Questions.question[randomArray][0]);
Intent intent = new Intent (this, QuizActivity.class);
startActivity(intent);
}
I have assumed calling android:onClick eliminated the need for an onclick listener. Can anyone provide assistance for how I could finish this correctly. With that last piece of code the app just crashes as I hit the button.
Your data model is not ideal. Create a class that represents a question, and is Parcelable, so you can pass that to your next activity. Something like this
public class Question implements Parcelable {
private final String mQuestion;
private final List<String> mAnswers;
private final int mCorrectAnswer;
public Question(final String question, final List<String> answers, int correctAnswer) {
mQuestion = question;
mAnswers = answers;
mCorrectAnswer = correctAnswer;
}
// implement parcelable interface below
}
Then you would receive this on your next activity, deserialize it and show the data as you see fit.
Consider also using fragments instead of activities.
Found my issue, firstly thank you all for your assistance. Secondly I was able to do this task using the code I was using, I was just putting it into the wrong class files. I was able to move this code:
final TextView textView1 = (TextView) findViewById(R.id.textView1);
int randomArray = (int) (Math.random() * 4);
textView1.setText(Questions.question[randomArray][0]);
into my onCreate method and it worked fine.
I've been working on an Android program for a bit and I'm going crazy here... I'm trying to let the user enter a few numbers that would be put into the middle of a URL.
I need the code to read from a text box.
Here's what I've got so far:
public void browser(View view)
{
Intent browserIntent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://www.website.com/(',R.id.isbn'));
startActivity(browserIntent);
}
Doing this just adds the (',R.id.isbn')); to the URL.
How do I fix this?
Thanks!
The answer Anand posted is a simple solution to your problem. If you want the ISBN to be in the middle of the URL, you can just concatenate it like this:
EditText t = (EditText) findViewById(R.id.isbn);
String isbn = t.getText().toString();
Intent browserIntent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://www.website.com/" + isbn + "/more-text-here"));
startActivity(browserIntent);
Read more about concatenating strings here:
http://www.javatpoint.com/string-concatenation-in-java
Supposing that you are talking about Android EditText field, you could read it's value using editText.getText().toString(). This is an example on how to use it in your application:
#Override
public void onCreate(Bundle savedInstanceState) {
//... init code cutted
Button button = (Button)findViewById(R.id.button);
EditText editText = (EditText)findViewById(R.id.isbn);
button.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
String isbnText = editText.getText().toString());
// other code to open the new activity
}
});
}
Try it in this way.
EditText t= (EditText)findViewById(R.id.isbn);
String st= t.getText().toString();
Uri.parse("http://www.website.com/"+st);
Let your URL be like String url ="http://www.website.com/%1s/somevalue/%2s/etc+%3s";
Call String.format(url,1,2,3);
Hope this will solve your problem
This is kind of hard to explain. Basically it's kind of like a simple game. I want the people to input their names (currently the submit button is not working correctly) hit submit for each name and when all names are in they hit play. It then opens up the next class. It needs to get the string array from the prior class as well as the number of players. It then needs to select each persons name in order and give them a task to do (which it randomly generates). Then it allows the other people to click a button scoring how they did. (I am not sure how to set up the score system. Not sure if there is a way to assign a score number to a particular array string) I would then like it after 5 rounds to display the winner. If you have any input or could help me out I would be extremely grateful. Thanks for taking the time... here are the two classes i have.
Class 1
public class Class1 extends Activity
{
int players=0;
String names[];
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.class1);
final EditText input = (EditText) findViewById(R.id.nameinput);
Button submitButton = (Button) findViewById(R.id.submit_btn);
submitButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View submit1)
{
players++;
for(int i=0; i < players; i++)
{
names[i] = input.getText().toString();
input.setText("");
}
}
});
Button doneButton = (Button) findViewById(R.id.done_btn);
doneButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View done1)
{
Intent done = new Intent(Class1.this, Class2.class);
done.putExtra("players", players);
done.putExtra("names", names[players]);
startActivity(done);
}
});
}
Class 2
public class Class2 extends Activity
{
int players, counter, score, ptasks,rindex;
String[] names, tasks;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.class2);
Intent game = getIntent();
players = game.getIntExtra("players", 1);
names = game.getStringArrayExtra("names");
Random generator = new Random();
tasks[0]= "task1";
tasks[1]= "task2";
tasks[2]= "task3";
tasks[3]= "task4";
tasks[4]= "task5";
tasks[5]= "task6";
tasks[6]= "task7";
tasks[7]= "task8";
tasks[8]= "task9";
tasks[9]= "task10";
while (counter <5)
{
for (int i = 0; i < players; i++)
{
TextView name1 = (TextView) findViewById(R.id.pname);
name1.setText( names[i]+":");
ptasks = 10;
rindex = generator.nextInt(ptasks);
TextView task = (TextView) findViewById(R.id.task);
task.setText( tasks[rindex]);
}
Button failButton = (Button) findViewById(R.id.fail_btn);
failButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View failed)
{
//not sure what to put here to get the scores set up
}
});
Button notButton = (Button) findViewById(R.id.notbad_btn);
notButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View notbad)
{
//not sure what to put here to get the scores set up
}
});
Button champButton = (Button) findViewById(R.id.champ_btn);
champButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View champp)
{
//not sure what to put here
}
});
counter++;
}
}
I'm sure this thing is riddled with errors. And I'm sorry if it is I'm not that well experienced a programmer. Thanks again
You can pass a string array from one activity to another using a Bundle.
Bundle bundle = new Bundle();
bundle.putStringArray("arrayKey", stringArray);
You can then access this stringArray from the next activity as follows:
Bundle bundle = this.getIntent().getExtras();
String[] stringArray = bundle.getStringArray("arrayKey");
I'm not sure if this is the only thing you intend to do. I hope it helps. Also, to assign a score to a particular string array, assuming your scores are int's you could use a HashMap as follows,
HashMap<String[],int> imageData = new HashMap<String[],int>();
But I'm not sure how you would pass this Map to another activity if you intend to do so.
http://developer.android.com/reference/android/content/Intent.html#putExtra(java.lang.String,%20java.lang.String[])
Use this cheat:
In Class2, convert you array string (tasks) to string (strSavedTask)by adding "|" separator. After that, pass your strSavedTask into Bundle and start to Class1.
When return to Class1, read strSavedTask from Bundle, split it by "|".
That's my cheat to pass array between 2 activity ^^
Hope this way can help you!