I'm working with the Android Application Development for Dummies book by Donn Felker. Specifically, I'm working with the Silent Mode App.
It should be simple to follow the instructions step by step, but as it turns out I can't even start the main activity without crashing the app. I must've gone over my code a dozen times and I can't still figure out what's wrong and make it work without LogCat firing errors like crazy.
Debug device is a Samsung Galaxy SII w/ Android 4.0.3.
Here's the MainAcitivity class
public class MainActivity extends Activity {
Button m_toggleButton = (Button)findViewById(R.id.toggleButton);
AudioManager m_audio = (AudioManager)getSystemService(AUDIO_SERVICE);
boolean m_isPhoneSilent;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkMode();
toggleImage();
generateClick();
}
#Override
protected void onResume()
{
super.onResume();
checkMode();
toggleImage();
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
private void checkMode()
{
m_audio = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
switch(m_audio.getRingerMode())
{
case AudioManager.RINGER_MODE_NORMAL:
m_isPhoneSilent = false;
break;
case AudioManager.RINGER_MODE_SILENT:
m_isPhoneSilent = true;
break;
}
}
private void generateClick()
{
m_toggleButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if (m_isPhoneSilent == true)
{
m_audio.setRingerMode
(AudioManager.RINGER_MODE_NORMAL);
m_isPhoneSilent = false;
}
else
{
m_audio.setRingerMode
(AudioManager.RINGER_MODE_SILENT);
m_isPhoneSilent = true;
}
toggleImage();
}
});
}
private void toggleImage()
{
ImageView imageView = (ImageView) findViewById(R.id.phone_icon);
Drawable newAsset;
if (m_isPhoneSilent == true)
{
newAsset = getResources().getDrawable(R.drawable.phone_silent);
}
else
{
newAsset = getResources().getDrawable(R.drawable.phone_on);
}
imageView.setImageDrawable(newAsset);
}
I've tried to debug, but I haven't found the problem. Please help.
public class MainActivity extends Activity {
Button m_toggleButton = (Button)findViewById(R.id.toggleButton); //<<<< here
//....your code
you are trying to find Button before setting layout for Activity so move it after setting setContentView as :
public class MainActivity extends Activity {
Button m_toggleButton ;
AudioManager m_audio;
boolean m_isPhoneSilent;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
m_toggleButton = (Button)findViewById(R.id.toggleButton);
m_audio = (AudioManager)getSystemService(AUDIO_SERVICE);
///... your code here
You can't call this
Button m_toggleButton = (Button)findViewById(R.id.toggleButton);
AudioManager m_audio = (AudioManager)getSystemService(AUDIO_SERVICE);
before your setContentView change it to this:
Button m_;
AudioManager m_audio;
boolean m_isPhoneSilent;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
m_toggleButton = (Button)findViewById(R.id.toggleButton);
m_audio = (AudioManager)getSystemService(AUDIO_SERVICE);
....
Related
Here is my code. I'm very new to Java and I know that this question is already been posted but still I didn't get the expected outpost so I had to post.
public class MainActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MediaPlayer policeSound = MediaPlayer.create(this, R.raw.police);
Button policeSounds = (Button) this.findViewById(R.id.police);
policeSounds.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (policeSound.isPlaying()){
policeSound.stop();
}
else {
policeSound.start();
}
}
});
}
}
I tried adding onBackPressed() code to this but it couldn't detect the 'policeSound' as it was detected in the previous method!
And someone please even teach me how to use #Override annotations!
To detect the 'policeSound' in other methods you need to make it be a field of a class:
private MediaPlayer policeSound;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
policeSound = MediaPlayer.create(this, R.raw.police);
Button policeSounds = (Button) this.findViewById(R.id.police);
policeSounds.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
if (policeSound.isPlaying()) {
policeSound.stop();
} else {
policeSound.start();
}
}
}
);
}
In your codes policeSound is a local variable which is be seen only in Oncreate() method,as Oleh Sokolov said, you should declare policeSound as a field of class.
About #Override , you could see this good explanation
and in android studio , when you press ctrl + o in java class file, you can override superclass method, and IDE will add #Override automatically for you.
Quite new to android studio but i'm facing a problem where my WebView is taking too long to load, so i've created a splashscreen for 4 seconds and plan to cover the loading using this splash screen. But I dont really know how to let it overlap so the WebView can load behind the splashscreen.
the java for my splash screen
public class MainActivity extends ActionBarActivity {
private static int SPLASH_TIME_OUT = 4000;
BottomBar mBottomBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Handler().postDelayed(new Runnable() {
#Override
public void run(){
Intent homeIntent = new Intent(MainActivity.this, HomeActivity.class);
startActivity(homeIntent);
finish();
}
},SPLASH_TIME_OUT);
getWindow().getDecorView().setBackgroundColor(Color.WHITE);
}
}
then i also have a bottombar that navigates to the first framgment with the webview and the java are as below
public class HomeActivity extends ActionBarActivity {
BottomBar mBottomBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
getWindow().getDecorView().setBackgroundColor(Color.WHITE);
mBottomBar = BottomBar.attach(this,savedInstanceState);
mBottomBar.setItemsFromMenu(R.menu.menu_main,new OnMenuTabClickListener() {
#Override
public void onMenuTabSelected(#IdRes int i) {
if(i==R.id.Bottombaritemone) {
HomeFragment f = new HomeFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.frame, f).commit();
}
else if(i==R.id.Bottombaritemtwo)
{
SearchFragment f =new SearchFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.frame,f).commit();
}
else if(i==R.id.Bottombaritemthree)
{
AccountFragment f =new AccountFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.frame,f).commit();
}
}
#Override
public void onMenuTabReSelected(#IdRes int i) {
}
});
mBottomBar.mapColorForTab(0,"#F2F2F2");
mBottomBar.mapColorForTab(1,"#F2F2F2");
mBottomBar.mapColorForTab(2,"#F2F2F2");
}
#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_main, menu);
return true;
}
and finally the java for my webview in the first HomeFragment
public class HomeFragment extends Fragment {
WebView my2WebView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.home,container,false);
getLoaderManager();
my2WebView = (WebView) view.findViewById(R.id.webView1);
WebSettings webSettings = my2WebView.getSettings();
my2WebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
webSettings.setUseWideViewPort(true);
webSettings.setSavePassword(true);
webSettings.setEnableSmoothTransition(true);
webSettings.setJavaScriptEnabled(true);
webSettings.getLoadsImagesAutomatically();
my2WebView.loadUrl("http://www.fidellaglobal.com/feed");
my2WebView.setWebViewClient(new WebViewClient());
return view;
}
so what can i do to making the webview in the first fragment to load when the splashscreen is on ? thank you :)
Initially set your WebView visibility invisible inside your layout file. Add you WebView in same screen which have delay Handler.
new Handler().postDelayed(new Runnable() {
#Override
public void run(){
// Make your webview visible
mWebView.setVisibility(View.VISIBLE);
}
},SPLASH_TIME_OUT);
I'm trying to implement the back press feature for a fragment and activity regarding the navigation drawer but it's not working. Does anyone know what I'm doing wrong / what is missing and what needs to be done in order to fix this?
activity class
public class BakerlooHDNActivity extends AppCompatActivity {
//save our header or result
private Drawer result = null;
// Declaring Views and Variables
ViewPager pager;
BakerlooHDNViewPagerAdapter adapter;
BakerlooHDNSlidingTabLayout bakerloohdntabs;
int Numboftabs = 2;
private int getFactorColor(int color, float factor) {
float[] hsv = new float[3];
Color.colorToHSV(color, hsv);
hsv[2] *= factor;
color = Color.HSVToColor(hsv);
return color;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bakerloo_hdn);
final String actionBarColor = "#B36305";
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
if(getSupportActionBar()!=null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(false);
getSupportActionBar().setTitle(Html.fromHtml("<font color='#FFFFFF'>" + getResources().getString(R.string.hdn) + "</font>"));
getSupportActionBar().setSubtitle(Html.fromHtml("<font color='#FFFFFF'>" + getResources().getString(R.string.zone_3) + "</font>"));
final Drawable upArrow = ContextCompat.getDrawable(this, R.drawable.abc_ic_ab_back_mtrl_am_alpha);
upArrow.setColorFilter(getResources().getColor(R.color.white), PorterDuff.Mode.SRC_ATOP);
getSupportActionBar().setHomeAsUpIndicator(upArrow);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getFactorColor(Color.parseColor(actionBarColor), 0.8f));
}
// start of navigation drawer
headerResult = new AccountHeaderBuilder()
.withActivity(getActivity())
.withCompactStyle(true)
.withHeaderBackground(R.color.bakerloo)
.withProfileImagesVisible(false)
.withTextColor(Color.parseColor("#FFFFFF"))
.withSelectionListEnabled(false)
.addProfiles(
new ProfileDrawerItem().withName(getString(R.string.hdn)).withEmail(getString(R.string.hello_world))
)
.build();
result = new DrawerBuilder()
.withActivity(getActivity())
.withAccountHeader(headerResult)
.withTranslucentStatusBar(false)
.withActionBarDrawerToggle(false)
.withSelectedItem(-1)
.addDrawerItems(
new PrimaryDrawerItem().withName(R.string.hello_world).withIdentifier(1).withCheckable(false)
)
.build();
// end of navigation drawer
}
#Override
public void onBackPressed() {
if (result.isDrawerOpen()) {
result.closeDrawer();
} else {
super.onBackPressed();
}
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(new Intent("BACKPRESSED_TAG"));
}
}
fragment class
public class FragmentBakerlooHDN extends android.support.v4.app.Fragment {
public FragmentBakerlooHDN() {
// Required empty constructor
}
BroadcastReceiver onNotice = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// do stuff when back in activity is pressed
result.closeDrawer();
}
};
// Declaring navigation drawer
private AccountHeader headerResult = null;
private Drawer result = null;
/**
* Whether or not the activity is in two-pane mode, i.e. running on a tablet
* device.
*/
private boolean mTwoPane;
#Override
public void onCreate(Bundle savedInstanceState) {
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(onNotice, new IntentFilter("BACKPRESSED_TAG"));
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_bakerloo_hdn, container, false);
// start of navigation drawer
headerResult = new AccountHeaderBuilder()
.withActivity(getActivity())
.withCompactStyle(true)
.withHeaderBackground(R.color.bakerloo)
.withProfileImagesVisible(false)
.withTextColor(Color.parseColor("#FFFFFF"))
.withSelectionListEnabled(false)
.addProfiles(
new ProfileDrawerItem().withName(getString(R.string.hdn)).withEmail(getString(R.string.hello_world))
)
.build();
result = new DrawerBuilder()
.withActivity(getActivity())
.withAccountHeader(headerResult)
.withTranslucentStatusBar(false)
.withActionBarDrawerToggle(false)
.withSelectedItem(-1)
.addDrawerItems(
new PrimaryDrawerItem().withName(R.string.hello_world).withIdentifier(1).withCheckable(false)
)
.build();
// end of navigation drawer
super.onCreate(savedInstanceState);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
View v = getView();
super.onActivityCreated(savedInstanceState);
}
}
try this:
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
#Override
public void onCreate() {
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.navdrawer);
}
#Override
public void onBackPressed() {
if(mDrawerLayout.isDrawerOpen(mDrawerList)) mDrawerLayout.closeDrawer(mDrawerList);
else super.onBackPressed();
}
EDIT:
You can use LocalBroadcastManager to update fragment when in activity back is pressed:
in fragment add new BroadcastReceiver() Instance:
BroadcastReceiver onNotice = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// do stuff when back in activity is pressed
// headerResult.closeDrawer();
}
};
and register it with tag in onCreate method:
LocalBroadcastManager.getInstance(this).registerReceiver(onNotice,
new IntentFilter("BACKPRESSED_TAG"));
Then, in Activity OnBackPressed method call broadcast:
LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent("BACKPRESSED_TAG"));
Do you have a reference inside your code to the interface? Looks like you're calling that interface directly hence the errors. Try renaming that method too. It might be conflicting with the super class's onBackPressed method.
Your problem is that your interface is named exactly as the property you are trying to use.
Rename it and use a instance.
#Override
public void onBackPressed() {
OnBackPressedListener instance = getSettedListener();
if (result.isDrawerOpen()) {
result.closeDrawer();
} else {
return instance.onBackPressed();
}
}
public interface OnBackPressedListener {
boolean onBackPressed();
}
This code would compile if you also implement the method getSettedListener on your code (that could be like the following):
public OnBackPressedListener getSettedListener() {
return new OnBackPressedListener(){
boolean onBackPressed(){
if(shouldConsumeBack)
return consumeBack();
else return false;
};
}
}
But this code could return the Fragment that does implements the method.
I have set the Image for my ImageButton in XML but trying to change the image in the code below does nothing. Any ideas why?
public class Test extends Activity implements OnClickListener {
ImageButton myImageButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_farm_main);
myImageButton = (ImageButton)findViewById(R.id.button);
myImageButton.setBackgroundResource(R.drawable.image1);
myImageButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
You just make sure your image is available in all drawable folder you will create a common drawable folder in your res and then paste your image at that folder then you will try his concept and or otherwise you will try like this..You just Set the image source it will give the answer
public class MainActivity extends Activity {
private ImageButton imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView =(ImageButton) findViewById(R.id.imageButton1);
imageView.setImageResource(R.drawable.ic_launcher);
}
}
I guess you want change the image not background.
Substitute
myImageButton.setBackgroundResource(R.drawable.image1);
with
myImageButton.setImageResource(R.drawable.image1);
This code below works perfectly fine if you have a imagebutton in your layout file and a drawable name ic_launcher in drawable directory.
public class MainActivity extends Activity implements OnClickListener{
ImageButton myImageButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myImageButton = (ImageButton) findViewById(R.id.button);
myImageButton.setImageResource(R.drawable.ic_launcher);
myImageButton.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
}
Comment below if that's not what you want.
I made 2 activities and an Intent extended class named SomeSpecialIntent, when you press on the first activity's textview you go to the second using new SomeSpecialIntent class instnace, but something strange goes with it on the way, because the phrase getIntent() instnaceof SomeSpecialIntent returns false on the second activity!
whats up with that?
the code for the check i made:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = (TextView)findViewById(R.id.textView1);
textView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new SomeSpecialIntent(MainActivity.this,SomeActivity.class));
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
public class SomeActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("Check",""+(getIntent() instanceof SomeSpecialIntent));//returns false!!!!
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
public class SomeSpecialIntent extends Intent {
public SomeSpecialIntent(Context context,
Class<?> class1) {
super(context,class1);
}
}