I am trying to use multiple chronometers in one activity but the behavior of each of them is not as expected.
I've expected that I would be able to start each timer simultaneously and I have declared different functions for each and different variables.
Activity Screenshot
Code
timeWhenStoppedSetup = 0;
timeWhenStoppedProcessing = 0;
timeWhenStoppedReconciliation = 0;
timeWhenStoppedCleaning = 0;
chronometerSetUp.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
#Override
public void onChronometerTick(Chronometer chronometerChanged) {
chronometerSetUp = chronometerChanged;
long time = SystemClock.elapsedRealtime() - chronometerSetUp.getBase();
int h = (int)(time /3600000);
int m = (int)(time - h*3600000)/60000;
int s= (int)(time - h*3600000- m*60000)/1000 ;
String t = (h < 10 ? "0"+h: h)+":"+(m < 10 ? "0"+m: m)+":"+ (s < 10 ? "0"+s: s);
chronometerSetUp.setText(t);
}
});
startSetUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startStopChronometerSetUp(startSetUp);
}
});
chronometerProcessing.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
#Override
public void onChronometerTick(Chronometer chronometerChanged) {
chronometerProcessing = chronometerChanged;
long time = SystemClock.elapsedRealtime() - chronometerProcessing.getBase();
int h = (int)(time /3600000);
int m = (int)(time - h*3600000)/60000;
int s= (int)(time - h*3600000- m*60000)/1000 ;
String t = (h < 10 ? "0"+h: h)+":"+(m < 10 ? "0"+m: m)+":"+ (s < 10 ? "0"+s: s);
chronometerProcessing.setText(t);
}
});
startProcessing.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startStopChronometerProcessing(startProcessing);
}
});
chronometerReconciliation.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
#Override
public void onChronometerTick(Chronometer chronometerChanged) {
chronometerReconciliation = chronometerChanged;
long time = SystemClock.elapsedRealtime() - chronometerReconciliation.getBase();
int h = (int)(time /3600000);
int m = (int)(time - h*3600000)/60000;
int s= (int)(time - h*3600000- m*60000)/1000 ;
String t = (h < 10 ? "0"+h: h)+":"+(m < 10 ? "0"+m: m)+":"+ (s < 10 ? "0"+s: s);
chronometerReconciliation.setText(t);
}
});
startReconciliation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startStopChronometerReconciliation(startReconciliation);
}
});
chronometerCleaning.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
#Override
public void onChronometerTick(Chronometer chronometerChanged) {
chronometerCleaning = chronometerChanged;
long time = SystemClock.elapsedRealtime() - chronometerCleaning.getBase();
int h = (int)(time /3600000);
int m = (int)(time - h*3600000)/60000;
int s= (int)(time - h*3600000- m*60000)/1000 ;
String t = (h < 10 ? "0"+h: h)+":"+(m < 10 ? "0"+m: m)+":"+ (s < 10 ? "0"+s: s);
chronometerCleaning.setText(t);
}
});
startCleaning.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startStopChronometerCleaning(startCleaning);
}
});
}
public void startStopChronometerSetUp(View view){
if(isStart){
chronometerSetUp.stop();
timeWhenStoppedSetup = chronometerSetUp.getBase() - SystemClock.elapsedRealtime();
isStart = false;
}else{
chronometerSetUp.setBase(SystemClock.elapsedRealtime() + timeWhenStoppedSetup);
chronometerSetUp.start();
isStart = true;
((Button)view).setBackgroundResource(stop);
}
}
public void startStopChronometerProcessing(View view){
if(isStart){
chronometerProcessing.stop();
timeWhenStoppedProcessing = chronometerProcessing.getBase() - SystemClock.elapsedRealtime();
isStart = false;
}else{
chronometerProcessing.setBase(SystemClock.elapsedRealtime() + timeWhenStoppedProcessing);
chronometerProcessing.start();
isStart = true;
((Button)view).setBackgroundResource(stop);
}
}
public void startStopChronometerReconciliation(View view){
if(isStart){
chronometerReconciliation.stop();
timeWhenStoppedReconciliation = chronometerReconciliation.getBase() - SystemClock.elapsedRealtime();
isStart = false;
}else{
chronometerReconciliation.setBase(SystemClock.elapsedRealtime() + timeWhenStoppedReconciliation);
chronometerReconciliation.start();
isStart = true;
((Button)view).setBackgroundResource(stop);
}
}
public void startStopChronometerCleaning(View view){
if(isStart){
chronometerCleaning.stop();
timeWhenStoppedCleaning = chronometerCleaning.getBase() - SystemClock.elapsedRealtime();
isStart = false;
}else{
chronometerCleaning.setBase(SystemClock.elapsedRealtime() + timeWhenStoppedCleaning);
chronometerCleaning.start();
isStart = true;
((Button)view).setBackgroundResource(stop);
}
}
Am I doing something wrong here or is this even possible?
The behavior of the other chronometers would be, to describe it, just random. Can start at random times etc.
Related
I managed to retrieve the data from firebase, implementing an infinite scroll... is working right but when i scroll till end, is loading the same last values always..
Tried to change the .limitToLast to .startAt but there is no difference.
private void isScrollCompleted() {
if (totalItem - currentFirstVisibleItem == currentVisibleItemCount
&& this.currentScrollState == SCROLL_STATE_IDLE) {
/** To do code here*/
oldestPostId = oldDummy;
Query query = SearchRef.orderByKey();
if (oldestPostId != null) {
query = query.limitToLast(limitToLast).endAt(oldestPostId);
}
dataList.clear();
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Query ordenar = mDatabase.child("Off-Topic").orderByChild("countthreads");
for (DataSnapshot child : dataSnapshot.getChildren()) {
MessageThread messageThread = child.getValue(MessageThread.class);
if (messageThread != null) {
oldestPostId = child.getKey();
oldestPostidScrollList.add(child.getKey());
if (oldestPostidScrollList.size() > m) {
String myIdss = oldestPostidScrollList.get(m);
oldDummy = myIdss;
}
messageThread.thread_id = child.getKey();
}
dataList.add(messageThread);
if (dataList.size() == 5) {
Collections.reverse(dataList);
for (int j = 0; j < dataList.size(); j++) {
threadsList.add(dataList.get(j));
}
threadsAdapter = new ThreadsAdapter(ThreadsActivity.this, R.layout.threads_listview,
threadsList, tryList, ThreadsActivity.this, ordenar);
progressBar.setVisibility(View.VISIBLE);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
progressBar.setVisibility(View.GONE);
}
}, 1000);
threadsListView.setSelection(scrollTO);
} else {
if (lastValueCalled) {
lastValueCalled = true;
for (int j = 0; j < dataList.size(); j++) {
threadsList.add(dataList.get(j));
}
scrollMyListViewToBottom();
}
}
}
scrollTO = scrollTO + 10;
int x = tryList.size();
int temp = x - m;
int count = temp - 10;
if (count > 10 && temp > 10) {
m = m + 10;
} else if (nCalled) {
Log.e("called", "data is over");
} else {
lastValueCalled = true;
if (lastValueCalled) {
nCalled = true;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Also checked the log and is giving the result "data is over" but continues doing the same thing always. Any clue?
public class MainActivity extends AppCompatActivity {
int foulCounterA = 0;
int scoreOnePointTeamA = 0;
int periodCount = 0;
private TextView tv1;
private TextView period;
private Button startbtn, cancelbtn;
private ToggleButton togbtn;
private boolean isPaused = false;
private boolean isCanceled = false;
private long remainingTime = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = (TextView) findViewById(R.id.tv1);
period = (TextView) findViewById(R.id.period_number);
startbtn = (Button) findViewById(R.id.startBtn);
cancelbtn = (Button) findViewById(R.id.cancelBtn);
togbtn = (ToggleButton) findViewById(R.id.togBtn);
cancelbtn.setEnabled(false);
togbtn.setEnabled(false);
startbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
foulCounterA = 0;
foulCounterB = 0;
displayForTeamAFoul(foulCounterA);
displayForTeamBFoul(foulCounterB);
if (periodCount < 3)
periodCount = periodCount + 1;
else periodCount = 4;
period.setText("Period " + periodCount);
startbtn.setEnabled(false);
cancelbtn.setEnabled(true);
togbtn.setEnabled(true);
isPaused = false;
isCanceled = false;
long millisInFuture = 20000; /////20sec
long countDownInterval = 1000; /////1sec
new CountDownTimer(millisInFuture, countDownInterval) {
#Override
public void onTick(long millisUntilFinished) {
if (isPaused || isCanceled) {
cancel();
} else {
tv1.setText("" + millisUntilFinished / 1000);
remainingTime = millisUntilFinished;
}
}
#Override
public void onFinish() {
startbtn.setEnabled(true);
togbtn.setEnabled(false);
if (periodCount < 4)
tv1.setText("Times up!");
else tv1.setText("Game Over!");
}
}.start();
}
});
togbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (togbtn.isChecked()) {
isPaused = true;
} else {
isPaused = false;
long millisInFuture = remainingTime;
long countDownInterval = 1000; /////1sec
new CountDownTimer(millisInFuture, countDownInterval) {
#Override
public void onTick(long millisUntilFinished) {
if (isPaused || isCanceled) {
cancel();
} else {
tv1.setText("" + millisUntilFinished / 1000);
remainingTime = millisUntilFinished;
}
}
#Override
public void onFinish() {
startbtn.setEnabled(true);
togbtn.setEnabled(false);
if (periodCount < 4)
tv1.setText("Times up!");
else tv1.setText("Game Over!");
}
}.start();
}
}
});
cancelbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
isCanceled = true;
period.setText("Period");
tv1.setText("Timer");
startbtn.setEnabled(true);
togbtn.setEnabled(false);
cancelbtn.setEnabled(false);
foulCounterA = 0;
foulCounterB = 0;
periodCount = 0;
displayForTeamAFoul(foulCounterA);
displayForTeamBFoul(foulCounterB);
}
});
}
public void onePointForTeamA(View v) {
scoreTeamA = scoreTeamA + 1;
scoreOnePointTeamA = scoreOnePointTeamA + 1;
displayForTeamA(scoreTeamA);
displayForTeamAOnePoint(scoreOnePointTeamA);
}
public void foulCountForTeamA(View v) {
if (foulCounterA < 5)
foulCounterA = foulCounterA + 1;
else
foulCounterA = 5;
displayForTeamAFoul(foulCounterA);
}
public void displayForTeamAOnePoint(int score) {
TextView scoreView = (TextView) findViewById(R.id.team_a_score_1_point);
scoreView.setText(String.valueOf(score));
}
public void displayForTeamAFoul(int score) {
TextView scoreView = (TextView) findViewById(R.id.team_a_foul);
scoreView.setText(String.valueOf(score));
}
}
I wanted to make the java code as simple as I can so I've just added the lines for my question. What I'm trying to do is
android:onClick="onePointForTeamA"make this button only clickable when foulCounterA = 5 Failed to add if (foulCounterA = 5); inside public void foulCountForTeamA(View v) {
It gave me an error that way. Says required: boolean, found: int.
What should I do with the code? Any help will be appreeciated
Regarding your concrete question, the syntax of if (foulCounterA = 5); is wrong, because the equation check is have to made by == operator.
So the correct syntax would be if (foulCounterA == 5);
As #OH GOD SPIDERS wrote in the comment, you should check the basics of java operators.
Also I recommend You to search for the answer before asking a new question.
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();
}
}
}
After each trivia game is over, the Results page displays. After about 20 seconds, which is how long each question gives you during the game before your time runs out and it goes to the next question, the Results page reloads. Then when you go to the Highscores page, the score has been entered twice. So something is screwed up in my QuestionView class below but I cannot find the bug.
If any further information is needed let me know. Thank you in advanced!
Results.java
total_score = dh.calculateTotalScore(score, percentage);
if(dh.getLowest() == -1) {
dh.insert(score, percentage, total_score, category);
} else {
dh.delete(dh.getLowest());
dh.insert(score, percentage, total_score, category);
}
DatabaseHelper.java
public long insert(long score, int percentage, long total_score, String category) {
ContentValues values = new ContentValues();
values.put(SCORE, score);
values.put(PERCENTAGE, percentage);
values.put(TOTAL_SCORE, total_score);
values.put(CATEGORY, category);
return db.insert(TABLE, null, values);
}
public void delete(long lowScore) {
lowScore = getLowest();
db.delete(TABLE, TOTAL_SCORE + "=" + lowScore, null);
}
public long getLowest() {
Cursor c = db.rawQuery("SELECT * FROM " + TABLE + " ORDER BY " + TOTAL_SCORE, null);
long count = c.getCount();
long lowScore = -1;
if(count == 10) {
c.moveToLast();
lowScore = c.getInt(c.getColumnIndex(TOTAL_SCORE));
}
return lowScore;
}
public long calculateTotalScore(long score, int percentage) {
long i;
return i = (percentage * 1000) + score;
}
QuestionView.java
public class QuestionView extends Activity {
int correctAnswers = 0;
int wrongAnswers = 0;
int answer = 0;
int i = 0;
long score = 0;
long startTime = 20000;
long interval = 1000;
long points;
boolean timerHasStarted = false;
String category;
Button answer1, answer2, answer3, answer4;
TextView question, pointCounter, questionNumber, timeCounter;
ArrayList<Question> queries;
Timer cdTimer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.questionviewmain);
answer1 = (Button)findViewById(R.id.answer1);
answer2 = (Button)findViewById(R.id.answer2);
answer3 = (Button)findViewById(R.id.answer3);
answer4 = (Button)findViewById(R.id.answer4);
question = (TextView)findViewById(R.id.question);
category = getIntent().getStringExtra("category");
queries = getIntent().getParcelableArrayListExtra("queries");
pointCounter = (TextView)findViewById(R.id.timer);
questionNumber = (TextView)findViewById(R.id.timeElapsedView);
timeCounter = (TextView)findViewById(R.id.timeCounter);
cdTimer = new Timer(startTime, interval);
loadQuestion();
}
public void loadQuestion() {
if(i == 10) {
endQuiz();
} else {
if(!timerHasStarted) {
cdTimer.start();
timerHasStarted = true;
} else {
cdTimer.start();
timerHasStarted = false;
}
answer = queries.get(i).getCorrectAnswer();
question.setText(queries.get(i).getQuery());
answer1.setText(queries.get(i).getA1());
answer2.setText(queries.get(i).getA2());
answer3.setText(queries.get(i).getA3());
answer4.setText(queries.get(i).getA4());
answer1.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
queries.get(i).setSelectedAnswer(0);
if(answer == 0) {
correctAnswers++;
nextQuestion();
} else {
wrongAnswers++;
nextQuestion();
}
}
});
answer2.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
queries.get(i).setSelectedAnswer(1);
if(answer == 1) {
correctAnswers++;
nextQuestion();
} else {
wrongAnswers++;
nextQuestion();
}
}
});
answer3.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
queries.get(i).setSelectedAnswer(2);
if(answer == 2) {
correctAnswers++;
nextQuestion();
} else {
wrongAnswers++;
nextQuestion();
}
}
});
answer4.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
queries.get(i).setSelectedAnswer(3);
if(answer == 3) {
correctAnswers++;
nextQuestion();
} else {
wrongAnswers++;
nextQuestion();
}
}
});
}
}
public ArrayList<Question> getQueries() {
return queries;
}
public void nextQuestion() {
score = score + points;
i++;
loadQuestion();
}
public class Timer extends CountDownTimer {
public Timer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
if(i >= 9) {
cdTimer.cancel();
endQuiz();
} else {
wrongAnswers++;
nextQuestion();
}
}
#Override
public void onTick(long millisUntilFinished) {
timeCounter.setText("Time remaining: " + (millisUntilFinished / 100));
points = (millisUntilFinished / 100) / 2;
pointCounter.setText("Points remaining: " + points);
if(i < 10) {
questionNumber.setText("Question " + (i + 1) + " of 10");
}
}
}
public void endQuiz() {
Intent intent = new Intent(QuestionView.this, Results.class);
intent.putExtra("correctAnswers", correctAnswers);
intent.putExtra("wrongAnswers", wrongAnswers);
intent.putExtra("score", score);
intent.putParcelableArrayListExtra("queries", queries);
intent.putExtra("category", category);
startActivity(intent);
}
}
THE FIX:
Changed:
if(i == 10) {
endQuiz();
}
...to this:
if(i == 10) {
cdTimer.cancel();
endQuiz();
}**
Probably endQuiz gets called twice. And only when you answer the last question before the timer is up.
Because, I don't see you canceling the timer when you answer the last question. So, even though you answered already, the timer is still ticking, and when it is up, it will call endQuiz.
If you don't answer the last question and let the time run out, then the result will be inserted only once, because endQuiz will be called only once, from the timer.
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