java.lang.NoClassDefFoundError: com.badlogic.gdx.backends.android.AndroidGL10 android studio - java

i try to run a code of application game 3D but the application don't work in my device and in onglet 'android Monitor' in android studio i have this fatal exception :
07-22 15:40:29.015 22222-22245/? E/AndroidRuntime: FATAL EXCEPTION: GLThread 4132
Process: com.anisbulbul.car.race, PID: 22222
java.lang.NoClassDefFoundError: com.badlogic.gdx.backends.android.AndroidGL10
at com.badlogic.gdx.backends.android.AndroidGraphics.setupGL(AndroidGraphics.java:301)
at com.badlogic.gdx.backends.android.AndroidGraphics.onSurfaceCreated(AndroidGraphics.java:346)
at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1500)
at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1239)
and this is the code of the activity
// Copyright: 2015, anisbulbul
// Home page: http://www.codecanyon.net/user/anisbulbul
package com.anisbulbul.car.race;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.multidex.MultiDex;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import com.anisbulbul.car.race.assets.GameAssets;
import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.games.Games;
import com.google.example.games.basegameutils.GameHelper;
public class MainActivity extends AndroidApplication implements
GameHelper.GameHelperListener, ActionResolver {
protected AdView adViewMain;
private GameHelper gameHelper;
protected View gameView;
AdView adView;
RelativeLayout layout;
private InterstitialAd interstitialAd;
private static final String AD_UNIT_ID_BANNER = "ca-app-pub-8606268298440779/7190429247";
private static final String AD_UNIT_ID_INTERSTITIAL = "ca-app-pub-8606268298440779/5713696049";
private static final String MORE_APPS_URL = "http://codecanyon.net/user/anisbulbul/portfolio";
private static boolean IS_ADMOB_ACTIVE = true;
private static boolean DEBUG = false;
private static boolean IS_PLAY_SERVICE_ACTIVE = true;
private static String GOOGLE_PLAY_URL;
private static String FACEBOOK_SHARE_URL;
private static String TWITTER_SHARE_URL;
private static String GOOGLE_PLUS_SHARE_URL;
private static String BLOG_URL;
#Override
public String[] getAchievmentIDs() {
String achievmentIDs[] = {
getResources().getString(R.string.achievement_bigginer),
getResources().getString(R.string.achievement_starter_good),
getResources().getString(R.string.achievement_race_cup_2),
getResources().getString(R.string.achievement_after_death),
getResources().getString(R.string.achievement_in_the_last_station) };
return achievmentIDs;
}
#Override
protected void attachBaseContext(Context context) {
super.attachBaseContext(context);
MultiDex.install(this);
}
private AdView createAdView() {
this.adViewMain = new AdView(this);
this.adViewMain.setAdSize(AdSize.SMART_BANNER);
this.adViewMain.setAdUnitId(AD_UNIT_ID_BANNER);
this.adViewMain.setId(12345);
LayoutParams var1 = new LayoutParams(-1, -2);
var1.addRule(12, -1);
var1.addRule(14, -1);
this.adViewMain.setLayoutParams(var1);
this.adViewMain.setBackgroundColor(-16777216);
return this.adViewMain;
}
private View createGameView(AndroidApplicationConfiguration var1) {
this.gameView = this.initializeForView(new CarRace3D(this), var1);
LayoutParams var2 = new LayoutParams(-1, -2);
var2.addRule(10, -1);
var2.addRule(14, -1);
var2.addRule(2, this.adViewMain.getId());
this.gameView.setLayoutParams(var2);
return this.gameView;
}
private void startAdvertising(AdView var1) {
var1.loadAd((new AdRequest.Builder()).build());
}
#Override
public void faceBookPost(String fbMessage) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent
.putExtra(
Intent.EXTRA_TEXT,
"https://facebook.com/share?url=https://play.google.com/store/apps/details?id="+getPackageName()+"&title="+fbMessage);
sendIntent.setType("text/plain");
this.startActivity(sendIntent);
}
#Override
public void googlePlusPost(String gplusMessage) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent
.putExtra(
Intent.EXTRA_TEXT,
"https://plus.google.com/share?url=https://play.google.com/store/apps/details?id="+getPackageName()+"&title="+gplusMessage);
sendIntent.setType("text/plain");
this.startActivity(sendIntent);
}
#Override
public void twitterPost(String twMessage) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent
.putExtra(
Intent.EXTRA_TEXT,
"https://twitter.com/intent/tweet?url=https://play.google.com/store/apps/details?id="+getPackageName()+"&related=codecanyon.net&text=i got high score"+twMessage);
sendIntent.setType("text/plain");
this.startActivity(sendIntent);
}
#Override
public void getAchievementsGPGS() {
if (this.gameHelper.isSignedIn()) {
this.startActivityForResult(Games.Achievements
.getAchievementsIntent(this.gameHelper.getApiClient()), 101);
} else if (!this.gameHelper.isConnecting()) {
this.loginGPGS();
return;
}
}
#Override
public void getLeaderboardHighScoreGPGS() {
if (this.gameHelper.isSignedIn()) {
this.startActivityForResult(
Games.Leaderboards.getLeaderboardIntent(
this.gameHelper.getApiClient(),
this.getString(R.string.leaderboard_high_score_race)),
100);
} else if (!this.gameHelper.isConnecting()) {
this.loginGPGS();
return;
}
}
#Override
public void getLeaderboardTrophyGPGS() {
if (this.gameHelper.isSignedIn()) {
this.startActivityForResult(
Games.Leaderboards.getLeaderboardIntent(
this.gameHelper.getApiClient(),
this.getString(R.string.leaderboard_race_trophy)),
100);
} else if (!this.gameHelper.isConnecting()) {
this.loginGPGS();
return;
}
}
#Override
public void getAllLeaderboardGPGS() {
if (this.gameHelper.isSignedIn()) {
this.startActivityForResult(Games.Leaderboards
.getAllLeaderboardsIntent(this.gameHelper.getApiClient()),
1);
} else if (!this.gameHelper.isConnecting()) {
this.loginGPGS();
return;
}
}
#Override
public boolean getSignedInGPGS() {
return this.gameHelper.isSignedIn();
}
#Override
public void loginGPGS() {
if(IS_PLAY_SERVICE_ACTIVE){
try {
this.runOnUiThread(new Runnable() {
public void run() {
MainActivity.this.gameHelper.beginUserInitiatedSignIn();
}
});
} catch (Exception var2) {
;
}
}
}
public void onActivityResult(int var1, int var2, Intent var3) {
super.onActivityResult(var1, var2, var3);
this.gameHelper.onActivityResult(var1, var2, var3);
}
public void onBackPressed() {
GameAssets.isGamePause = true;
if (GameAssets.isGameSound) {
GameAssets.raceMusic.pause();
GameAssets.accidentMusic.pause();
GameAssets.moveMusic.pause();
}
final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_LEFT_ICON);
dialog.setTitle(R.string.app_name);
ScrollView scrollView = new ScrollView(MainActivity.this);
LinearLayout dialogLayout = new LinearLayout(this);
dialogLayout.setOrientation(LinearLayout.VERTICAL);
TextView textView = new TextView(this);
textView.setText(R.string.back_option_text);
textView.setPadding(4, 0, 4, 10);
dialogLayout.addView(textView);
Button resumeButton = new Button(this);
resumeButton.setText("Resume");
resumeButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
GameAssets.isGamePause = false;
}
});
dialogLayout.addView(resumeButton);
Button moreGamesApps = new Button(this);
moreGamesApps.setText("More Games & Apps");
moreGamesApps.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(MORE_APPS_URL)));
dialog.dismiss();
GameAssets.isGamePause = false;
}
});
dialogLayout.addView(moreGamesApps);
Button rateButton = new Button(this);
rateButton.setText("Rate Game");
rateButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(GOOGLE_PLAY_URL)));
dialog.dismiss();
GameAssets.isGamePause = false;
}
});
dialogLayout.addView(rateButton);
Button facebookButton = new Button(this);
facebookButton.setText("Facebook");
facebookButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(FACEBOOK_SHARE_URL)));
dialog.dismiss();
GameAssets.isGamePause = false;
}
});
dialogLayout.addView(facebookButton);
Button twitterButton = new Button(this);
twitterButton.setText("Twitter");
twitterButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(TWITTER_SHARE_URL)));
dialog.dismiss();
GameAssets.isGamePause = false;
}
});
dialogLayout.addView(twitterButton);
Button googlePlusButton = new Button(this);
googlePlusButton.setText("Google Plus");
googlePlusButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(GOOGLE_PLUS_SHARE_URL)));
dialog.dismiss();
GameAssets.isGamePause = false;
}
});
dialogLayout.addView(googlePlusButton);
Button blogButton = new Button(this);
blogButton.setText("Blog");
blogButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(BLOG_URL)));
dialog.dismiss();
GameAssets.isGamePause = false;
}
});
dialogLayout.addView(blogButton);
Button quitButton = new Button(this);
quitButton.setText("Quit");
quitButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
finish();
}
});
dialogLayout.addView(quitButton);
scrollView.addView(dialogLayout);
dialog.setContentView(scrollView);
dialog.show();
dialog.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,
R.drawable.icon);
}
public void onCreate(Bundle var1) {
super.onCreate(var1);
this.getWindow().addFlags(128);
AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration();
cfg.useGL20 = false;
cfg.useAccelerometer = true;
cfg.useCompass = false;
FACEBOOK_SHARE_URL = "https://www.facebook.com/sharer/sharer.php?display=popup&u=http%3A%2F%2Fcodecanyon.net%2Fitem%2Frecorder-and-equalizer-player-with-effect%2F9904887%3Futm_source%3Dsharefb";
GOOGLE_PLAY_URL = "https://play.google.com/store/apps/developer?id="
+ getPackageName();
TWITTER_SHARE_URL = "https://twitter.com/intent/tweet?text=Check+out+%27Recorder+and+Equalizer+Player+with+Effect%27+on+%23EnvatoMarket+%23codecanyon&url=http%3A%2F%2Fcodecanyon.net%2Fitem%2Frecorder-and-equalizer-player-with-effect%2F9904887%3Futm_source%3Dsharetw";
GOOGLE_PLUS_SHARE_URL = "https://plus.google.com/share?url=http%3A%2F%2Fcodecanyon.net%2Fitem%2Frecorder-and-equalizer-player-with-effect%2F9904887%3Futm_source%3Dsharegp";
BLOG_URL = "http://anisbulbul.blogspot.com/";
this.requestWindowFeature(1);
this.getWindow().setFlags(1024, 1024);
this.getWindow().clearFlags(2048);
layout = new RelativeLayout(this);
layout.setLayoutParams(new LayoutParams(-1, -1));
adView = this.createAdView();
// layout.addView(adView);
layout.addView(this.createGameView(cfg));
this.setContentView(layout);
this.startAdvertising(adView);
this.interstitialAd = new InterstitialAd(this);
this.interstitialAd.setAdUnitId(AD_UNIT_ID_INTERSTITIAL);
interstitialAd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
if(DEBUG){
Toast.makeText(getApplicationContext(),
"Finished Loading Interstitial", Toast.LENGTH_SHORT)
.show();
}
}
#Override
public void onAdClosed() {
if(DEBUG){
Toast.makeText(getApplicationContext(), "Closed Interstitial",
Toast.LENGTH_SHORT).show();
}
}
});
if (this.gameHelper == null) {
this.gameHelper = new GameHelper(this, 1);
this.gameHelper.enableDebugLog(true);
}
this.gameHelper.setup(this);
}
#Override
public void onSignInFailed() {
}
#Override
public void onSignInSucceeded() {
}
#Override
public void onStart() {
super.onStart();
if(IS_PLAY_SERVICE_ACTIVE){
this.gameHelper.onStart(this);
}
}
#Override
public void onStop() {
super.onStop();
if(IS_PLAY_SERVICE_ACTIVE){
this.gameHelper.onStop();
}
}
#Override
public void openUri(String uri) {
this.startActivity(new Intent("android.intent.action.VIEW", Uri
.parse(uri)));
}
#Override
public void quitApplication() {
}
#Override
public void submitScoreGPGS(long score) {
if(this.gameHelper.isSignedIn()){
Games.Leaderboards.submitScore(this.gameHelper.getApiClient(),
this.getString(R.string.leaderboard_high_score_race), score);
} else if (!this.gameHelper.isConnecting()) {
this.loginGPGS();
return;
}
}
#Override
public void submitTrophyGPGS(long score) {
if(this.gameHelper.isSignedIn()){
Games.Leaderboards.submitScore(this.gameHelper.getApiClient(),
this.getString(R.string.leaderboard_race_trophy), score);
} else if (!this.gameHelper.isConnecting()) {
this.loginGPGS();
return;
}
}
#Override
public void unlockAchievementGPGS(String achievementId) {
if(this.gameHelper.isSignedIn()){
Games.Achievements
.unlock(this.gameHelper.getApiClient(), achievementId);
} else if (!this.gameHelper.isConnecting()) {
this.loginGPGS();
return;
}
}
#Override
public void showRated() {
try {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id="
+ getPackageName())));
} catch (ActivityNotFoundException e) {
}
}
#Override
public void showShare() {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, " Brain Puzzle Game "
+ " Visit: http://play.google.com/store/apps/details?id="
+ getPackageName());
sendIntent.setType("text/plain");
startActivity(sendIntent);
}
public void addLayout() {
try {
runOnUiThread(new Runnable() {
public void run() {
if (interstitialAd.isLoaded()) {
layout.addView(adView);
}
}
});
} catch (Exception e) {
}
}
#Override
public void showOrLoadInterstital() {
if (IS_ADMOB_ACTIVE) {
try {
runOnUiThread(new Runnable() {
public void run() {
addLayout();
if (interstitialAd.isLoaded()) {
interstitialAd.show();
if(DEBUG){
Toast.makeText(getApplicationContext(),
"Showing Interstitial", Toast.LENGTH_SHORT)
.show();
}
} else {
AdRequest interstitialRequest = new AdRequest.Builder()
.build();
interstitialAd.loadAd(interstitialRequest);
if(DEBUG){
Toast.makeText(getApplicationContext(),
"Loading Interstitial", Toast.LENGTH_SHORT)
.show();
}
}
}
});
} catch (Exception e) {
}
}
}
}
build.gradle file :
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion "25.0.3"
defaultConfig {
applicationId "com.anisbulbul.car.race"
minSdkVersion 9
targetSdkVersion 25
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
}
dependencies {
compile project(':_3DCarRace')
compile 'com.android.support:multidex:1.0.1'
compile 'com.google.android.gms:play-services:5.+'
//compile files('libs/gdx-backend-android-sources.jar')
//compile files('libs/gdx-backend-android.jar')
//compile "com.android.support:support-v7:25.3.1"
compile 'com.deadpan-gamez:libGdx-game-common:1.22'
compile fileTree(include: ['*.jar'], dir: 'libs')
}
i try to fix it but no solution
Thank you in advance.

Related

My android radio app automatically close when I click back button

I am trying to run my Android radio app in the background. So when I click the back button after a little time it has been forced to stop. Automatically calls the onDestroy() method. How do I fix this problem?
This is the main activity class onBackPressed() button code.
#Override
public void onBackPressed(){
System.out.println("onBackPressed");
serviceIntent.addCategory(Intent.CATEGORY_HOME);
serviceIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(serviceIntent);
moveTaskToBack(true);
//activity.moveTaskToBack(true);
}
This is the console log
> I/System.out: onPrepared I/System.out: onBackPressed I/System.out:
> onDestroy I/System.out: onDestroy1 I/System.out: onDestroy2
> V/MediaPlayer: resetDrmState: mDrmInfo=null
> mDrmProvisioningThread=null mPrepareDrmInProgress=false
> mActiveDrmScheme=false V/MediaPlayer: cleanDrmObj: mDrmObj=null
> mDrmSessionId=null W/MediaPlayer: mediaplayer went away with unhandled
> events
MainActivity
package com.jiat.yesradio;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements MusicStoppedListener {
private ImageView imagePlayPause;
String stream = "https://radio.lankayes.lk/8002/stream";
boolean musicPlaying = false;
Intent serviceIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
System.out.println("onCreate MainA");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imagePlayPause = (ImageView) findViewById(R.id.imagePlayPause);
imagePlayPause.setImageResource(R.drawable.play_icon);
serviceIntent = new Intent(this, MyPlayService.class);
// serviceIntent = new Intent(this, SimpleMyPlayService.class);
ApplicationClass.context = (Context) MainActivity.this;
imagePlayPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("onClick");
if (!musicPlaying) {
System.out.println("onClick_inside_music_player");
startService(serviceIntent);
playAudio();
imagePlayPause.setImageResource(R.drawable.pause_icon);
musicPlaying = true;
}
else {
stopPlayService();
stopService(serviceIntent);
imagePlayPause.setImageResource(R.drawable.play_icon);
musicPlaying = false;
}
}
});
}
#Override
public void onBackPressed(){
System.out.println("onBackPressed");
/* serviceIntent.addCategory(Intent.CATEGORY_HOME);
serviceIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(serviceIntent);*/
moveTaskToBack(true); //activity.moveTaskToBack(true);
}
private void stopPlayService() {
System.out.println("stopPlayService");
try {
stopService(serviceIntent);
} catch (SecurityException e) {
Toast.makeText(this, "Error:" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
private void playAudio() {
System.out.println("playAudio");
serviceIntent.putExtra("AudioLink", stream);
// serviceIntent.putExtra("SimpleAudioLink", stream);
try {
startService(serviceIntent);
} catch (SecurityException e) {
Toast.makeText(this, "Error:" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onMusicStopped() {
System.out.println("onMusicStopped");
imagePlayPause.setImageResource(R.drawable.play_icon);
musicPlaying = false;
}
}
MyPlayService class.
package com.jiat.yesradio;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.widget.Toast;
public class MyPlayService extends Service implements MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener,
MediaPlayer.OnErrorListener, MediaPlayer.OnSeekCompleteListener, MediaPlayer.OnInfoListener,
MediaPlayer.OnBufferingUpdateListener {
private MediaPlayer mediaPlayer;
String link;
private MusicStoppedListener musicStoppedListener;
Context context;
public MyPlayService() {
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
System.out.println("onBind");
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate() {
super.onCreate();
System.out.println("onCreate");
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnErrorListener(this);
mediaPlayer.setOnSeekCompleteListener(this);
mediaPlayer.setOnInfoListener(this);
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setLooping(true);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
System.out.println("onStartCommand");
link = intent.getStringExtra("AudioLink");
mediaPlayer.reset();
musicStoppedListener = (MusicStoppedListener) ApplicationClass.context;
if (!mediaPlayer.isPlaying()) {
try {
mediaPlayer.setDataSource(link);
mediaPlayer.prepareAsync();
} catch (Exception e) {
Toast.makeText(this, "Error:" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
System.out.println("onDestroy");
if (mediaPlayer != null) {
System.out.println("onDestroy1");
if (mediaPlayer.isPlaying()) {
System.out.println("onDestroy2");
mediaPlayer.stop();
}
mediaPlayer.release();
}
}
#Override
public void onBufferingUpdate(MediaPlayer mediaPlayer, int i) {
System.out.println("onBufferingUpdate");
}
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
/* if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
musicStoppedListener.onMusicStopped();
stopSelf();*/
System.out.println("onCompletion");
}
#Override
public boolean onError(MediaPlayer mediaPlayer, int what, int i1) {
System.out.println("onError");
switch (what) {
case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
Toast.makeText(this, "MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK", Toast.LENGTH_SHORT).show();
break;
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
Toast.makeText(this, "MEDIA_ERROR_SERVER_DIED", Toast.LENGTH_SHORT).show();
break;
case MediaPlayer.MEDIA_ERROR_UNKNOWN:
Toast.makeText(this, "MEDIA_ERROR_UNKNOWN", Toast.LENGTH_SHORT).show();
break;
}
return false;
}
#Override
public boolean onInfo(MediaPlayer mediaPlayer, int i, int i1) {
System.out.println("onInfo");
return false;
}
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
System.out.println("onPrepared");
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
}
}
#Override
public void onSeekComplete(MediaPlayer mediaPlayer) {
System.out.println("onSeekComplete");
}
}

I am working on OCR reader application. below is my java code. My question is how to start another method if one is completed?

When the user captures the image, the device will automatically read aloud the text. for that i have implemented texttospeech method but when this activity stop i want to start another task. how will it can be done?
After reading the captured text, I want to implement another text-to-speech method how can i do this?
package com.example.software2.ocrhy;
import static android.Manifest.permission.CAMERA;
import android.Manifest;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.Detector;
import com.google.android.gms.vision.text.TextBlock;
import com.google.android.gms.vision.text.TextRecognizer;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;
public class MainActivity2 extends AppCompatActivity {
private static final int REQUEST_SPEECH = 101;
private static final int REQ_CODE_SPEECH_INPUT = 100;
Button buttonCamera;
private Button button;
private TextView mVoiceInputTv;
private TextView textView;
private SurfaceView surfaceView;
private CameraSource cameraSource;
private TextRecognizer textRecognizer;
private static TextToSpeech textToSpeech;
private String stringResult = null;
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
mVoiceInputTv = (TextView) findViewById(R.id.textView);
textView = (TextView) findViewById(R.id.textView);
getWindow().getDecorView().setBackgroundColor(Color.WHITE);
ActivityCompat.requestPermissions(this, new String[]{CAMERA}, PackageManager.PERMISSION_GRANTED);
textToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
textToSpeech.setLanguage(Locale.CANADA);
textToSpeech.setSpeechRate(1f);
Toast.makeText(MainActivity2.this, "tap on the screen and say yes for read and no for return to the main menu", Toast.LENGTH_SHORT).show();
textToSpeech.speak("tap on the screen and say yes for read and no for return to the main menu", TextToSpeech.QUEUE_ADD, null);
}
}
});
}
private void textRecognizer() {
Toast.makeText(MainActivity2.this, "Tap on the screen and listen ", Toast.LENGTH_SHORT).show();
textToSpeech.speak(" Tap on the screen take a picture of any text with your device and listen", TextToSpeech.QUEUE_FLUSH, null);
textRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
cameraSource = new CameraSource.Builder(getApplicationContext(), textRecognizer)
.setRequestedPreviewSize(1280, 1024)
.setAutoFocusEnabled(true)
.build();
surfaceView = findViewById(R.id.surfaceView);
Context context = this;
surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
return;
}
cameraSource.start(surfaceView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
}
private void capture() {
textRecognizer.setProcessor(new Detector.Processor<TextBlock>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<TextBlock> detections) {
SparseArray<TextBlock> sparseArray = detections.getDetectedItems();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < sparseArray.size(); ++i) {
TextBlock textBlock = sparseArray.valueAt(i);
if (textBlock != null && textBlock.getValue() != null) {
stringBuilder.append(textBlock.getValue() + " ");
}
}
final String stringText = stringBuilder.toString();
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
stringResult = stringText;
resultObtained();
}
});
}
});
}
private void resultObtained() {
setContentView(R.layout.activity_main2);
textView = findViewById(R.id.textView);
textView.setText(stringResult);
textToSpeech.speak(stringResult, TextToSpeech.QUEUE_FLUSH, null, null);
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startVoiceInput();
}
});
}
private void startVoiceInput() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Hello, How can I help you?");
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
mVoiceInputTv.setText(result.get(0));
}
if (mVoiceInputTv.getText().toString().contentEquals("time and date")) {
Intent intent = new Intent(getApplicationContext(), MainActivity4.class);
startActivity(intent);
}
if (mVoiceInputTv.getText().toString().contentEquals("battery")) {
Intent intent = new Intent(getApplicationContext(), MainActivity6.class);
startActivity(intent);
mVoiceInputTv.setText(null);
}
if (mVoiceInputTv.getText().toString().contentEquals("location")) {
Intent intent = new Intent(getApplicationContext(), MainActivity8.class);
startActivity(intent);
mVoiceInputTv.setText(null);
}
if (mVoiceInputTv.getText().toString().contentEquals("weather")) {
Intent intent = new Intent(getApplicationContext(), MainActivity5.class);
startActivity(intent);
mVoiceInputTv.setText(null);
} else {
textToSpeech.speak( "Do not understand just tap on the screen Say again", TextToSpeech.QUEUE_FLUSH, null);
}
if (mVoiceInputTv.getText().toString().contentEquals("calculator")) {
Intent intent = new Intent(getApplicationContext(), MainActivity3.class);
startActivity(intent);
mVoiceInputTv.setText(null);
}
else if(mVoiceInputTv.getText().toString().contentEquals("exit")) {
finish();
}
else {
textToSpeech.speak("Do not understand just tap on the screen Say again", TextToSpeech.QUEUE_FLUSH, null);
}
if (mVoiceInputTv.getText().toString().contentEquals("yes")) {
setContentView(R.layout.surface);
surfaceView = findViewById(R.id.surfaceView);
surfaceView.setOnClickListener((View v) -> {
capture();
});
textRecognizer();
mVoiceInputTv.setText(null);
} else if (mVoiceInputTv.getText().toString().contentEquals("no")) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
break;
}
}
}
public boolean onKeyDown(int keyCode, #Nullable KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_VOLUME_UP){
textToSpeech.speak("You are in main menu. just swipe right and say what you want", TextToSpeech.QUEUE_FLUSH, null);
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
final Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
#Override
public void run() {
textToSpeech.speak("you are in main menu. just swipe right and say what you want", TextToSpeech.QUEUE_FLUSH, null);
}
},1000);
}
return true;
}
public void buttonStart(View view) {
startVoiceInput();
}
public void onPause() {
if (textToSpeech != null) {
textToSpeech.stop();
}
super.onPause();
}
}
just use the same mode on text to speech ADD and it will play when the first one is done, ADD = ADD, FLUSH = reset
textToSpeech.speak("this will play when first is done",
TextToSpeech.QUEUE_ADD, null);
You have to call startVoiceInput() again.
You are setting this call for an onClick() handler on a TextView already.

Pass username to another activity with RewardedAd

The problem is that I am trying to pass the name of the user when the adReward is complete to another activity. But I'm stuck in this activity, even though the video ad is loaded. (and it works well while there are no video ad to show). Here is my code:
My java.class
public class TheDay1 extends AppCompatActivity implements RewardedVideoAdListener {
Vibrator vibrator;
private RewardedVideoAd HDay1;
int currentActivity = 0;
boolean flag;
private EditText vname;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_the_day1);
vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
MobileAds.initialize(this,
"ca-app-pub-3940256099942544/6300978111");
///ADD BAN
AdView mAdView = findViewById(R.id.banner1);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
///////////////////////////////////
//VIDEO
HDay1 = MobileAds.getRewardedVideoAdInstance(this);
HDay1.setRewardedVideoAdListener(this);
loadRewardedVideoDAY1();
vname = findViewById(R.id.name);
final ImageView nm = findViewById(R.id.ID);
nm.setVisibility(View.INVISIBLE);
ColorMatrix matrix = new ColorMatrix();
matrix.setSaturation(0);
ColorMatrixColorFilter filter = new ColorMatrixColorFilter(matrix);
nm.setColorFilter(filter);
final Button closeAd = findViewById(R.id.closeDay1);
closeAd.setVisibility(View.INVISIBLE);
///////////////////////////////////////////////////////////////////////////////////////////
closeAd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
vibrator.vibrate(50);
loadRewardedVideoDAY1();
if (HDay1.isLoaded()) {
HDay1.show();
setCurrent(1);
}
String name = vname.getText().toString();
getusername(name);
}
});
}
////////////////////////////////////////////////////////////////
private void Day1() {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
private void getusername(String name) {
Intent intent = new Intent(this, ActivityTwo.class);
Resources resources = getResources();
String key = resources.getString(R.string.key_name);
intent.putExtra(key, name);
startActivity(intent);
}
private void loadRewardedVideoDAY1() {
if (!HDay1.isLoaded()) {
HDay1 = null;
HDay1 = MobileAds.getRewardedVideoAdInstance(this);
HDay1.setRewardedVideoAdListener(this);
///////////////TEST ID//////////////////
HDay1.loadAd("ca-app-pub-3940256099942544/5224354917", new AdRequest.Builder().build());
}
}
#Override
public void onRewardedVideoAdLoaded() {
Log.d("LOADED!", "onRewardedVideoAdLoaded");
}
#Override
public void onRewardedVideoAdOpened() {
Log.d("OPENED!", "onRewardedVideoAdLoaded");
}
#Override
public void onRewardedVideoStarted() {
Log.d("STARTED!", "onRewardedVideoAdLoaded");
}
#Override
public void onRewardedVideoAdClosed() {
loadRewardedVideoDAY1();
if (currentActivity == 1) {
Day1();
}
}
#Override
public void onRewarded(RewardItem rewardItem) {
loadRewardedVideoDAY1();
flag = true;
if (currentActivity == 1) {
Day1();
}
}
#Override
public void onRewardedVideoAdLeftApplication() {
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
}
#Override
public void onRewardedVideoCompleted() {
}
#Override
protected void onPause() {
HDay1.pause(this);
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
public void setCurrent(int val){
currentActivity = val;
}
Any idea what the problem could be? Thanks in advance
Try below code. Update ProcessData with your intent logic and update oncreate with other data required in your class
public class TheDay1 extends AppCompatActivity implements RewardedVideoAdListener {
private RewardedVideoAd mRewardedVideoAd;
private Boolean bRewardVideo = false;
#Override
public void onResume() {
super.onResume();
if (mRewardedVideoAd != null) {
mRewardedVideoAd.resume(this);
}
}
#Override
public void onPause() {
super.onPause();
if (mRewardedVideoAd != null) {
mRewardedVideoAd.pause(this);
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (mRewardedVideoAd != null) {
mRewardedVideoAd.destroy(this);
}
}
#Override
public void onRewardedVideoCompleted() {
//Toast.makeText(this, "onRewardedVideoCompleted", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdLoaded() {
//Toast.makeText(this, "onRewardedVideoAdLoaded", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdOpened() {
//Toast.makeText(this, "onRewardedVideoAdOpened", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoStarted() {
//Toast.makeText(this, "onRewardedVideoStarted", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdClosed() {
//Toast.makeText(this, "Reward Video Closed", Toast.LENGTH_SHORT).show();
// Load the next rewarded video ad.
if (bRewardVideo) {
ProcessData();
} else {
Toast.makeText(this, "Please View Reward Video to get Reward Points", Toast.LENGTH_LONG).show();
}
loadRewardedVideoAd();
}
#Override
public void onRewarded(RewardItem rewardItem) {
Toast.makeText(this, "Now you can close Ad to Process", Toast.LENGTH_LONG).show();
bRewardVideo = true;
}
#Override
public void onRewardedVideoAdLeftApplication() {
//Toast.makeText(this, "onRewardedVideoAdLeftApplication",Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
Toast.makeText(this, "Fail to Load Reward Video. Please try again!", Toast.LENGTH_SHORT).show();
}
private void loadRewardedVideoAd() {
bRewardVideo = false;
mRewardedVideoAd.loadAd(BuildConfig.REWARDVIDEOID,
new AdRequest.Builder().build());
}
private void ProcessData() {
Snackbar.make(findViewById(R.id.drawer_layout_law), "Please wait while we process the request... ", Snackbar.LENGTH_INDEFINITE).show();
//WRITE YOUR INTENT CODE HERE
Intent intent = new Intent(this, ActivityTwo.class);
Resources resources = getResources();
String key = resources.getString(R.string.key_name);
intent.putExtra(key, name);
startActivity(intent);
}
private void ShowRewardVideoDialog() {
if (mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.show();
} else {
loadRewardedVideoAd();
Toast.makeText(mctx, "Fail to Load Reward Video : Please try again", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
mRewardedVideoAd.setRewardedVideoAdListener(this);
loadRewardedVideoAd();
}
}

Bluetooth Callback funtion onCharacteristicRead is not making Intent call to another activity Working with <API21. Not in Marshmallow

I am trying to make an intent call from Bluetooth Low Energy Callback function onCharacteristicRead(). Please suggest me where i am wrong .
I am not sure if it is related to the context which we give to the intent class or some thing else.
It is showing me below error :
"Unable to start activity ComponentInfo::java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference"
Below is the code sample :
package com.example.pushkara.msable;
import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.ParcelUuid;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.logging.ConsoleHandler;
#TargetApi(18)
public class MainActivity extends AppCompatActivity {
private BluetoothAdapter mBluetoothAdapter;
private int REQUEST_ENABLE_BT = 1;
private Handler mHandler;
private static final long SCAN_PERIOD = 5000;
private BluetoothLeScanner mLEScanner;
private ScanSettings settings;
private List<ScanFilter> filters;
private BluetoothGatt mGatt;
private MsaScanCallback mScanCallback;
private Button mCheckInButton;
private Button mCheckOutButton;
private Button mNewButton;
private Boolean buttonvalue = false;
public static TextView mSecurityCode;
public static TextView rssiNdistance;
public final static UUID UUID_MSA_APP = UUID.fromString("13333333-3333-3333-3333-333333333337");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCheckInButton = (Button)findViewById(R.id.checkIn);
mCheckOutButton = (Button)findViewById(R.id.checkOut);
mSecurityCode= (TextView)findViewById(R.id.securityCode);
rssiNdistance= (TextView)findViewById(R.id.rssiNdistance);
mCheckOutButton.setOnClickListener(new MsaCheckInCheckout(false));
mCheckInButton.setOnClickListener(new MsaCheckInCheckout(true));
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("This app needs location access");
builder.setMessage("Please grant location access so this app can detect msa server.");
builder.setPositiveButton(android.R.string.ok, null);
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#TargetApi(Build.VERSION_CODES.M)
#Override
public void onDismiss(DialogInterface dialog) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
}
});
builder.show();
}
}
mHandler = new Handler();
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, "BLE Not Supported",
Toast.LENGTH_SHORT).show();
finish();
}
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
}
catch(Exception ex){
Log.i("msable"," [##MA]::::Exception 1" +ex.toString());
mSecurityCode.setText("[##MA]Exc1" + ex.toString());
}
}
private final ConnectDevice connectToDeviceCallback = new ConnectDevice() {
#Override
public void OnConnectToDevice(BluetoothDevice device){
connectToDevice(device);
}
};
public class MsaCheckInCheckout implements View.OnClickListener {
private boolean mCheckIn;
public MsaCheckInCheckout(boolean isCheckIn){
mCheckIn =isCheckIn;
}
#Override
public void onClick (View v) {
try {
// your code here;
Log.i("CLICK", mCheckIn + "");
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
} else {
if (Build.VERSION.SDK_INT >= 21) {
if (mGatt != null) {
mGatt.close();
mGatt = null;
}
mScanCallback = new MsaScanCallback(connectToDeviceCallback);
mLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
settings = new ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
.build();
ScanFilter filter = new ScanFilter.Builder().setServiceUuid(new ParcelUuid(UUID_MSA_APP)).build();
filters = new ArrayList<>();
filters.add(filter);
}
scanLeDevice(true);
}
}
catch(Exception ex){
Log.i("msable","[##MA] ::::Exception 2" +ex.toString());
mSecurityCode.setText("[##MA]Ex2" + ex.toString());
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[], #NonNull int[] grantResults) {
try {
switch (requestCode) {
case 1: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.d("1", "coarse location permission granted");
} else {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Functionality limited");
builder.setMessage("Since location access has not been granted, this app will not be able to discover msa server");
builder.setPositiveButton(android.R.string.ok, null);
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
}
});
builder.show();
}
}
}
}
catch(Exception ex){
Log.i("msable","[##MA] ::::Exception 3" +ex.toString());
mSecurityCode.setText("[##MA]Ex3" + ex.toString());
}
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
if (mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()) {
scanLeDevice(false);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mGatt == null) {
return;
}
mGatt.close();
mGatt = null;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
if (requestCode == REQUEST_ENABLE_BT) {
if (resultCode == Activity.RESULT_CANCELED) {
//Bluetooth not enabled.
finish();
return;
}
}
super.onActivityResult(requestCode, resultCode, data);
}
catch(Exception ex){
Log.i("msable","[##MA] ::::Exception 4" +ex.toString());
mSecurityCode.setText("[##MA]Ex4" + ex.toString());
}
}
private void scanLeDevice(final boolean enable) {
try {
Log.i("BLE", "**** scanLeDevice");
if(mBluetoothAdapter != null || mLEScanner !=null) {
Log.i("BLE", "**** Object not null proceed to stop scan");
if (enable) {
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
if (Build.VERSION.SDK_INT < 21) {
mBluetoothAdapter.stopLeScan(mLeScanCallback);
Log.i("BLE", "mBluetoothAdapter STOP SCAN");
} else {
Log.i("BLE", "mLEScanner STOP SCAN");
if(mLEScanner !=null) {
Log.i("BLE", "mLEScanner not null proceed for stop ");
}
else
{
Log.i("BLE", "mLEScanner is null !!!!!");
}
mLEScanner.stopScan(mScanCallback);
}
}
}, SCAN_PERIOD);
if (Build.VERSION.SDK_INT < 21) {
mBluetoothAdapter.startLeScan(mLeScanCallback);
Log.i("BLE", "mBluetoothAdapter START SCAN");
} else {
Log.i("START SCAN", "START SCAN");
mLEScanner.startScan(filters, settings, mScanCallback);
}
} else {
if (Build.VERSION.SDK_INT < 21) {
mBluetoothAdapter.stopLeScan(mLeScanCallback);
} else {
mLEScanner.stopScan(mScanCallback);
}
}
}
else
{
Log.i("BLE","**** Object is null");
}
}
catch(Exception ex){
Log.i("msable","[##MA] ::::Exception 5" +ex.toString());
mSecurityCode.setText("[##MA]Ex5" + ex.toString());
}
}
double getDistance(int rssi) {
return Math.pow(10d, ((double) -52 - rssi) / (10 * 2));
}
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
#Override
public void onLeScan(final BluetoothDevice device, final int rssi,
byte[] scanRecord) {
try {
Log.i("BLE","**** onLeScan LeScanCallback");
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.i("onLeScan", device.toString());
double distance = getDistance(rssi);
rssiNdistance.setText("rssi:"+rssi+" distance:"+distance);
if (distance <= 1) {
connectToDevice(device);
}
else{
mSecurityCode.setText("Out of Range!!!");
}
}
});
}
catch(Exception ex){
Log.i("msable","[##MA] ::::Exception 6" +ex.toString());
mSecurityCode.setText("[##MA]Ex6" + ex.toString());
}
}
};
public void connectToDevice(BluetoothDevice device) {
Log.i("BLE","**** connectToDevice");
if (mGatt == null) {
mGatt = device.connectGatt(this, false, gattCallback);
scanLeDevice(false);// will stop after first device detection
}else{
Log.i("gatt status","ATT");
}
}
private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
#Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
try {
Log.i("BLE","**** gattCallback onConnectionStateChange Status: "+status);
Log.i("onConnectionStateChange", "Status: " + status);
switch (newState) {
case BluetoothProfile.STATE_CONNECTED:
Log.i("gattCallback", "STATE_CONNECTED");
gatt.discoverServices();
break;
case BluetoothProfile.STATE_DISCONNECTED:
Log.e("gattCallback", "STATE_DISCONNECTED");
break;
default:
Log.e("gattCallback", "STATE_OTHER");
}
}
catch(Exception ex){
Log.i("msable","[##MA] ::::Exception 7" +ex.toString());
mSecurityCode.setText("[##MA]Ex7" + ex.toString());
}
}
#Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
try {
Log.i("BLE","**** onServicesDiscovered Status: "+status);
List<BluetoothGattService> services = gatt.getServices();
for (BluetoothGattService bg : services) {
Log.i(bg.toString(), bg.getUuid().toString());
if (UUID_MSA_APP.equals(bg.getUuid())) {
Log.i("MSA APP", "found");
BluetoothGattCharacteristic msacode = bg.getCharacteristics().get(0);
//gatt.setCharacteristicNotification(msacode, true);
gatt.readCharacteristic(msacode);
Log.i("BLE", "**** BluetoothGattCharacteristic msacode: " + msacode.toString());
}
else{
Log.i("MSA APP", "UUID_MSA_APP not Matching found");
}
}
}
catch(Exception ex){
Log.i("msable","[##MA] ::::Exception 8" +ex.toString());
mSecurityCode.setText("[##MA]Ex8" + ex.toString());
}
}
#Override
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic
characteristic, int status) {
try {
Log.i("BLE","**** onCharacteristicRead Status: "+status);
final byte[] data = characteristic.getValue();
if (data != null && data.length > 0) {
final StringBuilder stringBuilder = new StringBuilder(data.length);
for (byte byteChar : data)
stringBuilder.append(String.format("%02X ", byteChar));
Log.i("onCharacteristicRead", new String(data));
runOnUiThread(new Runnable() {
#Override
public void run() {
mSecurityCode.setText(new String(data));
Intent intent = new Intent(MainActivity.this, newActivity.class);
intent.putExtra("UniqueCode", new String(data));
startActivity(intent);
}
});
}
gatt.disconnect();
}
catch(Exception ex){
Log.i("msable","[##MA] ::::Exception 9" +ex.toString());
mSecurityCode.setText("[##MA]Ex9" + ex.toString());
}
}
};
}
In callback need to give intent a static context and had to set intent FLAG_ACTIVITY_NEW_TASK flag.
#Override
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic
characteristic, int status) {
try {
//Reads the requested characteristic and get the characteristic value.
final byte[] data = characteristic.getValue();
if (data != null && data.length > 0) {
final StringBuilder stringBuilder = new StringBuilder(data.length);
for (byte byteChar : data)
stringBuilder.append(String.format("%02X ", byteChar));
Intent intent = new Intent(callBackContext, InOutActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
callBackContext.startActivity(intent);
}
}
catch(Exception ex){
dbObj.PutLog("[##MA]EX7" + ex.toString());
}
finally{
if(gatt != null){
dbObj.PutLog("[MA] 5 CLOSE GATT");
gatt.disconnect();
gatt.close();
}
}
}
};
Here callBackContext.startActivity(intent); is a Static context given to intent. this solved my purpose
It seems that mSecurityCode is causing the exception. Please post the code where you initialize or write to that variable, and also where you setup the Bluetooth callback.

My face book app is not worrking when nativefacebook app installed

package com.facebook.samples.hellofacebook;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.*;
import com.facebook.model.GraphObject;
import com.facebook.model.GraphPlace;
import com.facebook.model.GraphUser;
import com.facebook.widget.*;
import java.util.*;
public class HelloFacebookSampleActivity extends FragmentActivity {
private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
private static final Location SEATTLE_LOCATION = new Location("") {
{
setLatitude(47.6097);
setLongitude(-122.3331);
}
};
private final String PENDING_ACTION_BUNDLE_KEY = "com.facebook.samples.hellofacebook:PendingAction";
private Button postStatusUpdateButton;
private Button postPhotoButton;
private Button pickFriendsButton;
private Button pickPlaceButton;
private LoginButton loginButton;
private ProfilePictureView profilePictureView;
private TextView greeting;
private PendingAction pendingAction = PendingAction.NONE;
private ViewGroup controlsContainer;
private GraphUser user;
private enum PendingAction {
NONE,
POST_PHOTO,
POST_STATUS_UPDATE
}
private UiLifecycleHelper uiHelper;
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
onSessionStateChange(session, state, exception);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(this, callback);
uiHelper.onCreate(savedInstanceState);
if (savedInstanceState != null) {
String name = savedInstanceState.getString(PENDING_ACTION_BUNDLE_KEY);
pendingAction = PendingAction.valueOf(name);
}
setContentView(R.layout.mainfb);
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions(Arrays.asList("email", "user_birthday"));
loginButton.setLoginBehavior(SessionLoginBehavior.SSO_WITH_FALLBACK);
loginButton.setUserInfoChangedCallback(new LoginButton.UserInfoChangedCallback() {
#Override
public void onUserInfoFetched(GraphUser user) {
HelloFacebookSampleActivity.this.user = user;
updateUI();
// It's possible that we were waiting for this.user to be populated in order to post a
// status update.
handlePendingAction();
}
});
profilePictureView = (ProfilePictureView) findViewById(R.id.profilePicture);
greeting = (TextView) findViewById(R.id.greeting);
postStatusUpdateButton = (Button) findViewById(R.id.postStatusUpdateButton);
postStatusUpdateButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onClickPostStatusUpdate();
}
});
postPhotoButton = (Button) findViewById(R.id.postPhotoButton);
postPhotoButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onClickPostPhoto();
}
});
pickFriendsButton = (Button) findViewById(R.id.pickFriendsButton);
pickFriendsButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onClickPickFriends();
}
});
pickPlaceButton = (Button) findViewById(R.id.pickPlaceButton);
pickPlaceButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onClickPickPlace();
}
});
controlsContainer = (ViewGroup) findViewById(R.id.main_ui_container);
final FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragment_container);
if (fragment != null) {
// If we're being re-created and have a fragment, we need to a) hide the main UI controls and
// b) hook up its listeners again.
controlsContainer.setVisibility(View.GONE);
if (fragment instanceof FriendPickerFragment) {
setFriendPickerListeners((FriendPickerFragment) fragment);
} else if (fragment instanceof PlacePickerFragment) {
setPlacePickerListeners((PlacePickerFragment) fragment);
}
}
// Listen for changes in the back stack so we know if a fragment got popped off because the user
// clicked the back button.
fm.addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
if (fm.getBackStackEntryCount() == 0) {
// We need to re-show our UI.
controlsContainer.setVisibility(View.VISIBLE);
}
}
});
}
#Override
protected void onResume() {
super.onResume();
uiHelper.onResume();
updateUI();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
outState.putString(PENDING_ACTION_BUNDLE_KEY, pendingAction.name());
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
if (pendingAction != PendingAction.NONE &&
(exception instanceof FacebookOperationCanceledException ||
exception instanceof FacebookAuthorizationException)) {
new AlertDialog.Builder(HelloFacebookSampleActivity.this)
.setTitle(R.string.cancelled)
.setMessage(R.string.permission_not_granted)
.setPositiveButton(R.string.ok, null)
.show();
pendingAction = PendingAction.NONE;
} else if (state == SessionState.OPENED_TOKEN_UPDATED) {
handlePendingAction();
}
updateUI();
}
private void updateUI() {
Session session = Session.getActiveSession();
boolean enableButtons = (session != null && session.isOpened());
postStatusUpdateButton.setEnabled(enableButtons);
postPhotoButton.setEnabled(enableButtons);
pickFriendsButton.setEnabled(enableButtons);
pickPlaceButton.setEnabled(enableButtons);
if (enableButtons && user != null) {
profilePictureView.setProfileId(user.getId());
greeting.setText(getString(R.string.hello_user, user.getFirstName()));
} else {
profilePictureView.setProfileId(null);
greeting.setText(null);
}
}
#SuppressWarnings("incomplete-switch")
private void handlePendingAction() {
PendingAction previouslyPendingAction = pendingAction;
// These actions may re-set pendingAction if they are still pending, but we assume they
// will succeed.
pendingAction = PendingAction.NONE;
switch (previouslyPendingAction) {
case POST_PHOTO:
postPhoto();
break;
case POST_STATUS_UPDATE:
postStatusUpdate();
break;
}
}
private interface GraphObjectWithId extends GraphObject {
String getId();
}
private void showPublishResult(String message, GraphObject result, FacebookRequestError error) {
String title = null;
String alertMessage = null;
if (error == null) {
title = getString(R.string.success);
String id = result.cast(GraphObjectWithId.class).getId();
alertMessage = getString(R.string.successfully_posted_post, message, id);
} else {
title = getString(R.string.error);
alertMessage = error.getErrorMessage();
}
new AlertDialog.Builder(this)
.setTitle(title)
.setMessage(alertMessage)
.setPositiveButton(R.string.ok, null)
.show();
}
private void onClickPostStatusUpdate() {
performPublish(PendingAction.POST_STATUS_UPDATE);
}
private void postStatusUpdate() {
if (user != null && hasPublishPermission()) {
final String message = getString(R.string.status_update, user.getFirstName(), (new Date().toString()));
Request request = Request
.newStatusUpdateRequest(Session.getActiveSession(), message, new Request.Callback() {
#Override
public void onCompleted(Response response) {
showPublishResult(message, response.getGraphObject(), response.getError());
}
});
request.executeAsync();
} else {
pendingAction = PendingAction.POST_STATUS_UPDATE;
}
}
private void onClickPostPhoto() {
performPublish(PendingAction.POST_PHOTO);
}
private void postPhoto() {
if (hasPublishPermission()) {
Bitmap image = BitmapFactory.decodeByteArray(
getIntent().getByteArrayExtra("byteArray"),0,getIntent().getByteArrayExtra("byteArray").length);
Request request = Request.newUploadPhotoRequest(Session.getActiveSession(), image, new Request.Callback() {
#Override
public void onCompleted(Response response) {
showPublishResult(getString(R.string.photo_post), response.getGraphObject(), response.getError());
}
});
request.executeAsync();
} else {
pendingAction = PendingAction.POST_PHOTO;
}
}
private void showPickerFragment(PickerFragment<?> fragment) {
fragment.setOnErrorListener(new PickerFragment.OnErrorListener() {
#Override
public void onError(PickerFragment<?> pickerFragment, FacebookException error) {
String text = getString(R.string.exception, error.getMessage());
Toast toast = Toast.makeText(HelloFacebookSampleActivity.this, text, Toast.LENGTH_SHORT);
toast.show();
}
});
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction()
.replace(R.id.fragment_container, fragment)
.addToBackStack(null)
.commit();
controlsContainer.setVisibility(View.GONE);
// We want the fragment fully created so we can use it immediately.
fm.executePendingTransactions();
fragment.loadData(false);
}
private void onClickPickFriends() {
final FriendPickerFragment fragment = new FriendPickerFragment();
setFriendPickerListeners(fragment);
showPickerFragment(fragment);
}
private void setFriendPickerListeners(final FriendPickerFragment fragment) {
fragment.setOnDoneButtonClickedListener(new FriendPickerFragment.OnDoneButtonClickedListener() {
#Override
public void onDoneButtonClicked(PickerFragment<?> pickerFragment) {
onFriendPickerDone(fragment);
}
});
}
private void onFriendPickerDone(FriendPickerFragment fragment) {
FragmentManager fm = getSupportFragmentManager();
fm.popBackStack();
String results = "";
Collection<GraphUser> selection = fragment.getSelection();
if (selection != null && selection.size() > 0) {
ArrayList<String> names = new ArrayList<String>();
for (GraphUser user : selection) {
names.add(user.getName());
}
results = TextUtils.join(", ", names);
} else {
results = getString(R.string.no_friends_selected);
}
showAlert(getString(R.string.you_picked), results);
}
private void onPlacePickerDone(PlacePickerFragment fragment) {
FragmentManager fm = getSupportFragmentManager();
fm.popBackStack();
String result = "";
GraphPlace selection = fragment.getSelection();
if (selection != null) {
result = selection.getName();
} else {
result = getString(R.string.no_place_selected);
}
showAlert(getString(R.string.you_picked), result);
}
private void onClickPickPlace() {
final PlacePickerFragment fragment = new PlacePickerFragment();
fragment.setLocation(SEATTLE_LOCATION);
fragment.setTitleText(getString(R.string.pick_seattle_place));
setPlacePickerListeners(fragment);
showPickerFragment(fragment);
}
private void setPlacePickerListeners(final PlacePickerFragment fragment) {
fragment.setOnDoneButtonClickedListener(new PlacePickerFragment.OnDoneButtonClickedListener() {
#Override
public void onDoneButtonClicked(PickerFragment<?> pickerFragment) {
onPlacePickerDone(fragment);
}
});
fragment.setOnSelectionChangedListener(new PlacePickerFragment.OnSelectionChangedListener() {
#Override
public void onSelectionChanged(PickerFragment<?> pickerFragment) {
if (fragment.getSelection() != null) {
onPlacePickerDone(fragment);
}
}
});
}
private void showAlert(String title, String message) {
new AlertDialog.Builder(this)
.setTitle(title)
.setMessage(message)
.setPositiveButton(R.string.ok, null)
.show();
}
private boolean hasPublishPermission() {
Session session = Session.getActiveSession();
return session != null && session.getPermissions().contains("publish_actions");
}
private void performPublish(PendingAction action) {
Session session = Session.getActiveSession();
if (session != null) {
pendingAction = action;
if (hasPublishPermission()) {
// We can do the action right away.
handlePendingAction();
} else {
// We need to get new permissions, then complete the action when we get called back.
session.requestNewPublishPermissions(new Session.NewPermissionsRequest(this, PERMISSIONS));
}
}
}
}
whenever i click login button it shows pop window that this app willl access your facebook details
after clicking ok buttton is shows like as previous
this is my code please help me someone
and i am new to android
if anybody having any suggestion please send mail to maruthu2j#gmail.com

Categories

Resources