Infinite Scroll is loading the same last value always - java

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?

Related

Issue :- Two click counters interacting with each other

I have 5 buttons and 2 menu button:
First list
back,
random,
next
Second list
copy,
share,
first quote,
latest quote
The menu buttons are the first quote and the latest quote
In the first list of buttons, I have added a counter of 10, which means after 10 clicks the interstitial ad should be shown.
In the second list of buttons, I have added a counter of 3, which means after 3 clicks the interstitial ad should be shown.
Now the problem comes when the first button counter reach 9 (means after one click it should shows the ad) and I press any button from 2) -> ad is showing
MainActivity.java
int triggerClicks = 3; // for copy,share,firstquote & latestquote
int countClicks = 0;
int triggerClicksNav = 10;// for back,next & random
#SuppressLint("SetTextI18n")
private void latestQuote() {
countClicks++;
if (countClicks != 3) {
position = quotes_list.size() - 1;
quotesTxt.setText(quotes_list.get(position));
countTxt.setText(position + "/" + quotes_list.size());
Log.d(TAG, quotes_list.toString());
}
if (mInterstitialAd != null && countClicks >= triggerClicks) {
mInterstitialAd.show(HomeActivity.this);
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
#Override
public void onAdDismissedFullScreenContent() {
super.onAdDismissedFullScreenContent();
mInterstitialAd = null;
intertitalAd();
position = quotes_list.size() - 1;
quotesTxt.setText(quotes_list.get(position));
countTxt.setText(position + "/" + quotes_list.size());
Log.d(TAG, quotes_list.toString());
countClicks = 0;
}
});
}
}
#SuppressLint("SetTextI18n")
private void firstQuote() {
countClicks++;
if (countClicks != 3) {
position = 0;
quotesTxt.setText(quotes_list.get(position));
countTxt.setText(position + "/" + quotes_list.size());
Log.d(TAG, quotes_list.toString());
}
if (mInterstitialAd != null && countClicks >= triggerClicks) {
mInterstitialAd.show(HomeActivity.this);
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
#Override
public void onAdDismissedFullScreenContent() {
super.onAdDismissedFullScreenContent();
mInterstitialAd = null;
intertitalAd();
position = 0;
quotesTxt.setText(quotes_list.get(position));
countTxt.setText(position + "/" + quotes_list.size());
countClicks = 0;
}
});
}
}
#SuppressLint("SetTextI18n")
private void back() {
countClicks++;
if (position > 0) {
position = (position - 1) % quotes_list.size();
quotesTxt.setText(quotes_list.get(position));
countTxt.setText(position + "/" + quotes_list.size());
Log.d(TAG, quotes_list.toString());
}
if (mInterstitialAd != null && countClicks >= triggerClicksNav) {
mInterstitialAd.show(HomeActivity.this);
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
#Override
public void onAdDismissedFullScreenContent() {
super.onAdDismissedFullScreenContent();
mInterstitialAd = null;
intertitalAd();
countClicks = 0;
}
});
}
}
#SuppressLint("SetTextI18n")
private void next() {
countClicks++;
position = (position + 1) % quotes_list.size();
quotesTxt.setText(quotes_list.get(position));
countTxt.setText(position + "/" + quotes_list.size());
if (mInterstitialAd != null && countClicks >= triggerClicksNav) {
mInterstitialAd.show(HomeActivity.this);
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
#Override
public void onAdDismissedFullScreenContent() {
super.onAdDismissedFullScreenContent();
mInterstitialAd = null;
intertitalAd();
countClicks = 0;
}
});
}
}
#SuppressLint("SetTextI18n")
private void random() {
countClicks++;
position = randomQ.nextInt(quotes_list.size());
quotesTxt.setText(quotes_list.get(position));
countTxt.setText(position + "/" + quotes_list.size());
if (mInterstitialAd != null && countClicks >= triggerClicksNav) {
mInterstitialAd.show(HomeActivity.this);
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
#Override
public void onAdDismissedFullScreenContent() {
super.onAdDismissedFullScreenContent();
mInterstitialAd = null;
intertitalAd();
countClicks = 0;
}
});
}
}
private void copy() {
countClicks++;
ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clipData = ClipData.newPlainText("text", quotesTxt.getText());
if (clipboardManager != null) {
clipboardManager.setPrimaryClip(clipData);
}
Toast.makeText(getApplicationContext(), "Copied", Toast.LENGTH_SHORT).show();
if (mInterstitialAd != null && countClicks >= triggerClicks) {
mInterstitialAd.show(HomeActivity.this);
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
#Override
public void onAdDismissedFullScreenContent() {
super.onAdDismissedFullScreenContent();
mInterstitialAd = null;
intertitalAd();
countClicks = 0;
}
});
}
}
private void share() {
countClicks++;
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, quotesTxt.getText());
startActivity(Intent.createChooser(intent, "Share to"));
if (mInterstitialAd != null && countClicks >= triggerClicks) {
mInterstitialAd.show(HomeActivity.this);
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
#Override
public void onAdDismissedFullScreenContent() {
super.onAdDismissedFullScreenContent();
mInterstitialAd = null;
intertitalAd();
countClicks = 0;
}
});
}
}
The problem get solved if I assign a different counter for every buttons but I don't like this solution, please if u have another solution please add it
int countClicksBack = 0;
int countClicksRandom = 0;
int countClicksNext = 0;
int countClicksCopy = 0;
int countClicksShare = 0;
int countClicksFirst = 0;
int countClicksLatest = 0;
The problem is that you're using the same counter to display your ad but, If I've understood, you want 2 different counter : one for buttons and one for menus. Right ? So, you have to declare 2 different counters.
By the way, your code is not "clean": the code used to display your ad can be exported in a own method, something like that:
private void showAd() {
mInterstitialAd.show(HomeActivity.this);
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
#Override
public void onAdDismissedFullScreenContent() {
super.onAdDismissedFullScreenContent();
mInterstitialAd = null;
intertitalAd();
countClicks = 0;
}
});
}
private void back() {
// your stuff
if (mInterstitialAd != null && countClicks >= triggerClicksNav) {
showAd();
}
}

How to make logic for n input in tictactoe game

i made the tictactoe game using dynamic layout and applied with logic of 3*3 matrix,if i enter 3 in input so it will make 3*3 matrix, if i will enter 4 in input so it will create 4*4 matrix,i have already make the logic for 3*3 matrix so now i want to make logic for tictactoe which can be applicable for all input.
public class Main2Activity extends AppCompatActivity implements View.OnClickListener {
GridLayout gridLayout;
LinearLayout linear;
FrameLayout frameLayout;
ArrayList<Button> buttons = new ArrayList<>();
Boolean player1 = true;
int turn, n;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.res, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int i1 = item.getItemId();
if (i1 == R.id.reset) {
resetBoard();
Toast.makeText(this, "game reset", Toast.LENGTH_SHORT).show();
} else if (i1 == R.id.newgame) {
resetgame();
Toast.makeText(this, "new game", Toast.LENGTH_SHORT).show();
} else if (i1 == R.id.homebtn) {
Intent i = new Intent(this, MainActivity.class);
startActivity(i);
finish();
}
return super.onOptionsItemSelected(item);
}
private void resetgame() {
resetBoard();
;
}
private void resetBoard() {
for (int i = 0; i < n * n; i++) {
buttons.get(i).setText("");
turn = 0;
player1 = true;
buttons.get(i).setEnabled(true);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
gridLayout = findViewById(R.id.grid);
frameLayout = findViewById(R.id.linearlayout);
linear = findViewById(R.id.linear);
Intent intent = getIntent();
String s = intent.getStringExtra("str");
n = parseInt(s);
linear.setGravity(Gravity.CENTER);
linear.setGravity(LinearLayout.HORIZONTAL);
gridLayout.setOrientation(GridLayout.VERTICAL);
for (int i = 0; i < n * n; i++) {
Button buttonView = new Button(this);
buttonView.setId(i);
buttonView.setOnClickListener(this);
gridLayout.setColumnCount(n);
gridLayout.setRowCount(n);
gridLayout.addView(buttonView);
buttons.add(buttonView);
}
}
#Override
public void onClick(View view) {
if (!((Button) view).getText().toString().equals("")) {
return;
}
if (player1) {
((Button) view).setText("X");
} else {
((Button) view).setText("O");
}
turn++;
if (checkforwin(view)) {
if (player1) {
player1win();
} else {
player2win();
}
} else if (turn == n * n) {
draw();
} else {
player1 = !player1;
}
}
private void player1win() {
Toast.makeText(this, "player 1 win", Toast.LENGTH_SHORT).show();
for (int i = 0; i < n * n; i++) {
if (buttons.get(i).getVisibility() == View.VISIBLE) {
buttons.get(i).setEnabled(false);
}
}
}
private void player2win() {
Toast.makeText(this, "player 2 win", Toast.LENGTH_SHORT).show();
for (int i = 0; i < n * n; i++) {
if (buttons.get(i).getVisibility() == View.VISIBLE) {
buttons.get(i).setEnabled(false);
}
}
}
private void draw() {
Toast.makeText(this, "draw", Toast.LENGTH_SHORT).show();
for (int i = 0; i < n * n; i++) {
if (buttons.get(i).getVisibility() == View.VISIBLE) {
buttons.get(i).setEnabled(false);
}
}
}
private boolean checkforwin(View view)
{
for (int i = 0; i<n; i++)
{
if (buttons.get(i).getText().toString().equals("X") && buttons.get(i + 3).getText().toString().equals("X") && buttons.get(i + 6).getText().toString().equals("X") ||
buttons.get(i).getText().toString().equals("O") && buttons.get(i + 3).getText().toString().equals("O") && buttons.get(i + 6).getText().toString().equals("O"))
{
return true;
}
}
for (int i=0;i<n*n;i=i+3)
{
if (buttons.get(i).getText().toString().equals("X") && buttons.get(i + 1).getText().toString().equals("X") && buttons.get(i + 2).getText().toString().equals("X") ||
buttons.get(i).getText().toString().equals("O") && buttons.get(i + 1).getText().toString().equals("O") && buttons.get(i + 2).getText().toString().equals("O"))
{
return true;
}
}
for (int i = 2; i<n; i++)
{
if (buttons.get(i).getText().toString().equals("X") && buttons.get(i + 2).getText().toString().equals("X") && buttons.get(i + 4).getText().toString().equals("X") ||
buttons.get(i).getText().toString().equals("O") && buttons.get(i + 2).getText().toString().equals("O") && buttons.get(i + 4).getText().toString().equals("O"))
{
return true;
}
}
for(int i = 0; i<n-2; i++)
{
if (buttons.get(i).getText().toString().equals("X") && buttons.get(i + 4).getText().toString().equals("X") && buttons.get(i + 8).getText().toString().equals("X") ||
buttons.get(i).getText().toString().equals("O") && buttons.get(i + 4).getText().toString().equals("O") && buttons.get(i + 8).getText().toString().equals("O"))
{
return true;
}
}
return false;
}
}
there is no error for 3*3 matrix,but i want to make dynamic logic which is applicable for all input.

Error notifyDataSetChanged() in RecyclerView when its scroll to last position

I am using RecyclerView to display the list of rows, each row has a buy button. when the user buys an element, the method notifydatasetchanged() is called and the buy button has to change the background color for example to red.
Important, The user have to buys only one element, and I have a thread that runs every 5 seconds looking for new answers, if there is a new answer, it is added to the list and scroll to last position.
My problem is when I have the list of buttons and only one is red and I have a new answer, I add it to the list but the button of some rows change to red.
this is my code:
private void responses() {
fin_thread = true;
thread = new Thread() {
#Override
public void run() {
while (fin_thread) {
try {
Thread.sleep(5000);
runOnUiThread(new Runnable() {
#Override
public void run() {
JsonObjectRequest service_call = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener < JSONObject > () {
#Override
public void onResponse(JSONObject response) {
try {
boolean status = response.getBoolean("value_status_response");
if (status) {
if (response.getInt("counter") > 0 && obj_response.size() > 0) {
JSONArray answer = response.getJSONArray("answer");
if (answer.length() != obj_response.size()) {
for (int i = 0; i < answer.length(); i++) {
boolean coincidence = false;;
JSONObject item = answer.getJSONObject(i);
for (int j = 0; j < obj_response.size(); j++) {
if (item.getId("id") == obj_response.get(j).getId()) {
coincidence = true;
break;
}
}
if (!coincidence) {
CResponse cr = new CResponse();
cr.setName(item.getString("name"));
cr.setPrice(item.getString("price"));
cr.setId(item.getInt("id"));
cr.setState(item.getInt("state"));
obj_response.add(cr);
sectionAdapter.notifyDataSetChanged();
scroll_to_last();
}
}
}
} else {
if (response.getInt("counter") > 0 && obj_response.size() == 0) {
JSONArray answer = response.getJSONArray("answer");
for (int i = 0; i < answer.length(); i++) {
JSONObject item = answer.getJSONObject(i);
CResponse cr = new CResponse();
cr.setName(item.getString("name"));
cr.setPrice(item.getString("price"));
cr.setId(item.getInt("id"));
cr.setState(item.getInt("state"));
obj_response.add(cr);
sectionAdapter.notifyDataSetChanged();
rv.setVisibility(View.VISIBLE);
progress_bar.setVisibility(View.GONE);
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
if (networkResponse != null) {
//ERROR
}
}
}
) {
#Override
public Map < String, String > getHeaders() throws AuthFailureError {
Map < String, String > params = new HashMap < String, String > ();
params.put("Authorization", "Basic " + auth);
return params;
}
};
Helpers.queue(Class.this).add(service_call);
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
thread.start();
}
private void scroll_to_last() {
lm.scrollToPosition(sectionAdapter.getItemCount() - 1);
}
My Adapter
#Override
public void onBindItemViewHolder(RecyclerView.ViewHolder holder, final int position) {
final MyViewPedidoDesc itemHolder = (MyViewPedidoDesc) holder;
control_btn_background(itemHolder, position);
}
private void control_btn_background(MyViewPedidoDesc itemHolder, int position) {
if (mData.get(position).getState() == 1) {
itemHolder.buy_btn.setBackgroundResource(R.drawable.red);
} else {
itemHolder.buy_btn.setBackgroundResource(R.drawable.blue);
}
}
I think the error appears is when I call scroll_to_last() method because if I don't call that the background color is only in one button.
Thanks in advace

Using Multiple Chronometers in one Activity

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.

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