I am trying to create a pie chart from the data stored in the database using MPAndroidChart.
The size of the database is not fixed so it might have 2 to 7 data.
This is how I'm taking the data from the database.
myDb = new DatabaseHelper(this);
Cursor pie = myDb.showKharcha();
String[] xData = new String[pie.getCount()];
float[] yData = new float[pie.getCount()];
int i = 0;
float total = 0;
while (pie.moveToNext()){
String kname = pie.getString(1);
Float kh= pie.getFloat(2);
float kharcha = kh.floatValue();
total = total + kharcha ;
xData[i]=kname;
yData[i]=kharcha;
i++;
}
And this is the part of using the data for pie chart.
ArrayList<PieEntry> yEntry= new ArrayList<>();
ArrayList<String> xEntry = new ArrayList<>();
for( i =0;i < yData.length;i++){
yData[i] = yData[i]*100/total;
yEntry.add(new PieEntry(yData[i],i));
}
for(i =0;i < xData.length;i++){
xEntry.add(xData[i]);
}
The error I get is null pointer exception error and this to be exact
Attempt to invoke virtual method 'void com.github.mikephil.charting.charts.PieChart.setRotationEnabled(boolean)' on a null object reference
The part containing setRotationEnabled(boolean) is as follows which is before calling the addDataSet method where everything I've provided takes place.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.piechart);
Log.d(TAG, "onCreate: starting to create chart");
pieChart.setRotationEnabled(true);
pieChart.setHoleRadius(25f);
pieChart.setTransparentCircleAlpha(0);
pieChart.setCenterText("Kharcha");
pieChart.setCenterTextSize(10);
addDataSet();}
I think I'm not being able to pass the float data to be used in a piechart.
Any help would be appreciated.
you forgot to get the PieChart from the layout
pieChart = (PieChart) findViewById(R.id.chart1);
Related
I am using HighChart for rendering graphs on android devices. But on the first time, it is not showing all data points when data points are more than 10k. When I tried to zoom in or zoom out several times, all data points became visible. I need a graph with 50k points at least. I am testing with sample code provided by HighChartjs.
public class MainActivity extends AppCompatActivity {
private ArrayList dataList;
int noOfData = 50000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataList = data();
HIChartView chartView = findViewById(R.id.hc);
chartView.plugins = new ArrayList<>(Arrays.asList("boost"));
HIOptions options = new HIOptions();
HIChart chart = new HIChart();
chart.setType("line");
chart.setZoomType("x");
options.setChart(chart);
HIBoost boost = new HIBoost();
boost.setUseGPUTranslations(true);
options.setBoost(boost);
HITitle title = new HITitle();
options.setTitle(title);
HISubtitle subtitle = new HISubtitle();
subtitle.setText("Using the Boost module");
options.setSubtitle(subtitle);
HITooltip tooltip = new HITooltip();
tooltip.setValueDecimals(2);
options.setTooltip(tooltip);
HILine line = new HILine();
line.setData(dataList);
int noOfData = this.dataList.size();
title.setText("Highcharts drawing " +noOfData +" points");
line.setLineWidth(1);
options.setSeries(new ArrayList<HISeries>(Collections.singletonList(line)));
chartView.setOptions(options);
}
private ArrayList data(){
ArrayList dataList = new ArrayList();
for (int i = 0; i < noOfData; i++) {
dataList.add(i, (Math.random() * 100));
}
return dataList;
}
}
Getting error logs: Highcharts error #26: www.highcharts.com/errors/26
E/Highcharts: Uncaught TypeError: Cannot read property 'forEach' of undefined
I have 3 string list and I want to add all values to menus but it gives error which is "Invalid index 0, size is 0". Briefly, menus is null and how can I add them?
private List<List<Restaurant.Menu>> menus = new ArrayList<>();
ArrayList<String> MenuName = new ArrayList<>();
ArrayList<String> FoodName = new ArrayList<>();
ArrayList<String> FoodPrice = new ArrayList<>();
//I get values in DB. DB is full.
MenusName = tinydb.getListString("MenuName");
FoodName = tinydb.getListString("FoodName");
FoodPrice = tinydb.getListString("FoodPrice");
int restaurantCounter = 0;
int menuCounter = 0;
for (int j = 0; j < MenusName.size(); j++)
{
menus.get(restaurantCounter).get(j).name = MenusName.get(j))
}
Example, I created them for each value, it works but if string is long, it enforces app and I wait 10 sec. for this process. I need efficient way. Thanks in advance.
menus.get(resCounter).add(new Restaurant.Menu());
menus.get(resCounter).get(menuCounter).foods.add(new Restaurant.Food());
.
.
menus.get(resCounter).get(menuCounter).name = MenuName.get(i));
menus.get(resCounter).get(menuCounter).foods.get(foodCounter).name = FoodName.get(i);
menus.get(resCounter).get(menuCounter).foods.get(foodCounter).price = FoodPrice.get(i);
You seem to be confusing arrays with lists here. Arrays have a fixed size once initialised, Lists don't. You need to add something to your menus list using menus.add(/*Add Menu Object here*/);
You haven't add any values to menus.so the object doesn't contain value at the index 0. This might be a reason.
I couldn't find a solution so I changed structure. I get all strings in restaurants and I used gson to convert them before store them. Also you can use gson for each string. It it same logic.
Gson gson = new Gson();
ArrayList<String> gsonString = new ArrayList<>();
for(int i=0; i<restaurants.size(); i++)
gsonString.add(gson.toJson(restaurants.get(i)));
tinydb.putListString("tinyRestaurant",gsonString);
Convert again...
Gson gson = new Gson();
for(int i=0; i<tinydb.getListString("tinyRestaurant").size(); i++)
restaurants.add(gson.fromJson(tinydb.getListString("tinyRestaurant").get(i), Restaurant.class));
I've been trying to plot a graph from two ArrayLists on my Android Application. I got the values from ArrayList succeed, but I can't call method to get values.
I create this method which gets values from my database:
public DataPoint[] setData(String data)
{
TextView editText4;
editText4 = (TextView) findViewById(R.id.editText4);
String[] lucas = data.split(",");
List<String> ok = new ArrayList<String>(Arrays.asList(lucas));
List<String> yes = new ArrayList<String>(Arrays.asList(lucas));
int n = ok.size(); //to find out the no. of data-points
editText4.setText(String.valueOf(n));
DataPoint[] values = new DataPoint[n]; //creating an object of type DataPoint[] of size 'n'
for (int i = 0; i < n; i++)
{
DataPoint v = new DataPoint(Double.parseDouble(ok.get(i)), Double.parseDouble(yes.get(i)));
values[i] = v;
}
return values;
}
My problem is here in setData (Cannot Resolve symbol 'setData') :
GraphView graph;
PointsGraphSeries<DataPoint> series; //an Object of the PointsGraphSeries for plotting scatter graphs
graph = (GraphView) findViewById(R.id.graph);
series = new PointsGraphSeries<>(setData); //initializing/defining series to get the data from the method 'data()'
graph.addSeries(series); //adding the series to the GraphView
series.setShape(PointsGraphSeries.Shape.POINT);
series.setSize(6);
As looking for your code looks that you have method setData(String data) but in series = new PointsGraphSeries<>(setData); you are calling variable. Please assing result from setData(String data) method to local variable and then use it in mentioned line of code.
hi
why load text from String array and set text to textview is very slow in big string array?
please help to me.
//get khotbe text from database and copy to khotbe activity
private void setkhotbetextarabicfarsi() {
this.sqliteDB = SQLiteDatabase.openOrCreateDatabase(this.getDatabasePath("aliname").getPath(), (SQLiteDatabase.CursorFactory) null);
Itemid = this.getIntent().getIntExtra("selectedFromListid", 1);
Cursor cursorLines = this.sqliteDB.rawQuery("SELECT * FROM khotbe where IDFehrest=" + this.Itemid , (String[]) null);
allrecs = cursorLines.getCount();
matn = new String[allrecs];
if (this.allrecs != 0) {
cursorLines.moveToFirst();
for (int i = 0; i < this.allrecs; ++i) {
String TextArabicOfKhotbe = cursorLines.getString(cursorLines.getColumnIndex("TextArabicOfKhotbe"));
int IDkhotbe = cursorLines.getInt(cursorLines.getColumnIndex("IDkhotbe"));
this.matn[i] = TextArabicOfKhotbe;
cursorLines.moveToNext();
}
}
and main code:
for(int var1 = 0; var1 < this.allrecs; ++var1) {
tvArabic = new JustifiedTextView(this);
tvArabic.setText(matn[var1]);
you are creating the textviews in loop that might making it slow.. try populating the array values using an adapter..
Also check the number of rows you are accessing from the DB. if they are huge in number, they would require more time to be fetched.
Use limit in that case.
I created a Piechart with MPandroidchart for my app. The chart works great. The problem is that the original data contains 4 data entry but the chart only show 3. Can somebody help? What is the limitation for this?
My PieChart
Hi Thank you so much for getting me back. The xVals and yVals are from SQLite database. xVals{30-,30-45,46-60,60-} String and yVals(6,14,13,3) float.
My codes are posted here:
private void AddDataCYNewCustomersAge(){
DataBaseHelper databasehelper = new DataBaseHelper (NewCustomerReportCurrentYear.this);
PieChart ageChart = new PieChart(this);
ageChart = (PieChart)findViewById(R.id.agechart);
//get yVals and datasets of marriage chart
ArrayList<Entry> yValsageCounts = new ArrayList<Entry>();
for(int i = 0;i < databasehelper.yDataIncomeCounts().size(); i++)
yValsageCounts.add(new Entry(databasehelper.yDataAgeCounts().get(i), i));
//get xVals of marriage chart
ArrayList<String> xValsage = new ArrayList<String>();
for(int i = 0;i < databasehelper.xDataAge().size();i++)
xValsage.add(databasehelper.xDataAge().get(i));
PieDataSet ageCounts = new PieDataSet(yValsageCounts, "");
//set yvals attribute
ageCounts.setSliceSpace(3);
ageCounts.setSelectionShift(5);
//add many colors
ageCounts.setColors(new int[]{R.color.Fuchsia, R.color.Aqua,R.color.Yellow,R.color.LightSeaGreen,R.color.Blue}, this);
// configue pie chart
ageChart.setUsePercentValues(true);
ageChart.setRotationEnabled(true);
ageChart.setRotationAngle(0);
ageChart.setDescriptionPosition(350, 550);
ageChart.setDrawHoleEnabled(true);
ageChart.setHoleColor(Color.TRANSPARENT);
ageChart.setHoleRadius(13);
ageChart.setTransparentCircleRadius(18);
ageChart.getLegend().setPosition(Legend.LegendPosition.RIGHT_OF_CHART);
//ageChart.getLegend().setXEntrySpace(3);
// ageChart.getLegend().setYEntrySpace(3);
ageChart.getLegend().setTextColor(Color.BLUE);
ageChart.setDescription("Income");
ageChart.setDescriptionTextSize(13);
ageChart.setDescriptionColor(Color.BLUE);
//get income chart data
PieData ageData = new PieData(xValsage,ageCounts);
ageData.setValueFormatter(new PercentFormatter());
ageData.setValueTextSize(11);
ageData.setValueTextColor(Color.BLUE);
ageChart.setData(ageData);
//refresh data
ageChart.invalidate();
}