Android: method that creates EditTexts - java

Good afternoon everyone.
I work in a chemistry lab at a university. I'm trying to create an app where the user puts in some sample data and the app performs some statistical calculations.
I would like some help with the following:
Create a method that takes the amount of samples as a parameter and creates a TextView and an EditText for each sample, one below the other.
Below is what I've done so far, but I know it's incomplete. can anybody help me?
'''
private void createBoxToAddBlankSamples(int numberOfBlanks){
List <TextView> blankSampleTitles = new ArrayList<>(numberOfBlanks);
List <EditText> blankSampleNumbers = new ArrayList<>(numberOfBlanks);
for (int i=0; i<=numberOfBlanks; i++) {
blankSampleTitles.add((TextView) findViewById(R.id.blank_title_1 + i));
blankSampleNumbers.add((EditText) findViewById(R.id.blank_value_1 + i));
}
}

Related

Static variable being fed into JTextfield is only JTextfield that I am failing to update. Can't figure out why but I think it's a scope issue

I am working on a simple game and have my main method inside my GUI class and have managed to get rid of all my issues with JTextfields not updating from my game loop that way except for one which coincidentally is the only one that is being fed a static double variable instead of raw strings. I can't seem to find out why online or by tinkering and finally broke down and decided to ask my first stackoverflow question.
public class BlackJackWindow extends JFrame
{
static double betAmount = 0;
static double money = 100; //The offending variable
static int playerAction = 0;`
Here is the kind of situation I am using it in that seems to do nothing when called.
public static void main(String[] args)
{
BlackJackWindow gui = new BlackJackWindow();
//Initializing main deck
Deck theDeck = new Deck();
theDeck.newDeck();
theDeck.shuffle();
//Dealing hands
Deck playerHand = new Deck();
Deck dealerHand = new Deck();
money = 100.00;
while(money > 0)
{
gui.moneyField = new JTextField("Money : " + money); //This line
seems to never occur on my GUI, what am I doing wrong?
gui.moneyField.validate();
Any help would be greatly appreciated!
Just creating the JTextField object and assigning it to a variable does not place it into the GUI, and in fact I'd recommend against trying to create a GUI in this way. Note that this has nothing to do with the static money field and all to do with creating a GUI in the wrong way.
What you probably want to do is to get the currently displayed JTextField and setting its text with the value held by money, but hard to say given the small amount of code you've posted.
Also this has nothing to do with scope and again all to do with references. You may be assuming that setting a field, here the gui.moneyField will change the JTextField displayed in the gui GUI, and that's not how references work.
Note that this answer is incomplete because your question and code is incomplete, in particular, we do not see how you create your GUI or how your variables relate to the problem at hand, it's all a mystery to us. For a better answer, please post a better and more complete question, one with a valid MCVE program post.
So not:
gui.moneyField = new JTextField("Money : " + money); //This line
but rather
gui.setMoneyText("Money : " + money);
where the method body within the GUI class could be something like:
public void setMoneyText(String text) {
moneyField.setText(text);
}
Also the while loop doesn't belong in event-driven GUI programs, but that's the subject of another answer to another question.

adding a field name as a method parameter

I have a Swing form where I want to detect edited field data so I can update the data via a web service. There doesn't seem to be a simple way to do this as there are a plethora of medium to complex code examples for this, most of which are over my head! However, I think I found a simple solution that will fit my needs and I wanted to run it by the group for input / suggestions. FYI: it may not matter but know that I am using NetBeans so things like listeners are auto-coded by the app.
Step 1: When I load the form, I am saving all the data to a Class array so I know the starting point of the each field. Here is the code for that load:
public void coSetSearchDetail(String coDetail){
String[] text;
System.out.println("SingleCO Result: "+ coDetail);
text = coDetail.split("\\|");
txtName_CoDetail.setText(text[1]);
txtAddr_CoDetail.setText(text[2]);
txtAddr2_CoDetail.setText(text[3]);
txtCity_CoDetail.setText(text[4]);
txtState_CoDetail.setText(text[5]);
txtZip_CoDetail.setText(text[6]);
stringarrayCoDetails[0] = text[0];
stringarrayCoDetails[1] = text[1];
stringarrayCoDetails[2] = text[2];
stringarrayCoDetails[3] = text[3];
stringarrayCoDetails[4] = text[4];
stringarrayCoDetails[5] = text[5];
stringarrayCoDetails[6] = text[6];
java.awt.CardLayout card = (java.awt.CardLayout)pnlMain.getLayout();
card.show(pnlMain, "pnlCoDetail");
}
Step 2: I created a Lost Focus event listener for one field and am testing the current value of the field against the array:
private void txtName_CoDetailFocusLost(java.awt.event.FocusEvent evt) {
if (!(txtName_CoDetail.getText().equals(stringarrayCoDetails[1]))){
createEditBorder();
}
}
private void createEditBorder (){
Border border = BorderFactory.createLineBorder(Color.RED, 2);
txtName_CoDetail.setBorder(border);
}
Besides the general question of "is this an OK approach?", I would like to be able to pass the field name to the createEditBorder method so the listener for each data field can call it and I have one method for "edited text" formatting.

How to change imageView depending on text in textView in android/java/eclipse

Is it possible to change an image in the imageView depending on the outcome of the text inside a textView.
For example if I have:
public void pourfive(View v){
TextView statusupdate = (TextView) findViewById(R.id.txt_statusupdate);
TextView fivecup = (TextView) findViewById(R.id.txt_fivecup);
TextView threecup = (TextView) findViewById(R.id.txt_threecup);
if (fivecup.getText().toString().equals("0")){
threecup.setText("0");
statusupdate.setText("You have no water in the 5 litre cup to pour!");
}
else if (threecup.getText().toString().equals("0") && (fivecup.getText().toString().equals("5"))){
fivecup.setText("2");
threecup.setText("3");
statusupdate.setText("You poured 3 litres into the 3 litre cup!");
}
In this instance I have a cup that can contain 1,2,3,4,5 different levels of coffee. If i wanted to have an image change to represent each one of these different levels. I think it might start something like this:
public void cupLevel(View v){
TextView threecup = (TextView) findViewById(R.id.txt_threecup);
threecup.getText();
}
I then think I would need some if and if else statements depending on the threecup number and some way to call the relevant image but I'm not sure how to call the required image.
Any help would be greatly appreciated thanks.
There are many ways you could approach this.
One of the simplest to understand if you're just starting out learning to program, would be to have a bunch of images for different levels of the cup. For example:
// Sets the image for the three cup, based on the fill level supplied
public void setThreeCupImage(int fillLevel) {
// make an int array containing the relevant images.
int[] threeCupLevels = {R.drawable.threecup_level_1,
R.drawable.threecup_level_2,
R.drawable.threecup_level_3};
// get reference to an ImageView you've put in you layout xml.
ImageView threeCupImage = (ImageView)findViewById(R.id.image_threecup);
// set the ImageView to display the required image from the array.
threeCupImage.setImageResource(threeCupLevels[fillLevel]);
}
Some tips regarding how you've written your other code...
Hard coding mathematical results is not a good idea as you have done here:
else if (threecup.getText().toString().equals("0") && (fivecup.getText().toString().equals("5"))){
fivecup.setText("2");
threecup.setText("3");
This is inflexible and quickly becomes bulky and complicated in larger problems. Try and make you code more general. Computers are good at maths! Let them do the maths for you!
For example, think about what the main variables are in this problem. They are:
The sizes of the cups
The levels they are filled to
A more general way to code your problem may be to first define a Cup class:
public class Cup {
// public fields of the class
public final int cupSize; // this is final because a cup does not change size.
public int cupLevel; // this is NOT final because level can vary
// class constructor
public Cup(int size, int level) {
cupSize = size;
cupLevel = level;
}
}
Then you can create cups and change their contents as needed:
// create a new cup with a size of 5 and fill level of 0 (empty)
Cup fiveCup = new Cup(5, 0)
// create a new cup with a size of 3 and fill level of 3 (full)
Cup threeCup = new Cup(3, 3)
// change the level of fiveCup
fiveCup.cupLevel = 2;
You could then write a method for pouring from one cup to another which can handle cups of any size or fill level:
public void pourCup(Cup source, Cup target) {
int spaceInTargetCup = target.cupSize - target.cupLevel;
if (source.cupLevel <= spaceInTargetCup) {
// there's room to pour all the contents of the source cup into the target cup
target.cupLevel += source.cupLevel; // add the contents of source to the target
source.cupLevel = 0; // the source is now empty
} else {
// there's not enough room to pour all the contents of the source in
source.cupLevel -= spaceInTargetCup; // empty as much as you can from the source
target.cupLevel = target.cupSize; // the target is now full
}
}
To pour the contents of threeCup into fiveCup you would simply call:
pourCup(threeCup, fiveCup);
...and to pour the contents of fiveCup into threeCup would obviously be:
pourCup(fiveCup, threeCup);
You can easily modify the method to let the user know what is going on with statements like:
statusupdate.setText("There is room to pour " + spaceInTargetCup + " litres into the " +
target.cupSize + " litre target cup");

How do I display what system.out.println() shows in the console, in an Android Application's activity?

For example, say I have a simple coin flip program that display a single line of text. After running the program as a Java Project, the console would display "There are 473 heads and 527 tails." I don't mean displaying this in LogCat, but actually displaying it when using the application.
//Basic coin flip statistics program.
package com.company.practice;
import java.util.Random;
public class CoinFlip {
public static void main(String[] args){
System.out.println("Toss a coin 1000 times");
int heads = 0;
int tails = 0;
Random r = new Random();
for(int flips = 0; flips < 1000; flips++){
//Change the # after < to set amount of flips.
int side = r.nextInt(2);
if(side == 0) heads++;
else tails++;
}
System.out.println("There are " + heads + " heads and " + tails + " tails.");
}
}
How would I display the line of code at the bottom that says, "System.out.println(...)" as text in an Android Application's activity?
You'd display it in the UI attached to the Activity.
An Android app is not constructed the same as a Java program. There's no "main" class. In fact, you usually don't declare an Application subclass. Instead, you construct a loose web of Activities that interact with each other using Intents. Each Activity has an associated layout that contains Views. When the Activity starts up, you load its main layout, then you store the View objects in variables in the Activity. When you want to modify the contents of a View,
you call a method (often setText()) to change the contents.
Layouts and Views can be defined in an XML file, or set up programmatically.
Those of you who have written Java programs before will have to step back some, and approach app construction from a somewhat different point of view. I strongly encourage you to browse through the documentation, particularly the training class, and look at the samples.

Android game Highscore implementation [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am making a space shooter for my final year project and thought it will be cool to include a local score/ High score screen. I don't know how to go about this and would really appreciate if someone can point me in the right direction, all the examples I found online look very complex to me. Also I want the score to be displayed on the game screen which is rendered with opengl es.
Thanks.
I have just finished creating a high score board for my OpenGL ES game that I'm currently working on. As it's for your final year project I won't be using this as a pastebin, but instead give you some pointers. In my application the scores are sent to my PHP script which stores values in MySQL.
What I used:
new class which handles everything to do with high scores
AlertDialog "alertName" - to ask for player name
EditText "input" added to the dialog with alertName.setView(input);
submitting the score to the server using an AsyncTask
this could be replaced with other Data Storage options, either internal, external, or SQLlite db
When the game is over (all lives gone, timer up, etc) I use a line of code, not too de-similar to this:
HighScore hs = new HighScore(context, score, level);
The context is required so AlertDialogs and Toasts can be created. The constructor calls the function submit() which shows the AlertDialog asking for the player name, then sends the data to the server.
My class contains this line of code to let the player know if they reached the top 100 after a response was received from the server:
Toast.makeText(mContext, "You didn't make the score board",
Toast.LENGTH_SHORT).show();
The high score list is stored in an ArrayList
private ArrayList<String> highscores = new ArrayList<String>();
And the data is padded using String.format in a similar fashion to this:
highscore_headers = String.format("%7s","rank") +
String.format("%11s","name") +
String.format("%10s","score") +
String.format("%5s","lvl");
And Then:
within your Renderer's onDrawFrame you could build the highscore class so you could call something like the one liner below, which would contain your translations, scales pushMatrix and popMatrix calls to draw the highscore data to the screen.
hs.draw(gl);
Which contains a loop, not too dissimilar to this:
for(int i=0; i<highscores.size(); i++){
text.drawText(gl, highscore.get(i).toString());
gl.glTranslatef(0f, -0.8f, 0f);
}
Note: Text is a class I wrote to draw various textures on the screen
depending on the char value of each character, which is then
translated to a set of x,y coordinates which relate to my
character map image file.
Hope this helps to push you in the right direction, and best of luck with your project
A screenshot of my android app's high score state rendered using OpenGL ES
EDIT: Sending Scores to PHP
This won't be an exact copy and paste of my source, but hopefully there will be enough information here to give you the general idea of it all. My final code also gives the device a uniqid, which users can track all of their scores that have been stored in the database - but that's something else.
php file:
I did mess around with signing requests, hashing scores, but for the purpose of my beta and getting the game published quicker I opted for just plain text entries. The code below, also does not detail highlighting the players submitted score, or getting rank based on time.
if(isset($_POST['name']) && isset($_POST['score'])){
$sql = "INSERT INTO highscores(name, score) VALUES (:name, :score)";
$data = array(":name"=>$_POST['name'], ":score"=>$_POST['score']);
$db->run($sql, $data);
echo display();
}
function display(){
$sql = "SELECT name, score FROM highscores ORDER BY score DESC";
$result = $db->run($sql, array());
return json_encode($result);
}
It should be noted that the $db object is a small class I made to wrap PDO methods prepare and execute, which return results as associative arrays
HighScore Android Class:
again, i won't copy/paste but this will illustrate how to post data to a server, receive a JSON string, then pad the string and add it to the highscores ArrayList. The code below is the constructor for the HighScore class, it asks for the users input.
List<NameValuePair>nameValuePairs = new ArraList<NameValuePair>(2);
AlertDialog alertName;
DefaultHttpClient client = new DefaultHttpClient();
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = "";
HighScore(Context context, int score){
nameValuePairs.add(new BasicNameValuePair("score", + score.toString()));
alertName = new AlertDialog(context).create();
EditText input = new EditText(context);
alertName.setTitle('Enter Your Name');
alertName.setButton(AlertDialog.BUTTON_POSITIVE, "OK",
new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which){
nameValuePairs.add(
new BasicNameValuePair("name", input.getText().toString())
);
SubmitAsync sa = new SubmitAsync();
sa.execute();
}
});
alertName.show();
}
The SubmitAsync class is a subclass of the HighScore class, it will setup the http client to send data, and add the received data. The data is digested as JSON and strings are padded as mentioned previously, then added to the highscore ArrayList
class SubmitAsync extends AsyncTask<String, Void, Void>{
#Override
protected Void doInBackground(String... params){
HttpPost postMethod = new HttpPost("http://address-of-script.php");
postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = client.execute(postMethod, responseHandler);
JSONArray jsonArray = new JSONArray(response);
for(int i=0; i<jsonArray.length(); i++){
JSONObject j = jsonArray.getJSONObject(i);
String name = String.format("%11s", j.get("name"));
String score = String.format("%10s", j.get("score"));
highscores.add(name + score);
}
}
}
That's the very basics and alot more code than I would have liked to have entered onto here at any one time, and most definitely my longest post ever. I would seriously consider the comments of #Dan, and research local storage over my server based approach to a highscore board
These code snippets will likely not work if copied and pasted. So please try to understand them and code yourself :)
Well, write a file with the high-scores in whatever format u want (like Name, score, date etc.) easier for u to parse later. And then, keep on editing it every time u want to write a new score. Blindly read it and display it.
I alerady do that in a same kind project, I do a list of object. This object represent one high score. If I need to store the list of High Scoren, I serialize the list and if I need to display it, I deserialize this file.

Categories

Resources