Gestures in activity - android - java

I need to implement few gestures in activity. I used Genymotion for that, saved gestures file in res/raw folder and wrote a code which is showing all good but keeps crashing the application. Does anyone know what could be the possible reason? I really tried to solve, but it seems i am missing something!
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GestureOverlayView gesturesView = new GestureOverlayView(this);
View inflate = getLayoutInflater().inflate(R.layout.activity_garden,
null);
gesturesView.addView(inflate);
gesturesView.addOnGesturePerformedListener(this);
gestures = GestureLibraries.fromRawResource(this, R.raw.gestures);
if (!gestures.load()) {
finish();
}
setContentView(gesturesView);
}
public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {
ArrayList<Prediction> predictions = gestures.recognize(gesture);
int index = 0;
double maxScore = predictions.get(index).score;
for (int i = 1; i < predictions.size(); i++) {
if (predictions.get(i).score > maxScore) {
index = i;
maxScore = predictions.get(i).score;
}
}
Prediction p = predictions.get(index);
if (p.name.equalsIgnoreCase("Love"))
daisy.setImageResource(sp.getInt("Love", 0));
if (p.name.equalsIgnoreCase("Hit"))
daisy.setImageResource(sp.getInt("Hit", 0));
if (p.name.equalsIgnoreCase("Pet"))
daisy.setImageResource(sp.getInt("Pet", 0));
Toast.makeText(this, p.name + "\n" + p.score, Toast.LENGTH_SHORT)
.show();
}

On your code, what happen if you don't get any prediction?
Well, index will be equals to 0, and predictions.get(index) will crash because there is no object at index 0.
public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {
ArrayList<Prediction> predictions = gestures.recognize(gesture);
if (predictions == null || predictions.isEmpty()) {
return;
}
// continue the regular flow
}

Related

Android: ProgressDialog Circle not showing

I tried to implement a loading circle in my application as it transitioned from the previous activity to this activity. As there are a ton of calculations in this activity, it turns black screen as it's doing the calculations for a good 10 to 15 seconds, once the calculations are done it'd display an image, seen in onCreate: resultImage.setImageBitmap(finalBitmap);
However, the circle doesn't appear, and it's still the same old black screen to image transition.
Imported:
import android.app.ProgressDialog;
Declared:
private ProgressDialog progressDialog;
Initialized:
progressDialog = new ProgressDialog(this);
progressDialog.setTitle(null);
progressDialog.setCancelable(false);
Made it visible:
progressDialog.show();
Changed its message as the code progressed:
progressDialog.setMessage("Finding Objects...");
progressDialog.setMessage("Calculating Areas...");
progressDialog.setMessage("Calculating Height...");
... etc etc
onCreate:
#Override
public void onCreate(Bundle savedInstanceState) {
progressDialog = new ProgressDialog(this);
progressDialog.setTitle(null);
progressDialog.setCancelable(false);
progressDialog.setMessage("Processing...");
progressDialog.show();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_auto_test);
if (!OpenCVLoader.initDebug()) {
Log.d("opencv", "OpenCVLoader.initDebug() - ERROR");
} else {
Log.d("opencv", "OpenCVLoader.initDebug() - OK");
}
String filePath = getIntent().getStringExtra(FILEPATH);
ArrayList<String> f = new ArrayList<String>();
File dir = new File(filePath);
File[] listFile;
listFile = dir.listFiles();
for (File e : listFile) {
f.add(e.getAbsolutePath());
}
paths = f;
resetVariables();
progressDialog.setMessage("Finding Objects...");
for (int xx = 0; xx < paths.size(); xx++) {
Bitmap areaBitmap = BitmapFactory.decodeFile(paths.get(xx));
getArea(areaBitmap);
}
if (loopCounter > 0) {
progressDialog.setMessage("Calculating Areas...");
meanBlackArea = blackArea / loopCounter;
Log.e("meanBlackArea", "30% of mean black " + String.valueOf(meanBlackArea * 0.3) + " 110% of mean black " + String.valueOf(meanBlackArea * 1.1));
Log.e("Loopcounter", String.valueOf(loopCounter));
}
resetVariables();
Log.e("~", "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
Log.e("Lowest Green", String.valueOf(greenArea));
Log.e("~", "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
progressDialog.setMessage("Calculating Height...");
int frameNumber = 0;
for (int x = 0; x < paths.size(); x++) {
Bitmap calculationsBitmap = BitmapFactory.decodeFile(paths.get(x));
numRectBlack = 0;
numRectGreen = 0;
tempBitmap = findCombineBitmap(calculationsBitmap);
if (check == true) {
if (Double.isInfinite(tempLineHeightCm) == false) {
frameNumber = x;
finalBitmap = tempBitmap;
}
}
}
progressDialog.setMessage("Tidying Up...");
TextView tvR = (TextView) findViewById(R.id.tvR);
if(tempLineHeightCm==0) {
tvR.setText("We could not detect a bounce!\nPlease do the following and try again:\n1. Remove all foreign objects from testing grounds.\n2.Make sure that there are ample lighting on the testing grounds.");
}else{
tvR.setText("Frame " + frameNumber + ", Bounce Height = " + tempLineHeightCm + "cm");
ImageView resultImage = (ImageView) findViewById(R.id.resultImage);
resultImage.setImageBitmap(finalBitmap);
progressDialog.dismiss();
}
}
Link to code file:
Google Drive
Notes:
MainActivity.java has a working progresscircle
TestAutoRun.java is the one I'm working on.
Show ProgressDialog, start new AsyncTask and do your heavy calculations in background. After the AsyncTask completes, hide the progress dialog and go to next activity.
If you don't know how to use AsyncTask, check the reference here.

How to stop infinite loop on sliders

I'm using this Slider.
This is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDemoSlider = (SliderLayout)findViewById(R.id.slider);
HashMap<String,Integer> file_maps = new HashMap<String, Integer>();
file_maps.put("Hannibal",R.drawable.hannibal);
file_maps.put("Big Bang Theory",R.drawable.bigbang);
file_maps.put("House of Cards",R.drawable.house);
file_maps.put("Game of Thrones", R.drawable.game_of_thrones);
for(String name : file_maps.keySet()){
TextSliderView textSliderView = new TextSliderView(this);
// initialize a SliderLayout
textSliderView
.description(name)
.image(file_maps.get(name))
.setScaleType(BaseSliderView.ScaleType.Fit)
.setOnSliderClickListener(this);
//add your extra information
textSliderView.bundle(new Bundle());
textSliderView.getBundle()
.putString("extra",name);
mDemoSlider.addSlider(textSliderView);
}
mDemoSlider.setPresetTransformer(SliderLayout.Transformer.Accordion);
mDemoSlider.setPresetIndicator(SliderLayout.PresetIndicators.Center_Bottom);
mDemoSlider.setCustomAnimation(new DescriptionAnimation());
mDemoSlider.stopAutoCycle();
mDemoSlider.addOnPageChangeListener(this);
}
Is there any way to stop infinite loop on sliders. I read that I should add mDemoSlider.stopAutoCycle(); but this does not have any effect.
Sorry, but you can't. At least not with this lib.
I've looked into the code and I saw that this "infinite scrolling" is default behavior, and if you want to disabled it you have either to implement your own slider, or suggest and edit for the original author...
The "problem" is on those two methods of the SliderLayout.java class:
/**
* move to next slide.
*/
public void moveNextPosition(boolean smooth) {
if (getRealAdapter() == null)
throw new IllegalStateException("You did not set a slider adapter");
mViewPager.setCurrentItem(mViewPager.getCurrentItem() + 1, smooth);
}
// ...
/**
* move to prev slide.
*/
public void movePrevPosition(boolean smooth) {
if (getRealAdapter() == null)
throw new IllegalStateException("You did not set a slider adapter");
mViewPager.setCurrentItem(mViewPager.getCurrentItem() - 1, smooth);
}
And the setCurrentItem is located inside the ViewPagerEx.java class, where you can see that this infinite scrolling is default behavior. (Look at the setCurrentItemInternal method).
void setCurrentItemInternal(int item, boolean smoothScroll, boolean always, int velocity) {
if (mAdapter == null || mAdapter.getCount() <= 0) {
setScrollingCacheEnabled(false);
return;
}
if (!always && mCurItem == item && mItems.size() != 0) {
setScrollingCacheEnabled(false);
return;
}
if (item < 0) {
item = 0;
} else if (item >= mAdapter.getCount()) {
item = mAdapter.getCount() - 1;
}
final int pageLimit = mOffscreenPageLimit;
if (item > (mCurItem + pageLimit) || item < (mCurItem - pageLimit)) {
// We are doing a jump by more than one page. To avoid
// glitches, we want to keep all current pages in the view
// until the scroll ends.
for (int i=0; i<mItems.size(); i++) {
mItems.get(i).scrolling = true;
}
}
final boolean dispatchSelected = mCurItem != item;
if (mFirstLayout) {
// We don't have any idea how big we are yet and shouldn't have any pages either.
// Just set things up and let the pending layout handle things.
mCurItem = item;
triggerOnPageChangeEvent(item);
requestLayout();
} else {
populate(item);
scrollToItem(item, smoothScroll, velocity, dispatchSelected);
}
}

Set Animation for a group of objects in Android

I have several TextView objects that I need to animate with the same Animation.
The way I'm doing it looks wrong, since I can only set Animation to each object at time
#Override
public void onClick(View v) {
Animation hideLeftBar, showLeftBar;
hideLeftBar = new TranslateAnimation(195, 0, 0, 0);
hideLeftBar.setDuration(1000);
hideLeftBar.setFillAfter(true);
showLeftBar = new TranslateAnimation(0, 195, 0, 0);
showLeftBar.setDuration(1000);
showLeftBar.setFillAfter(true);
switch(v.getId())
{
case R.id.btGMG:
if(img_GMG.getAlpha() == (float) 0.3)
{
img_GMG.setAlpha((float) 1);
imgLeftBar.startAnimation(showLeftBar);
txtRS.startAnimation(showLeftBar);
txtST.startAnimation(showLeftBar);
txtTR.startAnimation(showLeftBar);
txtI1.startAnimation(showLeftBar);
txtI2.startAnimation(showLeftBar);
txtI3.startAnimation(showLeftBar);
txtP1.startAnimation(showLeftBar);
txtP2.startAnimation(showLeftBar);
txtP3.startAnimation(showLeftBar);
txtS1.startAnimation(showLeftBar);
txtS2.startAnimation(showLeftBar);
txtS3.startAnimation(showLeftBar);
txtFP1.startAnimation(showLeftBar);
txtFP2.startAnimation(showLeftBar);
txtFP3.startAnimation(showLeftBar);
textIndutive.startAnimation(showLeftBar);
textCapacitive.startAnimation(showLeftBar);
}
else
{
img_GMG.setAlpha((float) 0.3);
imgLeftBar.startAnimation(hideLeftBar);
txtRS.startAnimation(hideLeftBar);
txtST.startAnimation(hideLeftBar);
txtTR.startAnimation(hideLeftBar);
txtI1.startAnimation(hideLeftBar);
txtI2.startAnimation(hideLeftBar);
txtI3.startAnimation(hideLeftBar);
txtP1.startAnimation(hideLeftBar);
txtP2.startAnimation(hideLeftBar);
txtP3.startAnimation(hideLeftBar);
txtS1.startAnimation(hideLeftBar);
txtS2.startAnimation(hideLeftBar);
txtS3.startAnimation(hideLeftBar);
txtFP1.startAnimation(hideLeftBar);
txtFP2.startAnimation(hideLeftBar);
txtFP3.startAnimation(hideLeftBar);
textIndutive.startAnimation(hideLeftBar);
textCapacitive.startAnimation(hideLeftBar);
}
break;
}
}
How can I reduce this? Should I do it programatically or using XML resources?
You should use an AnimatorSet. It has a playTogether() function that will play all your animations at the same time. See a good example here.
In order to run multiple animations in parallel you could use the View's ViewPropertyAnimator like this:
for (int i = 0; i < parentView.getChildCount(); i++) {
View childView = parentView.getChildAt(i);
childView.animate().translationX(DELTA_X).setDuration(DURATION_ANIM);
}
and for the other animation you could use .translationY()
It should implements programmatically. You can do this with ListView if all of your elements show same as each other. With ListView you can do more with your elements so easily.
List View | Android Developers
But if you want change this code rapidly you can use List of TextViews and use it easily:
List<TextView> textViews = null;
public void onCreate(View v) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textViews.add(findViewById(R.id.txtRS));
textViews.add(findViewById(R.id.txtST));
//Initialize other textViews here.
}
public void onClick(View v) {
for (int i = 0; i < textViews.size(); i++) {
textViews.get(i).startAnimation(showLeftBar);
}
}

How do I implement Google Play Game services in my app in Android Studio?

I'm trying to figure out exactly how to implement Google Play Game services in my app. On the Google Play Developer Console I've linked the game the relevant app using the SHA1 key and I know how to add leaderboards and achievements on here. I have also installed the Google Play services and Google Repository to Android Studio and added the dependency into build.gradle (as explained here: http://developer.android.com/google/play-services/setup.html) but I wasn't sure how to do the last 2 steps on that page (creating a Proguard exception and ensuring devices have the Google Play services APK) and if they are necessary - the latter of which even the Google Play Games sample projects don't seem to do.
Moreover, I'm not sure what code I actually need to put in my project to enable leaderboards and achievements, since according to this guide: https://developers.google.com/games/services/android/achievements, I use this code:
Games.Achievements.unlock(mGoogleApiClient, "my_achievement_id");
to unlock an achievement, for example, but there are no instructions on how I set up mGoogleApiClient. I've looked at the sample projects but it's still not clear what I'm supposed to do. Am I meant to copy and paste all of the code into my project? Are there certain sections I'm supposed to copy and paste? Do I have to write my own code for signing in to Google Play Games?
You should use getApiClient() instead of mGoogleApiClient.
Assuming you have an activity with a layout containing four buttons:
Leaderboard button - To launch the leaderboards,
Achievement button - To launch achievements
Sign in and Sign out buttons
For leaderboard, we push scores for best minutes, best distance covered and an overall highscore.
And for achievements, we unlock four achievements - survivor, warrior, lord, pride based on certain conditions.
Here's how you'd go about it:
public class GMSActivity extends BaseGameActivity implements OnClickListener{
Button lead;
Button achv;
final int RC_RESOLVE = 5000, RC_UNUSED = 5001;
//your game score. so we can push to cloud
int hS = 0;
//flags for achievements
boolean survivor;
boolean tribalWarriror;
boolean akonfemLord;
boolean zuluPride;
LinearLayout signInBar;
LinearLayout signOutBar;
Resources r;
private float bestTimeInSeconds;
private int bestTimeInMinutes;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.gms_layout);
r = getResources();
lead = (Button)findViewById(R.id.leaderboards);
achv = (Button)findViewById(R.id.achievements);
hS = loadScores();
findViewById(R.id.sign_in_button).setOnClickListener(this);
findViewById(R.id.sign_out_button).setOnClickListener(this);
lead.setOnClickListener(this);
achv.setOnClickListener(this);
signInBar = (LinearLayout)findViewById(R.id.sign_in_bar);
signOutBar = (LinearLayout)findViewById(R.id.sign_out_bar);
checkForAchievements();
if (isSignedIn()) {
onSignInSucceeded();
}else{
onSignInFailed();
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v == lead){
if (isSignedIn()) {
startActivityForResult(Games.Leaderboards.getAllLeaderboardsIntent(getApiClient()), RC_UNUSED);
} else {
showAlert(getString(R.string.leaderboards_not_available));
}
}else if(v ==achv){
if (isSignedIn()) {
startActivityForResult(Games.Achievements.getAchievementsIntent(getApiClient()), RC_UNUSED);
} else {
showAlert(getString(R.string.achievements_not_available));
}
}else if(v.getId() == R.id.sign_in_button){
beginUserInitiatedSignIn();
}else if(v.getId() == R.id.sign_out_button){
signOut();
hello.setText(getString(R.string.signed_out_greeting));
signInBar.setVisibility(View.VISIBLE);
signOutBar.setVisibility(View.GONE);
}
#Override
public void onSignInFailed() {
hello.setText(getString(R.string.signed_out_greeting));
signInBar.setVisibility(View.VISIBLE);
signOutBar.setVisibility(View.GONE);
}
#Override
public void onSignInSucceeded() {
signInBar.setVisibility(View.GONE);
signOutBar.setVisibility(View.VISIBLE);
// Set the greeting appropriately on main menu
Player p = Games.Players.getCurrentPlayer(getApiClient());
String displayName;
if (p == null) {
// Log.w(TAG, "mGamesClient.getCurrentPlayer() is NULL!");
displayName = "";
} else {
displayName = p.getDisplayName();
}
// hello.setText("Hello, " + displayName);
pushAccomplishments();
Toast.makeText(this, getString(R.string.your_progress_will_be_uploaded),
Toast.LENGTH_LONG).show();
}
//check for achievements and unlock the appropriate ones
void checkForAchievements() {
// Check if each condition is met; if so, unlock the corresponding
// achievement.
bestTimeInSeconds = loadGameBestTimeSec();
if(bestTimeInSeconds >= 900){ //15 minutes
survivor = true;
tribalWarriror = true;
}
}
void pushAccomplishments() {
if (survivor)
Games.Achievements.unlock(getApiClient(), getString(R.string.achievement_survivor));
if (tribalWarriror)
Games.Achievements.unlock(getApiClient(), getString(R.string.achievement_tribal_warrior));
if(bestTimeInSeconds >= 60){ //1 minute atleast
bestTimeInMinutes = (int)bestTimeInSeconds/60;
Games.Leaderboards.submitScore(getApiClient(), getString(R.string.leaderboard_best_time_minutes), bestTimeInMinutes);
}
if(bestTimeInSeconds >= 10){ // 1 meter atleast
int bestDistance = (int)bestTimeInSeconds/10;
Games.Leaderboards.submitScore(getApiClient(), getString(R.string.leaderboard_best_distance_meters), bestDistance);
}
Games.Leaderboards.submitScore(getApiClient(), getString(R.string.leaderboard_top_score_points), hS);
}
#Override
//loading scores and achievements
private int loadScores() {
// TODO Auto-generated method stub
int score = 0;
try{
preferences = new SecurePreferences(getApplicationContext(),
"besiPreferences", "1234", true);
score = Integer.parseInt(preferences.getString("highScore"));
}catch(Exception e){}
return score;
}
private float loadGameBestTimeSec() {
float time = 0;
try{
preferences = new SecurePreferences(getApplicationContext(),
"besiPreferences", "1234", true);
time = Float.parseFloat(preferences.getString("gameTimeSec"));
}catch(Exception e){}
return time;
}
private int loadCalabashesCompleted() {
try{
preferences = new SecurePreferences(getApplicationContext(),
"makolaPref", "1234", true);
return Integer.parseInt(preferences.getString("bookCompleted")== null ? "0" : preferences.getString("bookCompleted"));
}catch(Exception e){
return 0;
}
}
private int loadLevelCompleted() {
try{
preferences = new SecurePreferences(getApplicationContext(),
"makolaPref", "1234", true);
return Integer.parseInt(preferences.getString("levelCompleted")== null ? "0" : preferences.getString("levelCompleted"));
}catch(Exception e){
return 0;
}
}
}

"Mirror" android inside camera in screen view

I have the following java method:
private Camera openFrontFacingCameraGingerbread() {
int cameraCount = 0;
Camera cam = null;
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
cameraCount = Camera.getNumberOfCameras();
for (int camIdx = 0; camIdx < cameraCount; camIdx++) {
Camera.getCameraInfo(camIdx, cameraInfo);
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
try {
cam = Camera.open(camIdx);
} catch (RuntimeException e) {
Toast.makeText(debug, "failed", Toast.LENGTH_LONG).show();
}
}
}
and what I'm looking forward to do is mirror the camera in the screen. This is, as soon as I open the app I would like the user to see himself but I'm not being able to accomplish this.
Here is the onCreate method of the same class:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
openFrontFacingCameraGingerbread();
}
Can someone help me on this one? Thank you very much
You need to include a SurfaceView in your layout, and use setPreviewDisplay() and startPreview(). This will draw the camera's input in your Activity.
You should check the developer guides, and also take a look at Android - Camera Preview

Categories