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();
}
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);
}
How to insert the values of spinner to SQL lite database in android?
for instance my code has
ArrayList<String> yr = new ArrayList<String>();
for (int i = 2015; i <= 2030; i++) {
yr.add(Integer.toString(i));
}
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, yr);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
year.setAdapter(adapter1);
and i want to save the year selected by the user on the database
Implement OnItemSelectedListener for your class then call setOnItemSelectedListener for the spinner.
spinner.setOnItemSelectedListener(this);
Then add the following which gets invoked after year is selected in the dropdown:
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString();
//insert item to db
}
May be this will work
public void insertValuesInDb(ArrayAdapter adapter) {
for(int i = 0; i < adapter.size(); i++) {
item = adapter.getItem(i)
//insert item in database
}
}
If it helps you then don't forget to mark answer as accepted and if you have any further queries you can ask them in comments!
The title says it all, I'm trying to do that because I obtain a list from parse and the user must choose one of them from a spinner and based on the user's choice it responds and sets another filter to another spinner. The problem I'm having (really not much of a deal, but it's something that I'd like to do) is that when the list gets obtained from Parse it automatically selects the first one it retrieves and fills all the spinners automatically (of course you can change it and it will work perfectly).
The question is, how do I retrieve a list from parse, add it into a spinner in a way that it doesn't fill everything by itself ?
Here's my piece of code where I obtain the list and add it into a spinner:
groupSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
System.out.println("Group Item Selected Ran");
final String spinI1 = groupSpinner.getSelectedItem().toString();
ParseQuery<ParseObject> query = ParseQuery.getQuery("Hospitales");
query.whereEqualTo("grupo", spinI1);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> parseObjects, ParseException e) {
int size = 0;
size = parseObjects.size();
String[] mod = new String[size];
for (int i = 0; i < parseObjects.size(); i++) {
mod[i] = parseObjects.get(i).getString("Hospital");
System.out.println(mod[i]);
}
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(HandsetLocation.this, android.R.layout.simple_spinner_item, mod);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
hospitalSpinner.setAdapter(spinnerArrayAdapter);
}
});
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Any help would be appreciated greatly!
At my phone so cannot properly indent the code but here it goes:
String[] mod = new String[size+1];
mod[0] = "select value";
for (int i = 0; i < parseObjects.size(); i++) {
mod[i+1] = parseObjects.get(i).getString("Hospital");
System.out.println(mod[i+1]);
}
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);
I can't seem to figure out why my list row item won't change color:
/** Populate the Views in act_alliances.xml with data from the database */
private void loadAllianceData() {
TblAlliances mTAlliances = new TblAlliances(this);
mTAlliances.openRead();
Cursor mCursor = mTAlliances.selectSectorData(mSector);
// load Sector Name into act_alliance_detail.xml
TextView mTxtSctName = (TextView) findViewById(R.id.allc_sname);
mTxtSctName.setText("Sector: "+mSector);
// load the "Number of Alliances" field with the count from the cursor
TextView mTxtNumAllcs = (TextView) findViewById(R.id.allc_textView2);
mTxtNumAllcs.setText(String.valueOf(mCursor.getCount()));
String[] cols = new String[] {
mTAlliances.C_FID,
mTAlliances.C_FANAME,
mTAlliances.C_FPLTC,
mTAlliances.C_FSPWER
};
int[] to = new int[] {
R.id.allc_lstRow_textView1,
R.id.allc_lstRow_textView2,
R.id.allc_lstRow_invisible,
R.id.allc_lstRow_textView3
};
// connect to the ListView and clear it just in case this isnt the first time
ListView mListView = (ListView) findViewById(R.id.allc_listView);
mListView.destroyDrawingCache();
mListView.setVisibility(ListView.INVISIBLE);
mListView.setVisibility(ListView.VISIBLE);
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
SimpleCursorAdapter dataAdapter = new SimpleCursorAdapter(
this,
R.layout.act_alliances_list_row,
mCursor,
cols,
to,
0);
dataAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Cursor cursor, int column) {
if( column == 1 ){
TextView tv = (TextView) view;
String mPltc = cursor.getString(cursor.getColumnIndex("FPLTC"));
if (BuildConfig.DEBUG) {
Log.i(Constants.TAG_ACTALLIANCES, "loadAllianceData(): Political Relation: "+mPltc);
}
// Set color of item based on Political Relation
if(mPltc == "Ally"){tv.setTextColor(Color.parseColor("#6699ff"));}
if(mPltc == "Vassal"){tv.setTextColor(Color.parseColor("#00ff00"));}
if(mPltc == "Enemy"){tv.setTextColor(Color.parseColor("#ff0000"));}
return true;
}
return false;
}
});
// Assign adapter to ListView
mListView.setAdapter(dataAdapter);
mListView.setOnItemClickListener( new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// selected item
mAllianceForDetail = ((TextView) arg1.findViewById(R.id.allc_lstRow_textView2)).getText().toString();
startAct("AllianceDetail");
}
});
mTAlliances.close();
}
Everything in the SimpleCursorAdapter.ViewBinder seems to be in order, but the color won't change...i suspect that it may be WHERE i placed the ViewBinder more than the ViewBinder itself.
Any help would be appreciated!
You can't equalize object with a string. You need to use equals or equalsIgnoreCase functions
if (mPltc.equalsIgnoreCase("Ally")){tv.setTextColor(Color.parseColor("#6699ff"));}
if (mPltc.equalsIgnoreCase("Vassal")){tv.setTextColor(Color.parseColor("#00ff00"));}
if (mPltc.equalsIgnoreCase("Enemy")){tv.setTextColor(Color.parseColor("#ff0000"));}
return true;
Try using
if(mPltc.equals("Ally"))...
instead of
if(mPltc == "Ally")
(Same with "Vassal", "Enemy", etc)
You shouldn't use == on String objects, as it doesn't work the way you'd expect.