Android Graphview - Append Data - java

I´m not very good at programming, but I need to build an App where you can type in Datapoints and after clicking a button the datapoint should be added to a graph.
I started with a bar graph and it works, but for some reason the labels are in doubles, even if I type in 1 the bar is between 0.8 an 1.2 on the xaxis and the first 3 datapoints I type in doesn't show up.
Please excuse my bad english (and my bad programming).
public class BalkenActivity extends AppCompatActivity implements View.OnClickListener{
GraphView bargraph;
BarGraphSeries<DataPoint> series;
double xval = 1;
double yval;
TextView texty;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_balken);
Button button1 = findViewById(R.id.addbtn);
button1.setOnClickListener(this);
texty = findViewById(R.id.yvalue);
bargraph = findViewById(R.id.bargraph);
series = new BarGraphSeries<>(getDataPoint());
}
private DataPoint[] getDataPoint() {
DataPoint[] dp = new DataPoint[]
{
new DataPoint(0,0),
};
return dp;
}
public void onClick (View v) {
yval = new Double(texty.getText().toString()).doubleValue();
series.appendData(new DataPoint(xval++,yval),true,100);
bargraph.addSeries(series);
bargraph.getViewport().setScalable(true);
bargraph.getViewport().setMinX(0);
series.setSpacing(50);
series.setDrawValuesOnTop(true);
series.setValuesOnTopColor(Color.BLACK);
}
}

Without either a DefaultLabelFormatter or a GridLabelFormatter, GraphView will automatically format the graphs labels so that is why you are seeing double values.

Related

How can I use interface from a for loop

I have two inner classes named CalculatorClass and UpdatePayment in MainActivity class.
In UpdatePayment class there is a for loop and I have a array of Buttons.
I want to add listener to each button in loop. Those buttons will initialize the CalculatorClass and get value of calculations.
Demo code is:
public static class MainActivity{
private interface UpdateEditText{
void onCallback(String s);
}
private class CalculatorClass extends Dialog{
UpdateEditText updateEditText;
public CalculatorInterface(#NonNull Context context, UpdateEditText updateEditText) {
super(context);
this.updateEditText = updateEditText;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calculator);
initialize();
}
initialize(){
.......................
s = "Some texts";
updateEditText.onCallback(s);
}
}
private class UpdatePayment extends Dialog{
private Button[] button = new Button[100];
private EditText[] editText = new EditText[100];
public CalculatorInterface(#NonNull Context context) {
super(context);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.update);
initialize();
}
initialize(){
.......................
for(int i = 0; i < MAXSize; i++){
button[i] = new Button(MainActivity.this);
editText[i] = new EditText(MainActivity.this);
//add buttons to view to layout
button[i].setOnclickListener(new View.OnClickListener(){
public void onClick(View v) {
CalculatorClass calculator = new
CalculatorClass(MainActivity.this,
new UpdateEditText() {
#Override
public void onCallback(String s) {
editText[i - 1].setText(s);
}
});
calculator.show();
}
);
}
}
}
}
Problem is the line editText[i].setText(s) work for the last editText what ever button I click, i.e, any button I click, it fills the editText[MaxSize -1]
What should I do?
How can I perform this action for all i?
Please help me, I tried a lot searching in internet, still I didn't get any solution.
Anonymous classes are very much treated like static variables in java.It's happenning because your i value after your activity is initialized is equal to 1 less than the length of the edit text array.
editText[indicies_of_button_clicke].setText(s)
How you will get the indicies of button clicked is by :
se the tag to button below this line "editText[i] = new EditText(MainActivity.this);", like this :
button[i].setTag(i)
to retreive the index of your actual button clicked inside button clicklisteners,
v.getTag()// this will give you an integer value which will be the indices of actual button clicked
//use this value to set your edit text value.
Solution:
After a whole night, I got answer, now I feel awwww, this was easy go!
I never came in this thought.
button[i].setId(i);
then call:
CalculatorClass calculator = new CalculatorClass(MainActivity.this, v.getId(),
new UpdateEditText() {
#Override
public void onUpdate(String s, int ID) {
Log.i("test", ID + "");
editText[ID].setText(s);
}
});
At the same time, #Rishabh Ritweek answered correctly.
Thanks to him.

Android Studio - Close Icon of a Chip does not do anything (Java)

I created some Chips and they have an X symbol on the right side.
But when I click the X (intending to dismiss or remove the Chip), nothing happens.
I tried to use the method setOnCloseIconClickListener but it did not have an effect.
I click the X icon and the color of the icon changes and a clicking sound appears, but the Chip View remains on the screen.
And I also don't know what to write in the callback method of the click listener.
for(int i = 0; i<products.length; i++) {
//the chip component requires your app theme to be Theme.MaterialComponents (or a
//descendant)
chips[i] = new Chip(this);
//ScrollView can only host one direct child
ll1.addView(chips[i]);
chips[i].setText(products[i]);
chips[i].setCloseIconVisible(true);
}
I tried this, but it said the variable i has to be final which is not possible cause i is incrementing.
chips[i].setOnCloseIconClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
chips[i].close();
}
});
I found the solution. This is the code:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private EditText et1;
private ScrollView sv1;
private LinearLayout ll1;
private Chip[] chips;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et1 = findViewById(R.id.editText);
sv1 = findViewById(R.id.scrollView);
ll1 = new LinearLayout(this);
ll1.setOrientation(LinearLayout.VERTICAL);
sv1.addView(ll1);
}
public void splitToChips(View v) {
String content = et1.getText().toString();
String[] products = content.split(";");
chips = new Chip[products.length];
for(int i = 0; i<products.length; i++) {
chips[i] = new Chip(this);
ll1.addView(chips[i]);
chips[i].setText(products[i]);
chips[i].setCloseIconVisible(true);
chips[i].setOnCloseIconClickListener(this);
}
}
#Override
public void onClick(View v) {
Chip chip = (Chip) v;
ll1.removeView(chip);
}
}

Correct integer not being passed through PutExtra

My program displays a horizontally sliding row of buttons containing the text description of a work of art. When a button is clicked, ImageActivity launches to display the corresponding work of art. When I click on any of the text buttons, though, it always displays the very last painting in the Array.
I'm trying to pass an int ID to a second activity so that it will display the correct painting once it's corresponding description is clicked.
Thank you!
Here's my MainActivity:
import android.content.Intent;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
public class MainActivity extends Activity {
//CONTAINING PAINTINGS
private LinearLayout mLinearList;
private String id;
private Painting painting;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
//REFERENCE THE SCROLLABLE LAYOUT STRUCTURE IN MAIN_SCREEN.XML
mLinearList = (LinearLayout) findViewById(R.id.linearList);
//FILL THE SCROLLABLE LAYOUT STRUCTURE WITH PAINTINGS
fillTextCarousel();
}
private void fillTextCarousel() {
// POPULATE THE LINEAR LIST CAROUSEL WITH PAINTINGS AND DESCRIPTIONS
Button buttonItem;
for (int i = 0; i < RenaissanceDatabase.description.length; i++) {
//STORE THE INDIVIDUAL PAINTINGS AS BUTTONS
buttonItem = new Button(this);
painting = new Painting(RenaissanceDatabase.description[i], RenaissanceDatabase.id[i]);
//USE THE CONTENT DESCRIPTION PROPERTY TO STORE
//PAINTING DATA
buttonItem.setContentDescription(painting.getDescription());
buttonItem.setText(painting.getDescription());
//SET AN ONCLICK LISTENER FOR THE TEXT BUTTON
buttonItem.setOnClickListener(displayPainting);
//ADD THE IMAGE BUTTON TO THE SCROLLABLE LINEAR LIST
mLinearList.addView(buttonItem);
}
}
private View.OnClickListener displayPainting = new View.OnClickListener() {
public void onClick(View btn) {
// COLLECT THE IMAGE STORED FOR THE PAINTING
//String Painting_ID = Integer.toString(painting.getId());
Intent imgIntent = new Intent(getApplicationContext(), ImageActivity.class);
imgIntent.setAction(imgIntent.ACTION_SEND);
imgIntent.putExtra("image_id", painting.getId());
startActivity(imgIntent);
}
};
My ImageActivity that I am trying to pass an integer ID to:
public class ImageActivity extends Activity {
private Painting painting;
private int index;
private int[] IDs;
private String[] Desc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
Intent objIntent = getIntent();
int ID_Val = objIntent.getIntExtra("image_id", 0);
ImageView art = (ImageView) findViewById(R.id.imageView2);
art.setImageResource(ID_Val);
}
}
And the painting database, which I'm taking taking the ID from:
public class RenaissanceDatabase {
public static String description[] = {
"Venus of Urbino\nTitan, 1538",
"St. John the Baptist\nLeonardo da Vinci, 1516",
"Protrait of Baldassare Castiglione\nRaphael, 1515",
"The Entombent of Christ\nCaravaggio, 1603",
"Coronation of the Virgin\nFra Angelico, 1435",
"Mars and Venus\n Sandro Bottcelli, 1483"};
public static int id[] = {
R.drawable.painting1, // VENUS OF URBINO
R.drawable.painting2, // ST.JOHN BAPTIST
R.drawable.painting3, // BALDASSARE
R.drawable.painting4, // ENTOMBENT OF CHRIST
R.drawable.painting5, // CORONOATION
R.drawable.painting6 // MARS AND VENUS
};
}
Set the id for every button in your for loop -
for (int i = 0; i < RenaissanceDatabase.description.length; i++) {
//STORE THE INDIVIDUAL PAINTINGS AS BUTTONS
buttonItem = new Button(this);
painting = new Painting(RenaissanceDatabase.description[i], RenaissanceDatabase.id[i]);
//USE THE CONTENT DESCRIPTION PROPERTY TO STORE
//PAINTING DATA
buttonItem.setId(painting.getId());
....
}
}
And then change your OnClickListener -
private View.OnClickListener displayPainting = new View.OnClickListener() {
public void onClick(View btn) {
....
imgIntent.putExtra("image_id", btn.getId());
startActivity(imgIntent);
}
};
The way your code is set up this makes perfect sense.
Look at the loop you're using to configure everything.
for (int i = 0; i < RenaissanceDatabase.description.length; i++) {
.....
painting = new Painting(RenaissanceDatabase.description[i], RenaissanceDatabase.id[i]);
...
}
What is the value of painting at the end of this loop? It's whatever was in the last position in the array.
Now look at your code to pass the ID:
private View.OnClickListener displayPainting = new View.OnClickListener() {
public void onClick(View btn) {
....
imgIntent.putExtra("image_id", painting.getId());
.....
}
};
The code presented never updates the "current painting" to the one which was touched. You need to figure out which painting the user has touched, and use the ID of that painting.
Another answer has a recommendation to set the buttonId to the id of the painting - this has some issues so I wouldn't personally recommend that.
Instead I would use an Adapter and ViewHolder pattern and leverage the viewholder to contain this meta data. This is a much more scalable solution.

Android: Passing int value from one activity to another

I'm struggling to figure out why I can't pass an int value from one activity to another. The app will ask you to press a button to generate a random number from 1-100 which will be displayed below the button. There is also another button which will open a new activity simply showing the random number that was rolled... but I just get 0.
I've looked into similar questions asked but to no avail.
Here's my code from MainActivity
public class MainActivity extends ActionBarActivity {
int n;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void ButtonRoll(View view) {
TextView textRoll = (TextView) findViewById(R.id.textview_roll);
Random rand = new Random();
n = rand.nextInt(100) + 1;
String roll = String.valueOf(n);
textRoll.setText("Random number is " + roll);
}
public void OpenStats(View view) {
Intent getStats = new Intent(this, Stats.class);
startActivity(getStats);
}
public int GetNumber (){ return n; }
}
Heres my 2nd class.
public class Stats extends Activity {
MainActivity statistics = new MainActivity();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stats);
int n = statistics.GetNumber();
TextView tvStats = (TextView) findViewById(R.id.passedNumber_textview);
String number = String.valueOf(n);
tvStats.setText(number);
}
}
Is using getters the wrong way to get data from another class when using activities? Thanks for your time.
You should pass your data as an extra attached to your intent. To do this you need to first determine a global key to be used. You could do something like this in your MainActivity
public static final String SOME_KEY = "some_key";
then modify your OpenStats method to
public void OpenStats(View view) {
Intent getStats = new Intent(this, Stats.class);
getStats.putExtra(SOME_KEY, n);
startActivity(getStats);
}
and then in Stats.class onCreate method
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.stats);
int n = getIntent().getIntExtra(MainActivity.SOME_KEY, -1);
TextView tvStats = (TextView) findViewById(R.id.passedNumber_textview);
String number = String.valueOf(n);
tvStats.setText(number);
}
You obviously should make sure that you are calling ButtonRoll at least once or that you set n so that you aren't passing a null int.
Also, as note, convention states that methods should use lower camel case formatting. That is, the first word is completely lower case and the first letter of subsequent words is upper case. That would change your methods
OpenStats() -> openStats()
ButtonRoll() -> buttonRoll()
Classes/objects are upper camel case, just to help avoid confusion.

How to create a scoreboard with a textview, 2 variables and a button in java for Android

I know this is a simpleton question, but I am not going to school for java, just learning it online.
how to a have a textview with an initial value of 0. and then everytime you press a button it ads 25 points to the score board.
At first I wanted the button press to add a random number between 42-57 to the score board.
And then how to do convert that int or long to a string to make it fit into a textview and keep the current score, and then add a new score.
EDIT: ok so someone said I should post the code so here it is.. where do i put this..
TextView txv182 = (TextView) findViewById(R.id.welcome);
txv182.setText(toString(finalScore));
Because when I do it, I get an error: The method toString() in the type Object is not applicable for the arguments (int)
public class MainActivity extends Activity {
// Create the Chartboost object
private Chartboost cb;
MediaPlayer mp = new MediaPlayer();
SoundPool sp;
int counter;
int db1 = 0;
Button bdub1;
TextView txv182;
int finalScore;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txv182 = (TextView) findViewById(R.id.welcome);
finalScore = 100;
sp = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
db1 = sp.load(this, R.raw.snd1, 1);
bdub1 = (Button) findViewById(R.id.b4DUB1);
bdub1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (db1 != 0)
sp.play(db1, 1, 1, 0, 0, 1);
txv182.setText(finalScore);
}
});
First you need to store your score to certain integer variable say score and set it to any initial value you want and use.
TextView tv = (TextView) findViewById(R.id.myTextView);
tv.setText(toString(score));
you do not need to initialize the textview with value just in onclick() of button do score+=25and add text to your textview as above.
hope this helps
It's actually like this..
pernts+=25;
txv182.setText(String.valueOf(pernts));
in android, after the
public class MainActivity extends Activity {
but before..
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
i wrote..
int pernts;
String strI;
so then after the above #Override majigy, i wrote..
strI = "" + pernts;
pernts = 0;
because when i wrote it like.. int pernts = 0; it never worked, forcing me to add final and what not..
any way.. How to convert an integer value to string? anSwered the question..
and so the end was like this
pernts+=25;
txv182.setText(String.valueOf(pernts));
i figured out you have to add a value to the int variable not the string.. i kept wanting to add 25 and i was getting 25252525252525.., instead of 25 50 75 100.. kinda cool actually.. separating the logic of how to "add" 25 .. anyway thanks.. SOF!
30 minutes later... found this.. How can I generate random number in specific range in Android?
..
import android.app.Activity;
public class InsMenu extends Activity {
static TextView txv182;
static int pernts;
Button bdub1;
public static void addPernts() {
int min = 37;
int max = 77;
Random r = new Random();
int i1 = r.nextInt(max - min + 1) + min;
pernts+=i1;
txv182.setText(String.valueOf(pernts));
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.BLAHBLAH);
bdub1 = (Button) findViewById(R.id.b4DUB1);
txv182 = (TextView) findViewById(R.id.welcome);
bdub1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
addPernts();
}
--- i created my first objekt thanks to this too.. http://www.tutorialspoint.com/java/java_methods.htm ..

Categories