In my Android application i am creating a pie chart using achartengine library. When click a button it takes data from sqlite database and draw a pie chart. This is my code segment.
btnpieChart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
SelectDBAdapter selectDBAdapter = SelectDBAdapter
.getDBAdapterInstance(getActivity());
try {
selectDBAdapter.openDataBase();
chartDataMap = selectDBAdapter
.getPieChartData(strBusinessUnit,
currentPeriod, currentYear);
} catch (Exception e) {
selectDBAdapter.close();
e.printStackTrace();
} finally {
selectDBAdapter.close();
}
System.out.println("chartDataMap === "+ chartDataMap);
if (chartDataMap.size() > 0) {
for (Map.Entry<String, Double> entry : chartDataMap.entrySet()) {
lstBrandNames.add(entry.getKey());
lstAchievedVals.add(entry.getValue());
}
ArrayList<Double> distribution = calc_Percentage(lstAchievedVals);
System.out.println("distribution === " + distribution);
lstBrandNames = set_lables(lstBrandNames, distribution);
CategorySeries distributionSeries = new CategorySeries(
"Brands - Achievement Progress");
for (int i = 0; i < distribution.size(); i++) {
distributionSeries.add(lstBrandNames.get(i), distribution.get(i));
}
DefaultRenderer defaultRenderer = new DefaultRenderer();
defaultRenderer.setApplyBackgroundColor(true);
defaultRenderer.setBackgroundColor(Color.WHITE);
for (int i = 0; i < distribution.size(); i++) {
SimpleSeriesRenderer seriesRenderer = new SimpleSeriesRenderer();
Random rnd = new Random();
int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
seriesRenderer.setColor(color);
seriesRenderer.setGradientEnabled(false);
seriesRenderer.setDisplayChartValues(true);
seriesRenderer.setShowLegendItem(false);
defaultRenderer.setLabelsTextSize(25);
defaultRenderer.addSeriesRenderer(seriesRenderer);
}
defaultRenderer.setLabelsColor(Color.BLACK);
defaultRenderer.setChartTitle("Brands - Achievement Progress");
defaultRenderer.setChartTitleTextSize(30);
defaultRenderer.setZoomButtonsVisible(true);
defaultRenderer.setShowLabels(true);
Intent intent = ChartFactory.getPieChartIntent(
getActivity(), distributionSeries,
defaultRenderer, "Dash Board");
getActivity().startActivity(intent);
}
}
});
This creates pie chart. But there is a problem. Let's say, first, I click the button then it creates pie chart. Then I back from the pie chart screen and click again the button, then it duplicates pie chart data.
I found something like this as a solution.
layout = new LinearLayout(getActivity());
mChartView = ChartFactory.getPieChartView(getActivity(), distributionSeries, defaultRenderer);
layout.removeAllViews();
layout.addView(mChartView); getActivity().setContentView(layout);
I am doing all of these things in a fragment. I found that it's not a good thing of creating new layout within a fragment. And also when I use the above solution it creates pie chart once and cannot back from the pie chart screen.
I am very confused how can I solve this issue. I would be much appreciated if anyone please be so kind enough to explain what's going on here and how can I solve this issue.
Thanks a lot
Replace the fragment :
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.details, new NewFragmentToReplace, "NewFragmentTag");
ft.commit();
and if you want to go back to the previous fragmnet,ensure you add the above transaction to the back stack, i.e.
ft.addToBackStack(null);
Related
I'm trying to update the AnyChart pie chart with data provided through an input field, I want to have the pie chart update to reflect the added data.
Here's my code:
//Initialize the PieChart
AnyChartView anyChartView;
//Data Structures for Pie Chart
List<String> drinks = new ArrayList<>(Arrays.asList("Water", "Orange Juice", "Pepsi"));
List<Double> quantity = new ArrayList<>(Arrays.asList(50.5,20.2,15.2));
//Input fields
EditText drinkNameInput;
EditText drinkAmountInput;
//Button
Button addDrinkButton;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intakechart);
drinkNameInput = findViewById(R.id.drinkNameArea);
drinkAmountInput = findViewById(R.id.drinkAmountArea);
addDrinkButton = findViewById(R.id.addDrinkButton);
anyChartView = findViewById(R.id.any_chart_view);
Pie pie = AnyChart.pie();
List<DataEntry> dataEntries = new ArrayList<>();
for(int i = 0; i < drinks.size(); i++)
dataEntries.add(new ValueDataEntry(drinks.get(i), quantity.get(i)));
pie.data(dataEntries);
anyChartView.setChart(pie);
addDrinkButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
dataEntries.add(new ValueDataEntry(
drinkNameInput.getText().toString(),
Double.parseDouble(drinkAmountInput.getText().toString())
));
Log.v("Data: ", dataEntries.toString());
}
});
}
Whenever I add to the drinks and quantity lists from the inputted data, the pie chart does not update to reflect the changes. The lists however do contain the added drink and amount, so I know the button onClickListener is working. Does anyone see what's wrong?
Your chart has no reference to drinks or quantity. You will need to hold global reference to your dataEntries list and update that instead.
private List<DataEntry> dataEntries = new ArrayList<>();
public void onClick(View view) {
dataEntries.add(new ValueDataEntry(
drinkNameInput.getText().toString(),
Double.parseDouble(drinkAmountInput.getText().toString())));
pie.data(dataEntries);
}
Here is my code in which i m choosing the directory/Folder to get all (mp3) files in my listview. after adding files in listview i want to play them automatically one by one from first list item to end. I am trying to use indexes of the listview items in for loop. but logically wrong somewhare. May i missing something. Help will be appriciated. Thanks buddies.
DirectoryChooser directoryChooser = new DirectoryChooser();
directoryChooser.setTitle("Select a Folder for Playlist");
directoryChooser.setInitialDirectory(new File("D:\\Songs"));
File dir = directoryChooser.showDialog(new Stage());
playlist.getItems().addAll(dir.listFiles());
try {
playlist.getSelectionModel().selectLast();
lastItemIndex = playlist.getSelectionModel().getSelectedIndex();
playlist.getSelectionModel().selectFirst();
fileToPlayIndex = playlist.getSelectionModel().getSelectedIndex();
// JOptionPane.showMessageDialog(null,fileToPlayIndex );
for(int i=fileToPlayIndex; i<=lastItemIndex; i++ ){
fileToPlay = playlist.getSelectionModel().getSelectedItem();
Media media = new Media(fileToPlay.toURI().toString());
mediaPlayer = new MediaPlayer(media);
mdv.setMediaPlayer(mediaPlayer);
mdv.setPreserveRatio(true);
mediaPlayer.setAutoPlay(true);
DoubleProperty width = mdv.fitWidthProperty();
DoubleProperty height = mdv.fitHeightProperty();
width.bind(Bindings.selectDouble(mdv.sceneProperty(), "width"));
height.bind(Bindings.selectDouble(mdv.sceneProperty(),"Height"));
// voulume slider
volslider();
// seekslider implementation
seekslider();
mediaPlayer.play();
JOptionPane.showMessageDialog(null, "Media is playing ");
mediaPlayer.setOnEndOfMedia(new Runnable() {
#Override
public void run() {
mediaPlayer.stop();
JOptionPane.showMessageDialog(null, "Media Has been ended.");
playlist.getSelectionModel().selectNext();
//getting the changed(next) index of the list view item.
fileToPlayIndex = playlist.getSelectionModel().getSelectedIndex();
flag = 1;
mediaPlayer.dispose();
}
});
}
}
catch (Exception eex) {
JOptionPane.showMessageDialog(null,eex);
}
}
I have a set of ImageView in which some of them are red colored blink for some time like below.
I want to do that ,When I'm click on colored blinked imageViews it change as tic mark and when I'm click non blinked imageViews it change as cross mark.
My issue is my current code only tic the one imageview and all other imageViews are cross marked.
So how to make tic mark more than one ImageView.
Here is my code:
org_id = new int[]{R.id.img1_1, R.id.img1_2, R.id.img1_3, R.id.img1_4};
all = new int[]{R.id.img1_1, R.id.img1_2, R.id.img1_3, R.id.img1_4};
Random random = new Random();
for(int j=0;j<2;j++) {
id = all[random.nextInt(all.length)];
ObjectAnimator animator = ObjectAnimator.ofInt(findViewById(id), "backgroundResource", R.drawable.new_stateimg, R.drawable.org_state).setDuration(2000);
Toast.makeText(Game.this, "index" + findViewById(id), Toast.LENGTH_LONG).show();
animator.setEvaluator(new ArgbEvaluator());
animator.start();
for (int i=0; i < org_id.length; ++i) {
final int btn = org_id[i];
findViewById(btn).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if ((findViewById(id)).equals(findViewById(btn)))
{
findViewById(id).setBackgroundResource(R.drawable.correct);
} else {
Toast.makeText(Game.this, "wrong", Toast.LENGTH_SHORT).show();
findViewById(btn).setBackgroundResource(R.drawable.cross);
}
}
});
}
}
Compare your id like
if (id.getId() == btn.getId())
Do it in your code.
public void onClick(View view) {
ImageView imgView = (ImageView)view; //edited
if(imgView.getDrawable().getConstantState().equals
(getResources().getDrawable(R.drawable.correct).getConstantState()))
imgView.setBackgroundResource(R.drawable.incorrect);//set here you incorrect image which you want.
else
imgView.setBackgroundResource(R.drawable.correct);//set here your correct image
}
This application, displays an EEG devices OSC data. So far it can display the it receives from the device.
#Override
public void receiveDataPacket(DataPacket p) {
switch (p.getPacketType()) {
case EEG:
updateEeg(p.getValues());
break;
case ACCELEROMETER:
updateAccelerometer(p.getValues());
break;
case ALPHA_RELATIVE:
updateAlphaRelative(p.getValues());
break;
case BATTERY:
fileWriter.addDataPacket(1, p);
// It's library client responsibility to flush the buffer,
// otherwise you may get memory overflow.
if (fileWriter.getBufferedMessagesSize() > 8096)
fileWriter.flush();
break;
default:
break;
}
}
private void updateEeg(final ArrayList<Double> data) {
Activity activity = activityRef.get();
if (activity != null) {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
TextView tp9 = (TextView) findViewById(R.id.eeg_tp9);
TextView fp1 = (TextView) findViewById(R.id.eeg_fp1);
TextView fp2 = (TextView) findViewById(R.id.eeg_fp2);
TextView tp10 = (TextView) findViewById(R.id.eeg_tp10);
tp9.setText(String.format(
"%6.2f", data.get(Eeg.TP9.ordinal())));
fp1.setText(String.format(
"%6.2f", data.get(Eeg.FP1.ordinal())));
fp2.setText(String.format(
"%6.2f", data.get(Eeg.FP2.ordinal())));
tp10.setText(String.format(
"%6.2f", data.get(Eeg.TP10.ordinal())));
}
});
}
}
I would like to create an array that holds and records the EEG values from the different positions. I would like to populate this list and enable a button that can display a graphical representation of the data.
Could i create an array and populate it as followed in the recieveDataPacket(Datapacket p) case EEG? My problem the data is being updated via a refresh function, which refreshes it and gets the new data. There are 4 positions and i would like to atleast have 5-10 values from each position in an array to populate the line graph.
EEGData[] eegData = new EEGData[]
for(int i = 0; i<eegData.length; i++){
eegData[i] = new EEGData();}
refresh function:
public void onClick(View v) {
Spinner Spinner = (Spinner) findViewById(R.id.spinner);
if (v.getId() == R.id.refresh) {
MuManager.refreshPaired();
List<Device> pairedDevice = MManager.getPaired();
List<String> spinnerItems = new ArrayList<String>();
for (Device m: pairedDevice) {
String dev_id = m.getName() + "-" + m.getMacAddress();
Log.i("Device", dev_id);
spinnerItems.add(dev_id);
}
ArrayAdapter<String> adapterArray = new ArrayAdapter<String> (
this, android.R.layout.simple_spinner_item, spinnerItems);
Spinner.setAdapter(adapterArray);
}
I know that the data is constantly varrying, could i keep a counter for the first 15 values for each position then populate an array which the graph can pull data from.
I'm displaying a pie chart with data taken from the database. The database query has WHERE clause the year chosen by a Spinner. At the opening of Fragment everything works fine, but if you do not change year by Spinner method is called grafico(anno). I tried with onResume () but it does not work, you have some suggestions? thanks
private void grafico(String anno){
// Pie Chart Section Names
String[] code = new String[] {"A", "B"};
// Color of each Pie Chart Sections
int[] colors = { Color.rgb(153,204,0), Color.rgb(255,68,68)};
SQLiteDatabase db = new ResgistroSpeseHelper(getActivity()).getReadableDatabase();
String sql = "SELECT SUM(a), SUM(b) FROM table WHERE data LIKE '"+anno+"%'";
Cursor c = db.rawQuery(sql, null);
while (c.moveToNext()){
double a_ = c.getDouble(0);
double b_ = c.getDouble(1);
double somma = b_ + a_;
double perc_1 = (a_ / somma) * 100;
double perc_2 = (b_ / somma) * 100;
// Pie Chart Section Value
double[] distribution = { perc_2, perc_1 } ;
// Instantiating CategorySeries to plot Pie Chart
CategorySeries distributionSeries = new CategorySeries(" Android version distribution as on October 1, 2012");
for(
int i=0 ;
i < distribution.length;
i++){
// Adding a slice with its values and name to the Pie Chart
distributionSeries.add(code[i], distribution[i]);
//distributionSeries.add(perc_entrate);
}
// Instantiating a renderer for the Pie Chart
DefaultRenderer defaultRenderer = new DefaultRenderer();
for(int i = 0 ;i<distribution.length;i++){
SimpleSeriesRenderer seriesRenderer = new SimpleSeriesRenderer();
seriesRenderer.setColor(colors[i]);
seriesRenderer.setDisplayChartValues(true);
// Adding a renderer for a slice
defaultRenderer.addSeriesRenderer(seriesRenderer);
}
defaultRenderer.setLabelsTextSize (12);
defaultRenderer.setLegendTextSize(22);
defaultRenderer.setZoomButtonsVisible(true);
// Getting PieChartView to add to the custom layout
mChartView = ChartFactory.getPieChartView(getActivity(),distributionSeries, defaultRenderer);
// Getting a reference to view group linear layout chart_container
// Adding the pie chart to the custom layout
chartContainer.addView(mChartView);
}
c.close();
db.close();
}
//
#Override
public void onResume(){
years = ottieniAnni();
SpinnerAdapter adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, years);
yearSelector.setAdapter(adapter);
yearSelector.setSelection(0);
yearSelector.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view,
int position, long id) {
String anno = years.get(position);
grafico(anno);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
return;
}
});
super.onResume();
}