onClick listener not responding - android

I was making a project for my class. It's like whac a mole game. I have 9 imageView's in this. As you click on them, they will change to a predefined image of empty hole, if not, the handler will change it back to normal and you will loose a life. But for one picture, if it appears and you click on it, you loose a life. Right now I have fixed the image to be the later one. If I click on them very fast, the textView which shows lives, never gets updated to game over, and tasks continue, but if I click slowly, it gets updated to game over. I tried debugging and found out that when I have clicked on them very quickly, the code never goes to onClick listener.
Here is the code:
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import Hole;
public class MainActivity extends Activity {
final Activity mainActivityObject = this;
final int MIN_TYPES_OF_MOLES = 0;
final int TYPES_OF_MOLES_INC_INT = 1;
final int MAX_MOLE_LIFE_TIME = 3000;
final int LIFE_TIME_DECREASE_INT = 150;
final int MAX_MOLE_APPEARANCE_INT = 1000;
final int APPEARANCE_TIME_DECREASE_INT = 60;
final int SPEED_UP_TIME_INT = 20000;
final int BOMB_MOLE_ID = 3;
final int MIN_DIFFICULTY_LEVEL = 1;
private Toast toast;
final Handler handler = new Handler();
Runnable moleAliveChecker;
Runnable speedUp;
TextView lives;
TextView tView;
//private ImageView[] holeImage = new ImageView[9];
private Hole[] hole = new Hole[9];
private int totalScore = 0;
private int active = 0;
private int numberOfLives = 3;
private int appearanceInterval = MAX_MOLE_APPEARANCE_INT;
private int moleLifeTime = MAX_MOLE_LIFE_TIME;
private int typesOfMoles = MIN_TYPES_OF_MOLES;
private int speedUpTime = SPEED_UP_TIME_INT;
private int difficultyLevel = MIN_DIFFICULTY_LEVEL;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);// hide the title
setContentView(R.layout.activity_main);
tView = (TextView) findViewById(R.id.time_left);
lives = (TextView) findViewById(R.id.lives_left);
toast = Toast.makeText(getApplicationContext(), "", Toast.LENGTH_LONG);
//set images and listener for each hole, ends game if lives < 1
for(int counter=0;counter<9;counter++)
{
int resID=getResources().getIdentifier("hole"+(counter+1),"id",getPackageName());
hole[counter] = new Hole((ImageView)findViewById(resID), this);
final int i=counter;//inside the onClickListener, index number has to be final
hole[counter].getImage().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ImageView image = hole[i].getImage();
switch ((Integer) image.getTag()) {
case R.drawable.hole:
break;
default:
if (numberOfLives < 1) {
handler.removeCallbacks(speedUp);
lives.setText("GAME OVER!!");
}
else if (hole[i].getMole().ishit()) {
changeScoreAndLives(hole[i], i);
}
break;
}
}
});
}
// gives a time delay of 3 seconds before beginning the game and updates text view
// tView every 1 second and when time approaches 0, it starts the game
final Runnable r = new Runnable() {
int t = 3;
public void run() {
if (t > 0) {
tView.setText("Game begins in : " + t-- + " Seconds");
handler.postDelayed(this, 1000);
}
else if (t == 0)
{
t--;
tView.setText("Begin!!");
handler.postDelayed(this, 300);
}
else
{
if (numberOfLives >= 1) {
playGame();
handler.postDelayed(this, appearanceInterval);
}
}
}
};
handler.postDelayed(r, 1000);
// speeds up the game after a set interval (20 seconds)
speedUp = new Runnable() {
public void run() {
appearanceInterval -= APPEARANCE_TIME_DECREASE_INT;
moleLifeTime -= LIFE_TIME_DECREASE_INT;
typesOfMoles += TYPES_OF_MOLES_INC_INT;
difficultyLevel++;
if (difficultyLevel < 6 && numberOfLives >= 1) {
handler.postDelayed(this, speedUpTime);
}
toast.setText("Difficulty Level increased");
toast.show();
}
};
handler.postDelayed(speedUp, speedUpTime);
}
// end of onCreate
// not been used yet
private void resetOneStep()
{
if (difficultyLevel > MIN_DIFFICULTY_LEVEL) {
appearanceInterval += MAX_MOLE_APPEARANCE_INT;
moleLifeTime += MAX_MOLE_LIFE_TIME;
typesOfMoles -= MIN_TYPES_OF_MOLES;
difficultyLevel--;
handler.postDelayed(speedUp, speedUpTime);
}
}
// not related to the current problem as currently not being used
public void bombMoleCredit()
{
for (int count = 0; count < hole.length; count++)
if (hole[count].getMole() !=null) {
totalScore += hole[count].getMole().getPoints();
handler.removeCallbacksAndMessages(count);
hole[count].setImage(null, mainActivityObject);
}
tView.setText("Total Score: " + totalScore);
active = 0;
}
// called by onclick listener if lives > 0 to change lives, score, and image
public void changeScoreAndLives(Hole hole, int number)
{
totalScore = totalScore + hole.getMole().getPoints();
if (hole.getMole().getPoints() < 0) {
numberOfLives--;
lives.setText("Lives Left: " + numberOfLives);
}
if (hole.getMole().getID() == BOMB_MOLE_ID) {
bombMoleCredit();
return;
}
handler.removeCallbacksAndMessages(number);
hole.setImage(null, mainActivityObject);
active--;
tView.setText("Total Score: " + totalScore);
}
// called by runnable after a set interval
public void playGame()
{
if (active == 9)
return;
final int holeNumber = (int) (Math.random() * hole.length);
if (hole[holeNumber].getMole() == null && numberOfLives >= 1) {
hole[holeNumber].setMoleFromRange(4, 4, this);
active++;
// checks if the hole has been clicked or not after a few seconds, if not, player
// looses a life
moleAliveChecker = new Runnable() {
Hole holeToBeChecked = hole[holeNumber];
public void run() {
if (holeToBeChecked.getMole() != null && numberOfLives >= 1) {
if(holeToBeChecked.getMole().getID() == 4) {
holeToBeChecked.setImage(null, mainActivityObject);
active--;
return;
}
holeToBeChecked.setImage(null, mainActivityObject);
numberOfLives--;
active--;
TextView lives = (TextView) findViewById(R.id.lives_left);
lives.setText("Lives Left: " + numberOfLives);
toast.setText("OOPS!! you lost a life. Game Reset");
toast.show();
//resetOneStep();
}
}
};
handler.sendMessageDelayed(getPostMessage(moleAliveChecker, holeNumber), moleLifeTime);
}
else
playGame(); // in case the random number choses the image which has the mole
}
// to pass object as a token in postDelayed in handler, to cancel the callbacks
private final Message getPostMessage(Runnable r, Object token) {
Message m = Message.obtain(handler, r);
m.obj = token;
return m;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
All the other classes are working fine except for this one.
Other important classes:
Mole.java
import android.app.Activity;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import java.io.InputStream;
public class Mole
{
public static final int DEFAULT_ID = 0; // regular mole ID
// private methods
private JSONParser parser;
private JSONObject mole;
private int ID, timesToBeHit, timesHit, points;
private String name;
private JSONArray moles;
private boolean active;
public Mole(int ID, Activity map)
{
try {
// initialize and read json and convert each object to jsonArray
parser = new JSONParser();
// tries to set the value set by user. If fails, sets the default value
if (!setMoleByID(ID, map))
setMoleByID(DEFAULT_ID, map);
}
catch (Exception e)
{
e.printStackTrace();
}
}
// helper for constructor
private boolean setMoleByID(int ID, Activity map) throws Exception
{
InputStream is = map.getAssets().open("moles.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String json = new String(buffer, "UTF-8");
moles = (JSONArray)parser.parse(json);
// go through each object in array moles
for ( Object obj : moles)
{
// convert oobject to jsonObject
mole = (JSONObject) obj;
// if id matches it leaves the mole to be that jsonObject and exits
// the loop
if ((long)mole.get("ID") == ID)
break;
}
if ((long)mole.get("ID") != ID)
return false;
// initialize private data so that we don't have to rely on json
// anymore after this step
this.ID = (int)(long)mole.get("ID");
name = (String)mole.get("name");
timesToBeHit = (int)(long)mole.get("timesToBeHit");
timesHit = 0;
points = (int)(long)mole.get("points");
return true;
}
// get methods
public int getID() { return ID; }
public String getName() { return name; }
public int getTimesHit() { return timesHit; }
public int getTimesToBeHit() { return timesToBeHit; }
public int getPoints() { return points; }
public boolean ishit()
{
if (timesHit >= timesToBeHit - 1)
return true;
timesHit++;
return false;
}
public static int getTotalTypesOfMoles() throws Exception
{
return 5;
}
}
Hole.java
import android.app.Activity;
import android.widget.ImageView;
import com.example.phoenix.whac_a_mole03.R;
// NOT completed yet
// HOLE Class -----------------------------------------------------------------
public class Hole
{
private Mole mole;
private boolean active; // if true then mole is present
private ImageView image;
public Hole(ImageView view,final Activity map)
{
mole = null;
image = view;
setImage(mole, map);
}
// sets mole from a random value
public boolean setMoleFromRange(int minMoleID,
int maxMoleID, Activity map)
{
try {
int typesOfMoles = Mole.getTotalTypesOfMoles() - 1;
// checks for validity of data here
if (!(minMoleID >= 0 & minMoleID <= typesOfMoles))
return false;
if (!(maxMoleID >= 0 & maxMoleID <= typesOfMoles))
return false;
if (minMoleID > maxMoleID)
return false;
// chooses the random value between a range
int moleID =
(int) (Math.random() * (maxMoleID + 1 - minMoleID)) + minMoleID;
mole = new Mole(moleID, map);
setImage(mole, map);
return true;
}
catch (Exception e)
{
e.printStackTrace();
}
return false;
}
private void clear()
{
mole = null;
}
public void setImage(Mole mole, Activity map)
{
if (mole == null) {
image.setImageResource(R.drawable.hole);
image.setTag(R.drawable.hole);
clear();
return;
}
int imageID = map.getResources().getIdentifier("mole" + mole.getID() , "drawable", map.getPackageName());
image.setImageResource(imageID);
image.setTag(imageID);
this.mole = mole;
}
public boolean hit(Activity map)
{
if (!mole.ishit())
return false;
setImage(mole, map);
return true;
}
// get methods
public Mole getMole() { return mole; }
public ImageView getImage() { return image;}
// REST STUFF TO BE ADDED HERE-------------
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<TextView
android:id="#+id/time_left"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/lives_left"
android:layout_alignParentRight="true"
android:text="Lives Left: 3"
android:textAlignment="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<GridLayout
android:columnCount="3"
android:rowCount="3"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/hole1"
android:src="#drawable/hole"
android:layout_width="100dp"
android:layout_height="100dp" />
<ImageView
android:id="#+id/hole2"
android:src="#drawable/hole"
android:layout_width="100dp"
android:layout_height="100dp" />
<ImageView
android:id="#+id/hole3"
android:src="#drawable/hole"
android:layout_width="100dp"
android:layout_height="100dp" />
<ImageView
android:id="#+id/hole4"
android:src="#drawable/hole"
android:layout_width="100dp"
android:layout_height="100dp" />
<ImageView
android:id="#+id/hole5"
android:src="#drawable/hole"
android:layout_width="100dp"
android:layout_height="100dp" />
<ImageView
android:id="#+id/hole6"
android:src="#drawable/hole"
android:layout_width="100dp"
android:layout_height="100dp" />
<ImageView
android:id="#+id/hole7"
android:src="#drawable/hole"
android:layout_width="100dp"
android:layout_height="100dp" />
<ImageView
android:id="#+id/hole8"
android:src="#drawable/hole"
android:layout_width="100dp"
android:layout_height="100dp" />
<ImageView
android:id="#+id/hole9"
android:src="#drawable/hole"
android:layout_width="100dp"
android:layout_height="100dp" />
</GridLayout>
<GridLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/life1"/>
<ImageView
android:id="#+id/life2"/>
<ImageView
android:id="#+id/life3"/>
</GridLayout>
</RelativeLayout>
Any picture can be used as long as it is named mole4.png and when there is no mmole then hole.png
Thanks a lot. I will appreciate your help

Related

events not showing while using a library

I am using a library for calendar called "alamkanak weekview" and I tried to add an sqLite data base where I can add and delete the events and so i did make them the delete and adding to the data base works just fine but the showing of events is all once it shows no event after i add and once it show one but repeated the time that is the size of the elements in the table , i tried to fix this but couldn't because i lack experience in android
here's the class where i add my class that adds the events from the data base
public class BasicActivity extends BaseActivity {
public db_cal db;
public int newYear;
public int newMonth;
// public int idd = 0
// ;
private List<WeekViewEvent> getEventsForMonth(int year, int month) {
List<WeekViewEvent> tempList = new ArrayList<WeekViewEvent>();
Calendar tmpen=Calendar.getInstance();
db = new db_cal(getApplicationContext());
// Populate the week view with some events.
List<WeekViewEvent> events = new ArrayList<>();
List<events> evenement = db.getAllEvenement();
WeekViewEvent event= new WeekViewEvent();
events tmp;
for(events vent : evenement) {
Log.d("taille1", evenement.size() + "");
// tmp = vent.;
//event = new WeekViewEvent(tmp.getId(), tmp.getName(),tmp.getStart(), tmp.getEnd());
event.setId(vent.getId());
event.setName(vent.getName());
event.setStartTime(vent.getStart());
event.setEndTime(vent.getEnd());
//idd=idd+1;
Log.d("nom", vent.getName() + "");
event.setColor(getResources().getColor(randcol()));
events.add(event);
}
for (WeekViewEvent weekViewEvent : events) {
if ((weekViewEvent.getStartTime().get(Calendar.MONTH))+1 == month && weekViewEvent.getStartTime().get(Calendar.YEAR) ==
year) {
tempList.add(weekViewEvent);
}
}
return tempList;
}
public List<? extends WeekViewEvent> onMonthChange(int newYear, int newMonth) {
int month = newMonth;
return getEventsForMonth(newYear,month);// I tried to use newMonth-1 directly here but it dosen't work i don't know why but it doesn't matter
}
/* #Override
public List<? extends WeekViewEvent> onMonthChange(int newYear, int newMonth) {
this.newYear = newYear;
this.newMonth = newMonth;
/* Calendar tmpdb=Calendar.getInstance();
Calendar tmpen=Calendar.getInstance();
db = new db_cal(getApplicationContext());
// Populate the week view with some events.
List<WeekViewEvent> events = new ArrayList<>();
List<events> evenement = db.getAllEvenement();
WeekViewEvent event= new WeekViewEvent();
events tmp;
for(int i=0;i<evenement.size();i++) {
Log.d("taille1",evenement.size()+"");
tmp=evenement.get(i);
//event = new WeekViewEvent(tmp.getId(), tmp.getName(),tmp.getStart(), tmp.getEnd());
event.setId(i);
event.setName(tmp.getName());
event.setStartTime(tmp.getStart());
event.setEndTime(tmp.getEnd());
//idd=idd+1;
Log.d("nom",tmp.getName()+"");
event.setColor(getResources().getColor(randcol()));
events.add(event);
}
return events;
}*/
int randcol(){
int[]val={
R.color.event_color_01,
R.color.event_color_02,
R.color.event_color_03,
R.color.event_color_04
};
int rand=new Random().nextInt(val.length);
return val[rand];
}
/*#Override
public void onEmptyViewLongPress(Calendar time) {
}*/
}
and this is the class with the events called
package com.example.calendar;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.RectF;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.alamkanak.weekview.DateTimeInterpreter;
import com.alamkanak.weekview.MonthLoader;
import com.alamkanak.weekview.WeekView;
import com.alamkanak.weekview.WeekViewEvent;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
public abstract class BaseActivity extends AppCompatActivity implements WeekView.EventClickListener, MonthLoader.MonthChangeListener, WeekView.EventLongPressListener, WeekView.EmptyViewLongPressListener {
private static final int TYPE_DAY_VIEW = 1;
private static final int TYPE_THREE_DAY_VIEW = 2;
private static final int TYPE_WEEK_VIEW = 3;
private int mWeekViewType = TYPE_THREE_DAY_VIEW;
private WeekView mWeekView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base);
// Get a reference for the week view in the layout.
mWeekView = (WeekView) findViewById(R.id.weekView);
// Show a toast message about the touched event.
mWeekView.setOnEventClickListener(this);
// The week view has infinite scrolling horizontally. We have to provide the events of a
// month every time the month changes on the week view.
mWeekView.setMonthChangeListener(this);
// Set long press listener for events.
mWeekView.setEventLongPressListener(this);
// Set long press listener for empty view
mWeekView.setEmptyViewLongPressListener(this);
// Set up a date time interpreter to interpret how the date and time will be formatted in
// the week view. This is optional.
setupDateTimeInterpreter(false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
setupDateTimeInterpreter(id == R.id.action_week_view);
if(id == R.id.action_today)
{
mWeekView.goToToday();
return true;
}
if(id== R.id.action_day_view) {
if (mWeekViewType != TYPE_DAY_VIEW) {
item.setChecked(!item.isChecked());
mWeekViewType = TYPE_DAY_VIEW;
mWeekView.setNumberOfVisibleDays(1);
// Lets change some dimensions to best fit the view.
mWeekView.setColumnGap((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8, getResources().getDisplayMetrics()));
mWeekView.setTextSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 12, getResources().getDisplayMetrics()));
mWeekView.setEventTextSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 12, getResources().getDisplayMetrics()));
}
return true;
}
else if(id== R.id.action_three_day_view) {
if (mWeekViewType != TYPE_THREE_DAY_VIEW) {
item.setChecked(!item.isChecked());
mWeekViewType = TYPE_THREE_DAY_VIEW;
mWeekView.setNumberOfVisibleDays(3);
// Lets change some dimensions to best fit the view.
mWeekView.setColumnGap((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8, getResources().getDisplayMetrics()));
mWeekView.setTextSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 12, getResources().getDisplayMetrics()));
mWeekView.setEventTextSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 12, getResources().getDisplayMetrics()));
}
return true;
}
else if(id == R.id.action_week_view)
{
if (mWeekViewType != TYPE_WEEK_VIEW) {
item.setChecked(!item.isChecked());
mWeekViewType = TYPE_WEEK_VIEW;
mWeekView.setNumberOfVisibleDays(7);
// Lets change some dimensions to best fit the view.
mWeekView.setColumnGap((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, getResources().getDisplayMetrics()));
mWeekView.setTextSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 10, getResources().getDisplayMetrics()));
mWeekView.setEventTextSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 10, getResources().getDisplayMetrics()));
}
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Set up a date time interpreter which will show short date values when in week view and long
* date values otherwise.
*
* #param shortDate True if the date values should be short.
*/
private void setupDateTimeInterpreter(final boolean shortDate) {
mWeekView.setDateTimeInterpreter(new DateTimeInterpreter() {
#Override
public String interpretDate(Calendar date) {
SimpleDateFormat weekdayNameFormat = new SimpleDateFormat("EEE", Locale.FRANCE);
String weekday = weekdayNameFormat.format(date.getTime());
SimpleDateFormat format = new SimpleDateFormat(" d/M/Y", Locale.FRANCE);
// All android api level do not have a standard way of getting the first letter of
// the week day name. Hence we get the first char programmatically.
// Details: http://stackoverflow.com/questions/16959502/get-one-letter-abbreviation-of-week-day-of-a-date-in-java#answer-16959657
if (shortDate)
weekday = String.valueOf(weekday.charAt(0));
return weekday.toUpperCase() + format.format(date.getTime());
}
#Override
public String interpretTime(int hour) {
return ""+hour ;
}
});
}
#Override
public void onEmptyViewLongPress(Calendar time) {
Toast.makeText(this, "Empty view long pressed: " + getEventTitle(time), Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),addEvent.class));
finish();
}
protected String getEventTitle(Calendar time) {
return String.format("l'evenement de %02d:%02d %s/%d", time.get(Calendar.HOUR_OF_DAY), time.get(Calendar.MINUTE), time.get(Calendar.MONTH) + 1, time.get(Calendar.DAY_OF_MONTH));
}
#Override
public void onEventClick(WeekViewEvent event, RectF eventRect) {
Toast.makeText(this, "l'evenement : " + event.getName(), Toast.LENGTH_SHORT).show();
}
#Override
public void onEventLongPress(final WeekViewEvent event, RectF eventRect) {
//Toast.makeText(this, "Long pressed event: " + event.getName(), Toast.LENGTH_SHORT).show();
AlertDialog.Builder supprimer = new AlertDialog.Builder(BaseActivity.this);
supprimer.setMessage("voulez vous supprimer cet evenement ?")
.setCancelable(false)
.setPositiveButton("confirmer", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
db_cal db = new db_cal(getApplicationContext());
Calendar b=event.getStartTime();
Calendar e = event.getEndTime();
String name = event.getName();
db.supprimer(b,e,name);
}
}).setNegativeButton("annuler", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = supprimer.create();
alert.setTitle("supprimer evenement");
alert.show();
}
public WeekView getWeekView() {
return mWeekView;
}
}
i would like to show these events correctly if anyone can help

Android checkboxes, how to implement if statement.

I am currently coding an android app but I encountered some difficulty.
I am able to receive some checkbox values from another activity using the getIntent().getExtras().getBoolean()function.
But my question is, how can i make sure that checkboxes with the characters 'wb' or 'ab' or 'alb' together with(or not) 'cs' appearing, a count is performed and the one with the greatest value between 'wb', 'ab' and 'alb' is chosen and a summary is displayed via a texfield.
e.g. if there appearances of 'wb' are greater than those of 'alb' and ab, then the result is displayed "you have a widened bronchus".
package com.example.vic.cdmes_;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class results extends AppCompatActivity {
private Button displayResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_results);
viewResults();
}
private void viewResults() {
final Boolean wb1 = getIntent().getExtras().getBoolean("wb1");
final Boolean wb2 = getIntent().getExtras().getBoolean("wb2");
final Boolean wb3 = getIntent().getExtras().getBoolean("wb3");
final Boolean wb4 = getIntent().getExtras().getBoolean("wb4");
final Boolean wb5 = getIntent().getExtras().getBoolean("wb5");
final Boolean wb6 = getIntent().getExtras().getBoolean("wb6");
final Boolean wb7 = getIntent().getExtras().getBoolean("wb7");
final Boolean cs1 = getIntent().getExtras().getBoolean("cs1");
final Boolean cs2 = getIntent().getExtras().getBoolean("cs2");
final Boolean vb1 = getIntent().getExtras().getBoolean("vb1");
final Boolean vb2 = getIntent().getExtras().getBoolean("vb2");
final Boolean vb3 = getIntent().getExtras().getBoolean("vb3");
final Boolean vb4 = getIntent().getExtras().getBoolean("vb4");
final Boolean vb5 = getIntent().getExtras().getBoolean("vb5");
final Boolean alb1 = getIntent().getExtras().getBoolean("alb1");
final Boolean alb2 = getIntent().getExtras().getBoolean("alb2");
final Boolean alb3 = getIntent().getExtras().getBoolean("alb3");
final Boolean ab1 = getIntent().getExtras().getBoolean("ab1");
final Boolean ab2 = getIntent().getExtras().getBoolean("ab2");
final Boolean ab3 = getIntent().getExtras().getBoolean("ab3");
final Boolean ab4 = getIntent().getExtras().getBoolean("ab4");
displayResult = (Button)findViewById(R.id.displayResults);
displayResult.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(results.this,.toString(),
// Toast.LENGTH_SHORT).show();
if(wb1&&wb2&&wb3&&wb4&&wb5&&wb6&&wb7&&cs1&&cs2)
{
//if the number of checkboxes exceeds
}
else
if (vb1&&vb2&&vb3&&vb4&&vb5&&cs1&&cs2)
{
//display the person might be having a widened bronchus
}
else
if (alb1&&alb2&&alb3&&cs1&&cs2)
{
//display the person might be having a alb disease
}
else
if (ab1&&ab2&&ab3&&ab4&&cs1&&cs2)
{
//display the person might be having a airborne disease
}
}
});
}
}
thanks for the help in advance.
Set Default Boolean value. Like This
final Boolean wb1 = getIntent().getExtras().getBoolean("wb1",true);
You can get the count of wb, ab and alb below, using that you can write the if statement.
int wbCount = 0, abCount = 0, albCount = 0;
boolean cs = (cs1 && cs2);
for(int i=1; i <= 7; i++) {
if(getIntent().getExtras().getBoolean("wb"+i) && cs) {
wbCount++;
}
}
for(int i=1; i <= 3; i++) {
if(getIntent().getExtras().getBoolean("alb"+i) && cs) {
albCount++;
}
}
for(int i=1; i <= 4; i++) {
if(getIntent().getExtras().getBoolean("ab"+i) && cs) {
abCount++;
}
}

How a button click can call another activity?

So I am trying to create an android app to show some simple battery information. And now I want to take that info and plot a graph inside the app. I have the following codes:
public class MainActivity extends ActionBarActivity {
private TextView level,voltage, status1,temp,health1,tech,sour,amp;
Thread myThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
level=(TextView)findViewById(R.id.level);
voltage=(TextView)findViewById(R.id.volt);
status1=(TextView)findViewById(R.id.stat);
temp=(TextView)findViewById(R.id.temp);
health1=(TextView)findViewById(R.id.healt);
tech=(TextView)findViewById(R.id.tech);
sour=(TextView)findViewById(R.id.source);
Button b = (Button) findViewById(R.id.ex);
Button g = (Button) findViewById(R.id.graphButton);
amp=(TextView)findViewById(R.id.current);
b.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
g.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
//how can i jump to DynamicGraphActivity
}
});
this.registerReceiver(this.myBatteryReceiver,
new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
private BroadcastReceiver myBatteryReceiver
= new BroadcastReceiver(){
#SuppressLint("InlinedApi")
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
if (arg1.getAction().equals(Intent.ACTION_BATTERY_CHANGED)){
int lv = arg1.getIntExtra("level", 0);
level.setText("Level: "
+ String.valueOf(lv) + "%");
voltage.setText("Voltage: "
+ String.valueOf((float)arg1.getIntExtra("voltage", 0)/1000) + "V");
temp.setText("Temperature: "
+ String.valueOf((float)arg1.getIntExtra("temperature", 0)/10) + "c");
tech.setText("Technology: " + arg1.getStringExtra("technology"));
int status = arg1.getIntExtra("status", BatteryManager.BATTERY_STATUS_UNKNOWN);
String strStatus;
if (status == BatteryManager.BATTERY_STATUS_CHARGING){
strStatus = "Charging";
} else if (status == BatteryManager.BATTERY_STATUS_DISCHARGING){
strStatus = "Dis-charging";
} else if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING){
strStatus = "Not charging";
} else if (status == BatteryManager.BATTERY_STATUS_FULL){
strStatus = "Full";
} else {
strStatus = "Unknown";
}
status1.setText("Status: " + strStatus);
//int source=arg1.getIntExtra("source", BatteryManager.BATTERY_STATUS_UNKNOWN);
if(Build.VERSION.SDK_INT >= 21){
BatteryManager battery = (BatteryManager)getSystemService(Context.BATTERY_SERVICE);
int current=battery.getIntProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW);
int currentAvg=battery.getIntProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_AVERAGE);
int energy=battery.getIntProperty(BatteryManager.BATTERY_PROPERTY_ENERGY_COUNTER);
int capacity=battery.getIntProperty(BatteryManager.BATTERY_PROPERTY_CHARGE_COUNTER);
int bCapacity=battery.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
String string1 = "Current: "+ current*1000+" uA"+"\n";
string1+="Average Current: "+currentAvg+" uA"+"\n";
string1+="Remaining energy: "+energy+" nWh"+"\n";
string1+="Capacity: "+capacity+" uAh"+"\n\n";
amp.setText(string1);
}
int health = arg1.getIntExtra("health", BatteryManager.BATTERY_HEALTH_UNKNOWN);
String strHealth;
if (health == BatteryManager.BATTERY_HEALTH_GOOD){
strHealth = "Good";
} else if (health == BatteryManager.BATTERY_HEALTH_OVERHEAT){
strHealth = "Over Heat";
} else if (health == BatteryManager.BATTERY_HEALTH_DEAD){
strHealth = "Dead";
} else if (health == BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE){
strHealth = "Over Voltage";
} else if (health == BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE){
strHealth = "Unspecified Failure";
} else{
strHealth = "Unknown";
}
health1.setText("Health: " + strHealth);
}
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
2nd Activity or DynamicGraphActivity:
public class DynamicGraphActivity extends Activity {
private static GraphicalView view;
private LineGraph line = new LineGraph();
private static Thread thread;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
thread = new Thread() {
public void run()
{
for (int i = 0; i < 15; i++)
{
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Point p = MockData.getDataFromReceiver(i); // We got new data!
line.addNewPoints(p); // Add it to our graph
view.repaint();
}
}
};
thread.start();
}
#Override
protected void onStart() {
super.onStart();
view = line.getView(this);
setContentView(view);
}
}
import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.TimeSeries;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import android.content.Context;
import android.graphics.Color;
public class LineGraph {
private GraphicalView view;
private TimeSeries dataset = new TimeSeries("Rain Fall");
private XYMultipleSeriesDataset mDataset = new XYMultipleSeriesDataset();
private XYSeriesRenderer renderer = new XYSeriesRenderer(); // This will be used to customize line 1
private XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer(); // Holds a collection of XYSeriesRenderer and customizes the graph
public LineGraph()
{
// Add single dataset to multiple dataset
mDataset.addSeries(dataset);
// Customization time for line 1!
renderer.setColor(Color.WHITE);
renderer.setPointStyle(PointStyle.SQUARE);
renderer.setFillPoints(true);
// Enable Zoom
mRenderer.setZoomButtonsVisible(true);
mRenderer.setXTitle("Day #");
mRenderer.setYTitle("CM in Rainfall");
// Add single renderer to multiple renderer
mRenderer.addSeriesRenderer(renderer);
}
public GraphicalView getView(Context context)
{
view = ChartFactory.getLineChartView(context, mDataset, mRenderer);
return view;
}
public void addNewPoints(Point p)
{
dataset.add(p.getX(), p.getY());
}
}
import java.util.Random;
public class MockData {
// x is the day number, 0, 1, 2, 3
public static Point getDataFromReceiver(int x)
{
return new Point(x, generateRandomData());
}
private static int generateRandomData()
{
Random random = new Random();
return random.nextInt(40);
}
}
public class Point {
private int x;
private int y;
public Point( int x, int y)
{
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
Now inside the button g, I want to call DynamicGraphActivity class so that it calls the class and plots a graph using some random values. but its not working. When i click on the button, it doesnt do anything. How can I fix this?
And my another question is, how can I plot the battery info such as voltage, charge or discharge over time using these codes/
Any help would be greatly appreciated.
Thank you
Well there is a difference between any class or an activity.
Activity have a visual layout maps to it.Check this link for more info.
Inside your g button click listener add this code.
g.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, DynamicGraphActivity.class);
startActivity(intent);
}
});
Also you need to add the other activity in the AndroidManifest.xml as well under application tag.(You already have activity tag inside application tag if you create a new app.But you don't need any intent filters for newer activity)
<activity
android:name=".DynamicGraphActivity"
/>
I noticed one more thing you are using same layout(main.xml) for both activities.
Create another layout in layouts folder and map it to the DynamicGraphActivity.
Lets say you create second.xml.
So your DynamicGraphActivity oncreate() have:
setContentView(R.layout.second);
Intent 2ndActivity = new Intent(this, blabla.class);
startActivity(2ndActivity);
For the button and for the extra value you can use Bundle,Parcel or just use putExtra.
And for the battery info, Read from google developer
In your button click put this code
Intent intent = new Intent(MainActivity.this, DynamicGraphActivity.class);
startActivity(intent);
and define this activity in your AndroidManifest.xml
<activity
android:name=".DynamicGraphActivity"
android:theme="#android:style/Theme.Translucent.NoTitleBar" />
and for Battery information you can refer this links...
http://developer.android.com/reference/android/os/BatteryManager.html
http://mobiledevtuts.com/android/android-sdk-get-device-battery-information/
Get battery level and state in Android

Android: Adding functionality that activty changes when game is complete

I wish to add the following functionality to my game:
-When the game is complete (no more cards are visible on screen) then move to a new activity
I am aware how to move to another activty using intents but I am not sure how to implement the functionality in this case.
I.e. what variable/info can I use to ensure the game is complete when I move before moving to the next activity?
For reference, The game is based off this open source game Images of the game are shown here to give an idea.
Current code:
public class Manager extends Activity {
private static int ROW_COUNT = -1;
private static int COL_COUNT = -1;
private Context context;
private Drawable backImage;
private int [] [] cards;
private List<Drawable> images;
private Card firstCard;
private Card seconedCard;
private ButtonListener buttonListener;
private static Object lock = new Object();
int turns;
private TableLayout mainTable;
private UpdateCardsHandler handler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
handler = new UpdateCardsHandler();
loadImages();
setContentView(R.layout.main);
TextView url = ((TextView)findViewById(R.id.myWebSite));
Linkify.addLinks(url, Linkify.WEB_URLS);
backImage = getResources().getDrawable(R.drawable.icon);
/*
((Button)findViewById(R.id.ButtonNew)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
newGame();
}
});*/
buttonListener = new ButtonListener();
mainTable = (TableLayout)findViewById(R.id.TableLayout03);
context = mainTable.getContext();
Spinner s = (Spinner) findViewById(R.id.Spinner01);
ArrayAdapter adapter = ArrayAdapter.createFromResource(
this, R.array.type, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s.setAdapter(adapter);
s.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(
android.widget.AdapterView<?> arg0,
View arg1, int pos, long arg3){
((Spinner) findViewById(R.id.Spinner01)).setSelection(0);
int x,y;
switch (pos) {
case 1:
x=4;y=4;
break;
case 2:
x=4;y=5;
break;
case 3:
x=4;y=6;
break;
case 4:
x=5;y=6;
break;
case 5:
x=6;y=6;
break;
default:
return;
}
newGame(x,y);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
private void newGame(int c, int r) {
ROW_COUNT = r;
COL_COUNT = c;
cards = new int [COL_COUNT] [ROW_COUNT];
mainTable.removeView(findViewById(R.id.TableRow01));
mainTable.removeView(findViewById(R.id.TableRow02));
TableRow tr = ((TableRow)findViewById(R.id.TableRow03));
tr.removeAllViews();
mainTable = new TableLayout(context);
tr.addView(mainTable);
for (int y = 0; y < ROW_COUNT; y++) {
mainTable.addView(createRow(y));
}
firstCard=null;
loadCards();
turns=0;
((TextView)findViewById(R.id.tv1)).setText("Tries: "+turns);
}
private void loadImages() {
images = new ArrayList<Drawable>();
images.add(getResources().getDrawable(R.drawable.card1));
images.add(getResources().getDrawable(R.drawable.card2));
images.add(getResources().getDrawable(R.drawable.card3));
images.add(getResources().getDrawable(R.drawable.card4));
images.add(getResources().getDrawable(R.drawable.card5));
images.add(getResources().getDrawable(R.drawable.card6));
images.add(getResources().getDrawable(R.drawable.card7));
images.add(getResources().getDrawable(R.drawable.card8));
images.add(getResources().getDrawable(R.drawable.card9));
images.add(getResources().getDrawable(R.drawable.card10));
images.add(getResources().getDrawable(R.drawable.card11));
images.add(getResources().getDrawable(R.drawable.card12));
images.add(getResources().getDrawable(R.drawable.card13));
images.add(getResources().getDrawable(R.drawable.card14));
images.add(getResources().getDrawable(R.drawable.card15));
images.add(getResources().getDrawable(R.drawable.card16));
images.add(getResources().getDrawable(R.drawable.card17));
images.add(getResources().getDrawable(R.drawable.card18));
images.add(getResources().getDrawable(R.drawable.card19));
images.add(getResources().getDrawable(R.drawable.card20));
images.add(getResources().getDrawable(R.drawable.card21));
}
private void loadCards(){
try{
int size = ROW_COUNT*COL_COUNT;
Log.i("loadCards()","size=" + size);
ArrayList<Integer> list = new ArrayList<Integer>();
for(int i=0;i<size;i++){
list.add(new Integer(i));
}
Random r = new Random();
for(int i=size-1;i>=0;i--){
int t=0;
if(i>0){
t = r.nextInt(i);
}
t=list.remove(t).intValue();
cards[i%COL_COUNT][i/COL_COUNT]=t%(size/2);
Log.i("loadCards()", "card["+(i%COL_COUNT)+
"]["+(i/COL_COUNT)+"]=" + cards[i%COL_COUNT][i/COL_COUNT]);
}
}
catch (Exception e) {
Log.e("loadCards()", e+"");
}
}
private TableRow createRow(int y){
TableRow row = new TableRow(context);
row.setHorizontalGravity(Gravity.CENTER);
for (int x = 0; x < COL_COUNT; x++) {
row.addView(createImageButton(x,y));
}
return row;
}
private View createImageButton(int x, int y){
Button button = new Button(context);
button.setBackgroundDrawable(backImage);
button.setId(100*x+y);
button.setOnClickListener(buttonListener);
return button;
}
class ButtonListener implements OnClickListener {
#Override
public void onClick(View v) {
synchronized (lock) {
if(firstCard!=null && seconedCard != null){
return;
}
int id = v.getId();
int x = id/100;
int y = id%100;
turnCard((Button)v,x,y);
}
}
private void turnCard(Button button,int x, int y) {
button.setBackgroundDrawable(images.get(cards[x][y]));
if(firstCard==null){
firstCard = new Card(button,x,y);
}
else{
if(firstCard.x == x && firstCard.y == y){
return; //the user pressed the same card
}
seconedCard = new Card(button,x,y);
turns++;
((TextView)findViewById(R.id.tv1)).setText("Tries: "+turns);
TimerTask tt = new TimerTask() {
#Override
public void run() {
try{
synchronized (lock) {
handler.sendEmptyMessage(0);
}
}
catch (Exception e) {
Log.e("E1", e.getMessage());
}
}
};
Timer t = new Timer(false);
t.schedule(tt, 1300);
}
}
}
class UpdateCardsHandler extends Handler{
#Override
public void handleMessage(Message msg) {
synchronized (lock) {
checkCards();
}
}
public void checkCards(){
if(cards[seconedCard.x][seconedCard.y] == cards[firstCard.x][firstCard.y]){
firstCard.button.setVisibility(View.INVISIBLE);
seconedCard.button.setVisibility(View.INVISIBLE);
}
else {
seconedCard.button.setBackgroundDrawable(backImage);
firstCard.button.setBackgroundDrawable(backImage);
}
firstCard=null;
seconedCard=null;
}
}
}
The easiest way to do this would be to check win conditions with an if statement. This should be done in the method when a turn is actually taken which I assume happens in the turnCard() method.
if (winConditionMet) {
displayWinningScreen();
} else if (lossConditionMet) {
displayLosingScreen();
}
If conditions have been met, then call a method which handles wrapping up that screen, and then launching a new activity. For instance you could add a button to the screen with whatever text you wanted, that when pushed, would take the user to the next screen, be it your score screen, replay screen, main menu, or what have you.
Edit: Okay, since this is a game of memory, you could iterate through the cards at the end of every turn taken and check if any card still has its image set to backImage. If there are none left that are set to backImage, you can then end the game with your code inside of the if statement.
Or, instead of using an ArrayList, you could use some form of Map to keep track of if each card has been permanently turned up or not with the boolean value.

Show log messages on screen for Android application

Is it possible to display the log messages (which I print using android.util.Log) on screen in an Android application?
Is there any other better method to just output lines on the screen?
Something like System.out.println?
Like others have suggested, you can use log cat. If you are using the emulator or debugging a device, you can use adb logcat to view the messages. In Eclipse debug perspective, there is a window that will do that for you.
Another way, without a debugger attached, is to use the CatLog - Logcat Reader application.
Yes zero4
what you are attempting to do is dropping 'logcat' comand on android shell & getting command output as output stream.This link will help you.
I use "android.widget.Toast.makeText(Context context, CharSequence text, int duration)" to do something like what you are asking. Seems like the easiest way to get some quick messages on the screen and make it go away automatically (based on the last parameter).
:-)
Well, there is a solution to log anything you want on screen using this lib. It didn't worked for me, so I develop my own solution you can find an example of it here. It's really simple, just add a class OnScreenLog to your project
package br.com.ideiageni.onscreenlogSample;
import android.app.Activity;
import android.graphics.Color;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
/**
* Created by ariel on 07/07/2016.
*/
public class OnScreenLog {
private static int timeoutTime = 1000;
private static TextView tvLog;
private static int logCount = 0;
private static int logCountMax = 30;
private static String[] logs = new String[logCountMax];
private static int cntClicks = 0;
private static boolean visibility = false;
private static Activity activity;
private int maxClicks = 5;
public OnScreenLog(){}
public OnScreenLog(Activity activity, int ViewID){
OnScreenLog.activity = activity;
tvLog = new TextView(activity.getApplicationContext());
maintainLog("Log is working");
tvLog.setLayoutParams(new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT));
tvLog.setTextColor(Color.BLACK);
tvLog.setBackgroundColor(Color.LTGRAY);
tvLog.setAlpha((float) 0.4);
View v = null;
LinearLayout linearLayout;
RelativeLayout relativeLayout;
try {
linearLayout = (LinearLayout) activity.findViewById(ViewID);
} catch (ClassCastException e) {linearLayout = null;};
try {
relativeLayout = (RelativeLayout) activity.findViewById(ViewID);
} catch (ClassCastException e) {relativeLayout = null;};
if(linearLayout != null) {
linearLayout.addView(tvLog);
v = linearLayout;
} else if(relativeLayout != null) {
relativeLayout.addView(tvLog);
v = relativeLayout;
}
if(v != null) {
v.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
cntClicks++;
timerHandler.removeCallbacks(rTimeout);
timerHandler.postDelayed(rTimeout, timeoutTime);
if (cntClicks > maxClicks-1) {
setLogVisible(!visibility);
timerHandler.removeCallbacks(rTimeout);
cntClicks = 0;
}
break;
}
return false;
}
});
}
}
public void log (String text){
String logText = text;
maintainLog(logText);
}
public void log (int text){
String logText = String.valueOf(text);
maintainLog(logText);
}
public void log (int[] text){
StringBuilder builder = new StringBuilder();
for (int i : text) {
builder.append(i);
builder.append("-");
}
String logText = builder.toString();
maintainLog(logText);
}
public void log (byte[] text){
StringBuilder builder = new StringBuilder();
for (int i : text) {
builder.append(i);
builder.append("-");
}
String logText = builder.toString();
maintainLog(logText);
}
private void maintainLog(String newText){
String logText = "";
if(logCount<logCountMax) logCount++;
for(int i=logCount-1; i>0; i--){
logs[i] = logs[i-1];
}
logs[0] = newText;
for(int i=0; i<logCount; i++){
if(i<logCount-1) logText+=logs[i]+System.getProperty("line.separator");
else logText+=logs[i];
}
tvLog.setText(logText);
}
public void clearLog(){
tvLog.setText("");
}
public void setLogVisible(boolean visibility){
if(visibility) tvLog.setVisibility(View.VISIBLE);
else tvLog.setVisibility(View.INVISIBLE);
OnScreenLog.visibility = visibility;
}
public static int getLogCountMax() {
return logCountMax;
}
public static void setLogCountMax(int logCountMax) {
OnScreenLog.logCountMax = logCountMax;
logs = new String[logCountMax];
}
public int getMaxClicks() {
return maxClicks;
}
public void setMaxClicks(int maxClicks) {
this.maxClicks = maxClicks;
}
Handler timerHandler = new Handler();
Runnable rTimeout = new Runnable() {
#Override
public void run() {
cntClicks = 0;
}
};
}
then, for instance:
public class Activity1 extends AppCompatActivity {
private OnScreenLog log;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_1);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
log = new OnScreenLog(this, R.id.content_1);
log.log("Started log on Activity 1");
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), Activity2.class);
startActivity(intent);
log.log("Starting Activity 2");
Snackbar.make(view, "Starting Activity 2", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
Where R.id.content_1 is the name of the main LinearLayout or RelativeLayout of your activity.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/content_1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="br.com.ideiageni.onscreenlogSample.Activity1"
tools:showIn="#layout/activity_1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Activity 1!" />
</RelativeLayout>
Neither solutions print the current log messages, so you'll need to tell it to log to screen the same informations you log today on your current log.
Work not finished yet but can be used for anyone in need. Missing some directions on how to use. Suggestions are welcome.

Categories

Resources