How do i use alert builder dialog to display a message - java

I want to use an a dialog to display a message contained in the method below instead of just setText, but each time I use the alertBuilder, the message does not display. Can someone please point me in the right direction?
below is the code:
#Override
public void onPreviewFrame(byte[] data, Camera cam) {
if (data == null) throw new NullPointerException();
Camera.Size size = cam.getParameters().getPreviewSize();
if (size == null) throw new NullPointerException();
if (!processing.compareAndSet(false, true)) return;
int width = size.width;
int height = size.height;
int imgAvg = ImageProcessing.decodeYUV420SPtoRedAvg(data.clone(), height, width);
Log.i(TAG, "imgAvg="+imgAvg);
if (imgAvg == 0 || imgAvg == 255) {
processing.set(false);
return;
}
int averageArrayAvg = 0;
int averageArrayCnt = 0;
for (int i = 0; i < averageArray.length; i++) {
if (averageArray[i] > 0) {
averageArrayAvg += averageArray[i];
averageArrayCnt++;
}
}
int rollingAverage = (averageArrayCnt > 0) ? (averageArrayAvg / averageArrayCnt) : 0;
TYPE newType = currentType;
if (imgAvg < rollingAverage) {
newType = TYPE.RED;
if (newType != currentType) {
beats++;
// Log.d(TAG, "BEAT!! beats="+beats);
}
} else if (imgAvg > rollingAverage) {
newType = TYPE.GREEN;
}
if (averageIndex == averageArraySize) averageIndex = 0;
averageArray[averageIndex] = imgAvg;
averageIndex++;
// Transitioned from one state to another to the same
if (newType != currentType) {
currentType = newType;
image.postInvalidate();
}
long endTime = 20;
//System.currentTimeMillis();
double totalTimeInSecs = (endTime - startTime) / 1000d;
if (totalTimeInSecs >= 20) {
double bps = (beats / totalTimeInSecs);
int dpm = (int) (bps * 60d);
if (dpm < 30 || dpm > 180) {
startTime = System.currentTimeMillis();
beats = 0;
processing.set(false);
return;
}
Log.d(TAG,
"totalTimeInSecs="+totalTimeInSecs+" beats="+beats);
if (beatsIndex == beatsArraySize) beatsIndex = 0;
beatsArray[beatsIndex] = dpm;
beatsIndex++;
int beatsArrayAvg = 0;
int beatsArrayCnt = 0;
for (int i = 0; i < beatsArray.length; i++) {
if (beatsArray[i] > 0) {
beatsArrayAvg += beatsArray[i];
beatsArrayCnt++;
}
}
int beatsAvg = (beatsArrayAvg / beatsArrayCnt);
//maybe here
startTime = System.currentTimeMillis();
beats = 0;
text.setText(String.valueOf(beatsAvg) + "bpm");
}
The code works fine, but I just want to use a dialog to display the text.setText message. How do I do this?

public class DialogCaller {
public static void showDialog(Context context,String title,String message,
DialogInterface.OnClickListener onClickListener) {
AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setTitle(title);
dialog.setMessage(message);
dialog.setPositiveButton("Ok",onClickListener);
dialog.show();
}
}
Add this class to your android project.
whenever you want to display an message just call the class with with context,title,message, and a listener for okay button in dialog. Like this.
Add the below code in the place of text.setText(String.valueOf(beatsAvg) + "bpm");
DialogCaller.showDialog(getActivity()/getApplicationContext(),"Kingmeka dialog ",String.valueOf(beatsAvg) + "bpm",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage(String.valueOf(beatsAvg) + "bpm");
alertDialogBuilder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// Do what needs to be done
}
});
alertDialogBuilder.setNegativeButton("No",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
Use above code for showing your message in alert dialog. Customize it according to your need. For details see this

Related

Dialog not dismiss in if condition

I am try to dismiss dialog in if condition true part but it is not worked.
In dialog entered in if condition but not dismiss.in If condition toast message display properly.
public void showIncomingCall() {
int getTotal = 0;
if(showincoming != null && showincoming.isShowing() )
{
//adapter1.notifyDataSetChanged();
//showincoming.dismiss();
return;
}
else {
showincoming = new Dialog(MainActivity.this);
showincoming.requestWindowFeature(Window.FEATURE_NO_TITLE);
showincoming.setContentView(R.layout.custome_dialog);
listdialog = (ListView) showincoming.findViewById(R.id.incoming_list);
//adapter1 = new CustomeListAdapter(MainActivity.this);
listdialog.setAdapter(adapter1);
//adapter1.notifyDataSetChanged();
close = (ImageButton) showincoming.findViewById(R.id.dialog_close);
close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showincoming.dismiss();
adapter1.notifyDataSetChanged();
}
});
adapter1.notifyDataSetChanged();
for (int i = 0; i < listdialog.getCount(); i++) {
parentView = getViewByPosition(i, listdialog);
String getString = ((TextView) parentView.findViewById(R.id.tvLineStatus)).getText().toString();
if (getString.toString().equals("Idle") || getString.toString().equals("Disconnect") || getString.toString().equals("Dialing")) {
getTotal += 1;
}
}
if (getTotal >= 7) {
showincoming.dismiss();
Toast.makeText(getApplicationContext(),"getTotal" + getTotal,Toast.LENGTH_LONG).show();
adapter1.notifyDataSetChanged();
//adapter1.setNotifyOnChange(true);
}
//Toast.makeText(MainActivity.this,getTotal+"getTotal",Toast.LENGTH_LONG).show();
adapter1.notifyDataSetChanged();
listdialog.invalidateViews();
if(!showincoming.isShowing()) {
showincoming.show();
}
}
}
showincoming = new Dialog(MainActivity.this);
declare this below int getTotal = 0;
i.e outside else statement
then you can get referance of dialog object and can dissmiss dialog. try this and let me know

How to trigger alert

My source code is here https://github.com/jackygrahamez/MayDay
I have a HomeActivity.java with an onCreate method
...
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome_screen);
Bundle bundle=getIntent().getExtras();
boolean startedByCUP=false;
if(bundle!=null) {
Log.e(">>>>>>", "START_BY_CUP");
startedByCUP = bundle.getBoolean("START_BY_CUP");
}
...
I am trying to figure out how I can tie the condition where bundle is true to trigger the multiClickEvent so that after 5 clicks an alarm will trigger. The hardware trigger is built into this
HardwareTriggerReceiver.java
...
#Override
public void onReceive(Context context, Intent intent) {
Log.e(">>>>>>>", "in onReceive of HWReceiver");
String action = intent.getAction();
if (!isCallActive(context) && isScreenLocked(context)
&& (action.equals(ACTION_SCREEN_OFF) ||
action.equals(ACTION_SCREEN_ON))) {
multiClickEvent.registerClick(System.currentTimeMillis());
if (multiClickEvent.isActivated()) {
onActivation(context);
resetEvent();
}
}
}
...
MultiClickEvent.java
package com.mayday.md.trigger;
import android.util.Log;
public class MultiClickEvent {
public static final int TIME_INTERVAL = 10000;
private static final int TOTAL_CLICKS = 5;
private Long firstEventTime;
private int clickCount = 0;
public void reset() {
firstEventTime = null;
clickCount = 0;
}
public void registerClick(Long eventTime) {
if (isFirstClick() || notWithinLimit(eventTime)) {
firstEventTime = eventTime;
clickCount = 1;
return;
}
clickCount++;
Log.e(">>>>>>", "MultiClickEvent clickCount = " + clickCount);
}
private boolean notWithinLimit(long current) {
return (current - firstEventTime) > TIME_INTERVAL;
}
private boolean isFirstClick() {
return firstEventTime == null;
}
public boolean isActivated() {
return clickCount >= TOTAL_CLICKS;
}
}
I have tried creating an instance of MultiClickEvent into the HomeActivity but that did not track the clicks.
I ended up tracking the clicks on the Gear Fit app and then sending the alarm all within the onCreate
if(bundle!=null) {
if (!hardwareTriggerReceiver.isCallActive(getApplicationContext())) {
int c = mPref.getInt("numRun", 0);
int TIME_INTERVAL = 10000;
int TOTAL_CLICKS = 5;
long delta = 0;
Long eventTime = System.currentTimeMillis();
mPref.edit().putLong("eventTime", eventTime).commit();
Long firstEventTime = mPref.getLong("firstEventTime", 0);
if (firstEventTime == 0) {
firstEventTime = eventTime;
mPref.edit().putLong("firstEventTime", firstEventTime).commit();
}
delta = eventTime - firstEventTime;
Log.e(">>>>>>", "START_BY_CUP delta "+delta);
if (delta < TIME_INTERVAL) {
c++;
mPref.edit().putInt("numRun",c).commit();
Log.e(">>>>>>", "START_BY_CUP "+c);
if (c >=TOTAL_CLICKS) {
hardwareTriggerReceiver.onActivation(getApplicationContext());
mPref.edit().putInt("numRun", 0).apply();
mPref.edit().putLong("firstEventTime", 0).apply();
}
} else {
mPref.edit().putInt("numRun", 0).apply();
mPref.edit().putLong("firstEventTime", 0).apply();
}
}
}

Android refresh rating bar upon triggeration

I am having some problem when trying to refresh the rating bar after user submitted their rating. So basically I am passing the existing rating amount when certain button on my other Activity was triggered:
viewDtlEventBtn.setOnClickListener(new OnClickListener(){
public void onClick(View v){
Object[] obj = new Object[2];
obj[0] = String.valueOf(eventIDTV.getText());
obj[1] = eventReviewModel;
new GetEventDetailAsyncTask(new GetEventDetailAsyncTask.OnRoutineFinished() {
public void onFinish() {
// Passing whole object with value into another activity
Intent eventDtlIntent = new Intent(context, EventDetailMain.class);
// Pass in a list of rating star together with amount
eventDtlIntent.putExtra("eventPopulateStarObj", populateRatingStar);
context.startActivity(eventDtlIntent);
}
}).execute(obj);
}
});
And I am populating the rating bar when onCreate():
ratingStarList = (ArrayList<EventReview>) i
.getSerializableExtra("eventPopulateStarObj");
public void populateRatingProgressBar() {
int totalStar = 0;
// Get the total amount of rate records
for (int j = 0; j < ratingStarList.size(); j++) {
if (ratingStarList.get(j).getStarAmt() != null) {
totalStar += Integer.parseInt(ratingStarList.get(j)
.getStarAmt());
}
}
txtTotalRate.setText(totalStar + " Ratings for this event");
// Set progress bar based on the each rates
for (int i = 0; i < ratingStarList.size(); i++) {
if (ratingStarList.get(i).getStarAmt() != null) {
if (ratingStarList.get(i).getEventReviewRate().equals("5")) {
pb5Star.setProgress(Integer.parseInt(ratingStarList.get(i)
.getStarAmt()));
} else if (ratingStarList.get(i).getEventReviewRate()
.equals("4")) {
pb4Star.setProgress(Integer.parseInt(ratingStarList.get(i)
.getStarAmt()));
} else if (ratingStarList.get(i).getEventReviewRate()
.equals("3")) {
pb3Star.setProgress(Integer.parseInt(ratingStarList.get(i)
.getStarAmt()));
} else if (ratingStarList.get(i).getEventReviewRate()
.equals("2")) {
pb2Star.setProgress(Integer.parseInt(ratingStarList.get(i)
.getStarAmt()));
} else if (ratingStarList.get(i).getEventReviewRate()
.equals("1")) {
pb1Star.setProgress(Integer.parseInt(ratingStarList.get(i)
.getStarAmt()));
}
}
}
}
It did populated correctly. However, I not sure how to refresh the rating bar after user submitted their rating. Here is the code when user submit their rating:
public void promptSubmitStar() {
AlertDialog.Builder Dialog = new AlertDialog.Builder(getActivity());
Dialog.setTitle("Confirm Rating");
LayoutInflater li = (LayoutInflater) getActivity().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
View dialogView = li.inflate(R.layout.option_submit_star, null);
txtPromptStarRate = (TextView) dialogView
.findViewById(R.id.txtPromptStarRate);
txtPromptStarRate.setText("Confirm to submit " + starRate
+ " stars for this event?");
Dialog.setView(dialogView);
Dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
EventReview eventReviewModel = new EventReview();
eventReviewModel.setEventID(eventID);
eventReviewModel.setEventReviewBy(userID);
eventReviewModel.setEventReviewRate(String.valueOf(starRate));
new CreateEventReviewAsyncTask(context)
.execute(eventReviewModel);
dialog.dismiss();
// Disable the rating bar by setting a touch listener which
// always return true
ratingBar.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View view, MotionEvent event) {
return true;
}
});
}
});
Dialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
Dialog d = Dialog.show();
EventDialogueBox.customizeDialogueBox(context, d);
}
Any ideas? Thanks in advance.
Use setRating(starRate); to programmatically set the rating on the RatingBar.

Fatal runtime error at android.media.audiofx.Equalizer.<init>

I am working on equalier app and no errors in code at all. when I run app on phone it force closes, I logcat and this is result
03-22 02:49:17.945: E/AndroidRuntime(4318): at android.media.audiofx.Equalizer.<init>(Equalizer.java:149)
03-22 02:50:34.796: E/AndroidRuntime(4423): at android.media.audiofx.Equalizer.<init>(Equalizer.java:149)
I tried on android gingerbread kitkat and jellybean
this is the main activity code:
public class MainActivity extends Activity
implements SeekBar.OnSeekBarChangeListener,
CompoundButton.OnCheckedChangeListener,
View.OnClickListener
{
//as usual "define variables"
TextView bass_boost_label = null;
SeekBar bass_boost = null;
CheckBox enabled = null;
Button flat = null;
Button Button1;
Equalizer eq = null;
BassBoost bb = null;
int min_level = 0;
int max_level = 100;
static final int MAX_SLIDERS = 8; // Must match the XML layout
SeekBar sliders[] = new SeekBar[MAX_SLIDERS];
TextView slider_labels[] = new TextView[MAX_SLIDERS];
int num_sliders = 0;
/*=============================================================================
onCreate
=============================================================================*/
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
/*=============================================================================
onCreate
=============================================================================*/
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//initalize layout
setContentView(R.layout.activity_main);
//initialize the checkbox
enabled = (CheckBox)findViewById(R.id.enabled);
enabled.setOnCheckedChangeListener (this);
//initialize flat button
flat = (Button)findViewById(R.id.flat);
flat.setOnClickListener(this);
Button1 = (Button)findViewById(R.id.button1);
Button1.setOnClickListener(this);
//the seekbars
bass_boost = (SeekBar)findViewById(R.id.bass_boost);
bass_boost.setOnSeekBarChangeListener(this);
bass_boost_label = (TextView) findViewById (R.id.bass_boost_label);
sliders[0] = (SeekBar)findViewById(R.id.slider_1);
slider_labels[0] = (TextView)findViewById(R.id.slider_label_1);
sliders[1] = (SeekBar)findViewById(R.id.slider_2);
slider_labels[1] = (TextView)findViewById(R.id.slider_label_2);
sliders[2] = (SeekBar)findViewById(R.id.slider_3);
slider_labels[2] = (TextView)findViewById(R.id.slider_label_3);
sliders[3] = (SeekBar)findViewById(R.id.slider_4);
slider_labels[3] = (TextView)findViewById(R.id.slider_label_4);
sliders[4] = (SeekBar)findViewById(R.id.slider_5);
slider_labels[4] = (TextView)findViewById(R.id.slider_label_5);
sliders[5] = (SeekBar)findViewById(R.id.slider_6);
slider_labels[5] = (TextView)findViewById(R.id.slider_label_6);
sliders[6] = (SeekBar)findViewById(R.id.slider_7);
slider_labels[6] = (TextView)findViewById(R.id.slider_label_7);
sliders[7] = (SeekBar)findViewById(R.id.slider_8);
slider_labels[7] = (TextView)findViewById(R.id.slider_label_8);
//define equilizer
eq = new Equalizer (0, 0);
if (eq != null)
{
eq.setEnabled (true);
int num_bands = eq.getNumberOfBands();
num_sliders = num_bands;
short r[] = eq.getBandLevelRange();
min_level = r[0];
max_level = r[1];
for (int i = 0; i < num_sliders && i < MAX_SLIDERS; i++)
{
int[] freq_range = eq.getBandFreqRange((short)i);
sliders[i].setOnSeekBarChangeListener(this);
slider_labels[i].setText (formatBandLabel (freq_range));
}
}
for (int i = num_sliders ; i < MAX_SLIDERS; i++)
{
sliders[i].setVisibility(View.GONE);
slider_labels[i].setVisibility(View.GONE);
}
bb = new BassBoost (0, 0);
if (bb != null)
{
}
else
{
bass_boost.setVisibility(View.GONE);
bass_boost_label.setVisibility(View.GONE);
}
updateUI();
}
/*=============================================================================
onProgressChanged
=============================================================================*/
#Override
public void onProgressChanged (SeekBar seekBar, int level,
boolean fromTouch)
{
if (seekBar == bass_boost)
{
bb.setEnabled (level > 0 ? true : false);
bb.setStrength ((short)level); // Already in the right range 0-1000
}
else if (eq != null)
{
int new_level = min_level + (max_level - min_level) * level / 100;
for (int i = 0; i < num_sliders; i++)
{
if (sliders[i] == seekBar)
{
eq.setBandLevel ((short)i, (short)new_level);
break;
}
}
}
}
/*=============================================================================
onStartTrackingTouch
=============================================================================*/
#Override
public void onStartTrackingTouch(SeekBar seekBar)
{
}
/*=============================================================================
onStopTrackingTouch
=============================================================================*/
#Override
public void onStopTrackingTouch(SeekBar seekBar)
{
}
/*=============================================================================
formatBandLabel
=============================================================================*/
public String formatBandLabel (int[] band)
{
return milliHzToString(band[0]) + "-" + milliHzToString(band[1]);
}
/*=============================================================================
milliHzToString
=============================================================================*/
public String milliHzToString (int milliHz)
{
if (milliHz < 1000) return "";
if (milliHz < 1000000)
return "" + (milliHz / 1000) + "Hz";
else
return "" + (milliHz / 1000000) + "kHz";
}
/*=============================================================================
updateSliders
=============================================================================*/
public void updateSliders ()
{
for (int i = 0; i < num_sliders; i++)
{
int level;
if (eq != null)
level = eq.getBandLevel ((short)i);
else
level = 0;
int pos = 100 * level / (max_level - min_level) + 50;
sliders[i].setProgress (pos);
}
}
/*=============================================================================
updateBassBoost
=============================================================================*/
public void updateBassBoost ()
{
if (bb != null)
bass_boost.setProgress (bb.getRoundedStrength());
else
bass_boost.setProgress (0);
}
/*=============================================================================
onCheckedChange
=============================================================================*/
#Override
public void onCheckedChanged (CompoundButton view, boolean isChecked)
{
if (view == (View) enabled)
{
eq.setEnabled (isChecked);
}
}
/*=============================================================================
onClick
=============================================================================*/
#Override
public void onClick (View view)
{
if (view == (View) flat)
{
setFlat();
}
if (view == (View) Button1)
{
Intent myIntent = new Intent(MainActivity.this, Guide.class);
MainActivity.this.startActivity(myIntent);
}
}
/*=============================================================================
updateUI
=============================================================================*/
public void updateUI ()
{
updateSliders();
updateBassBoost();
enabled.setChecked (eq.getEnabled());
}
/*=============================================================================
setFlat
=============================================================================*/
public void setFlat ()
{
if (eq != null)
{
for (int i = 0; i < num_sliders; i++)
{
eq.setBandLevel ((short)i, (short)0);
}
}
if (bb != null)
{
bb.setEnabled (false);
bb.setStrength ((short)0);
}
updateUI();
}
/*=============================================================================
showAbout
=============================================================================*/
public void showAbout ()
{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("About Simple EQ");
alertDialogBuilder.setMessage(R.string.copyright_message);
alertDialogBuilder.setCancelable(true);
alertDialogBuilder.setPositiveButton (R.string.ok,
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
}
});
AlertDialog ad = alertDialogBuilder.create();
ad.show();
}
/*=============================================================================
onOptionsItemSelected
=============================================================================*/
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.about:
showAbout();
return true;
}
return super.onOptionsItemSelected(item);
}
}

Achartengine's piechart does not refresh from repaint function

I'm building an application that makes piechart from database according to precise date interval. Unfortunately the achartengine's repaint function is not working when I'm stepping with the buttons.
When the Activity starts everything is fine the chart is okay but when i'm using the buttons then nothing happens.
I hope somebody can help me.
here is the code:
private GraphicalView chartView;
...
tabHost.addTab(tabHost.newTabSpec("").setIndicator("Grafikon")
.setContent(new TabHost.TabContentFactory() {
public View createTabContent(String arg0) {
final View view = LayoutInflater.from(SumMenuActivity.this).inflate(
R.layout.summenu_tab3, null);
periodSeekBar = (SeekBar) view.findViewById(R.id.summenutab3_periodslide);
final TextView periodName = (TextView) view
.findViewById(R.id.summenutab3_periodtw);
if (chartView == null) {
LinearLayout layout = (LinearLayout) view.findViewById(R.id.chart);
intValChanger(intVal, 0);
layout.addView(chartView);
} else {
chartView.repaint();
}
periodSeekBar
.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if (progress == 0) {
periodName.setText("Heti");
} else if (progress == 1) {
periodName.setText("Havi");
} else if (progress == 2) {
periodName.setText("Eves");
}
intVal = 0;
intValChanger(intVal, progress);
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
final View minusButton = view.findViewById(R.id.summenutab3_frombutton);
final View plusButton = view.findViewById(R.id.summenutab3_tobutton);
minusButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
intVal--;
intValChanger(intVal, periodSeekBar.getProgress());
if (chartView != null) {
chartView.refreshDrawableState();
chartView.repaint();
}
}
});
plusButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
intVal++;
intValChanger(intVal, periodSeekBar.getProgress());
if (chartView != null) {
chartView.refreshDrawableState();
chartView.repaint();
}
}
});
return view;
}
...
public void intValChanger(int intVal, int type) {
Calendar start = Calendar.getInstance();
Calendar end = Calendar.getInstance();
if (type == 0) {
start.setFirstDayOfWeek(Calendar.MONDAY);
end.setFirstDayOfWeek(Calendar.MONDAY);
int currentStartOfWeek = (start.get(Calendar.DAY_OF_WEEK) + 7 - start
.getFirstDayOfWeek()) % 7;
int currentEndOfWeek = (end.get(Calendar.DAY_OF_WEEK) + 7 - end.getFirstDayOfWeek()) % 7;
start.add(Calendar.DAY_OF_YEAR, -currentStartOfWeek + intVal * 7);
end.add(Calendar.DAY_OF_YEAR, (-currentEndOfWeek + intVal * 7) + 6);
} else if (type == 1) {
start.set(Calendar.DATE, 1);
start.set(Calendar.MONTH, start.get(Calendar.MONTH) + 1 * intVal);
end.set(Calendar.DATE, start.getActualMaximum(Calendar.DATE));
end.set(Calendar.MONTH, end.get(Calendar.MONTH) + 1 * intVal);
} else if (type == 2) {
start.set(Calendar.YEAR, start.get(Calendar.YEAR) + 1 * intVal);
start.set(Calendar.MONTH, 0);
start.set(Calendar.DATE, 1);
end.set(Calendar.YEAR, end.get(Calendar.YEAR) + 1 * intVal);
end.set(Calendar.MONTH, 11);
end.set(Calendar.DATE, 31);
}
if (tabHost.getCurrentTab() == 0) {
populateTimeList(start.getTime(), end.getTime());
} else if (tabHost.getCurrentTab() == 1) {
populateSumArrayList(start.getTime(), end.getTime());
} else if (tabHost.getCurrentTab() == 2) {
populateChart(start.getTime(), end.getTime());
}
Toast.makeText(getApplicationContext(),
android.text.format.DateFormat.format("yyyy-MM-dd", start) +
"-tól " + android.text.format.DateFormat.format("yyyy-MM-dd", end)
+ "-ig", 3).show();
}
public GraphicalView executeChart(Context context, ArrayList<String> name,
ArrayList<Integer> value) {
ArrayList<Integer> colors = new ArrayList<Integer>();
CategorySeries categorySeries = new CategorySeries("Torta diagram");
for (int i = 0; i < name.size(); i++) {
Random r = new Random();
categorySeries.add(name.get(i), value.get(i));
colors.add(Color.rgb(r.nextInt(256), r.nextInt(256), r.nextInt(256)));
}
DefaultRenderer renderer = buildCategoryRenderer(colors);
renderer.setLabelsTextSize(14);
GraphicalView gview = ChartFactory.getPieChartView(context,
categorySeries, renderer);
return gview;
}
protected DefaultRenderer buildCategoryRenderer(ArrayList<Integer> colors) {
DefaultRenderer renderer = new DefaultRenderer();
for (int color : colors) {
SimpleSeriesRenderer r = new SimpleSeriesRenderer();
r.setColor(color);
renderer.addSeriesRenderer(r);
}
return renderer;
}
public void populateChart(Date from, Date to) {
ArrayList<String> tmpName = new ArrayList<String>();
ArrayList<Integer> tmpValue = new ArrayList<Integer>();
ArrayList<Category> tmpCategory = getCategories();
ArrayList<Transaction> tmpTransaction = new ArrayList<Transaction>();
for (int i = 0; i < tmpCategory.size(); i++) {
tmpName.add(tmpCategory.get(i).getName());
tmpTransaction = (ArrayList<Transaction>) getTransactionsByTimeIntvalAndId(from, to,
tmpCategory.get(i).getId());
int ammount = 0;
for (int j = 0; j < tmpTransaction.size(); j++) {
ammount += tmpTransaction.get(j).getAmmount();
}
tmpValue.add(ammount);
}
for (int i = 0; i < tmpName.size(); i++) {
Log.d("DEBUG MESSAGE", tmpName.get(i) + ": " + tmpValue.get(i));
}
chartView = null;
chartView = executeChart(SumMenuActivity.this, tmpName, tmpValue);
Log.d("DEBUG MESSAGE", "megtörtént a repaint!" + chartView);
}
I have not used Achart but this is a simple pie chart implementation. You can refer the demo and it might help.
In this demo after you update the values, you need to call invalidate() to redraw the pie chart.
https://github.com/blessenm/PieChartDemo

Categories