How to remove MPAndroidChart when activity is in portrait mode? - java

I am using MPAndroidChart for one of my activities I have overridden the onConfigurationChanged, and when I change the orientation to landscape everything is working fine but when I switch back to portrait mode still I am seeing the chart, exactly I want to remove chart when activity switches back to portrait mode.
Here is my code
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
BarChart chart = new BarChart(this);
if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE)
{
setContentView(chart);
chart.animateXY(1000, 1000);
chart.setDescription("");
chart.setGridBackgroundColor(Color.TRANSPARENT);
ArrayList<BarEntry> entries = new ArrayList<>();
entries.add(new BarEntry(Float.valueOf(tvA.getText().toString()), 0));
entries.add(new BarEntry(Float.valueOf(tvB.getText().toString()), 1));
entries.add(new BarEntry(Float.valueOf(tvC.getText().toString()), 2));
entries.add(new BarEntry(Float.valueOf(tvD.getText().toString()), 3));
entries.add(new BarEntry(Float.valueOf(tvOtherPrograms.getText().toString()), 4 ));
BarDataSet dataSet = new BarDataSet(entries, "Weekly Chart");
dataSet.setColors(ColorTemplate.COLORFUL_COLORS);
ArrayList<String> subjectNames = new ArrayList<>();
subjectNames.add("A");
subjectNames.add("B");
subjectNames.add("C");
subjectNames.add("D");
subjectNames.add("E");
BarData data = new BarData(subjectNames, dataSet);
data.setValueTextColor(Color.WHITE);
chart.setData(data);
XAxis xAxis = chart.getXAxis();
xAxis.setTextColor(Color.WHITE);
xAxis.setDrawLabels(true);
YAxis yAxis =chart.getAxisLeft();
yAxis.setTextColor(Color.WHITE);
}
}

Related

LibGDX Button in table goes offscreen

Trying to place two buttons in a table row.
Right-most button appears slightly offscreen.
Adding to table with .add(btn).right() but seems not to have any effect.
Documentation says something about removing the Align.left and vise-versa but I'm not sure what they're saying.
Working from mobile.
Took pic, uploaded to ImageBucket but can't see whole thing so took two more (top + bottom of screen) just in case.
Top of screen:
https://i1161.photobucket.com/albums/q501/StudioGilliam/Screenshot_20190430-224041_TextBasedRPG.jpg
As you can see, the labels display fine.
Bottom of screen:
https://i1161.photobucket.com/albums/q501/StudioGilliam/Screenshot_20190430-224024_TextBasedRPG.jpg
The offending code:
public class TextBasedRPG implements ApplicationListener
{
private Stage stage;
private TextButton btnNext;
private TextButton btnItems;
private Label lblPlayer1;
private Label lblEnemy1;
private Label lblInfo;
#Override
public void create()
{
stage = new Stage(new ScreenViewport());
Gdx.input.setInputProcessor(stage);
// UI STUFF
// Labels
Label.LabelStyle styleL = new Label.LabelStyle(new BitmapFont(), Color.BLACK);
lblPlayer1 = new Label("Player data", styleL);
lblPlayer1.setFontScale(3.5f);
lblEnemy1 = new Label("Enemy data", styleL);
lblEnemy1.setFontScale(3.5f);
lblEnemy1.setAlignment(Align.right);
lblInfo = new Label("Information", styleL);
lblInfo.setFontScale(4.0f);
// Buttons
TextButton.TextButtonStyle styleTB = new TextButton.TextButtonStyle();
styleTB.font = new BitmapFont();
styleTB.up = new NinePatchDrawable(new NinePatch(new Texture(Gdx.files.internal("ButtonGreyUp.png")), 10, 10, 10, 10));
styleTB.down = new NinePatchDrawable(new NinePatch(new Texture(Gdx.files.internal("ButtonGreyDown.png")), 10, 10, 10, 10));
btnNext = new TextButton("Next Turn", styleTB);
btnNext.setTransform(true);
btnNext.setScale(6.0f);
btnNext.setTouchable(Touchable.enabled);
btnNext.align(Align.right);
btnItems = new TextButton("Play", styleTB);
btnItems.setTransform(true);
btnItems.setScale(6.0f);
btnItems.setTouchable(Touchable.enabled);
// Table
Table table = new Table();
table.setBounds(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
table.setFillParent(true);
table.pad(50);
table.add(lblPlayer1).expandX().left();
table.add(lblEnemy1).expandX().right();
table.row();
table.add(lblInfo).expandY().colspan(2);
table.row();
table.add(btnItems).expandX().left();
table.add(btnNext).expandX().right();
table.debugAll();
stage.addActor(table);
}
#Override
public void render()
{
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stage.act();
stage.draw();
}
#Override
public void dispose(){stage.dispose();}
#Override
public void resize(int width, int height){}
#Override
public void pause(){}
#Override
public void resume(){}
I don't recommend using setScale() since it only affects the representation of the actor and causes problems with the actual dimensions within the table.
You should use a fitting width and height for your buttons and use a font with a bigger textsize.
You could use GDX Freetype to generate your fonts with the correct size on startup.
Here is an example approach for the solution:
I use the following approach for my UI elements here as an example for a Label:
This is in my static UIHelper Class:
public static Cell addToTable(Table table, Label label, float width) {
Label.LabelStyle style = new Label.LabelStyle(skin.get("default", Label.LabelStyle.class));
float aspectRatio = style.background.getMinWidth()/style.background.getMinHeight();
float height = width / aspectRatio;
style.font = Assets.font;
style.fontColor = Assets.font.getColor();
label.setStyle(style);
label.setAlignment(Align.center);
return table.add(label).width(width).height(height);
}
Then I can just call:
float width = (float)Gdx.graphics.getWidth()*0.8f; // I want my label to be 80% of the screen width
UIHelper.addToTable(table, levelLabel, width).colspan(3).pad(20);
For my fonts, I do this:
private static BitmapFont generateFont(){
FreeTypeFontGenerator generator = new FreeTypeFontGenerator(Gdx.files.internal("skins/beemelon/passion-one-regular.ttf"));
FreeTypeFontGenerator.FreeTypeFontParameter parameter = new FreeTypeFontGenerator.FreeTypeFontParameter();
parameter.size = (int) (38 * Gdx.graphics.getDensity()); // Change the 38 to a value fit for your game
parameter.color = new Color(255f / 255f, 165f / 255f, 23f / 255f, 1f); // Divide by 255f to get a value between 0 and 1
parameter.borderWidth = parameter.size / 10f;
parameter.borderColor = Color.BLACK;
BitmapFont bitmapFont = generator.generateFont(parameter);
generator.dispose();
return bitmapFont;
}
Hope this helps or pushes you in the right direction.

adding Icons with String to MPAndroid Chart as XAxisValues

github.PhilJay:MPAndroidChart:v2.0.9`
I was wondering if I can add star icons and numbers as XAxisValues like image below?
I've already added the numbers and it's working fine but I don't know how to add star icons! Is there a way to combine text and icons?
Here is my code so far:
private ArrayList<BarDataSet> getDataSet(int stars1, int stars2, int stars3, int stars4, int stars5) {
ArrayList<BarDataSet> dataSets = null;
ArrayList<BarEntry> valueSet1 = new ArrayList<>();
BarEntry v1e1 = new BarEntry(stars5, 4);
valueSet1.add(v1e1);
BarEntry v1e2 = new BarEntry(stars4, 3);
valueSet1.add(v1e2);
BarEntry v1e3 = new BarEntry(stars3, 2);
valueSet1.add(v1e3);
BarEntry v1e4 = new BarEntry(stars2, 1);
valueSet1.add(v1e4);
BarEntry v1e5 = new BarEntry(stars1, 0);
valueSet1.add(v1e5);
BarDataSet barDataSet1 = new BarDataSet(valueSet1, "");
barDataSet1.setColors(new int[]{getResources().getColor(R.color.chart5), getResources().getColor(R.color.chart4),
getResources().getColor(R.color.chart3), getResources().getColor(R.color.chart2), getResources().getColor(R.color.chart1)});
barDataSet1.setValueTextSize(9);
dataSets = new ArrayList<>();
dataSets.add(barDataSet1);
return dataSets;
}
private ArrayList<String> getXAxisValues() {
ArrayList<String> xAxis = new ArrayList<>();
xAxis.add("1");
xAxis.add("2");
xAxis.add("3");
xAxis.add("4");
xAxis.add("5");
return xAxis;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
BarData data = new BarData(getXAxisValues(), getDataSet(stars1, stars2, stars3, stars4, stars5));
barChart.setData(data);
barChart.setDescription("");
barChart.invalidate();
barChart.getXAxis().setDrawGridLines(false);
barChart.getXAxis().setDrawAxisLine(false);
barChart.setDrawGridBackground(false);
barChart.getAxisLeft().setDrawGridLines(false);
barChart.getAxisRight().setDrawGridLines(false);
barChart.getAxisLeft().setDrawAxisLine(false);
barChart.getAxisRight().setDrawAxisLine(false);
barChart.getLegend().setEnabled(false);
barChart.getXAxis().setDrawLabels(true);
barChart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);
barChart.getAxisRight().setDrawLabels(false);
barChart.getAxisLeft().setDrawLabels(false);
}
Thanks for your time... ♥
Just use ★ character and it will be displayed well. You can use x axis value formatter for formatting values:
barChart.getXAxis().setValueFormatter(new IAxisValueFormatter() {
#Override
public String getFormattedValue(float value, AxisBase axis) {
return "value ★";
}
}
Here is result :

Remove BarDataSet in MPAndroidChart

I'm using MPAndroidChart to build BarChart, but I can't set my BarDataSet(1) and set my column's content(2) to vertical. Can anyone help?
public void LoadChart(final ArrayList<String> nameDate, ArrayList<Float> fl){
com.github.mikephil.charting.charts.BarChart chart = (com.github.mikephil.charting.charts.BarChart) findViewById(R.id.barchart);
/* final String[] nameDate={"JAN","FEB","MAR","APR","MAY","JUN"};
Float[] fl = new Float[]{30f,80f,60f,50f,70f,60f};*/
List<BarEntry> entries = new ArrayList<>();
for(int i=0;i<fl.size();i++)
{
entries.add(new BarEntry(i, fl.get(i)));
}
mDB.open();
BarDataSet set = new BarDataSet(entries, "BarDataSet");
set.setColor(Color.rgb(103,203,27));
BarData data = new BarData(set);
data.setBarWidth(0.9f); // set custom bar width
chart.setData(data);
chart.setFitBars(true); // make the x-axis fit exactly all bars
chart.animateXY(2000, 2000);
chart.setScaleEnabled(false);
chart.invalidate(); // refresh
Description description = chart.getDescription();
description.setEnabled(false);
XAxis xAxis = chart.getXAxis();
xAxis.setDrawGridLines(false);
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
xAxis.setDrawGridLines(false);
xAxis.setGranularity(1f);
xAxis.setValueFormatter(new IAxisValueFormatter() {
#Override
public String getFormattedValue(float value, AxisBase axis) {
return nameDate.get((int) value);
}
});
YAxis yLabels = chart.getAxisLeft();
yLabels.setDrawGridLines(false);
YAxis yLabels1 = chart.getAxisRight();
yLabels1.setEnabled(false);
}
Yes, is possible, just using following code:
mChart.setDescription(""); // Hide the description
mChart.getAxisLeft().setDrawLabels(false);
mChart.getAxisRight().setDrawLabels(false);
mChart.getXAxis().setDrawLabels(false);
mChart.getLegend().setEnabled(false);
try this
OR
pieChart.setUsePercentValues(true);
pieChart.getDescription().setEnabled(false);
pieChart.setExtraOffsets(0, 0, 0,0 );
pieChart.setDragDecelerationFrictionCoef(0.95f);
mChart.setCenterTextTypeface(mTfLight);
mChart.setCenterText(generateCenterSpannableText());
pieChart.setDrawHoleEnabled(false);
// mChart.setHoleColor(Color.WHITE);
// mChart.setTransparentCircleColor(Color.WHITE);
// mChart.setTransparentCircleAlpha(110);
// mChart.setHoleRadius(58f);
// mChart.setTransparentCircleRadius(61f);
pieChart.setDrawCenterText(false);
pieChart.setRotationAngle(0);
// enable rotation of the chart by touch
pieChart.setRotationEnabled(false);
pieChart.setHighlightPerTapEnabled(false);
// mChart.setUnit(" €");
// mChart.setDrawUnitsInChart(true);
// add a selection listener
pieChart.setOnChartValueSelectedListener(this);
setData(4, 100);
pieChart.animateY(0, Easing.EasingOption.EaseInOutQuad);
// mChart.spin(2000, 0, 360);
// mSeekBarX.setOnSeekBarChangeListener(this);
// mSeekBarY.setOnSeekBarChangeListener(this);
Legend l = pieChart.getLegend();
l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
l.setOrientation(Legend.LegendOrientation.VERTICAL);
l.setDrawInside(false);
l.setXEntrySpace(7f);
l.setYEntrySpace(0f);
l.setYOffset(0f);
// mChart.setDescription(""); // Hide the description
// mChart.getAxisLeft().setDrawLabels(false);
// mChart.getAxisRight().setDrawLabels(false);
// mChart.getXAxis().setDrawLabels(false);
pieChart.getLegend().setEnabled(false); // Hi
// entry label styling
pieChart.setEntryLabelColor(Color.WHITE);
// mChart.setEntryLabelTypeface(mTfRegular);
pieChart.setEntryLabelTextSize(12f);
return rootView;
and try this code bar data set is not visible again

Creating a bar chart with MPAndroidChart using double values

Hi I am trying to create a bar chart using MPAndroidChart library in Android Studio for my java application. I have managed to plot a bar chart using single integer values, but I would like to plot double values.
Here is my code for plotting single integer values
public class walk extends AppCompatActivity {
HorizontalBarChart barChart;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_walk);
barChart = (HorizontalBarChart) findViewById(R.id.bargraph);
ArrayList<BarEntry> barEntries = new ArrayList<>();
barEntries.add(new BarEntry(10f,0));
barEntries.add(new BarEntry(5f,1));
BarDataSet barDataSet = new BarDataSet(barEntries,"ACTIVITIES");
ArrayList <String> pa = new ArrayList<>();
pa.add("WALKING");
pa.add("RUNNING");
BarData theData = new BarData(pa,barDataSet);
barChart.setData(theData);
barDataSet.setBarSpacePercent(70f);
}
I would like to plot the following values 20.333333333333332 and 2.0071271275749623.
I would appreciate any help I could get, apologies if anything is unclear I am new to this site.
Converting double to float before plotting :
double point1 = 20.333333333333332;
double point2 = 2.0071271275749623;
float fp1 = (float)point1;
float fp2 = (float)point2;
ArrayList<BarEntry> barEntries = new ArrayList<>();
barEntries.add(new BarEntry(fp1,0));
barEntries.add(new BarEntry(fp2,1));
BarDataSet barDataSet = new BarDataSet(barEntries,"ACTIVITIES");

How to save/restore the views in eclipse e4

I have two sections. In the left section I am using checkbox tableviewer for displaying list of file names. The right section is for showing graphs(I am using JFreechart). I have a handler which is used for dynamically adding tabs to the right side section. IF I am in first tab and made some checkbox selections in left side tableviewer ,the graph is displayed in right side. When I create a new tab(right side) , the left side tableviewer should reset.
When I select the first tab again and I want to see the previous selection in left side section.Can anyone please give some ideas how to save/restore the views based on the tab change?
Left side section code for file viewer:
#PostConstruct
public void createComposite(Composite parent) {
parent.setLayout(new GridLayout(1, false));
tableViewer = new CheckboxTableViewer(parent, SWT.BORDER);
tableViewer.getTable().setLayoutData(new GridData(GridData.FILL_BOTH));
}
public void setTableInput(File[] selectedFiles) {
tableViewer.setContentProvider(ArrayContentProvider.getInstance());
tableViewer.setLabelProvider(new FileLabelProvider());
prevSelectedFiles = selectedFiles;
tableViewer.setInput(selectedFiles);
tableViewer.addCheckStateListener(new ICheckStateListener() {
#Override
public void checkStateChanged(CheckStateChangedEvent event) {
filesSelected = tableViewer.getCheckedElements();
// some code to display graph
}}}
Right side code(Graph)
#PostConstruct
public void postConstruct(final Composite parent) {
final JFreeChart chart = createChart(dataset, title);
new ChartComposite(parent, SWT.NONE, chart, true);
}
private JFreeChart createChart(TimeSeriesCollection dataset, String string) {
final JFreeChart chart = ChartFactory.createTimeSeriesChart(
"REPORT GENERATION", "TimeStamp", "ms", dataset, true, true,
false);
chart.setBackgroundPaint(Color.WHITE);
final XYPlot plot = (XYPlot) chart.getPlot();
plot.setDataset(0, dataset);
plot.setBackgroundPaint(Color.WHITE);
plot.setDomainGridlinePaint(Color.BLACK);
plot.setRangeGridlinePaint(Color.BLACK);
Shape shape = new Ellipse2D.Double(-2.0, -2.0, 4.0, 4.0);
XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot
.getRenderer();
renderer.setSeriesShape(0, shape);
renderer.setSeriesShape(1, shape);
renderer.setSeriesShape(2, shape);
renderer.setBaseShapesVisible(true);
renderer.setSeriesOutlinePaint(0, Color.GRAY);
renderer.setSeriesOutlinePaint(1, Color.GRAY);
renderer.setSeriesOutlinePaint(2, Color.GRAY);
renderer.setUseFillPaint(true);
renderer.setSeriesFillPaint(0, Color.red);
renderer.setSeriesFillPaint(1, Color.green);
renderer.setSeriesFillPaint(2, Color.blue);
renderer.setSeriesPaint(0, Color.red);
renderer.setSeriesPaint(1, Color.green);
renderer.setSeriesPaint(2, Color.blue);
NumberAxis yaxis = (NumberAxis) plot.getRangeAxis();
yaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
yaxis.setAutoRangeIncludesZero(false);
plot.setRangeAxis(yaxis);
DateAxis axis = (DateAxis) plot.getDomainAxis();
axis.setAutoTickUnitSelection(true);
// axis.setTickUnit(new DateTickUnit(DateTickUnitType.SECOND,120));
axis.setDateFormatOverride(new SimpleDateFormat("HH:mm:ss"));
// DateAxis.createStandardDateTickUnits();
axis.setTickMarksVisible(true);
axis.setTickLabelsVisible(true);
return chart;
}
public void setValue(ArrayList<TreeMap<Timestamp, Long>> statisticalValues, String protocolName, String statistics) {
// //System.out
// .println("setting the value for timeseries-->" + i);
TimeSeries ts = null;
for (TreeMap<Timestamp, Long> entries : statisticalValues) {
ts = new TimeSeries(protocolName + "_" + statistics,
Second.class);
for (Entry<Timestamp, Long> seriesData : entries.entrySet()) {
ts.addOrUpdate(new Second(seriesData.getKey()),
seriesData.getValue());
}
}
dataset.addSeries(ts);
}
The handler responsible for dynamic creation of tab(Grapgh part):
public class DynamicPartsHandler {
#Execute
public void execute(EPartService partService, EModelService modelService,
MApplication application,Shell shell) {
String partName = "Graph";
MPart part = partService
.createPart("com.wincor.commtrace.project.partDescriptor.1");
MPartStack stack = (MPartStack) modelService.find(
"com.wincor.commtrace.project.partstack.2", application);
stack.getChildren().add(part);
part.setLabel(partName);
part.setVisible(true);
part.setCloseable(true);
partService.showPart(part, PartState.ACTIVATE);
}
}
Thanks in advance

Categories