Make visible and invisible imageView by a button - java

I have three Activities with one button in each of them. Act1 with btn1, Act2 with btn2, and Act3 with btn3. I have another Activity as MainActivity with three imageViews: ImageView1, imageView2 and imageView3, all of which are initially invisible. I want it so when I click on btn1 in act1, imageView1 in MainActivity will be visible and when click on btn1 again, imageView1 will be invisible again. And similarly for imageView2 and imageView3.
I have this code so far:
Activity1
public class Activity1 extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity1);
Button btn1 = (Button) findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String visibilityStr = PublicSharedPreferences.getDefaults("keyVisibility", getApplicationContext());
if (visibilityStr != null) {
if (visibilityStr.equals("0")) {
Toast.makeText(act1.this, "it visibled", Toast.LENGTH_SHORT).show();
visibilityStr = "1";
btn1.setImageResource(R.mipmap.img1);
} else {
visibilityStr = "0";
Toast.makeText(act1.this, "it invisibled", Toast.LENGTH_SHORT).show();
btn1.setImageResource(R.mipmap.img2);
}
} else {
visibilityStr = "1";
Toast.makeText(act1.this, "it visibled", Toast.LENGTH_SHORT).show();
btn1.setImageResource(R.mipmap.img1);
}
PublicSharedPreferences.setDefaults("keyVisibility", visibilityStr, getApplicationContext());
}
});
}
Activity2
public class Activity2 extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity2);
Button btn1 = (Button) findViewById(R.id.btn2);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String visibilityStr = PublicSharedPreferences.getDefaults("keyVisibility", getApplicationContext());
if (visibilityStr != null) {
if (visibilityStr.equals("0")) {
Toast.makeText(act2.this, "it visibled", Toast.LENGTH_SHORT).show();
btn2.setImageResource(R.mipmap.img1);
visibilityStr = "1";
} else {
visibilityStr = "0";
Toast.makeText(act2.this, "it invisibled", Toast.LENGTH_SHORT).show();
btn2.setImageResource(R.mipmap.img2);
}
} else {
visibilityStr = "1";
Toast.makeText(act2.this, "it visibled", Toast.LENGTH_SHORT).show();
btn2.setImageResource(R.mipmap.img1);
}
PublicSharedPreferences.setDefaults("keyVisibility", visibilityStr, getApplicationContext());
}
});
}
Activity3
public class Activity3 extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity3);
Button btn1 = (Button) findViewById(R.id.btn3);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String visibilityStr = PublicSharedPreferences.getDefaults("keyVisibility", getApplicationContext());
if (visibilityStr != null) {
if (visibilityStr.equals("0")) {
Toast.makeText(act3.this, "it visibled", Toast.LENGTH_SHORT).show();
Btn3.setImageResource(R.mipmap.img1);
visibilityStr = "1";
} else {
visibilityStr = "0";
Toast.makeText(act3.this, "it invisibled", Toast.LENGTH_SHORT).show();
btn3.setImageResource(R.mipmap.img2);
}
} else {
visibilityStr = "1";
Toast.makeText(act3.this, "it visibled", Toast.LENGTH_SHORT).show();
btn3.setImageResource(R.mipmap.img1);
}
PublicSharedPreferences.setDefaults("keyVisibility", visibilityStr, getApplicationContext());
}
});
}
MainActivity with three imageViews:
ImageView imgView1 = (ImageView) findViewById(R.id.imgView1);
String visibilityStr= PublicSharedPreferences.getDefaults("keyVisibility", getApplicationContext());
if (visibilityStr.equals("0"))
imgView1.setVisibility(View.INVISIBLE);
else
imgView1.setVisibility(View.VISIBLE);
ImageView imgView2 = (ImageView) findViewById(R.id.imgView2);
String visibilityStr= PublicSharedPreferences.getDefaults("keyVisibility", getApplicationContext());
if (visibilityStr.equals("0"))
imgView2.setVisibility(View.INVISIBLE);
else
imgView2.setVisibility(View.VISIBLE);
ImageView imgView3 = (ImageView) findViewById(R.id.imgView3);
String visibilityStr= PublicSharedPreferences.getDefaults("keyVisibility", getApplicationContext());
if (visibilityStr.equals("0"))
imgView3.setVisibility(View.INVISIBLE);
else
imgView3.setVisibility(View.VISIBLE);
They work well. But the problem is that when I click on btn1, all imageViews in MainActivity change (become visible or invisible) or when I click on btn3, all imageViews change. I want it so btn1 just changes imageView1 and btn2 just changes imageView2 and btn3 just changes imageView3, instead of one of the buttons changing all of the imageViews. How can I do that? Which part of the code is wrong?

the problem is you only have 1key Preference its all keyVisibility so when you click on any of your button this key changes to either 1 or 0 base on your code
here
ImageView imgView1 = (ImageView) findViewById(R.id.imgView1);
String visibilityStr1= PublicSharedPreferences.getDefaults("keyVisibility1", getApplicationContext());
if (visibilityStr1.equals("0"))
imgView1.setVisibility(View.INVISIBLE);
else
imgView1.setVisibility(View.VISIBLE);
ImageView imgView2 = (ImageView) findViewById(R.id.imgView2);
String visibilityStr2= PublicSharedPreferences.getDefaults("keyVisibility2", getApplicationContext());
if (visibilityStr2.equals("0"))
imgView2.setVisibility(View.INVISIBLE);
else
imgView2.setVisibility(View.VISIBLE);
ImageView imgView3 = (ImageView) findViewById(R.id.imgView3);
`String visibilityStr3= PublicSharedPreferences.getDefaults("keyVisibility3",` `getApplicationContext());`
if (visibilityStr3.equals("0"))
imgView3.setVisibility(View.INVISIBLE);
else
imgView3.setVisibility(View.VISIBLE);
and ofcoure you should change the keyVisibility on your act1,act2 and act3

First of all, please do a little more study on Android SharedPreferences (how to save/get a sharepreference value properly in/from your local storage).
After you are done with your research, here's some hint for you. Hope you will be able to implement this on your own.
Save value - save your boolean value when you click the button
Context mContext = getApplicationContext();
SharedPreferences mPrefs = mContext.getSharedPreferences("MySharedPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean("IsImageViewVisible", true);
// use different keys for different imageviews;
//ex: for ImageView1, use IsImageView_1_Visible; for ImageView2, use IsImageView_2_Visible etc
editor.commit();
Get values in your MainActivity
Context mContext = getApplicationContext();
SharedPreferences mPrefs = mContext.getSharedPreferences("MySharedPrefs", Context.MODE_PRIVATE);
Boolean isImageViewVisible = mPrefs.getBoolean("IsImageViewVisible", false); // here,false is default value
Then, check all imageview's visibility in MainActivity:
if(isImageViewVisible){
// image is visible
} else{
// image is invisible
}

this is very easy ,you can use one of this methods
1 : Shared Preferences :
in your Activities (Act1,Act2,Act3)
write this codes on onClick event :
// on Act1
final SharedPreferences sharedPreferences=getSharedPreferences("mainconf",MODE_PRIVATE);
buttonOnAct1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// check if isVisable and change value
if (sharedPreferences.getBoolean("isImg1Visable",true)){
sharedPreferences.edit().putBoolean("isImg1Visable",false).apply();
}else {
// show it again
sharedPreferences.edit().putBoolean("isImg1Visable",true).apply();
}
}
});
// on Act2
final SharedPreferences sharedPreferences=getSharedPreferences("mainconf",MODE_PRIVATE);
buttonOnAct2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// check if isVisable and change value
if (sharedPreferences.getBoolean("isImg2Visable",true)){
sharedPreferences.edit().putBoolean("isImg2Visable",false).apply();
}else {
// show it again
sharedPreferences.edit().putBoolean("isImg2Visable",true).apply();
}
}
});
// on Act3
final SharedPreferences sharedPreferences=getSharedPreferences("mainconf",MODE_PRIVATE);
buttonOnAct3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// check if isVisable and change value
if (sharedPreferences.getBoolean("isImg3Visable",true)){
sharedPreferences.edit().putBoolean("isImg3Visable",false).apply();
}else {
// show it again
sharedPreferences.edit().putBoolean("isImg3Visable",true).apply();
}
}
});
And code of your MainActivity :
public class MainActivity extends AppCompatActivity {
private ImageView imageView1;
private ImageView imageView2;
private ImageView imageView3;
private SharedPreferences sharedPreferences;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
imageView1=(ImageView)findViewById(R.id.img1);
imageView2=(ImageView)findViewById(R.id.img2);
imageView3=(ImageView)findViewById(R.id.img3);
sharedPreferences=getSharedPreferences("mainconf",MODE_PRIVATE);
}
// important PART OF CODE
#Override
protected void onResume() {
super.onResume();
if (sharedPreferences.getBoolean("isImg1Visable",true)){
imageView1.setVisibility(View.VISIBLE);
}else {
imageView1.setVisibility(View.GONE);
}
if (sharedPreferences.getBoolean("isImg2Visable",true)){
imageView2.setVisibility(View.VISIBLE);
}else {
imageView2.setVisibility(View.GONE);
}
if (sharedPreferences.getBoolean("isImg3Visable",true)){
imageView3.setVisibility(View.VISIBLE);
}else {
imageView3.setVisibility(View.GONE);
}
}
}
2 : public static Variables:
write your variables as static
example :
// in Your MainActivty under class
public static ImageView imageView1;
public static ImageView imageView2;
public static ImageView imageView3;
// in your Act1 Act2 Act3
// for hiding from mainactivity
MainActivity.imageView1.setVisibility(View.GONE); // or View.INVISIBLE
// for showing on main activity
MainActivity.imageView1.setVisibility(View.VISIBLE);

Related

passing data from a bottom sheet dialog in first Activity to second Activity

I have a problem with passing data in android. let me explain my problem.
there are two activities called MainActivity and ProductInformationActivity.
in mainActivity there is a settingButton and onClickListener of the button, a bottom sheet dialog will open up. in bottomSheetDialog there are saveButton and three editText. whenever a user click on saveButton it should pass editTexts data's as PercentageClass to productInformationActivity . (percentage Class is a model to save percentages and pass theme between activities).
I create an interface Called "OnPercentageClicked" then I created an instance of this interface and create setter for that (setOnAddPercentageClicked).
in saveButtonListener I create instance of percentege class and set EditTexts data to it and finally I add percentage to interface's method.
this is mainACtivity:
public class MainActivity extends AppCompatActivity {
private View bottomSheetView;
private BottomSheetDialog bottomSheetDialog;
private OnAddPercentageClicked onAddPercentageClicked;
public void setOnAddPercentageClicked(OnAddPercentageClicked onAddPercentageClicked) {
this.onAddPercentageClicked = onAddPercentageClicked;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar mainToolbar = findViewById(R.id.mainToolbar);
setSupportActionBar(mainToolbar);
ImageButton settingbtn = findViewById(R.id.activityMain_settingBTN);
ViewPager2 viewPager2 = findViewById(R.id.activityMain_viewpager);
TabLayout tabLayout = findViewById(R.id.activityMain_tabLayout);
MainViewPagerAdapter adapter = new MainViewPagerAdapter(this);
viewPager2.setAdapter(adapter);
createDialog();
TabLayoutMediator tabLayoutMediator = new TabLayoutMediator(tabLayout, viewPager2, new TabLayoutMediator.TabConfigurationStrategy() {
#Override
public void onConfigureTab(#NonNull TabLayout.Tab tab, int position) {
switch (position){
case 0 : tab.setText("کالا ها"); break;
case 1 : tab.setText("دسته بندی ها"); break;
}
}
});
tabLayoutMediator.attach();
settingbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bottomSheetDialog.show();
TextInputEditText firstPercentage = bottomSheetDialog.findViewById(R.id.priceIncrementPercentage_firstPercentageET);
TextInputEditText secondPercentage = bottomSheetDialog.findViewById(R.id.priceIncrementPercentage_secondPercentageET);
TextInputEditText thirdPercentage = bottomSheetDialog.findViewById(R.id.priceIncrementPercentage_thirdPercentageET);
Button percentageSaveButton = bottomSheetDialog.findViewById(R.id.priceIncrementPercentage_saveBTN);
assert percentageSaveButton != null;
percentageSaveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (firstPercentage.getText().length()>0 && secondPercentage.getText().length()>0 && thirdPercentage.getText().length()>0){
Percentage percentage = new Percentage();
percentage.setFirstPercentage(Integer.parseInt(firstPercentage.getText().toString()));
percentage.setSecondPercentage(Integer.parseInt(secondPercentage.getText().toString()));
percentage.setThirdPercentage(Integer.parseInt(thirdPercentage.getText().toString()));
onAddPercentageClicked.onButtonClicked(percentage);
bottomSheetDialog.dismiss();
Toast.makeText(MainActivity.this, "ذخیره شد", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(MainActivity.this, "لطفا همه ی فیلد ها را پر کنید", Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
public void createDialog(){
bottomSheetDialog = new BottomSheetDialog(MainActivity.this,R.style.bottom_sheet_dialog_theme);
bottomSheetDialog.setContentView(getLayoutInflater().inflate(R.layout.price_increment_percentage,(LinearLayout)findViewById(R.id.priceIncrementPercentage_container),false));
}
}
in productInfomation Activity i want to get the percentage class which i used in MainActivity.
so I implement OnAddPercentageClicked then I create an instance of main activity and call the setter which I created in MainActivity (setOnAddPercentageClicked).
this is productInformationActivity :
public class ProductInformation extends AppCompatActivity implements View.OnClickListener ,OnAddPercentageClicked{
private Percentage percentage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_information);
MainActivity mainActivity = new MainActivity();
mainActivity.setOnAddPercentageClicked(this);
TextView productName = findViewById(R.id.activityProductInformation_productNameTV);
TextView productPrice = findViewById(R.id.activityProductInformation_productPriceTV);
TextView productPriceFirstPercentage = findViewById(R.id.productPriceFirstPercentage);
TextView productPriceSecondPercentage = findViewById(R.id.productPriceSecondPercentage);
TextView productPriceThirdPercentage = findViewById(R.id.productPriceThirdPercentage);
TextView productCategoryName = findViewById(R.id.activityProductInformation_categoryNameTV);
ImageButton close = findViewById(R.id.activity_product_information_closeIB);
close.setOnClickListener(this);
if (percentage !=null){
productPriceFirstPercentage.setText("قیمت کالا +"+percentage.getFirstPercentage()+" درصد");
productPriceSecondPercentage.setText("قیمت کالا +"+percentage.getSecondPercentage()+" درصد");
productPriceThirdPercentage.setText("قیمت کالا +"+percentage.getThirdPercentage()+" درصد");
}
//
// }
if (getIntent().hasExtra("PRODUCT")){
Product product = getIntent().getParcelableExtra("PRODUCT");
productName.setText(product.getTitle());
productPrice.setText(String.valueOf(product.getPrice()));
productCategoryName.setText(String.valueOf(product.getCategoryId()));
}
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.activity_product_information_closeIB){
finish();
}
}
#Override
public void onButtonClicked(Percentage percentage) {
Log.i(TAG, "onButtonClicked: " + percentage);
this.percentage = percentage;
}
}
and when i run this code i get an error which says that the interface in MainActicvity is null.
would you please help me ?
thanks.

After an imageButton is clicked, how do I best disable other imageButtons, AND assign a variable with the selected imageButton’s value?

Context: My Style Activity corresponds to a layout with 4 imageButtons and a regular button. I want the user to only be able to select one imageButton at a time. Upon the click of the regular button, I want to send the data regarding which imageButton is selected to my ReviewActivity while simultaneously opening my ReflectionActivity.
I have 2 questions. First, how do I dry up my code surrounding OnClick's and disabled imageButtons? Second, how do I set a variable based on which imageButton was selected and send to another activity with an intent? I am fairly sure I've done this the long/hard way. All suggestions greatly appreciated!
public class StyleActivity extends AppCompatActivity {
Button btn_open_reflection;
ImageButton style1;
ImageButton style2;
ImageButton style3;
ImageButton style4;
public static final String style_selection = "com.example.application.hearttoart.style_selection";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_style );
// set up image buttons for the onClick function
style1 = (ImageButton)findViewById(R.id.style1);
style2 = (ImageButton)findViewById(R.id.style2);
style3 = (ImageButton)findViewById(R.id.style3);
style4 = (ImageButton)findViewById(R.id.style4);
// TODO: DRY up when possible, lots of repeated code here
style1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {
style2.setEnabled(false);
style3.setEnabled(false);
style4.setEnabled(false);
String style_selection = "#string/style1";
}
});
style2.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {
style1.setEnabled(false);
style3.setEnabled(false);
style4.setEnabled(false);
String style_selection = "#string/style2";
}
});
style3.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {
style1.setEnabled(false);
style2.setEnabled(false);
style4.setEnabled(false);
String style_selection = "#string/style3";
}
});
style4.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {
style1.setEnabled(false);
style2.setEnabled(false);
style3.setEnabled(false);
String style_selection = "#string/style4";
}
});
btn_open_reflection =(Button) findViewById(R.id.btn_open_style);
btn_open_reflection.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick (View view){
// Open Style Activity - Navigate to Activity from the Click
openReflection();
sendStyle();
}
});
}
public void sendStyle() {
Intent styleIntent = new Intent(StyleActivity.this, ReviewActivity.class );
styleIntent.putExtra("style", style_selection);
}
public void openReflection() {
Intent intent = new Intent( this, ReflectionActivity.class );
startActivity( intent );
}
}
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button btn_open_reflection;
ImageButton style1;
ImageButton style2;
ImageButton style3;
ImageButton style4;
String style_selection = "com.example.application.hearttoart.style_selection";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// set up image buttons for the onClick function
style1 = (ImageButton)findViewById(R.id.style1);
style2 = (ImageButton)findViewById(R.id.style2);
style3 = (ImageButton)findViewById(R.id.style3);
style4 = (ImageButton)findViewById(R.id.style4);
btn_open_reflection =(Button) findViewById(R.id.btn_open_style);
btn_open_reflection.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick (View view){
// Open Style Activity - Navigate to Activity from the Click
openReflection();
}
});
}
public void openReflection() {
Intent intent = new Intent( MainActivity.this, OtherActivity.class );
intent.putExtra("style", style_selection);
startActivity(intent);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.style1:
//disable other buttons
style2.setEnabled(false);
style3.setEnabled(false);
style4.setEnabled(false);
style_selection = "#string/style1";
break;
case R.id.style2:
style1.setEnabled(false);
style3.setEnabled(false);
style4.setEnabled(false);
style_selection = "#string/style2";
break;
case R.id.style3:
style1.setEnabled(false);
style2.setEnabled(false);
style4.setEnabled(false);
style_selection = "#string/style4";
break;
case R.id.style4:
style1.setEnabled(false);
style2.setEnabled(false);
style3.setEnabled(false);
style_selection = "#string/style4";
break;
}
}
}
This link might help.

My MediaPlayer and transition effect not working

Why I cannot put mp3 sound and transition effect to my button onClick?
While launching Activity2 my app crashing. How can I use MediaPlayer and my transition effect to my button onClick in private View.OnClickListener?
I'm using Transition effect (Bungee) from library
My code...
public class Activity2 extends AppCompatActivity {
private Button button3;
private Button entrycity;
private static final String NAME = "name";
private boolean isEnabled;
private SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_2);
button3 = findViewById(R.id.button3);
button3.setOnClickListener(onButton1Click);
entrycity = findViewById(R.id.entrycity);
entrycity.setOnClickListener(onButton2Click);
sharedPreferences = getSharedPreferences(NAME, MODE_PRIVATE);
isEnabled = sharedPreferences.getBoolean(winflagi.IS_ENABLED, false);
entrycity.setEnabled(isEnabled);
if (isEnabled){
entrycity.setBackgroundResource(R.drawable.oval);
}
else {
entrycity.setBackgroundResource(R.drawable.oval3);
}
}
final MediaPlayer mp = MediaPlayer.create(this, R.raw.menunewquite);
private View.OnClickListener onButton1Click = new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Activity2.this, flagi1.class));
mp.start();
Bungee.fade(this);
}
};
private View.OnClickListener onButton2Click = new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Activity2.this, cities1.class));
mp.start
Bungee.fade(this);
}
};
}
Try to declare MediaPlayer inside the body of the listener.

App crashes when implementing mute button [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I programmed a quiz now I set up a mediaplayer under the FOR-query, that every time the user hits a correct answer the sound will be played. Now in the same Activity I want that bttOFF will mute the sound of the Activity how can I do that? I set up an onClickListener with mp.setVolume(0,0); But the app crashes on restart. Thanks for looking! :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;
Dialog dialog2;
TextView closeButton;
TextView closeButton2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
final MediaPlayer mp = new MediaPlayer();
//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
Button bttON = (Button)findViewById(R.id.bttON);
bttON.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.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();
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);
}
private void createDialog2() {
dialog2 = new Dialog(this);
dialog2.setTitle("Settings");
dialog2.setContentView(R.layout.popup_menu1_2);
closeButton2 = (TextView) dialog2.findViewById(R.id.closeTXT2);
}
Logcat:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at shapy.appz.QuizActivity.onCreate(QuizActivity.java:96)
your get to findViewById fro your closeButton and closeButton2
As shown in the documentation for the MediaPlayer class [here]( https://developer.android.com/reference/android/media/MediaPlayer.html#setVolume(float, float) ) the needed parameters are floats. You could try to do this:
public void onClick(View v) {
mp.setVolume( 0.0, 0.0 );
}
And see if that solves your problem.
setVolume
added in API level 1
void setVolume (float leftVolume, float rightVolume)
Sets the volume on this player. This API is recommended for balancing the output of audio streams within an application. Unless you are writing an application to control user settings, this API should be used in preference to setStreamVolume(int, int, int) which sets the volume of ALL streams of a particular type. Note that the passed volume values are raw scalars in range 0.0 to 1.0. UI controls should be scaled logarithmically.
Parameters
leftVolume float: left volume scalar
rightVolume float: right volume scalar

Opening next Activity

I have have a problem here with my code. I want to open the next Activity using submit button but I'm having issues. Can anybody help me on the mistake I am making so that I can implement it? Thanks
public class Chairperson extends Activity implements View.OnClickListener{
TextView textView;
Button submit_btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chairperson);
submit_btn = (Button) findViewById(R.id.submit_btn);
submit_btn.setOnClickListener(this);
textView = (TextView) findViewById(R.id.welcome_txt);
String message = getIntent().getStringExtra("message");
textView.setText(message);
Button submit_btn = (Button) findViewById(R.id.submit_btn);
final TextView submitTextView = (TextView) findViewById(R.id.submitTextView);
final RadioGroup rg1 = (RadioGroup) findViewById(R.id.rg1);
submit_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Get the checked Radio Button ID from Radio Grou[
int selectedRadioButtonID = rg1.getCheckedRadioButtonId();
// If nothing is selected from Radio Group, then it return -1
if
(selectedRadioButtonID != -1) {
RadioButton selectedRadioButton = (RadioButton) findViewById(selectedRadioButtonID);
String selectedRadioButtonText = selectedRadioButton.getText().toString();
submitTextView.setText(selectedRadioButtonText + " selected.");
} else {
submitTextView.setText("Nothing selected .");
}
}
});
}
#Override
public void onClick(View v) {
startActivity(new Intent(this, ViceChairperson.class));
}
}
I have written a code for your button, delete all previous code for submit_btn in your code and replace with this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addListenerOnButton();
public void addListenerOnButton() {
final Context context = this;
submit_btn = (Button) findViewById(R.id.submit_btn);
submit_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (radioGroup.getCheckedRadioButtonId() == -1)
{
Toast.makeText(context, "Select an option.", Toast.LENGTH_LONG).show();
}
else{
Intent intent = new Intent(context, ViceChairperson.class);
startActivity(intent);
finish();
}
}
});
}
}
If you have any issues please let me know.
Just move the line
startActivity(new Intent(getApplicationContext(), ViceChairperson.class));
after the if (selectedRadioButtonID != -1) check. If that check succeeds you start the new activity, if not, nothing is launched.
There's no need for the second onClick method, which is not bound to anything and will never be invoked.

Categories

Resources