SharedPreferences in Non-Activity - android

Hi I need to get a String from an Activity to another Class. I need the String VideoID in the Test2 class. I wanted to use sharedpreferences, but this does not work. How can i use sharedpreferences here? Or any other idea how i can get the String? Thanks
In my Activity I have this Button:
// Video Button
final Button videobutton = (Button) findViewById(R.id.videobutton);
videobutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Video ID save
SharedPreferences.Editor editor = getSharedPreferences("VideoID_saver", MODE_PRIVATE).edit();
editor.putString("VideoID", current_video);
editor.commit();
Intent OpenTest = new Intent(Questions.this, Test2.class);
startActivity(OpenTest);
}
});
The Test2.class looks like this:
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayer.ErrorReason;
import com.google.android.youtube.player.YouTubePlayer.PlaybackEventListener;
import com.google.android.youtube.player.YouTubePlayer.PlayerStateChangeListener;
import com.google.android.youtube.player.YouTubePlayer.Provider;
import com.google.android.youtube.player.YouTubePlayerView;
public class Test2 extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
public static final String API_KEY = "AIzaSyCb2pCHbqhBDKaYzFvU7g1SBG14YrM3XWE";
//Test
SharedPreferences prefs = getSharedPreferences("VideoID_saver", MODE_PRIVATE);
String testtext = prefs.getString("VideoID", "");
//http://youtu.be/<VIDEO_ID>
public final String VIDEO_ID = testtext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test2);
/** Initializing YouTube player view **/
YouTubePlayerView youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtube_player);
youTubePlayerView.initialize(API_KEY, this);
}
#Override
public void onInitializationFailure(Provider provider, YouTubeInitializationResult result) {
Toast.makeText(this, "Failured to Initialize!", Toast.LENGTH_LONG).show();
}
#Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player, boolean wasRestored) {
/** add listeners to YouTubePlayer instance **/
player.setPlayerStateChangeListener(playerStateChangeListener);
player.setPlaybackEventListener(playbackEventListener);
/** Start buffering **/
if (!wasRestored) {
player.cueVideo(VIDEO_ID);
}
}
private PlaybackEventListener playbackEventListener = new PlaybackEventListener() {
#Override
public void onBuffering(boolean arg0) {}
#Override
public void onPaused() {}
#Override
public void onPlaying() {}
#Override
public void onSeekTo(int arg0) {}
#Override
public void onStopped() {}
};
private PlayerStateChangeListener playerStateChangeListener = new PlayerStateChangeListener() {
#Override
public void onAdStarted() {}
#Override
public void onError(ErrorReason arg0) {}
#Override
public void onLoaded(String arg0) {}
#Override
public void onLoading() {}
#Override
public void onVideoEnded() {}
#Override
public void onVideoStarted() {}
};

You're probably somehow accessing different SharedPreferences instances. It's easier to make sure this doesn't happen using the getDefaultSharedPreferences() method:
In you Activity:
PreferenceManager.getDefaultSharedPreferences(this)
.edit()
.putString("VideoID", current_video)
.apply();
In your Test2 onCreate method:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String testtext = prefs.getString("VideoID", "");

Couple of things. Test2 is inheriting an activity it seems, so not sure why your title says Non-Activity. SharedPreferences reading and writing seems ok but maybe reading the sharedpreferences even before the constructor on the activity has had change to run is too early.

Your goal is to get a string from button to test2. It seems like it would be better to avoid shared preferences entirely and pass the string to the next activity directly via the put/getExtra function.
Like so:
Intent OpenTest = new Intent(Questions.this, Test2.class);
i.putExtra("VideoID", current_video);
startActivity(OpenTest);
Then extract it from your new activity in your OnCreate method:
//http://youtu.be/<VIDEO_ID>
public final String VIDEO_ID;
#
Override
protected void onCreate(Bundle savedInstanceState) {
//Test
Intent intent = getIntent();
VIDEO_ID = intent.getExtras().getString("VideoID");
}

Related

Android: How to go back to previous screen after playing YouTube video

My app plays a specific YouTube video when a button is clicked.
After watching the video I want the YouTube video player to close and the app to go back to the previous screen instead of displaying more suggested videos.
Here is the code I have, how do I do that?
package com.newapp;
import android.os.Bundle;
import android.widget.Toast;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayer.Provider;
import com.google.android.youtube.player.YouTubePlayerView;
public class Level_1_Training extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener{
public static final String API_KEY = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
public static final String VIDEO_ID = "XXXXXXXXXXXXXXX";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
YouTubePlayerView youTubePlayerView = (YouTubePlayerView)findViewById(R.id.youtubeplayerview);
youTubePlayerView.initialize(API_KEY, this);
}
#Override
public void onInitializationFailure(Provider provider,
YouTubeInitializationResult result) {
Toast.makeText(getApplicationContext(),
"onInitializationFailure()",
Toast.LENGTH_LONG).show();
}
#Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player,
boolean wasRestored) {
player.setPlayerStyle(YouTubePlayer.PlayerStyle.MINIMAL);
if (!wasRestored) {
player.loadVideo(VIDEO_ID);
}
}
}
You can get onVideoEnded() callback.
Youtube API link here https://developers.google.com/youtube/android/player/reference/com/google/android/youtube/player/YouTubePlayer.PlayerStateChangeListener#onVideoEnded()
You can add your logic in implemented method.
#Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player,
boolean wasRestored) {
player.setPlayerStyle(YouTubePlayer.PlayerStyle.MINIMAL);
if (!wasRestored) {
player.loadVideo(VIDEO_ID);
player.setPlayerStateChangeListener(new PlayerStateChangeListener() {
#Override
public void onAdStarted() { }
#Override
public void onError(ErrorReason arg0) { }
#Override
public void onLoaded(String arg0) { }
#Override
public void onLoading() { }
#Override
public void onVideoEnded() {
//your logic ,if the previous activity to be called ,
// you can perform backpress() or intent to call other activity.
// also dont forget to remove player in the
// onStop() method of the youtube activity.
}
#Override
public void onVideoStarted() { }
});
}
}
Useful references
https://developers.google.com/youtube/v3/code_samples/java
https://developers.google.com/youtube/v3/
https://stacktips.com/tutorials/android/youtube-android-player-api-example

Unable to read output from barcode scanner

I want to upload the result from the barcode scanner to the edit text, but it is not displaying in the edit text. May I know what the problem is and how do I solve it?
This is my code
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.google.zxing.Result;
import me.dm7.barcodescanner.zxing.ZXingScannerView;
public class ScannerActivity extends AppCompatActivity {
private ZXingScannerView scannerView;
private EditText ScanBarcode;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scanner);
ScanBarcode = (EditText)findViewById(R.id.editscanbar);
}
public void scanCode(View view){
scannerView = new ZXingScannerView(this);
scannerView.setResultHandler(new ZXingScannerResultHandler());
setContentView(scannerView);
scannerView.startCamera();
}
#Override
public void onPause(){
super.onPause();
scannerView.stopCamera();
}
class ZXingScannerResultHandler implements ZXingScannerView.ResultHandler{
#Override
public void handleResult(Result result){
String resultCode = result.getText().toString();
ScanBarcode.setText(resultCode);
Toast.makeText(ScannerActivity.this, resultCode,
Toast.LENGTH_SHORT).show();
setContentView(R.layout.activity_scanner);
scannerView.stopCamera();
}
}
}
I've changed it and there is still nothing showing up in the edit text
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import com.google.zxing.Result;
import me.dm7.barcodescanner.zxing.ZXingScannerView;
public class ScannerActivity extends AppCompatActivity implements
ZXingScannerView.ResultHandler {
private ZXingScannerView mScannerView;
private EditText ScanBarcode;
#Override
public void onCreate(Bundle State) {
super.onCreate(State);
mScannerView = new ZXingScannerView(this);
setContentView(R.layout.activity_scanner);
ScanBarcode = (EditText)findViewById(R.id.editscanbar);
}
public void scanCode(View view){
mScannerView.setResultHandler(this);
setContentView(mScannerView);
mScannerView.startCamera();
}
#Override
public void onResume(){
super.onResume();
mScannerView.setResultHandler(this);
mScannerView.startCamera();
}
#Override
public void onPause(){
super.onPause();
mScannerView.stopCamera();
}
#Override
public void handleResult(Result rawResult){
ScanBarcode.setText(rawResult.getText());
setContentView(R.layout.activity_scanner);
mScannerView.stopCamera();
}
}
you should implement the ResultHandler in your Activity, override the callback method and there set the result of the scan in your EditText, example:
public class SimpleScannerActivity extends Activity implements ZXingScannerView.ResultHandler {
private ZXingScannerView mScannerView;
private EditText editText;
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
mScannerView = new ZXingScannerView(this); // Programmatically initialize the scanner view
setContentView(mScannerView); // Set the scanner view as the content view
EditText editText = (EditText)findViewById(R.id.myedittext);
}
#Override
public void onResume() {
super.onResume();
mScannerView.setResultHandler(this); // Register ourselves as a handler for scan results.
mScannerView.startCamera(); // Start camera on resume
}
#Override
public void onPause() {
super.onPause();
mScannerView.stopCamera(); // Stop camera on pause
}
#Override
public void handleResult(Result rawResult) {
// Do something with the result here
editText.setText(rawResult.getText());
Log.v(TAG, rawResult.getText()); // Prints scan results
Log.v(TAG, rawResult.getBarcodeFormat().toString()); // Prints the scan format (qrcode, pdf417 etc.)
// If you would like to resume scanning, call this method below:
mScannerView.resumeCameraPreview(this);
}
}
Hope it helps!

How to set the library in android studio

I am trying to set a waveInApp library http://www.materialup.com/posts/waveinapp
I have declared all the required thing .The app
working but the background wave is not working .I am not able to set the wave function as a beginner in android development .
I am able to set the all the basic things including the media player.
Here I am not able to set the speech recognization handler
Here is what I have done
import android.content.Context;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;
import com.cleveroad.audiovisualization.AudioVisualization;
import com.cleveroad.audiovisualization.DbmHandler;
import com.cleveroad.audiovisualization.SpeechRecognizerDbmHandler;
import com.cleveroad.audiovisualization.VisualizerDbmHandler;
public class MainActivity extends AppCompatActivity {
private AudioVisualization audioVisualization;
private Context context;
private ImageButton button1,button2;
private MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
audioVisualization = (AudioVisualization)findViewById(R.id.visualizer_view);
button1=(ImageButton)findViewById(R.id.imageButton);
button2=(ImageButton)findViewById(R.id.imageButton2);
mediaPlayer =MediaPlayer.create(this,R.raw.song);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"playing",Toast.LENGTH_SHORT).show();
mediaPlayer.start();
}
});
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"pause",Toast.LENGTH_SHORT).show();
mediaPlayer.pause();
VisualizerDbmHandler vizualizerHandler = DbmHandler.Factory.newVisualizerHandler(getContext(), 0);
audioVisualization.linkTo(vizualizerHandler);
// set speech recognizer handler
SpeechRecognizerDbmHandler speechRecHandler = DbmHandler.Factory.newSpeechRecognizerHandler(context);
speechRecHandler.innerRecognitionListener(...);
audioVisualization.linkTo(speechRecHandler);
}
});
}
#Override
public void onResume() {
super.onResume();
audioVisualization.onResume();
}
#Override
public void onPause() {
audioVisualization.onPause();
super.onPause();
}
}
So how to set the above handeler. I am not able to set the connect audio visualization view to audio output . How to set the following method with the media player
// set speech recognizer handler
SpeechRecognizerDbmHandler speechRecHandler = DbmHandler.Factory.newSpeechRecognizerHandler(context);
speechRecHandler.innerRecognitionListener(...);
audioVisualization.linkTo(speechRecHandler);
// set audio visualization handler. This will REPLACE previously set speech recognizer handler
VisualizerDbmHandler vizualizerHandler = DbmHandler.Factory.newVisualizerHandler(getContext(), 0);
audioVisualization.linkTo(vizualizerHandler);
Except this all are working.any hint or advice will be helpfull.
I tried to search
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.cleveroad.audiovisualization.AudioVisualization;
import com.cleveroad.audiovisualization.DbmHandler;
import com.cleveroad.audiovisualization.SpeechRecognizerDbmHandler;
public class SpeechRecognitionFragment extends Fragment {
public static SpeechRecognitionFragment newInstance() {
return new SpeechRecognitionFragment();
}
private AudioVisualization audioVisualization;
private Button btnRecognize;
private SpeechRecognizerDbmHandler handler;
private boolean recognizing;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_gles, container, false);
audioVisualization = (AudioVisualization) view.findViewById(R.id.visualizer_view);
btnRecognize = (Button) view.findViewById(R.id.btn_recognize);
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
btnRecognize.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (recognizing) {
handler.stopListening();
} else {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getContext().getPackageName());
handler.startListening(intent);
}
btnRecognize.setEnabled(false);
}
});
handler = DbmHandler.Factory.newSpeechRecognizerHandler(getContext());
handler.innerRecognitionListener(new SimpleRecognitionListener() {
#Override
public void onReadyForSpeech(Bundle params) {
super.onReadyForSpeech(params);
onStartRecognizing();
}
#Override
public void onResults(Bundle results) {
super.onResults(results);
onStopRecognizing();
}
#Override
public void onError(int error) {
super.onError(error);
onStopRecognizing();
}
});
audioVisualization.linkTo(handler);
}
private void onStopRecognizing() {
recognizing = false;
btnRecognize.setText(R.string.start_recognition);
btnRecognize.setEnabled(true);
}
private void onStartRecognizing() {
btnRecognize.setText(R.string.stop_recognition);
btnRecognize.setEnabled(true);
recognizing = true;
}
#Override
public void onDestroyView() {
audioVisualization.release();
super.onDestroyView();
}
private static class SimpleRecognitionListener implements RecognitionListener {
#Override
public void onReadyForSpeech(Bundle params) {
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float rmsdB) {
}
#Override
public void onBufferReceived(byte[] buffer) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int error) {
}
#Override
public void onResults(Bundle results) {
}
#Override
public void onPartialResults(Bundle partialResults) {
}
#Override
public void onEvent(int eventType, Bundle params) {
}
}
}
from https://github.com/Cleveroad/WaveInApp/blob/master/app/src/main/java/com/cleveroad/example/SpeechRecognitionFragment.java
So can some one tell me why fragment is used and how I can set this in my main activity?
I know i am late to post this answer...but for future use try this
check my code you will find your answer
first of all in the liberay you have to make some changes in your xml.
<com.cleveroad.audiovisualization.GLAudioVisualizationView
android:id="#+id/visualizer_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:av_bubblesSize= "#dimen/bubble_size"
app:av_bubblesRandomizeSizes= "true"
app:av_wavesHeight= "#dimen/wave_height"
app:av_wavesFooterHeight="#dimen/footer_height"
app:av_wavesCount="7"
app:av_layersCount="4" />
then
private VisualizerDbmHandler handler;
MediaPlayer mp ;
private AudioVisualization audioVisualization;
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View ve = inflater.inflate(R.layout.cat, container, false);
ibCapture = (ImageButton) ve.findViewById(R.id.ibCapture);
audioVisualization = (AudioVisualization)ve.findViewById(R.id.visualizer_view);
hell();
return ve;
}
ibCapture.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (bool) {
bool = false;
mp = MediaPlayer.create(getContext(), R.raw.blackcat);
mp.setLooping(true);
handler = VisualizerDbmHandler.Factory.newVisualizerHandler(getContext(),mp);
audioVisualization.linkTo(handler);
mp.start();
((home)getActivity()).vis();
} else {
bool = true;
((home)getActivity()).visgone();
stopPlaying();
}
}
});
Replace
audioVisualization = (AudioVisualization) glAudioVisualizationView;
With
audioVisualization = (AudioVisualization)findViewById(R.id.glAudioVisualizationView);
glAudioVisualizationView should be id of AudioVisualization in your layout file
define
private AudioVisualization audioVisualization;
initialize it
audioVisualization = (AudioVisualization) view.findViewById(R.id.visualizer_view);
for speech use below code
SpeechRecognizerDbmHandler speechRecHandler = DbmHandler.Factory.newSpeechRecognizerHandler(getContext());
speechRecHandler.innerRecognitionListener();
audioVisualization.linkTo(speechRecHandler);
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getContext().getPackageName());
speechRecHandler.startListening(intent);
for a media on your device use below code, Sandeep Singh Answer
MediaPlayer mp = MediaPlayer.create(getContext(), R.raw.blackcat);
mp.setLooping(true);
handler = VisualizerDbmHandler.Factory.newVisualizerHandler(getContext(),mp);
audioVisualization.linkTo(handler);
mp.start();

Android YouTube API access player from onClickListener

I'm following this tutorial to set up a custom YouTube player via YouTube API: http://www.techrepublic.com/blog/android-app-builder/using-googles-youtube-api-in-your-android-apps/
Here's the code for loading a pre-set YouTube video:
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;
import com.google.android.youtube.player.YouTubePlayer.Provider;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
static private final String DEVELOPER_KEY = "mykey";
static private final String VIDEO = "Yc8YrVc47TI";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
YouTubePlayerView youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
youTubeView.initialize(DEVELOPER_KEY, this);
}
#Override
public void onInitializationFailure(Provider provider, YouTubeInitializationResult error) {
Toast.makeText(this, "Oh no! "+error.toString(), Toast.LENGTH_LONG).show();
}
#Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player, boolean wasRestored) {
player.loadVideo(VIDEO);
}
}
Now I'm trying to load a different YouTube video by clicking a button. So I setup an onClickListener for my button1 and try to access the YouTube player, but it won't work.
public class MainActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
static private final String DEVELOPER_KEY = "mykey";
static private final String VIDEO = "Yc8YrVc47TI";
Button button1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
YouTubePlayerView youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
youTubeView.initialize(DEVELOPER_KEY, this);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
youTubeView.loadVideo("Erd2k6EKxCQ");
}
});
}
#Override
public void onInitializationFailure(Provider provider, YouTubeInitializationResult error) {
Toast.makeText(this, "Oh no! "+error.toString(), Toast.LENGTH_LONG).show();
}
#Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player, boolean wasRestored) {
player.loadVideo(VIDEO);
}
}
How do I load a specific video from button1's onClickListener to the YouTubePlayer player.component?
public class Community extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener,View.OnClickListener{
final static String youtube_key = " you key ";
YouTubePlayerView youTubePlayerView;
YouTubePlayer.OnInitializedListener onInitializedListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_community);
youTubePlayerView = (YouTubePlayerView) findViewById(R.id.home_community_youtubeview);
youTubePlayerView.initialize(youtube_key,this);
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
youTubePlayer.loadVideo("vk1Rk5AaDO4");
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
#Override
public void onClick(View view) {
}
}
You need to create a new activity to extend the YouTubePlayerView Context. This is what my activity looks like, but you need to create an intent from main to call it. IE this is a different class than main.
public class Beat extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener, OnClickListener{
static private final String DEVELOPER_KEY = "your key here";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.beat);
// changes to xml file named beat
// initializes the video
YouTubePlayerView yt2 = (YouTubePlayerView)findViewById(R.id.youtube_view2);
yt2.initialize(DEVELOPER_KEY, this);
setupActionBar();
}
public void onInitializationSuccess(Provider provider, YouTubePlayer player,
boolean wasRestored) {
player.loadVideo(Main.VIDEO[0]);
}

The application just "stop unexpectedly" when run on the phone

When I run my application on the emulator, it run right and no problem happens. But when I run it on the phone, a problem appear "stop unexpectedly".
In my application:
The main activity (Background) can exchange to 4 activities: LivingRoom, DiningRoom, Wc, Garage. The problem "stop unexpectedly" just happens when i try to go to the DiningRoom activity.
This is my code :
1.Background
package com.example.background;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import at.abraxas.amarino.Amarino;
public class BackgroundActivity extends Activity {
private Button Wc, Dining_Room, Living_Room, Garage;
private Intent D_intent, L_intent, G_intent, W_intent;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Amarino.connect(this, DEVICE_ADDRESS);
Living_Room = (Button) findViewById(R.id.living);
//Living_Room.setBackgroundColor(Color.TRANSPARENT);
Living_Room.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
L_intent = new Intent(view.getContext(), LivingRoom.class);
startActivityForResult(L_intent, 0);
}
});
Dining_Room = (Button) findViewById(R.id.dining);
// Dining_Room.setBackgroundColor(Color.TRANSPARENT);
Dining_Room.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
D_intent = new Intent(view.getContext(), DiningRoom.class);
startActivityForResult(D_intent, 0);
}
});
Wc = (Button) findViewById(R.id.wc);
//Wc.setBackgroundColor(Color.TRANSPARENT);
Wc.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
W_intent = new Intent(view.getContext(), Wc.class);
startActivityForResult(W_intent, 0);
}
});
Garage = (Button) findViewById(R.id.garage);
// Garage.setBackgroundColor(Color.TRANSPARENT);
Garage.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
G_intent = new Intent(view.getContext(), Garage.class);
startActivityForResult(G_intent, 0);
}
});
}
}
2.DiningRoom
package com.example.background;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.ToggleButton;
import at.abraxas.amarino.Amarino;
public class DiningRoom extends Activity implements OnCheckedChangeListener, OnSeekBarChangeListener{
private static final String DEVICE_ADDRESS = "00:06:66:43:9B:56";
final int DELAY = 150;
ToggleButton button;
SeekBar seekbar1;
SeekBar seekbar2;
boolean light2;
int light1;
int fan;
long lastchange;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.diningroom);
//back ve trang chinh
Button backhome = (Button) findViewById(R.id.D_backhome);
backhome.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
}
});
Amarino.connect(this, DEVICE_ADDRESS);
button = (ToggleButton) findViewById(R.id.Dbutton);
seekbar1 = (SeekBar) findViewById(R.id.Dseekbar1);
seekbar2 = (SeekBar) findViewById(R.id.Dseekbar2);
button.setOnCheckedChangeListener(this);
seekbar1.setOnSeekBarChangeListener(this);
seekbar2.setOnSeekBarChangeListener(this);
}
//---START----------------------------------------------------------------------------------------------
#Override
protected void onStart(){
super.onStart();
// load last state
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
light2 = pref.getBoolean("light2", true);
light1 = pref.getInt("light1", 0);
fan = pref.getInt("fan", 0);
button.setChecked(light2);
seekbar1.setProgress(light1);
seekbar2.setProgress(fan);
new Thread(){
public void run(){
try{
Thread.sleep(6000);
}catch (InterruptedException e) {}
update_light2();
update_light1_fan();
}
}.start();
}
//STOP--------------------------------------------------------------------------------
#Override
protected void onStop(){
super.onStop();
PreferenceManager.getDefaultSharedPreferences(this)
.edit()
.putBoolean("light2", light2)
.putInt("light1", light1)
.putInt("fan", fan)
.commit();
Amarino.disconnect(this, DEVICE_ADDRESS);
}
//UPDATE LIGHT2--------------------------------------------------------------------------------
private void Update_Light2_State(final CompoundButton button){
light2 = button.isChecked();
update_light2();
}
private void update_light2(){
int a;
a = (light2 == true)? 255:0;
Amarino.sendDataToArduino(this, DEVICE_ADDRESS, 'o', a);
}
//UPDATE LIGHT1 FAN-------------------------------------------------------------------------------------
private void Update_Light1_Fan_State(final SeekBar seekbar){
switch (seekbar.getId()){
case R.id.Dseekbar1:
light1 = seekbar.getProgress();
update_light1();
break;
case R.id.Dseekbar2:
fan = seekbar.getProgress();
update_fan();
break;
}
}
private void update_light1_fan(){
update_light1();
update_fan();
}
private void update_light1(){
Amarino.sendDataToArduino(this, DEVICE_ADDRESS, 'p', light1);
}
private void update_fan(){
Amarino.sendDataToArduino(this, DEVICE_ADDRESS, 'q', fan);
}
//---TRACE--------------------------------------------------------------------------------------
#Override
public void onCheckedChanged(CompoundButton button, boolean isChecked) {
if (System.currentTimeMillis() - lastchange > DELAY ){
Update_Light2_State(button);
lastchange = System.currentTimeMillis();
}
}
#Override
public void onProgressChanged(SeekBar seekbar, int progress, boolean fromUser) {
if (System.currentTimeMillis() - lastchange > DELAY ){
Update_Light1_Fan_State(seekbar);
lastchange = System.currentTimeMillis();
}
}
#Override
public void onStartTrackingTouch(SeekBar seekbar) {
lastchange = System.currentTimeMillis();
}
#Override
public void onStopTrackingTouch(SeekBar seekbar) {
Update_Light1_Fan_State(seekbar);
}
}
3.Logcat
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.background/com.example.background.DiningRoom}: java.lang.ClassCastException:
java.lang.Boolean
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2669)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2685)
at android.app.ActivityThread.access$2300(ActivityThread.java:126)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2038)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4633)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: java.lang.Boolean
at android.app.ContextImpl$SharedPreferencesImpl.getInt(ContextImpl.java:2721)
at com.example.background.DiningRoom.onStart(DiningRoom.java:80)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1129)
at android.app.Activity.performStart(Activity.java:3781)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2642)
... 11 more
Force finishing activity com.example.background/.DiningRoom
Force finishing activity com.example.background/.BackgroundActivity
I also try to wrote another application similar to the above application. But I just have only 1 sub activity: DiningRoom, then it ran well on the phone.
The Background when I just have one sub activity
[CODE]
public class Test1Activity extends Activity {
private Button Dining_Room;
private Intent D_intent;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Dining_Room = (Button) findViewById(R.id.dining);
// Dining_Room.setBackgroundColor(Color.TRANSPARENT);
Dining_Room.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
D_intent = new Intent(view.getContext(), Dining.class);
startActivityForResult(D_intent, 0);
}
});
}
}
[/CODE]
Careful reading of logcat reveals that:
Caused by: java.lang.ClassCastException: java.lang.Boolean
at android.app.ContextImpl$SharedPreferencesImpl.getInt(ContextImpl.java:2721)
at com.example.background.DiningRoom.onStart(DiningRoom.java:80)
This means, that shared preference was boolean instead of int on line 80.
PS: I develop lightweight dependency injection framework for android, and it already covers
loading / saving preferences. Just grab it here:
https://github.com/ko5tik/andject
I would guess that the value "light1" in your shared preferences was not saved as an integer (but as a boolean).
From the docs:
Throws ClassCastException if there is a preference with this name that
is not an int.

Categories

Resources