android app crash after adding actionbar.setsubtitle - java

I tried to run my app (from bignerdranch) and could not run it after adding the following code:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
ActionBar actionBar = getActionBar();
actionBar.setSubtitle("Bodies of Water");
}
I get a runtime exception . If i remove these lines the app runs ok .
ofcourse i added the line #TargetApi(11)
i tried changing my target sdk, i tried copying other people's code. nothing works!!
this is my code :
private void updateQuestion() {
int question = mQuestionBank[mCurrentIndex].getQuestion();
mQuestionTextView.setText(question);
}
private void checkAnswer(boolean userPressedTrue) {
boolean answerIsTrue = mQuestionBank[mCurrentIndex].isTrueQuestion();
int messageResId = 0;
if (mIsCheater[mCurrentIndex]) {
messageResId = R.string.judgment_toast;
} else {
if (userPressedTrue == answerIsTrue) {
messageResId = R.string.correct_toast;
} else {
messageResId = R.string.incorrect_toast;
}
}
Toast.makeText(this, messageResId, Toast.LENGTH_SHORT).show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null) {
return;
}
mIsCheater[mCurrentIndex] = data.getBooleanExtra(
CheatActivity.EXTRA_ANSWER_SHOWN, false);
}
#TargetApi(11)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate(Bundle) called");
setContentView(R.layout.activity_quiz);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
ActionBar actionBar = getActionBar();
actionBar.setSubtitle("Bodies of Water");
}
mQuestionTextView = (TextView) findViewById(R.id.question_text_view);
mTrueButton = (Button) findViewById(R.id.true_button);
mTrueButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer(true);
}
});
mFalseButton = (Button) findViewById(R.id.false_button);
mFalseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer(false);
}
}
);
mNextButton = (Button) findViewById(R.id.next_button);
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
// mIsCheater=false;
updateQuestion();
}
});
if (savedInstanceState != null) {
mCurrentIndex = savedInstanceState.getInt(KEY_INDEX, 0);
mIsCheater[mCurrentIndex] = savedInstanceState.getBoolean(CHEATED);
}
mCheatButton = (Button) findViewById(R.id.cheat_button);
mCheatButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(QuizActivity.this, CheatActivity.class);
boolean answerIsTrue = mQuestionBank[mCurrentIndex]
.isTrueQuestion();
i.putExtra(CheatActivity.EXTRA_ANSWER_IS_TRUE, answerIsTrue);
startActivityForResult(i, 0);
}
});
updateQuestion();
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
Log.i(TAG, "onSaveInstanceState");
savedInstanceState.putInt(KEY_INDEX, mCurrentIndex);
savedInstanceState.putBoolean(CHEATED, mIsCheater[mCurrentIndex]);
}
#Override
public void onStart() {
super.onStart();
Log.d(TAG, "onStart() called");
}
#Override
public void onPause() {
super.onPause();
Log.d(TAG, "onPause() called");
}
#Override
public void onResume() {
super.onResume();
Log.d(TAG, "onResume() called");
}
#Override
public void onStop() {
super.onStop();
Log.d(TAG, "onStop() called");
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy() called");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.quiz, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
`
what could be the problem?
please help me..

I had the same problem with bignerdranch.
It seems that because QuizActivity is a subclass of ActionBarActivity
instead of Activity I have to use getSupportActionBar() instead of
getActionBar()

Related

From Splash screen to Onboarding where I have 3 slides, then to Dashboard activity which ends up crashing not going through to dashboard

I initialy had Radio player i.e RadioActivity, which was working perfectly
The problem
I later decided to have a dashboad as the main activity where you can click a button to take you to the RadioActivty. Now app keeps crashing after splashscreen
Find The Codes Below
SplashScreen
private static int SPLASH_TIMER = 8000;
ImageView backgroundImage;
ImageView theLogo;
TextView poweredByLine;
Animation sideAnim, bottomAnim;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
getWindow().setFlags(WindowManager.LayoutParams.FLAGS_CHANGED,WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
setContentView(R.layout.activity_splash_screen);
backgroundImage = findViewById(R.id.background_image);
theLogo = findViewById(R.id.the_Logo);
poweredByLine = findViewById(R.id.powered_by_line);
sideAnim = AnimationUtils.loadAnimation(this, R.anim.side_anim);
bottomAnim = AnimationUtils.loadAnimation(this, R.anim.bottom_anim);
backgroundImage.setAnimation(sideAnim);
theLogo.setAnimation(sideAnim);
poweredByLine.setAnimation(bottomAnim);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(getApplicationContext(), OnBoarding.class);
startActivity(intent);
finish();
}
},SPLASH_TIMER);
}
}
OnBoarding
CardView nextCard;
LinearLayout dotsLayout;
ViewPager viewPager;
TextView[] dots;
int currentPosition;
SaveState saveState ;
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_onboarding);
nextCard = findViewById(R.id.nextCard);
dotsLayout = findViewById(R.id.dotsLayout);
viewPager = findViewById(R.id.slider);
dotsFunction(0);
saveState = new SaveState(OnBoarding.this,"OB");
if (saveState.getState() == 1){
Intent i = new Intent(OnBoarding.this,DashboardActivity.class);
startActivity(i);
finish();
}
OnBoardingAdapter adapter = new OnBoardingAdapter(this);
viewPager.setAdapter(adapter);
nextCard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
viewPager.setCurrentItem(currentPosition+1,true);
}
});
viewPager.setOnPageChangeListener(onPageChangeListener);
}
#RequiresApi(api = Build.VERSION_CODES.M)
private void dotsFunction(int pos){
dots = new TextView[4];
dotsLayout.removeAllViews();
for (int i = 0; i < dots.length ; i++){
dots[i] = new TextView(this);
dots[i].setText(Html.fromHtml("•"));
dots[i].setTextColor(getColor(R.color.white)); //this is the non selection color
dots[i].setTextSize(30);
dotsLayout.addView(dots[i]);
}
if (dots.length > 0){
dots[pos].setTextColor(getColor(R.color.teal_700)); //this is the selection color
dots[pos].setTextSize(40); //this is the selection size
}
}
ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onPageSelected(int position) {
dotsFunction(position);
currentPosition = position;
if (currentPosition <= 2){
nextCard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
viewPager.setCurrentItem(currentPosition+1);
}
});
}else{
nextCard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveState.setState(1);
Intent i = new Intent(OnBoarding.this, DashboardActivity.class);
startActivity(i);
finish();
}
});
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
}
DashBoardActivity
public class DashboardActivity extends AppCompatActivity implements View.OnClickListener{
private ImageView imageViewWebsite,imageViewEvents,imageViewLive,
imageViewVideos,imageViewBranches,imageViewDonate,
imageViewEkuwe,imageViewRadio,imageViewAudio;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
//defininf Cards
imageViewWebsite = (ImageView) findViewById(R.id.website_card);
imageViewEvents = (ImageView) findViewById(R.id.event_card);
imageViewLive = (ImageView) findViewById(R.id.live_card);
imageViewVideos = (ImageView) findViewById(R.id.videos_card);
imageViewBranches = (ImageView) findViewById(R.id.branches_card);
imageViewDonate = (ImageView) findViewById(R.id.donate_card);
imageViewEkuwe = (ImageView) findViewById(R.id.ekuwe_card);
imageViewRadio = (ImageView) findViewById(R.id.radio_card);
imageViewAudio = (ImageView) findViewById(R.id.audio_card);
//Add CLick listener to the card
imageViewWebsite.setOnClickListener(this);
imageViewEvents.setOnClickListener(this);
imageViewLive.setOnClickListener(this);
imageViewVideos.setOnClickListener(this);
imageViewBranches.setOnClickListener(this);
imageViewDonate.setOnClickListener(this);
imageViewEkuwe.setOnClickListener(this);
imageViewRadio.setOnClickListener(this);
imageViewAudio.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent i;
switch (v.getId()){
case R.id.website_card : i = new Intent(this, WebsiteActivity.class);startActivity(i); break;
case R.id.event_card : i = new Intent(this,EventsActivity.class);startActivity(i); break;
case R.id.live_card : i = new Intent(this, LiveActivity.class);startActivity(i); break;
case R.id.videos_card : i = new Intent(this, VideoActivity.class);startActivity(i); break;
case R.id.branches_card : i = new Intent(this,BranchesActivity.class);startActivity(i); break;
case R.id.donate_card : i = new Intent(this, DonateActivity.class);startActivity(i); break;
case R.id.ekuwe_card : i = new Intent(this,EkuweActivity.class);startActivity(i); break;
case R.id.radio_card : i = new Intent(this,RadioActivity.class);startActivity(i); break;
case R.id.audio_card : i = new Intent(this,AudioActivity.class);startActivity(i); break;
default:break;
}
}
}
RadioActivity
public class RadioActivity extends AppCompatActivity {
private TextView nowPlaying;
private ImageView playStop;
private BroadcastReceiver broadcastReceiver;
private String nowPlayingData = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radio);
playStop = findViewById(R.id.playStopBtn);
nowPlaying = findViewById(R.id.radioStationNowPlaying);
setIsPlaying(false);
processPhoneListenerPermission();
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
TelephonyManager tm = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
if (tm != null) {
if (tm.getCallState() == TelephonyManager.CALL_STATE_RINGING) {
if (getIsPlaying()) {
stop();
}
System.exit(0);
}
}
}
};
IntentFilter filter = new IntentFilter();
filter.addAction("android.intent.action.PHONE_STATE");
registerReceiver(broadcastReceiver, filter);
loadNowPlaying();
playStop.setOnClickListener(view -> {
if (isNetworkAvailable()) {
if (getIsPlaying()) {
stop();
} else {
play();
}
} else {
Toast.makeText(getApplicationContext(), "No internet", Toast.LENGTH_LONG).show();
}
});
}
private void loadNowPlaying() {
Thread t = new Thread() {
public void run() {
try {
while (!isInterrupted()) {
runOnUiThread(() -> reloadShoutCastInfo());
Thread.sleep(20000);
}
} catch (InterruptedException ignored) {
}
}
};
t.start();
}
private void reloadShoutCastInfo() {
if (isNetworkAvailable()) {
AsyncTaskRunner runner = new AsyncTaskRunner();
runner.execute();
}
}
#SuppressLint("StaticFieldLeak")
private class AsyncTaskRunner extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
FFmpegMediaMetadataRetriever mmr = new FFmpegMediaMetadataRetriever();
mmr.setDataSource(STREAMING_URL);
nowPlayingData = mmr.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_ICY_METADATA).replaceAll("StreamTitle", "").replaceAll("[=,';]+", "");
mmr.release();
return null;
}
#Override
protected void onPostExecute(String result) {
nowPlaying.setText(nowPlayingData);
}
}
private void processPhoneListenerPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE}, 121);
}
}
public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = null;
if (cm != null) {
networkInfo = cm.getActiveNetworkInfo();
}
return networkInfo != null && networkInfo.isConnectedOrConnecting();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == 121) {
if (!(grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
Toast.makeText(getApplicationContext(), "Permission not granted.\nWe can't pause music when phone ringing.", Toast.LENGTH_LONG).show();
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", (dialog, id) -> {
if (getIsPlaying()) {
stop();
}
System.exit(0);
})
.setNegativeButton("No", (dialog, id) -> dialog.cancel());
AlertDialog alert = builder.create();
alert.show();
}
private void setIsPlaying(boolean status) {
SharedPreferences.Editor editor = getApplicationContext().getSharedPreferences("isPlaying", MODE_PRIVATE).edit();
editor.putBoolean("isPlaying", status);
editor.apply();
}
private boolean getIsPlaying() {
SharedPreferences prefs = getApplicationContext().getSharedPreferences("isPlaying", MODE_PRIVATE);
return prefs.getBoolean("isPlaying", false);
}
private void play() {
setIsPlaying(true);
Intent servicePlayIntent = new Intent(this, MyService.class);
servicePlayIntent.putExtra("playStop", "play");
startService(servicePlayIntent);
playStop.setImageResource(R.drawable.ic_pause);
Toast.makeText(getApplicationContext(), "Loading ...", Toast.LENGTH_LONG).show();
}
private void stop() {
setIsPlaying(false);
Intent serviceStopIntent = new Intent(this, MyService.class);
serviceStopIntent.putExtra("playStop", "stop");
startService(serviceStopIntent);
playStop.setImageResource(R.drawable.ic_play);
Toast.makeText(getApplicationContext(), "Stop Radio...", Toast.LENGTH_LONG).show();
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onDestroy() {
stopService(new Intent(getApplicationContext(), MyService.class));
unregisterReceiver(broadcastReceiver);
super.onDestroy();
}
}
OnBoardingAdapter
public class OnBoardingAdapter extends PagerAdapter {
Context context;
LayoutInflater layoutInflater;
public OnBoardingAdapter(Context context) {
this.context = context;
}
int titles[] = {
R.string.title1,
R.string.title2,
R.string.title3,
R.string.title4
};
int subtitles[] = {
R.string.subtitle1,
R.string.subtitle2,
R.string.subtitle3,
R.string.subtitle4
};
int images[] = {
R.drawable.on_boarding_vector_1,
R.drawable.on_boarding_vector_2,
R.drawable.on_boarding_vector_3,
R.drawable.on_boarding_vector_4
};
int bg[] = {
R.drawable.bg1,
R.drawable.bg2,
R.drawable.bg3,
R.drawable.bg4
};
#Override
public int getCount() {
return titles.length;
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == (ConstraintLayout) object;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View v = layoutInflater.inflate(R.layout.slide,container,false);
ImageView image = v.findViewById(R.id.slideImg);
TextView title = v.findViewById(R.id.sliderTitle);
TextView subtitle = v.findViewById(R.id.sliderSubtitle);
ConstraintLayout layout = v.findViewById(R.id.sliderLayout);
image.setImageResource(images[position]);
title.setText(titles[position]);
subtitle.setText(subtitles[position]);
layout.setBackgroundResource(bg[position]);
container.addView(v);
return v;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((ConstraintLayout) object);
}
}
I found the solution to this, I had to turn to Design Mode and Inspected everything i
found the problem on line 18 DashboardActivity.xml
I changed this
com.google.android.material.bottomappbar.BottomAppBar to
com.google.android.material.appbar.AppBarLayout

Use public boolean onKeyDown in all activities

I'm new in Android Studio and I have created a simple application with 10 activities.
Now, I want to intercept the KeyEvent.KEYCODE_BACK from the user in all of my activities.
I'm opening a dialog when KEYCODE_BACK. It's ok in my MainActivity but I don't want to copy this code in all of my activities.
Would anyone have an idea ?
public class MainActivity extends AppCompatActivity
{
Dialog myDialog;
Button BoutonAccepter;
Button BoutonRefuser;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
myDialog = new Dialog(this);
if (keyCode == KeyEvent.KEYCODE_BACK)
{
myDialog.setContentView(R.layout.popup);
BoutonAccepter = (Button) myDialog.findViewById(R.id.BoutonAccepter);
BoutonRefuser = (Button) myDialog.findViewById(R.id.BoutonRefuser);
BoutonAccepter.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(getApplicationContext(), "Non", Toast.LENGTH_LONG).show();
myDialog.dismiss();
}
});
BoutonRefuser.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(getApplicationContext(), "Oui", Toast.LENGTH_LONG).show();
myDialog.dismiss();
}
});
myDialog.show();
}
else
{
return super.onKeyDown(keyCode, event);
}
return true;
}
}
I think that you should separate this code into a separate abstract class and make exdends of this class for all your activities
public abstract class BaseActivity extends AppCompatActivity
{
Dialog myDialog;
Button BoutonAccepter;
Button BoutonRefuser;
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
myDialog = new Dialog(this);
if (keyCode == KeyEvent.KEYCODE_BACK)
{
myDialog.setContentView(R.layout.popup);
BoutonAccepter = (Button) myDialog.findViewById(R.id.BoutonAccepter);
BoutonRefuser = (Button) myDialog.findViewById(R.id.BoutonRefuser);
BoutonAccepter.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(getApplicationContext(), "Non", Toast.LENGTH_LONG).show();
myDialog.dismiss();
}
});
BoutonRefuser.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(getApplicationContext(), "Oui", Toast.LENGTH_LONG).show();
myDialog.dismiss();
}
});
myDialog.show();
}
else
{
return super.onKeyDown(keyCode, event);
}
return true;
}
}
And in all activities
public class ActivityA extends BaseActivity {
}

How to always check a condition in Android?

I want to develop an app to toggle the device's audio status. If the audio status is silent then my button's text should be "silent", if it's normal the text should be "normal"
Here is my only class:
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button btn1= (Button) findViewById(R.id.btn1);
final AudioManager audio = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
if (audio.getRingerMode()==AudioManager.RINGER_MODE_NORMAL)
{
btn1.setText("Normal");
}
else if (audio.getRingerMode()==AudioManager.RINGER_MODE_SILENT)
{
btn1.setText("Silent");
}
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (audio.getRingerMode()==AudioManager.RINGER_MODE_NORMAL)
{
audio.setRingerMode(AudioManager.RINGER_MODE_SILENT);
btn1.setText("Silent");
}
else if (audio.getRingerMode()==AudioManager.RINGER_MODE_SILENT)
{
audio.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
btn1.setText("Normal");
}
}
});
}
});
How can I always check this condition in Android ?
If you need to get the mode of current ringer even if it was changed outside from you application context then you should register a BroadcastReceiver for AudioManager.RINGER_MODE_CHANGED_ACTION.
This receiver will be called everytime someone changes the ringer mode.
Do this inside onCreate.
BroadcastReceiver receiver=new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
if (audio.getRingerMode()==AudioManager.RINGER_MODE_NORMAL)
{
btn1.setText("Silent");
}
else if (audio.getRingerMode()==AudioManager.RINGER_MODE_SILENT)
{
btn1.setText("Normal");
}
}
};
IntentFilter filter=new IntentFilter(AudioManager.RINGER_MODE_CHANGED_ACTION);
registerReceiver(receiver,filter);
Just do this
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (audio.getRingerMode()==AudioManager.RINGER_MODE_NORMAL)
{
audio.setRingerMode(AudioManager.RINGER_MODE_SILENT);
btn1.setText("Silent");
}
else if (audio.getRingerMode()==AudioManager.RINGER_MODE_SILENT)
{
audio.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
btn1.setText("Normal");
}
}
});
what your are doing is
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (audio.getRingerMode()==AudioManager.RINGER_MODE_NORMAL)
{
audio.setRingerMode(AudioManager.RINGER_MODE_SILENT);
btn1.setText("Silent");
}
else if (audio.getRingerMode()==AudioManager.RINGER_MODE_SILENT)
{
audio.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
btn1.setText("Normal");
}
}
});
}
});

How to Reference Buttons in the same Activity from a Custom View

I am trying to make a simple drawing application, but am running into problems switching the paint color.Here is the tutorial I used to get to the point I am at. Here is my code:
Drawing_View.java
public class Drawing_View extends View {
private Path path = new Path();
private Paint paint = new Paint();
public String paint_color = "#FFBB00";
public Drawing_View(Context context, AttributeSet attrs) {
super(context, attrs);
paint.setAntiAlias(true);
paint.setStrokeWidth(5f);
paint.setColor(Color.parseColor(paint_color));
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(path, paint);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float eventY = event.getY();
float eventX = event.getX();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// Set a new starting point
path.moveTo(eventX, eventY);
return true;
case MotionEvent.ACTION_MOVE:
// Connect the points
path.lineTo(eventX, eventY);
break;
default:
return false;
}
invalidate();
return true;
}
}
Here is the code for the activity the custom view sits inside.
Drawing_Main.java
public class Drawing_Main extends ActionBarActivity {
Button green_light,green_dark,blue_light,blue_dark,blue_verydark,purple,magenta,red,orange_dark,orange_light,orange_lightest,yellow,black;
String btn_color_hex;
SharedPreferences.Editor editor = getSharedPreferences("paint_color", MODE_PRIVATE).edit();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_emoji_creation);
green_light = (Button)findViewById(R.id.button1);
green_dark = (Button)findViewById(R.id.button2);
blue_light = (Button)findViewById(R.id.button3);
blue_dark = (Button)findViewById(R.id.button4);
blue_verydark = (Button)findViewById(R.id.button5);
purple = (Button)findViewById(R.id.button6);
magenta = (Button)findViewById(R.id.button7);
red = (Button)findViewById(R.id.button8);
orange_dark = (Button)findViewById(R.id.button9);
orange_light = (Button)findViewById(R.id.button10);
orange_lightest = (Button)findViewById(R.id.button11);
yellow = (Button)findViewById(R.id.button12);
black = (Button)findViewById(R.id.button13);
green_light.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btn_color_hex="#0fad00";
editor.putString("paint_color_hex", btn_color_hex);
editor.commit();
}
});
green_dark.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
blue_light.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
blue_dark.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
blue_verydark.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
purple.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
magenta.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
red.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
orange_light.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
orange_lightest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
orange_dark.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
yellow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
black.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_emojicreation, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
As you can see I started exploring the sharedPreferences option, after my attempt to create a service failed. If a Service is the best option, how can I make Drawing_View.java constantly listen for color changes? Thanks everyone!
You could add a setPaintColor method to your Drawing_View class. That way, you would not need to use SharedPreferences
and you could just change the paint color in your onClickListeners.
Something like this should work:
In your Drawing_View class, add:
public void setPaintColor (String color) {
paint.setColor(Color.parseColor(color));
}
In your onClickListener, call the setPaintColor method:
drawingView.setPaintColor(color);
I assume that your Drawing_View is already instantiated.
Update
You need to instantiate your Drawing_View the same way you instantiated the Buttons in your activity's onCreate method.
public class Drawing_Main extends ActionBarActivity {
...
Drawing_View drawingView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_emoji_creation);
drawingView = (Drawing_View)findViewById(R.id.drawing_view);
green_light = (Button)findViewById(R.id.button1);
...
I hope this helps.

One of webview reload page after change screen orientation

First code:
package com.fshare.zsee;
public class ZSEEActivity extends TabActivity {
private WebView webview ;
private WebView webviewtwo;
private TabHost mTabHost;
private WebSettings webviewtwoSettings;
private int error;
protected void onStart() {
super.onStart();
// The activity is about to become visible.
}
protected void onStop() {
super.onStop();
// The activity is about to become visible.
}
protected void onRestart() {
super.onRestart();
}
protected void onDestroy(){
super.onDestroy();
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Activity activity = this;
mTabHost = getTabHost();
mTabHost.addTab(mTabHost.newTabSpec("tab_test1").setIndicator("Zastępstwa").setContent(R.id.tab1));
mTabHost.addTab(mTabHost.newTabSpec("tab_test2").setIndicator("Plan Lekcji").setContent(R.id.tab2));
mTabHost.addTab(mTabHost.newTabSpec("tab_test3").setIndicator("O programie").setContent(R.id.tab3));
webview = (WebView) findViewById(R.id.webView1);
webviewtwo = (WebView) findViewById(R.id.webView2);
webviewtwoSettings = webviewtwo.getSettings();
if (savedInstanceState != null){
error = savedInstanceState.getInt("webtwoerror");
webview.restoreState(savedInstanceState.getBundle("stateone"));
webviewtwo.restoreState(savedInstanceState.getBundle("statetwo"));
if(error == 1){
webviewtwoSettings.setTextSize(TextSize.NORMAL);
}
else{
webviewtwoSettings.setTextSize(TextSize.LARGER);
}
mTabHost.setCurrentTab(savedInstanceState.getInt("CURRENT_TAB"));
}
else{
webviewtwoSettings.setTextSize(TextSize.LARGER);
webview.loadUrl("http://zsee.bytom.pl/ogloszenia.php");
webviewtwo.loadUrl("http://zsee.bytom.pl/plannew/index.html");
//error = 0 ;
mTabHost.setCurrentTab(0);
}
webview.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
String summary = "<html><body><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" ><center>Coś się zepsuło :(</center></body></html>";
webview.loadData(summary, "text/html","utf-8");
Toast.makeText(activity, "O nie! " + description, Toast.LENGTH_SHORT).show();
}
});
webviewtwo.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
webviewtwoSettings.setTextSize(TextSize.NORMAL);
String summary = "<html><body><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" ><center>Coś się zepsuło :(</center></body></html>";
webviewtwo.loadData(summary, "text/html","utf-8");
Toast.makeText(activity, "O nie! " + description, Toast.LENGTH_SHORT).show();
error = 1 ;
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK)
{
// put your stuff here or just block the back button for perticular activity
Intent i = new Intent();
i.setAction(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_HOME);
this.startActivity(i);
}
return super.onKeyDown(keyCode, event);
}
protected void onSaveInstanceState(Bundle outState) {
Bundle outStateone = new Bundle();
Bundle outStatetwo = new Bundle();
webview.saveState(outStateone);
webviewtwo.saveState(outStatetwo);
outState.putBundle("stateone", outStateone);
outState.putBundle("statetwo", outStatetwo);
outState.putInt("CURRENT_TAB", mTabHost.getCurrentTab());
outState.putInt("webtwoerror", error);
}
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.item1:
final AlertDialog alertdialog= new AlertDialog.Builder(this).create();
alertdialog.setTitle("O Programie");
alertdialog.setMessage("Zmiany w 1.0.1: \n-Obsługa planu z dnia 17.10.2011\n-Drobne Poprawki");
alertdialog.setButton("Fajno", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
alertdialog.cancel();
}
});
alertdialog.show();
return true;
case R.id.item2:
finish();
case R.id.item3:
if(mTabHost.getCurrentTab() == 0){
webview.loadUrl("http://zsee.bytom.pl/ogloszenia.php");
}
else if(mTabHost.getCurrentTab() == 1)
{
error = 0 ;
webviewtwo.loadUrl("http://zsee.bytom.pl/plannew/index.html");
webviewtwoSettings.setTextSize(TextSize.LARGER);
}
default:
return super.onOptionsItemSelected(item);
}
}
}
And now very simple question. Why webviewtwo reload page after change orientation and webview (webView1) doesen't ? and how to prevent it? Now only webView1 doesen't reload page after change screen orientation.
Sierran
I am not sure why the first one doesn't change but adding this to my manifest inside of the activity tag worked for me
android:configChanges="orientation|keyboardHidden|keyboard"

Categories

Resources