How can I update AnyChart from input? - java

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);
}

Related

swapAdapter() is is refreshing RecyclerView view but not the data - Android - Java

The recyclerView is used to display a custom ArrayList of products and this view can be switched between different types of products by the user via radio buttons that call swapAdapter. The products are all filtered by diameter via spinner bar selection, and since the user will want to get products of matching diameter, the filter must hold as the adapters swap. All of this is working in the view, however when the user selects an item to add to the cart, the cart will show the wrong item. It will be from the same position however, from the previous adapter. As these adapters switch so does the last adapter. Why are the views refreshing but the data linked to the position is always one and only one step behind?
Here is the RecyclerView
mRecyclerView = findViewById(R.id.inventory_recycler_view);
mLayoutManager = new LinearLayoutManager(this);
aAdapter = new CustomAdapter(aList);
bAdapter = new CustomAdapter(bList);
cAdapter = new CustomAdapter(cList);
dAdapter = new CustomAdapter(dList);
eAdapter = new CustomAdapter(eList);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(aAdapter);
and here is the radio group
bButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mRecyclerView.swapAdapter(bAdapter, true);
bAdapter.getFilter().filter(filterDiameterString);
// bAdapter.notifyDataSetChanged();
}
});
cButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mRecyclerView.swapAdapter(cAdapter, true);
cAdapter.getFilter().filter(filterDiameterString);
// cAdapter.notifyDataSetChanged();
}
});
dButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mRecyclerView.swapAdapter(dAdapter, true);
dAdapter.getFilter().filter(filterDiameterString);
// dAdapter.notifyDataSetChanged();
}
});
eButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mRecyclerView.swapAdapter(miscAdapter, true);
eAdapter.getFilter().filter(filterDiameterString);
// eAdapter.notifyDataSetChanged();
}
});
The following has been attempted:
notifyDataSetChange
recyclerview.invalidate
adapter.clear()
I was able to resolve this issue by adding a setter to my arraylist in the custom adapter and then changed the list via the setter then called notify data set change.

how to call the output of a method in another Activity 's textview?

im programming an app to sort numbers and display the sorting process
after the input is sorted , a new button will be showen to display the selection sort steps in a new activity
[SelectionSort activity 1
I want the output of the function SelectionSortMethod in SelectionSortclass to be displayed in a new activity activity_Ssteps
SelectionSort.java :
public class SelectionSort extends AppCompatActivity {
EditText input;
EditText output;
Button Ssteps ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_selection_sort);
input=findViewById(R.id.input);
output=findViewById(R.id.output);
Ssteps = findViewById(R.id.steps);
Ssteps.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent s = new Intent(SelectionSort.this, com.example.sorted.Ssteps.class);
startActivityForResult(s, 1);
}
});}
public void sortButtonPressed(View view){
String[] numberList = input.getText().toString().split(",");
Integer[] numbers = new Integer[numberList.length];
for (int i = 0; i < numberList.length; i++) {
numbers[i] = Integer.parseInt(numberList[i]);
}
SelectionSortmethod(numbers);
output.setText(Arrays.toString(numbers));
// if button "sort " is pressed , the button "view steps "will be displayed
Ssteps.setVisibility(View.VISIBLE);
}
}
public static void SelectionSortmethod (Integer[] arr)
{
// some code for sorting and showing the steps
}
Ssteps.java :
public class Ssteps extends AppCompatActivity {
TextView steps_text ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ssteps);
setTitle("selection sort steps ");
steps_text =findViewById(R.id.Stepstextview);
}
}
You can just use intent.extras like so:
Intent s = new Intent(SelectionSort.this, com.example.sorted.Ssteps.class);
s.putExtra("AnyID",YOURDATA);
startActivity(s);
And then in your Ssteps.class you can get the data using
the id like this:
String ss = getIntent.getExtra("AnyID"); //the id is the same as the other one above
steps_text.settext(ss);
Working with Intents like Youssof described is the way to go for small applications like yours. However as you progress in Android programming, you should definitely have a look at splitting your application in Fragments rather than Activities. They can use a Viewmodel, which makes sharing lots of data between screens much easier. Also Fragments can be use in androidx Navigation component, whos changing Fragments can be beautifully arranged in a UI. Very convenient for product reviews.

Creating array of data, for line graphs in Android?

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.

Displaying list values with each button click

How can i display list items on each button click. Lets say there are 4 names in the list. When I press next it displays the first name. Then when you press next it displays the second name and so on.
The only way I think is using the list.get() method. however I dont know how to use the method so that it knows how many values there are in the list and displaying then on each button hit. I think i need to use for method however I hadnt had any luck with it.
public class ZaidimasActivity extends ZaidejaiActivity {
public TextView mPlayer;
public TextView mKlausimas;
public Button mNext;
public Button mBack;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_zaidimas);
/** //get the player list from ZaidejaiActivity
Bundle recdData = getIntent().getExtras();
String myVal = recdData.getString("playerList"); */
Intent zaidejuInfo = getIntent();
Bundle extrasBundle = zaidejuInfo.getExtras();
final ArrayList<String> players = extrasBundle.getStringArrayList("playerList");
//show the first players name
mPlayer = (TextView)findViewById(R.id.ZaidejoVardas);
players.size();
mPlayer.setText(players.get(0));
mNext = (Button)findViewById(R.id.KitasBtn);
mNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPlayer.setText(players.get(1));
}
});
mBack = (Button)findViewById(R.id.GryztiMeniuBtn);
mBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent gryztiMeniu = new Intent(ZaidimasActivity.this, ZaidejaiActivity.class);
startActivity(gryztiMeniu);
}
});
}
Here you go, maintain a variable for storing the global array index and increment it every time the button is clicked.
private int count = 0; // Global array index. Make it as class field
final ArrayList<String> players = extrasBundle.getStringArrayList("playerList");
mPlayer = (TextView)findViewById(R.id.ZaidejoVardas);
players.size();
mPlayer.setText(players.get(0));
mNext = (Button)findViewById(R.id.KitasBtn);
mNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
count++;
mPlayer.setText(players.get((count)%players.size())); //Incrementing global count and making sure it never exceeds the players list size
}
});

Android onResume() aChartengine Pie Chart

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();
}

Categories

Resources