trying to understand Java activities by following a book - java

I am new to programming and I am trying to figure out how Activities in android programming work by making a small app,which should let me know in which state of the activity I am.
I am getting an error in the setContentView because Android Studio says "cannot resolve symbol "R""
Here is my code:
package com.example.daniele.activity;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends Activity {
String tag = "Lifecycle";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.d(tag, "in the onCreate() event");
}
public void onStart() {
super.onStart();
Log.d(tag, "in the onStart() event");
}
public void onRestart() {
super.onRestart();
Log.d(tag, "in the onRestart() event");
}
public void onResume() {
super.onResume();
Log.d(tag, "in the onResume() event");
}
public void onPause() {
super.onPause();
Log.d(tag, "in the onPause() event");
}
public void onStop() {
super.onStop();
Log.d(tag, "in the onStop() event");
}
public void onDestroy() {
super.onDestroy();
Log.d(tag, "in the onDestroy() event");
}
}
here is my AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.daniele.activity" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Everyone is suggesting you the fix. Good. But since you are learning, you should also understand what is happening here:
All layout files are in xml
Every xml file is compiled and made available to java classes
The compiled class is called R.java
To make
R.java available to your class you need to import it

Under
import android.util.Log;
add this
import com.example.daniele.R;
Alternatively when you see a red underline under something, you can hover above it and Android Studio usually tells you what you need to do. In this case, "Optimize Imports" or something similar.

"R" errors usually happen when one or more of your XML files is corrupt. Start by seeing if your apps manifest looks correct!

You will need to import R because your activity is in a different package.
import com.example.daniele.R;

Related

Android - Handle global configuration changes

I'm writing a service that tracks system changes, meaning, I'm willing to track whenever a keyboard becomes visible / hidden for any application.
To achieve the following task, i built a small Activity that launches a services
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent serviceIntent = new Intent(this, MyService.class);
startService(serviceIntent);
//setContentView(R.layout.activity_main);
}
}
The manifest.xml itself
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="somepackage">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".MyService"
android:enabled="true"
android:exported="true"
android:configChanges="orientation|screenSize|keyboardHidden"></service>
</application>
</manifest>
and the service itself:
public class MyService extends Service {
public MyService() {
}
private static final String TAG =
"abbeyservice";
#Override
public void onCreate() {
Log.d(TAG, "Service onCreate");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "Service onStartCommand");
return Service.START_STICKY;
}
#Override
public IBinder onBind(Intent arg0) {
Log.i(TAG, "Service onBind");
return null;
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
#Override
public void onDestroy() {
Log.i(TAG, "Service onDestroy");
}
}
Problem is I'm notified for changes within, and only for my activity. Which is seen as a white screen for unknown reasons(even though i didn't use SetContentView(..))
When you talk of "keyboard" you are talking about the soft keyboard. This doesn't result in a configuration change, as the configuration has not changed.
There are devices with hardware keyboards that slide out, so they generate a configuration change event when they are slid out or back in again. There is also a possibility to attach an external keyboard to some Android devices and the act of connecting or disconnecting a hardware keyboard also generates a configuration change event.
To detect if the keyboard is shown in your own app, see
How to check visibility of software keyboard in Android?
As far as I know, there is no way to find out if the soft keyboard is shown in another app.

My android app stops responding after the Splash Screen

I'm programming a new app which contains a splash screen.
I've finished it and it was all good. After I've opened android studio again to work on the navigation bar I've tried to run the app to see the result but the application stopped and crashed after the display of the splash screen.
this is Main class
package com.example.computer.bsinfoshop;
public class Main extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
and this is the class od splash screen
package com.example.computer.bsinfoshop;
import android.graphics.Typeface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class Screen extends AppCompatActivity {
TextView tv;
ImageView img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen);
tv = (TextView)findViewById(R.id.textView);
img = (ImageView)findViewById(R.id.imageView);
Typeface font = Typeface.createFromAsset(getAssets(),"fonts/Satisfy-Regular.ttf");
tv.setTypeface(font);
img.setImageResource(R.drawable.rsz_2rsz_img);
Thread timerThread = new Thread(){
public void run(){
try
{
sleep(3700);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
finally {
Intent intent = new Intent(Screen.this , Main.class);
startActivity(intent);
}
}
};
timerThread.start();
}
#Override
protected void onPause() {
super.onPause();
finish();
}
}
and here where i think is the problem
the manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.computer.bsinfoshop">
<application
android:allowBackup="true"
android:icon="#drawable/logo"
android:label="#string/app_name">
<activity
android:name=".Screen"
android:theme="#style/App">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Information"
android:label="Information"
android:theme="#style/AppTheme">
</activity>
<activity
android:name="com.example.computer.bsinfoshop.Main"
android:theme="#style/AppTheme">
</activity>
</application>
</manifest>
I just want to know what is the problem in my code and how can I fix it. thank you ^^
Change Thread to something like this:
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
finish();
startActivity(new Intent(Screen.this, Main.class));
}
}, 1500);
To be honest, I think this is not the correct way of creating a Splash Screen. That way you force the user to wait for 3 seconds which causes a bad user-experience.
Have a look at that tutorial and your users will thank you! https://www.bignerdranch.com/blog/splash-screens-the-right-way/

Function Isolating Camera's LED Light and java.lang.NullPointerException: Attempt to invoke virtual method 'void android.hardware.Camera$Parameters

I am struggling to control the LED light next to my camera in the app I am trying to make for my own education purposes. I have tried to follow the methods in http://www.mkyong.com/android/how-to-turn-onoff-camera-ledflashlight-in-android/ , but I am trying to make the function more abstract and more general in order to increase reusable functionality and make the code more readable.
Upon creating my activity we first check, using PackageManager, that a LED camera does in fact exist. I then open the camera. The onClick function runs the functions changeScreen() and toggleLight(). Here you can see the clear advantages of using abstraction, ie toggleLight() works as a black box, using code set out elsewhere. The changeScreen function I know is correct, well before adding toggleLight() it was working correctly.
As the code should be correct, as it was taken from the example, I believe I have a problem with variable scope.
1) Where does the boolean isLighOn need to be declared, in the function or in the activity?
2) Same problem with the camera variable
How else should I go about creating an abstract function toggleLight()? I have checked around on this website, but a lot of posts send you to the link provided above. Moreover I believe an answer to this question would help many users and would provide reusable code.
Here is my code so far and I have posted the error I am getting below again.
package com.mycompany.myapplication;
import android.app.*;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.drawable.ColorDrawable;
import android.hardware.Camera;
import android.os.*;
import android.util.Log;
import android.view.*;
import android.widget.*;
public class MainActivity extends Activity {
public RelativeLayout container;
private boolean isLighOn = false;
private Camera camera;
#Override
protected void onStop() {
super.onStop();
if (camera != null) {
camera.release();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Context context = this;
PackageManager pm = context.getPackageManager();
// if device support camera?
if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Log.e("err", "Device has no camera!");
return;
}
camera = Camera.open();
container = (RelativeLayout) findViewById(R.id.MainActivity);
container.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
changeScreen(v);
toggleLight();
}
});
}
public void changeScreen(View v) {
ColorDrawable cd = (ColorDrawable) this.container.getBackground();
TextView ON = (TextView) findViewById(R.id.ON);
TextView OFF = (TextView) findViewById(R.id.OFF);
if (cd != null && cd.getColor() == getResources().getColor(R.color.BLACK)) {
container.setBackgroundColor(getResources().getColor(R.color.WHITE));
OFF.setVisibility(View.INVISIBLE);
ON.setVisibility(View.VISIBLE);
} else {
container.setBackgroundColor(getResources().getColor(R.color.BLACK));
OFF.setVisibility(View.VISIBLE);
ON.setVisibility(View.INVISIBLE);
}
}
public void toggleLight(){
final Camera.Parameters p = camera.getParameters();
if (isLighOn) {
Log.i("info", "torch is turn off!");
p.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
camera.stopPreview();
isLighOn = false;
} else {
Log.i("info", "torch is turn on!");
p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
camera.startPreview();
isLighOn = true;
}
}
}
When I load the app on my Android Studio emulator, I get the screen "ON". However, when you click the screen the app crashes. This is only error message I can find in the IDE. I am not sure how to interpret this error message.
In response to a comment below I am now posting the code containing the permissions.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mycompany.myapplication">
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Don't rely on an emulator to produce reliable camera behavior. Always verify camera-related code on real device!

method OnCreate(bundle) never gets called and application crashes

I've been trying to make an application that uses lock screen concepts for which as a dry run I've created an app that locks the screen once the given button is clicked, well I've used the basic concepts nothing new here's my Java code
package com.example.gaurav.locknowtest2;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.app.admin.DevicePolicyManager;
import android.app.admin.DeviceAdminReceiver;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends DeviceAdminReceiver{
public class controller extends Activity{
DevicePolicyManager dpm;
ComponentName comname;
Button b1;
TextView display;
public void OnCreate(Bundle xyz){
super.onCreate(xyz);
dpm=(DevicePolicyManager)getSystemService(Context.DEVICE_POLICY_SERVICE);
comname=new ComponentName(this,MainActivity.class);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.start);
display=(TextView)findViewById(R.id.xyz);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, comname);
startActivityForResult(intent,1);
display.setText("just to test the method");
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 1:
if (resultCode == Activity.RESULT_OK) {
dpm.lockNow();
} else {
Log.i("DeviceAdminSample", "Administration enable FAILED!");
}
return;
}
}
}
}
next up here's my manifest that I think is creating all the problems
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.gaurav.locknowtest2" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity$controller"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".MainActivity"
android:permission="android.permission.BIND_DEVICE_ADMIN" >
<meta-data
android:name="android.app.device_admin"
android:resource="#xml/device_admin_sample" />
<intent-filter>
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
</intent-filter>
</receiver>
</application>
</manifest>
I need to get this done by this week so please take a look..
Your method is not written correcrt.
public void OnCreate(Bundle xyz){
you have a CAPITAL O
it should be like this:
#Override
public void onCreate(Bundle savedInstanceState) {
...
}
Java is case-sensitive, so naming your method
public void OnCreate(Bundle bundle) {
is not
protected void onCreate(Bundle bundle) {
use the #Override annotation to ensure that you actually are overriding a method.
Also, public class controller extends Activity { should be public static class controller extends Activity { apart from the fact that as per Java naming conventions, classes should start with a Capital letter.
A class extending Activity cannot be an inner class of another class because the android system needs to be able to create new instances of your Activity class without an instance of another class. Your controller class is an inner class of MainActivity so cannot be instantiated without an instance of MainActivity.
See this answer:
Nested inner Activity class in android
Also, as pointed out by others, you have a typo in onCreate. This means that you have made a completely separate method, not overridden onCreate. However this doesn't explain why the application crashes. (You can write an Activity class that doesn't override onCreate, and it works without any exceptions being thrown.)

getGSMSignalStrength() Always Returns 99

I know there is another question on here relating to this, but I don't think it applies to me, as I'm pretty sure I use GSM (isGSM() returns true). In any case, getCdmaDbm returns -1 for me anyway. I am using Android 4.1.1 and an HTC One X. Here is my code (most of which isn't mine):
MainActivity:
package com.example.receptionlookup;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.view.Menu;
import android.widget.Toast;
public class MainActivity extends Activity {
TelephonyManager Tel;
MyPhoneStateListener MyListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* Update the listener, and start it */
MyListener = new MyPhoneStateListener();
Tel = ( TelephonyManager )getSystemService(Context.TELEPHONY_SERVICE);
Tel.listen(MyListener ,PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
}
#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;
}
/* Called when the application is minimized */
#Override
protected void onPause()
{
super.onPause();
Tel.listen(MyListener, PhoneStateListener.LISTEN_NONE);
}
/* Called when the application resumes */
#Override
protected void onResume()
{
super.onResume();
Tel.listen(MyListener,PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
}
/* —————————– */
/* Start the PhoneState listener */
/* —————————– */
private class MyPhoneStateListener extends PhoneStateListener
{
/* Get the Signal strength from the provider, each tiome there is an update */
#Override
public void onSignalStrengthsChanged(SignalStrength signalStrength)
{
super.onSignalStrengthsChanged(signalStrength);
Toast.makeText(getApplicationContext(), "Go to Firstdroid!!! GSM Cinr = "
+ String.valueOf(signalStrength.getGsmSignalStrength()), Toast.LENGTH_SHORT).show();
}
};/* End of private Class */
}
AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.receptionlookup"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.receptionlookup.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
</manifest>
Does anyone know what the problem is? If I go to Settings->About->Network, I can see the signal strength there. Isn't there some way to just read this value? I've tried several third party apps, and none of them are able to read my signal strength either. I've also tried the proprietary getGSMSignalBar() method, but I get a NoSuchMethodException.
As you can read in the 3GPP 127 007 8.5 the implementation of the at+csq is optional (the command which suppose to give the signal strength). Apparently HTC hide this value from 3rd party applications and they probably have another way to achieve that value for display in their own proprietary Settings application.
The fact that other applications also cannot get that information justifies my case.
This issue is tightly related to yours - thay said that HTC is one of the OEMs that does not worth the modem related developing time.
Try this:
Class signalStrengthClass = signalStrength.getClass();
try {
Method method = signalStrengthClass.getMethod(
"getGsmSignalBar", null);
method.setAccessible(true);
Integer bars = (Integer) method.invoke(signalStrength,
(Object[]) null);
}
} catch (Exception e) {
e.printStackTrace();
}

Categories