App force closes after implementing media player - java

I programmed a quiz app there is one question, 3 choices, and ONE correct answer. Now I set up that on click on the right answer the MediaPlayer starts playing the sound. It worked fine but after I rebuilt the app forcecloses during splashscreen. Logcat says the error is the public void onClick(View view) under the FOR query.
Thanks for watching :D
public class QuizActivity extends AppCompatActivity {
private ActionBarDrawerToggle mToggle;
private QuestionLibrary mQuestionLibrary = new QuestionLibrary();
private TextView mScoreView;
private TextView mQuestionView;
private Button mButtonChoice1;
private Button mButtonChoice2;
private Button mButtonChoice3;
private String mAnswer;
private int mScore = 0;
private int mQuestionNumber = 0;
Dialog dialog;
TextView closeButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
final MediaPlayer mp = new MediaPlayer();
createDialog();
Button dialogButton = (Button) findViewById(R.id.dialogbtn);
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.show();
}
});
closeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
TextView shareTextView = (TextView) findViewById(R.id.share);
shareTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(Intent.ACTION_SEND);
myIntent.setType("text/plain");
myIntent.putExtra(Intent.EXTRA_SUBJECT, "Hello!");
myIntent.putExtra(Intent.EXTRA_TEXT, "My highscore in Quizzi is very high! I bet you can't beat me except you are cleverer than me. Download the app now! https://play.google.com/store/apps/details?id=amapps.impossiblequiz");
startActivity(Intent.createChooser(myIntent, "Share with:"));
}
});
mQuestionLibrary.shuffle();
setSupportActionBar((Toolbar) findViewById(R.id.nav_action));
DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true); // Able to see the Navigation Burger "Button"
((NavigationView) findViewById(R.id.nv1)).setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.nav_stats:
startActivity(new Intent(QuizActivity.this, Menu2.class));
break;
case R.id.nav_about:
startActivity(new Intent(QuizActivity.this, Menu3.class));
break;
}
return true;
}
});
mScoreView = (TextView) findViewById(R.id.score_score);
mQuestionView = (TextView) findViewById(R.id.question);
mButtonChoice1 = (Button) findViewById(R.id.choice1);
mButtonChoice2 = (Button) findViewById(R.id.choice2);
mButtonChoice3 = (Button) findViewById(R.id.choice3);
final List<Button> choices = new ArrayList<>();
choices.add(mButtonChoice1);
choices.add(mButtonChoice2);
choices.add(mButtonChoice3);
updateQuestion();
for (final Button choice : choices) {
choice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (choice.getText().equals(mAnswer)) {
try {
mp.reset();
AssetFileDescriptor afd;
afd = getAssets().openFd("sample.mp3");
mp.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
mp.prepare();
mp.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
updateScore();
updateQuestion();
Toast.makeText(QuizActivity.this, "Correct", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(QuizActivity.this, "Wrong... Try again!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(QuizActivity.this, Menu2.class);
intent.putExtra("score", mScore); // pass score to Menu2
startActivity(intent);
}
}
});
}
}
private void updateQuestion() {
if (mQuestionNumber < mQuestionLibrary.getLength()) {
mQuestionView.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
mButtonChoice1.setText(mQuestionLibrary.getChoice1(mQuestionNumber));
mButtonChoice2.setText(mQuestionLibrary.getChoice2(mQuestionNumber));
mButtonChoice3.setText(mQuestionLibrary.getChoice3(mQuestionNumber));
mAnswer = mQuestionLibrary.getCorrectAnswer(mQuestionNumber++);
} else {
Toast.makeText(QuizActivity.this, "Last Question! You are very intelligent!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(QuizActivity.this, Menu2.class);
intent.putExtra("score", mScore);
startActivity(intent);
}
}
private void updateScore() {
mScoreView.setText(String.valueOf(++mScore));
SharedPreferences mypref = getPreferences(MODE_PRIVATE);
int highScore = mypref.getInt("highScore", 0);
if (mScore > highScore) {
SharedPreferences.Editor editor = mypref.edit();
editor.putInt("highScore", mScore);
editor.apply();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return mToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}
private void createDialog() {
dialog = new Dialog(this);
dialog.setTitle("Tutorial");
dialog.setContentView(R.layout.popup_menu1_1);
closeButton = (TextView) dialog.findViewById(R.id.closeTXT);
}
}

Try something like:
OnCreate{
mButtonChoice1 = (Button) findViewById(R.id.choice1);
mButtonChoice2 = (Button) findViewById(R.id.choice2);
mButtonChoice3 = (Button) findViewById(R.id.choice3);
mButtonChoice1.setOnClickListener(this);
mButtonChoice2.setOnClickListener(this);
mButtonChoice3.setOnClickListener(this);
}
public void onClick(View v) {
Button b = (Button)v;
String buttonText = b.getText().toString();
if(buttonText.equals(something)){
if (mp.isPlaying()) {
mp.stop();
mp.release();
mp = new MediaPlayer();
}
AssetFileDescriptor descriptor = getAssets().openFd("sample.mp3"");
mp.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
descriptor.close();
mp.prepare();
mp.start();
}
}

Related

Activity intent not working on button click

Hello Stackoverflow community!
Recently, a strange error occured to me. It is with a button in my app. When i press it there is nothing happening. No errors, or crashes but also Intent is not functioning. The transition to DeleteAccountActivity is not happening. I don't know why is this happening. The intent which I am using is very simple(passes nothing). Please help me
AccountSettingsActivity.java
public class AccountSettingsActivity extends AppCompatActivity {
private static final String TAG = "AccountSettingsActivity";
private static final int ACTIVITY_NUM = 4;
private String user_id;
private Context mContext;
public SectionsStatePagerAdapter pagerAdapter;
private ViewPager mViewPager;
private RelativeLayout mRelativeLayout;
private Button mDelete;
User mUser;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_accountsettings);
mContext = AccountSettingsActivity.this;
Log.d(TAG, "onCreate: started.");
mViewPager = (ViewPager) findViewById(R.id.viewpager_container);
mRelativeLayout = (RelativeLayout) findViewById(R.id.relLayout1);
mDelete = (Button) findViewById(R.id.btnDelete);
User mUser = new User();
setupSettingsList();
setupBottomNavigationView();
setupFragments();
getIncomingIntent();
//setup the backarrow for navigating back to "ProfileActivity"
ImageView backArrow = (ImageView) findViewById(R.id.backArrow);
backArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating back to 'ProfileActivity'");
finish();
mDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext, DeleteAccountActivity.class);
startActivity(intent);
}
});
}
});
}
private void deleteAccounts(){
/* DatabaseReference deleteUser = FirebaseDatabase.getInstance().getReference("users").child(user_id);
DatabaseReference deleteUserPhotos = FirebaseDatabase.getInstance().getReference("user_photos").child(user_id);
DatabaseReference deleteUserPhotoComments = FirebaseDatabase.getInstance().getReference("comments").child(user_id);
deleteUser.removeValue();
deleteUserPhotos.removeValue();
deleteUserPhotoComments.removeValue();*/
// getActivity().overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
FirebaseDatabase.getInstance().getReference()
.child(getString(R.string.dbname_users))
// .child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(mUser.getUser_id())
.removeValue();
/* FirebaseDatabase.getInstance().getReference()
.child(getString(R.string.dbname_followers))
.child(mUser.getUser_id())
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.removeValue(); */
}
private void getIncomingIntent(){
Intent intent = getIntent();
if(intent.hasExtra(getString(R.string.selected_image))
|| intent.hasExtra(getString(R.string.selected_bitmap))){
//if there is an imageUrl attached as an extra, then it was chosen from the gallery/photo fragment
Log.d(TAG, "getIncomingIntent: New incoming imgUrl");
if(intent.getStringExtra(getString(R.string.return_to_fragment)).equals(getString(R.string.edit_profile_fragment))){
if(intent.hasExtra(getString(R.string.selected_image))){
//set the new profile picture
FirebaseMethods firebaseMethods = new FirebaseMethods(AccountSettingsActivity.this);
firebaseMethods.uploadNewPhoto(getString(R.string.profile_photo), null, 0,
intent.getStringExtra(getString(R.string.selected_image)), null);
}
else if(intent.hasExtra(getString(R.string.selected_bitmap))){
//set the new profile picture
FirebaseMethods firebaseMethods = new FirebaseMethods(AccountSettingsActivity.this);
firebaseMethods.uploadNewPhoto(getString(R.string.profile_photo), null, 0,
null,(Bitmap) intent.getParcelableExtra(getString(R.string.selected_bitmap)));
}
}
}
if(intent.hasExtra(getString(R.string.calling_activity))){
Log.d(TAG, "getIncomingIntent: received incoming intent from " + getString(R.string.profile_activity));
setViewPager(pagerAdapter.getFragmentNumber(getString(R.string.edit_profile_fragment)));
}
}
private void setupFragments(){
pagerAdapter = new SectionsStatePagerAdapter(getSupportFragmentManager());
pagerAdapter.addFragment(new EditProfileFragment(), getString(R.string.edit_profile_fragment)); //fragment 0
pagerAdapter.addFragment(new SignOutFragment(), getString(R.string.sign_out_fragment)); //fragment 1
// pagerAdapter.addFragment(new DeleteAccountFragment(), "Delete Account");
}
public void setViewPager(int fragmentNumber){
mRelativeLayout.setVisibility(View.GONE);
Log.d(TAG, "setViewPager: navigating to fragment #: " + fragmentNumber);
mViewPager.setAdapter(pagerAdapter);
mViewPager.setCurrentItem(fragmentNumber);
}
private void setupSettingsList(){
Log.d(TAG, "setupSettingsList: initializing 'Account Settings' list.");
ListView listView = (ListView) findViewById(R.id.lvAccountSettings);
ArrayList<String> options = new ArrayList<>();
options.add(getString(R.string.edit_profile_fragment)); //fragment 0
options.add(getString(R.string.sign_out_fragment)); //fragement 1
// options.add("Delete Account");
ArrayAdapter adapter = new ArrayAdapter(mContext, android.R.layout.simple_list_item_1, options);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "onItemClick: navigating to fragment#: " + position);
setViewPager(position);
}
});
}
/**
* BottomNavigationView setup
*/
private void setupBottomNavigationView(){
Log.d(TAG, "setupBottomNavigationView: setting up BottomNavigationView");
BottomNavigationViewEx bottomNavigationViewEx = (BottomNavigationViewEx) findViewById(R.id.bottomNavViewBar);
BottomNavigationViewHelper.setupBottomNavigationView(bottomNavigationViewEx);
BottomNavigationViewHelper.enableNavigation(mContext, this,bottomNavigationViewEx);
Menu menu = bottomNavigationViewEx.getMenu();
MenuItem menuItem = menu.getItem(ACTIVITY_NUM);
menuItem.setChecked(true);
}
}
DeleteAccountActivity.java
public class DeleteAccountActivity extends AppCompatActivity {
Button yesButton;
Button cancelButton;
Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
setContentView(R.layout.activity_delete_account);
yesButton = (Button) findViewById(R.id.btnDelete2);
cancelButton = (Button) findViewById(R.id.btnDelete3);
yesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deleteAllData();
Intent intent = new Intent(mContext, RegisterActivity.class);
startActivity(intent);
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, AccountSettingsActivity.class);
}
});
}
public void deleteAllData(){
DatabaseReference deleteUser = FirebaseDatabase.getInstance().getReference()
.child("users")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
DatabaseReference deleteUserPhotos = FirebaseDatabase.getInstance().getReference()
.child("user_photos")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
DatabaseReference deleteUserPhotoComments = FirebaseDatabase.getInstance().getReference()
.child("user_account_settings")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
DatabaseReference deleteUserFollowing = FirebaseDatabase.getInstance().getReference()
.child("following")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
DatabaseReference deleteUserFollowers = FirebaseDatabase.getInstance().getReference()
.child("followers")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
deleteUser.removeValue();
deleteUserPhotos.removeValue();
deleteUserPhotoComments.removeValue();
deleteUserFollowing.removeValue();
deleteUserFollowers.removeValue();
}
}
Issue :
Press backarrow (But this will finish the activity)
Press mdelete to trigger the intent. (so no way to trigger intent)
Because when you press backarrow, you are setting the listener on mdelete which actually has the code to trigger intent and finish will kill the activity so no way to trigger intent
Solution : Separate the listeners
backArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating back to 'ProfileActivity'");
finish();
}
});
mDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext, DeleteAccountActivity.class);
startActivity(intent);
}
});
Please, change the lines with setting the clickListeners to this:
ImageView backArrow = (ImageView) findViewById(R.id.backArrow);
backArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating back to 'ProfileActivity'");
finish();
}
});
mDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext, DeleteAccountActivity.class);
startActivity(intent);
}
});
I think your onCreate() method should look like this:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_accountsettings);
mContext = AccountSettingsActivity.this;
Log.d(TAG, "onCreate: started.");
mViewPager = (ViewPager) findViewById(R.id.viewpager_container);
mRelativeLayout = (RelativeLayout) findViewById(R.id.relLayout1);
mDelete = (Button) findViewById(R.id.btnDelete);
User mUser = new User();
setupSettingsList();
setupBottomNavigationView();
setupFragments();
getIncomingIntent();
mDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext, DeleteAccountActivity.class);
startActivity(intent);
}
});
//setup the backarrow for navigating back to "ProfileActivity"
ImageView backArrow = (ImageView) findViewById(R.id.backArrow);
backArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating back to 'ProfileActivity'");
finish();
}
});
}
One simple thing i can see by skimming through is that the onClick listener for your button that should take you to delete activity is assigned inside the back arrow onClick listener.
So the only time your delete button is assigned a click listener is when you press the back button, and it wont still assign because you already called
finish();
On the activity
Change
backArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating back to 'ProfileActivity'");
finish();
mDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext, DeleteAccountActivity.class);
startActivity(intent);
} });
} });
To
backArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating back to 'ProfileActivity'");
finish();
} });
mDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext, DeleteAccountActivity.class);
startActivity(intent);
} });
Hope this helps.

Sound is stopping after a period of time

The code of the mediaplayer (which starts under the comment: //Code of the mediaplayer begins) is every time called when I click a button. After some time when I click the button, the sound is not played anymore.
It is like : I click for 10 times and it is returning the sound when I click again it stops and does not work anymore. Thanks for looking, If there is any solution comment below! :D
Logcat:
E/AudioFlinger: no more track names available
E/AudioFlinger: createTrack_l() initCheck failed -12; no control block?
E/AudioTrack: AudioFlinger could not create track, status: -12
E/AudioSink: Unable to create audio track
E/ExtendedNuPlayerDecoder: error in opening audio sink. Could be fatal!!!
**Code of the main activity'*:
public class QuizActivity extends AppCompatActivity {
private ActionBarDrawerToggle mToggle;
private QuestionLibrary mQuestionLibrary = new QuestionLibrary();
private TextView mScoreView;
private TextView mQuestionView;
private Button mButtonChoice1;
private Button mButtonChoice2;
private Button mButtonChoice3;
private String mAnswer;
private int mScore = 0;
private int mQuestionNumber = 0;
Dialog dialog;
Dialog dialog2;
TextView closeButton;
TextView closeButton2;
CheckBox checkBoxmp;
private MediaPlayer mp, mp2;
SharedPreferences mypref;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
//Dialog 1
createDialog();
Button dialogButton = (Button) findViewById(R.id.dialogbtn);
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.show();
}
});
closeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
//end Dialog 1
//Dialog 2
createDialog2();
Button dialogButton2 = (Button) findViewById(R.id.dialogbtn2);
dialogButton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog2.show();
}
});
closeButton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog2.dismiss();
}
});
//end Dialog 2
SharedPreferences mypref = getPreferences(MODE_PRIVATE);
final SharedPreferences.Editor editor = mypref.edit();
checkBoxmp.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
editor.putBoolean("playSounds", !isChecked);
editor.commit();
if (!isChecked){
mp.setVolume(1,1);
mp2.setVolume(1,1);
}else{
mp.setVolume(0,0);
mp2.setVolume(0,0);
}
}
})
;
final boolean playSounds = mypref.getBoolean("playSounds", false);
checkBoxmp.setChecked(!playSounds);
if(playSounds){
mp.setVolume(1,1);
mp2.setVolume(1,1);
}
else{
mp.setVolume(0,0);
mp2.setVolume(0,0);
}
TextView shareTextView = (TextView) findViewById(R.id.share);
shareTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(Intent.ACTION_SEND);
myIntent.setType("text/plain");
myIntent.putExtra(Intent.EXTRA_SUBJECT, "Hello!");
myIntent.putExtra(Intent.EXTRA_TEXT, "My highscore in Quizzi is very high! I bet you can't beat me except you are cleverer than me. Download the app now! https://play.google.com/store/apps/details?id=amapps.impossiblequiz");
startActivity(Intent.createChooser(myIntent, "Share with:"));
}
});
mQuestionLibrary.shuffle();
setSupportActionBar((Toolbar) findViewById(R.id.nav_action));
DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true); // Able to see the Navigation Burger "Button"
((NavigationView) findViewById(R.id.nv1)).setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.nav_stats:
startActivity(new Intent(QuizActivity.this, Menu2.class));
break;
case R.id.nav_about:
startActivity(new Intent(QuizActivity.this, Menu3.class));
break;
}
return true;
}
});
mScoreView = (TextView) findViewById(R.id.score_score);
mQuestionView = (TextView) findViewById(R.id.question);
mButtonChoice1 = (Button) findViewById(R.id.choice1);
mButtonChoice2 = (Button) findViewById(R.id.choice2);
mButtonChoice3 = (Button) findViewById(R.id.choice3);
final List<Button> choices = new ArrayList<>();
choices.add(mButtonChoice1);
choices.add(mButtonChoice2);
choices.add(mButtonChoice3);
updateQuestion();
//Code of the mediaplayer begins:
for (final Button choice : choices) {
choice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (choice.getText().equals(mAnswer)) {
try {
mp = new MediaPlayer();
if (playSounds) {
mp.setVolume(1, 1);
} else {
mp.setVolume(0, 0);
}
mp.reset();
AssetFileDescriptor afd;
afd = getAssets().openFd("sample.mp3");
mp.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
mp.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer unused) {
mp.release();
mp = null;
}
});
mp.start();
updateScore();
updateQuestion();
Toast.makeText(QuizActivity.this, "Correct", Toast.LENGTH_SHORT).show();
} else {
try {
mp2 = new MediaPlayer();
if (playSounds) {
mp2.setVolume(1, 1);
} else {
mp.setVolume(0, 0);
}
mp2.reset();
AssetFileDescriptor afd;
afd = getAssets().openFd("wrong.mp3");
mp2.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
mp2.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mp2.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer unused) {
mp2.release();
mp2 = null;
}
});
mp2.start();
Toast.makeText(QuizActivity.this, "Wrong... Try again!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(QuizActivity.this, Menu2.class);
intent.putExtra("score", mScore); // pass score to Menu2
startActivity(intent);
}
}
});
}
}
//End mediaplayer main code
private void updateQuestion() {
if (mQuestionNumber < mQuestionLibrary.getLength()) {
mQuestionView.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
mButtonChoice1.setText(mQuestionLibrary.getChoice1(mQuestionNumber));
mButtonChoice2.setText(mQuestionLibrary.getChoice2(mQuestionNumber));
mButtonChoice3.setText(mQuestionLibrary.getChoice3(mQuestionNumber));
mAnswer = mQuestionLibrary.getCorrectAnswer(mQuestionNumber++);
} else {
Toast.makeText(QuizActivity.this, "Last Question! You are very intelligent!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(QuizActivity.this, Menu2.class);
intent.putExtra("score", mScore);
startActivity(intent);
}
}
private void updateScore() {
mScoreView.setText(String.valueOf(++mScore));
SharedPreferences mypref = getPreferences(MODE_PRIVATE);
int highScore = mypref.getInt("highScore", 0);
if (mScore > highScore) {
SharedPreferences.Editor editor = mypref.edit();
editor.putInt("highScore", mScore);
editor.apply();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return mToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}
private void createDialog() {
dialog = new Dialog(this);
dialog.setTitle("Tutorial");
dialog.setContentView(R.layout.popup_menu1_1);
closeButton = (TextView) dialog.findViewById(R.id.closeTXT);
}
private void createDialog2() {
dialog2 = new Dialog(this);
dialog2.setTitle("Settings");
dialog2.setContentView(R.layout.popup_menu1_2);
closeButton2 = (TextView) dialog2.findViewById(R.id.closeTXT2);
checkBoxmp = (CheckBox) dialog2.findViewById(R.id.ckeckBox);
}
}
You are not releasing MediaPlayers. That could be the reason behind this issue. Without touching most of your logic, one way to do this is:
Make mp and mp2, private members of QuizActivity.
public class QuizActivity extends AppCompatActivity {
...
private MediaPlayer mp, mp2;
...
}
Create MediaPlayer whenever required, and release it when playback is done.
mp = new MediaPlayer();
if (playSounds) {
mp.setVolume(1, 1);
} else {
mp.setVolume(0, 0);
}
AssetFileDescriptor afd;
...
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer unused) {
mp.release();
mp = null;
}
});
mp.start();
At other places, you will have to perform null checks as shown below, before accessing mp and mp2 to avoid NPE.
if (null != mp && null != mp2) {
if (!isChecked) {
mp.setVolume(1, 1);
mp2.setVolume(1, 1);
} else {
mp.setVolume(0, 0);
mp2.setVolume(0, 0);
}
}
Other approach would be to add click-listeners only after creating media players.
This link sheds more light on MediaPlayer release.
And the complete source would look as shown below.
public class QuizActivity extends AppCompatActivity {
private ActionBarDrawerToggle mToggle;
private QuestionLibrary mQuestionLibrary = new QuestionLibrary();
private TextView mScoreView;
private TextView mQuestionView;
private Button mButtonChoice1;
private Button mButtonChoice2;
private Button mButtonChoice3;
private String mAnswer;
private int mScore = 0;
private int mQuestionNumber = 0;
Dialog dialog;
Dialog dialog2;
TextView closeButton;
TextView closeButton2;
CheckBox checkBoxmp;
private MediaPlayer mp, mp2;
SharedPreferences mypref;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
//Dialog 1
createDialog();
Button dialogButton = (Button) findViewById(R.id.dialogbtn);
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.show();
}
});
closeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
//end Dialog 1
//Dialog 2
createDialog2();
Button dialogButton2 = (Button) findViewById(R.id.dialogbtn2);
dialogButton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog2.show();
}
});
closeButton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog2.dismiss();
}
});
//end Dialog 2
SharedPreferences mypref = getPreferences(MODE_PRIVATE);
final SharedPreferences.Editor editor = mypref.edit();
checkBoxmp.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
editor.putBoolean("playSounds", !isChecked);
editor.commit();
if (null != mp && null != mp2) {
if (!isChecked) {
mp.setVolume(1, 1);
mp2.setVolume(1, 1);
} else {
mp.setVolume(0, 0);
mp2.setVolume(0, 0);
}
}
}
});
final boolean playSounds = mypref.getBoolean("playSounds", false);
checkBoxmp.setChecked(!playSounds);
TextView shareTextView = (TextView) findViewById(R.id.share);
shareTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(Intent.ACTION_SEND);
myIntent.setType("text/plain");
myIntent.putExtra(Intent.EXTRA_SUBJECT, "Hello!");
myIntent.putExtra(Intent.EXTRA_TEXT, "My highscore in Quizzi is very high! I bet you can't beat me except you are cleverer than me. Download the app now! https://play.google.com/store/apps/details?id=amapps.impossiblequiz");
startActivity(Intent.createChooser(myIntent, "Share with:"));
}
});
mQuestionLibrary.shuffle();
setSupportActionBar((Toolbar) findViewById(R.id.nav_action));
DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true); // Able to see the Navigation Burger "Button"
((NavigationView) findViewById(R.id.nv1)).setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.nav_stats:
startActivity(new Intent(QuizActivity.this, Menu2.class));
break;
case R.id.nav_about:
startActivity(new Intent(QuizActivity.this, Menu3.class));
break;
}
return true;
}
});
mScoreView = (TextView) findViewById(R.id.score_score);
mQuestionView = (TextView) findViewById(R.id.question);
mButtonChoice1 = (Button) findViewById(R.id.choice1);
mButtonChoice2 = (Button) findViewById(R.id.choice2);
mButtonChoice3 = (Button) findViewById(R.id.choice3);
final List<Button> choices = new ArrayList<>();
choices.add(mButtonChoice1);
choices.add(mButtonChoice2);
choices.add(mButtonChoice3);
updateQuestion();
//Code of the mediaplayer begins:
for (final Button choice : choices) {
choice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (choice.getText().equals(mAnswer)) {
try {
mp = new MediaPlayer();
if (playSounds) {
mp.setVolume(1, 1);
} else {
mp.setVolume(0, 0);
}
AssetFileDescriptor afd;
afd = getAssets().openFd("sample.mp3");
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mp.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
mp.start();
updateScore();
updateQuestion();
Toast.makeText(QuizActivity.this, "Correct", Toast.LENGTH_SHORT).show();
} else {
try {
mp2 = new MediaPlayer();
if (playSounds) {
mp2.setVolume(1, 1);
} else {
mp2.setVolume(0, 0);
}
AssetFileDescriptor afd;
afd = getAssets().openFd("wrong.mp3");
mp2.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mp2.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mp2.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
mp2.start();
Toast.makeText(QuizActivity.this, "Wrong... Try again!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(QuizActivity.this, Menu2.class);
intent.putExtra("score", mScore); // pass score to Menu2
startActivity(intent);
}
}
});
}
}
//End mediaplayer main code
private void updateQuestion() {
if (mQuestionNumber < mQuestionLibrary.getLength()) {
mQuestionView.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
mButtonChoice1.setText(mQuestionLibrary.getChoice1(mQuestionNumber));
mButtonChoice2.setText(mQuestionLibrary.getChoice2(mQuestionNumber));
mButtonChoice3.setText(mQuestionLibrary.getChoice3(mQuestionNumber));
mAnswer = mQuestionLibrary.getCorrectAnswer(mQuestionNumber++);
} else {
Toast.makeText(QuizActivity.this, "Last Question! You are very intelligent!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(QuizActivity.this, Menu2.class);
intent.putExtra("score", mScore);
startActivity(intent);
}
}
private void updateScore() {
mScoreView.setText(String.valueOf(++mScore));
SharedPreferences mypref = getPreferences(MODE_PRIVATE);
int highScore = mypref.getInt("highScore", 0);
if (mScore > highScore) {
SharedPreferences.Editor editor = mypref.edit();
editor.putInt("highScore", mScore);
editor.apply();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return mToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}
private void createDialog() {
dialog = new Dialog(this);
dialog.setTitle("Tutorial");
dialog.setContentView(R.layout.popup_menu1_1);
closeButton = (TextView) dialog.findViewById(R.id.closeTXT);
}
private void createDialog2() {
dialog2 = new Dialog(this);
dialog2.setTitle("Settings");
dialog2.setContentView(R.layout.popup_menu1_2);
closeButton2 = (TextView) dialog2.findViewById(R.id.closeTXT2);
checkBoxmp = (CheckBox) dialog2.findViewById(R.id.ckeckBox);
}
}

Create Delete Dialog on selected piechart value?

I created this android app using the MPAndroidChart Library, which allows the user to create a quick PieChart using an ArrayList (I added some screenshots, for clarification).
My problem is that I want to allow the user to delete an entry from the piechart (and the array list), the pie chart should then be rendered without the removed entry.
Is there any way I can achieve this by allowing the user to long press an item, which opens some sort of yes/no dialog?
Screenshots gallery
Code:
package com.example.quickpie;
public class Main extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final List<PieEntry> entries = new ArrayList<>();
final EditText editText = (EditText) findViewById(R.id.editText);
final EditText editText2 = (EditText) findViewById(R.id.editText2);
final EditText editText3 = (EditText) findViewById(R.id.editText3);
final Button button = (Button) findViewById(R.id.button);
final Button button2 = (Button) findViewById(R.id.button2);
final TextView textView = (TextView) findViewById(R.id.textView);
final TextView textView2 = (TextView) findViewById(R.id.textView2);
final TextView textView3 = (TextView) findViewById(R.id.textView3);
editText.requestFocus();
button.setOnClickListener(new View.OnClickListener() {
public void onClick (View v) {
//if(editText.getFreezesText())
if (editText.getText().toString().matches("")) {
Toast.makeText(getBaseContext(), "You did not enter a Valid Item ID", Toast.LENGTH_LONG).show();
return;
}
else if (editText2.getText().toString().matches("")) {
Toast.makeText(getBaseContext(), "You did not enter a Valid Quantitiy", Toast.LENGTH_LONG).show();
return;
}
else {
String nomen = (editText.getText().toString());
float number = Float.parseFloat(editText2.getText().toString());
final PieChart piechart = (PieChart) findViewById(R.id.piechart);
entries.add(new PieEntry(number, nomen));
editText.setText("");
editText2.setText("");
textView3.setSingleLine(false);
textView3.append("\n" + nomen + " " + number);
editText.requestFocus();
PieDataSet set = new PieDataSet(entries, "");
//colors
getResources().getColor(R.color.violp);
getResources().getColor(R.color.bluep);
getResources().getColor(R.color.redp);
getResources().getColor(R.color.greenp);
getResources().getColor(R.color.yellowp);
getResources().getColor(R.color.orangep);
getResources().getColor(R.color.lightbluep);
getResources().getColor(R.color.purplep);
getResources().getColor(R.color.darkredp);
set.setColors(new int[]{R.color.bluep, R.color.greenp, R.color.violp, R.color.redp, R.color.yellowp, R.color.orangep, R.color.lightbluep, R.color.purplep, R.color.darkredp}, getApplicationContext());
PieData data = new PieData(set);
piechart.setData(data);
Description description = new Description();
description.setText(getResources().getString(R.string.besch));
piechart.setDescription(description);
Toast.makeText(getBaseContext(), (R.string.loading),
Toast.LENGTH_SHORT).show();
String mitte = (editText3.getText().toString());
piechart.setCenterText(mitte);
piechart.setCenterTextSize(30);
piechart.setNoDataText(String.valueOf(R.string.nodata));
piechart.notifyDataSetChanged();
piechart.animateX(2000, Easing.EasingOption.EaseInExpo);
piechart.animateY(2000, Easing.EasingOption.EaseInExpo);
piechart.invalidate();
editText3.setVisibility(View.VISIBLE);
editText3.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
String mitte = (editText3.getText().toString());
piechart.setCenterText(mitte);
editText3.setText("");
editText.requestFocus(); //editText3.setVisibility(View.INVISIBLE);
InputMethodManager imm = (InputMethodManager) getSystemService(Main.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
//do something
}
return false;
}
});
editText3.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (MotionEvent.ACTION_UP == event.getAction()) {
piechart.setCenterText("");
textView3.setHint(R.string.hint1);
}
return false; // return is important...
}
});
button.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Toast.makeText(getBaseContext(), R.string.longpresshint, Toast.LENGTH_LONG).show();
return true;
}
});
final Button button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mitte = (editText3.getText().toString());
piechart.setCenterText(mitte);
//piechart.setVisibility(View.VISIBLE);
//editText.setVisibility(View.INVISIBLE);
//textView2.setVisibility(View.INVISIBLE);
//textView3.setVisibility(View.INVISIBLE);
//editText3.setVisibility(View.INVISIBLE);
// editText2.setVisibility(View.INVISIBLE);
//button.setVisibility(View.INVISIBLE);
//button2.setVisibility(View.INVISIBLE);
Toast.makeText(getBaseContext(), (R.string.loading),
Toast.LENGTH_SHORT).show();
piechart.animateX(2000, Easing.EasingOption.EaseInExpo);
piechart.animateY(2000, Easing.EasingOption.EaseInExpo);
InputMethodManager imm = (InputMethodManager) getSystemService(Main.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
}
});
}}
}
)
;
}
#Override
public void onBackPressed(){
super.onBackPressed();
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
Please try this
button.setOnClickListener(new View.OnClickListener() {
public void onClick (View v) {
//if(editText.getFreezesText())
if (editText.getText().toString().matches("")) {
Toast.makeText(getBaseContext(), "You did not enter a Valid Item ID", Toast.LENGTH_LONG).show();
return;
}
else if (editText2.getText().toString().matches("")) {
Toast.makeText(getBaseContext(), "You did not enter a Valid Quantitiy", Toast.LENGTH_LONG).show();
return;
}
else {
piechart.invalidate();
}

android.widget.Button cannot be cast to android.widget.CheckBox

I'm getting the error from the title in my Android project. I have searched for similar issues, which had me checkboxes casting, which seems ok, and also to clean and rebuild the project, which it did not work.
The app is crashing when I click the "Register" Button after a register form that contains EditTexts (for username, email and password) and Checkboxes for the user to pick multiple items. What should I do next?
public class RegisterActivity extends Activity {
ArrayList<Sport> sports = new ArrayList<>();
ArrayList<Sport> selectedSports = new ArrayList<>();
private void initializeSports(){
String[] sportsArray = getResources().getStringArray(array.sportsName);
for (int i = 0; i < sportsArray.length; i++){
sports.add(new Sport(i + 1, sportsArray[i]));
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(layout.activity_register);
initializeSports();
final EditText etEmail = (EditText) findViewById(id.etEmail);
final EditText etUsername = (EditText) findViewById(id.etUsername);
final EditText etPassword = (EditText) findViewById(id.etPassword);
final Button bRegister = (Button) findViewById(id.bRegister);
final CheckBox cbSoccer = (CheckBox) findViewById(id.cbSoccer);
cbSoccer.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
selectItem(v);
}
});
final CheckBox cbFootball = (CheckBox) findViewById(id.cbFootball);
cbFootball.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
selectItem(v);
}
});
final CheckBox cbBasket = (CheckBox) findViewById(id.cbBasket);
cbBasket.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
selectItem(v);
}
});
final CheckBox cbTennis = (CheckBox) findViewById(id.cbTennis);
cbTennis.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
selectItem(v);
}
});
final CheckBox cbSwimming = (CheckBox) findViewById(id.cbSwimming);
cbSwimming.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
selectItem(v);
}
});
final CheckBox cbGym = (CheckBox) findViewById(id.cbGym);
cbGym.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
selectItem(v);
}
});
final CheckBox cbOther = (CheckBox) findViewById(id.cbOther);
cbOther.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
selectItem(v);
}
});
bRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String username = etUsername.getText().toString();
final String email = etEmail.getText().toString();
final String passcode = etPassword.getText().toString();
selectItem(v);
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
RegisterActivity.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
builder.setMessage("Register Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(username, email, passcode, selectedSports, responseListener);
RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
queue.add(registerRequest);
}
});
}
public void selectItem(View v){
boolean checked = ((CheckBox)v).isChecked();
switch(v.getId()){
case R.id.cbSoccer:
if(checked){
selectedSports.add(sports.get(0));
} else{
selectedSports.remove(sports.get(0));
} break;
case R.id.cbFootball:
if(checked){
selectedSports.add(sports.get(1));
} else{
selectedSports.remove(sports.get(1));
} break;
case R.id.cbTennis:
if(checked){
selectedSports.add(sports.get(2));
} else{
selectedSports.remove(sports.get(2));
} break;
case R.id.cbSwimming:
if(checked){
selectedSports.add(sports.get(3));
} else{
selectedSports.remove(sports.get(3));
} break;
case R.id.cbGym:
if(checked){
selectedSports.add(sports.get(4));
} else{
selectedSports.remove(sports.get(4));
} break;
case R.id.cbBasket:
if(checked){
selectedSports.add(sports.get(5));
} else{
selectedSports.remove(sports.get(5));
} break;
case R.id.cbOther:
if(checked){
selectedSports.add(sports.get(6));
} else{
selectedSports.remove(sports.get(6));
} break;
}
}
}
You are casting the view to CheckBox in your selectItem(v) method and in your listener
bRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectItem(v);
}
});
You are passing the View v, i.e, the clicked button, so the button can not be casted to CheckBox.
Remove this line from listener
selectItem(v);
and it will be alright.
In the selectItem(v) method the view passed to the method is an instance of Button since it is written in the onClickListener of button
If you want to do the same first make a check in selectItem(View v) method
if(v instanceof CheckBox) {
boolean checked = ((CheckBox)v).isChecked();
}
Then proceed with the rest of code

Bluetooth sending data

Im new at android development. I'm developing an app where first of all, I have a main activity where I must turn On/Off the bluetooth, make it discoverable, search devices and connect to them.
After this, I go to other activity where I have a text view with a edittext and a send button, where I can write something and send it.
I've got working all the bluetooth enabling/disabling stuff, but now I need to connect to new found devices and then enter to the chat type activity and send.
I now this is pretty much work, but it would be great if you can give me an example of how can I do this. This is the code i have:
public class BTActivity extends Activity {
// Intent request codes
private static final int REQUEST_DISCOVERABLE_BT = 0;
private static final int REQUEST_CONNECT_DEVICE = 1;
private static final int REQUEST_ENABLE_BT = 2;
// Debugging
private static final String TAG = "BluetoothChat";
private static final boolean D = true;
// Name of the connected device
public static String mConnectedDeviceName = null;
// Array adapter for device list
private ArrayAdapter<String> mArrayAdapter;
// Local Bluetooth adapter
private BluetoothAdapter mBluetoothAdapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button button1 = (Button) findViewById(R.id.boton1);
final Button button2 = (Button) findViewById(R.id.boton2);
final Button button3 = (Button) findViewById(R.id.boton3);
final Button button4 = (Button) findViewById(R.id.boton4);
final Button button5 = (Button) findViewById(R.id.boton5);
button5.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
lanzarComunicacion (null);
}
});
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
button3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
});
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//LLAMA A LA DIALOG ACTIVITY PARA VISUALIZAR LOS DISPOSITIVOS
LanzarBusqueda(null);
}
});
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (!mBluetoothAdapter.isDiscovering()) {
Context context = getApplicationContext();
CharSequence text = "MAKING YOUR DEVICE DISCOVERABLE";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
}
}
});
button4.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mBluetoothAdapter.disable();
Context context = getApplicationContext();
CharSequence text = "TURNING_OFF BLUETOOTH";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, 15);
toast.show();
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CONNECT_DEVICE:
if (resultCode == Activity.RESULT_OK) {
connectDevice(data);
}
}
}
private void connectDevice(Intent data) {
String address = data.getExtras().getString(DeviceListDialog.EXTRA_DEVICE_ADDRESS);
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
BTCommunication.mChatService.connect(device);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.bt, menu);
return true;
}
public void lanzarComunicacion (View view) {
Intent i = new Intent(this, BTCommunication.class);
startActivity(i);
}
public void LanzarBusqueda (View view) {
Intent i = new Intent(this, DeviceListDialog.class);
startActivity(i);
}
}

Categories