mCamera cannot be resolved to a variable (Android, Eclipse) - java

I am very new to Android development. I am following Google's Android "classes" and am receiving an error for this code in Eclipse:
package com.feistie.myfirstapp;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize member TextView so we can manipulate it later
mTextView = (TextView) findViewById(R.id.text_message);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// For the main activity, make sure the app icon in the action bar
//does not behave as a buutton
ActionBar actionBar = getActionBar();
actionBar.setHomeButtonEnabled(false);
}
}
#Override
public void onDestroy() {
super.onDestroy(); // Always call the superclass
// Stop method tracing that the activity started during onCreate()
android.os.Debug.stopMethodTracing();
}
#Override
public void onPause() {
super.onPause(); // Always call the superclass method first
// Release the Camera because we don't need it when paused
// and other activities might need to use it.
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
/** Called when the user clicks the Send button */
public void sendMessage (View view) {
// Do Something in response to button
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
There is an error for each of these lines:
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
The error for the first and third lines says "mCamera cannot be resolved to a variable." The error for the second line just says "mCamera cannot be resolved."
If you need more information please let me know.
Thanks!

You need to declare mCamera before you can reference it:
public class MainActivity extends Activity {
Camera mCamera;
And then you need to initialize it, probably in onResume()
#Override
protected void onResume() {
super.onResume();
mCamera = Camera.open()
}
Make sure you added the appropriate permission that you manifest:
<uses-permission android:name="android.permission.CAMERA" />
Addition
You need to declare_every_ variable before you try use it in Java. I don't see where you declare mTextView either.
public class MainActivity extends Activity {
Camera mCamera;
TextView mTextView;

Related

Android: onBackPressed not being recognized

EDIT: Realized and solved the problem on my own. Thank you.
Please bear with me it's actually my first time using Android Studio and Stackoverflow. What I am trying to make is a music player, there are 2 activities. In the second activity when the user taps the play button, the music plays. If the user backs, the music will stop playing and go back to the first activity. Somehow on back pressed is not working. It's grayed out and it tells me that the Method is never used.
package com.radiantminds.radiantminds;
import android.content.Intent;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
public class player1 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player1);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.mozardpianosonata); //create mediaplayer with song
ImageButton yButton = (ImageButton) findViewById(R.id.imageButton5);
yButton.setOnClickListener(new View.OnClickListener() {
public void onBackPressed(){ //this is not working
if(mp.isPlaying())
{
mp.stop(); // stop music on backpress
}
}
#Override
public void onClick(View view) { //play music on click
if (mp.isPlaying()) {
mp.pause();
} else {
mp.start();
}
}
});
}
}
You have to put it on an Activity, don't forget to call #Override
#Override
public void onBackPressed()
{
super.onBackPressed(); //if you want to do something new remove this line
}
The problem is that you have to place the onBackPressedMethod() outside, as follows :
public class player1 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player1);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.mozardpianosonata); //create mediaplayer with song
ImageButton yButton = (ImageButton) findViewById(R.id.imageButton5);
yButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) { //play music on click
if (mp.isPlaying()) {
mp.pause();
} else {
mp.start();
}
}
});
}
#Override
public void onBackPressed(){ //this is not working
if(mp.isPlaying())
{
mp.stop(); // stop music on backpress
}
//if you want to do the back action aswell, uncomment the following line
//super.onBackPressed();
}
Make sure the #override is there above the method and you don't declare the method twice.
other alternative is:
onKeyDown()
or add:
super.onBackPressed();
in the method onBackPressed (though i dont suggest it really)

Declaration of MapView (ArcGIS for Android) Center and Zoom

I am begginer in java and ArcGIS for android. I want to make simple app with MapView.
I have problem with declaration of MapView center and Zoom. I need to do it programmatically (application startup) in java file, not in xml file. I will try explain it on on simple example.
Problem is in mMapView.setMapOptions(options); I need to do in onCreate(), if I make Button with mMapView.setMapOptions(options); everything is OK. I searched solution in samples and on the internet, but I think, that I do not know how to ask on it.
Sorry for my english and thank you for your comments.
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import com.esri.android.map.MapOptions;
import com.esri.android.map.MapView;
public class MainActivity extends Activity {
MapView mMapView = null;
Button b1;
MapOptions options = new MapOptions(MapOptions.MapType.TOPO, 49.591241, 17.255503, 16);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMapView = (MapView) findViewById(R.id.map);
//mMapView.centerAndZoom(49.591241, 17.255503, 8);
btnClick();
mMapView.setMapOptions(options);
mMapView.setAllowRotationByPinch(true);
mMapView.setRotationAngle(25);
mMapView.enableWrapAround(true);
}
public void btnClick() {
b1 = (Button) findViewById(R.id.button);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
//mMapView.centerAndZoom(49.591241, 17.255503, 10);
mMapView.setMapOptions(options);
}
});
}
#Override
protected void onPause() {
super.onPause();
// Call MapView.pause to suspend map rendering while the activity is paused, which can save battery usage.
mMapView.pause();
}
#Override
protected void onResume() {
super.onResume();
// Call MapView.unpause to resume map rendering when the activity returns to the foreground.
mMapView.unpause();
}
#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;
}
#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);
}
}
You could remove the MapView declaration from your XML and create it inside the activity. Then just add the MapView to your layout.
XML (details omitted)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="#+id/mapLayout"></LinearLayout>
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
MapView mapView = MapView(MainActivity.this, mapOpts);
// other logic/initializations
ViewGroup mapLayout = findViewById(R.id.mapLayout);
mapLayout.addView(mapView); // might have to specify index param if you need buttons
This is my solution by previous answer. Thanks zec!
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import com.esri.android.map.MapOptions;
import com.esri.android.map.MapView;
public class MainActivity extends Activity {
MapView mMapView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MapOptions options = new MapOptions(MapOptions.MapType.TOPO, 49.591241, 17.255503, 16);
mMapView = new MapView(MainActivity.this, options);
setContentView(mMapView);
}
#Override
protected void onPause() {
super.onPause();
// Call MapView.pause to suspend map rendering while the activity is paused, which can save battery usage.
mMapView.pause();
}
#Override
protected void onResume() {
super.onResume();
// Call MapView.unpause to resume map rendering when the activity returns to the foreground.
mMapView.unpause();
}
}

ImageButton setImageResource crashing app

So I've got a small problem which is doing my head in. I do know that the solution is something obvious and simple, but I'm new to programming and can't seem to get my head around it.
Basically, I've been following a Flashlight tutorial using Android Studio. In the tutorial, they used a simple button that would toggle into Flashlight ON, and Flashlight OFF modes.
I did not want to use just a button, and instead wanted to use an ImageButton instead, taking up the entire screen, and the clicking of the image would turn on the flashlight and change the image.
So, I simply modified the code after the flash would turn on into a setImageResource change. But clicking the image crashes the app rightaway unfortunately :(
Hope someone can help a noob out! Below is my Main Java file.
package com.dbz.flash;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.Toast;
public class MainActivity extends Activity {
private boolean isFlashOn = false;
private Camera camera;
private ImageButton btnSwitch;
#Override
protected void onStop() {
super.onStop();
if (camera != null) {
camera.release();
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSwitch = (ImageButton) findViewById(R.id.btnSwitch);
Context context = this;
PackageManager pm = context.getPackageManager();
if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Log.e("err", "Device has no camera!");
Toast.makeText(getApplicationContext(),
"Your device doesn't have camera!",
Toast.LENGTH_SHORT).show();
return;
}
camera = Camera.open();
final Parameters p = camera.getParameters();
btnSwitch.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if (isFlashOn) {
Log.i("info", "torch is turned off!");
p.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
isFlashOn = false;
//button.setText("Torch-ON");
btnSwitch.setImageResource(R.drawable.off);
} else {
Log.i("info", "torch is turned on!");
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
isFlashOn = true;
//button.setText("Torch-OFF");
btnSwitch.setImageResource(R.drawable.on);
}
}
});
}
}
`

Change between activities does not work

I'm trying to change between activities in my Android app (2.1-update1), but it doesn't work.
Any suggestions?
The only thing that happens when I debug the app is that it stops on this part of the code in Instrumentation.java:
public void waitForIdle() {
synchronized (this) {
while (!mIdle) {
try {
wait();
} catch (InterruptedException e) {
}
}
}
}
Eclipse says that it is in Thread 1 on
Instrumentation.checkStartActivityResult(int, Object) line: 1537. If I
resume the app, the next stop is in ZygoteInit.java trying to run
Throwable cause = ex.getCause(); ... Eclipse says
ZygoteInit$MethodAndArgsCaller.run() line: 864.
Here is the source code:
HappyHomes.java
package com.example.app;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class HappyHomes extends Activity {
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button login = (Button) findViewById(R.id.btnLogin);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ProgressDialog laddRuta = ProgressDialog.show(HappyHomes.this, "",
"Loggar in, vänligen vänta...", true);
Intent myIntent = new Intent(view.getContext(), Kategorier.class);
myIntent.
startActivity(myIntent);
}
});
}
}
Kategorier.java
package com.example.app;
import android.app.Activity;
import android.os.Bundle;
public class Kategorier extends Activity {
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.kategorier);
}
}
Thanks for helping!
Make sure that Kategorier is registered in your AndroidManifest.xml file.
Change myIntent.startActivity(myIntent); to HappyHomes.this.startActivity(myIntent);
There is no any startActivity() method in Intent class . you must be doing wrong.
just write startActivity(myIntent)
All the Services, Broadcast Receivers and Activites must be declared in manifest file.

Runtime error while switching between activities in Android

I got a runtime error when I press the button that should change the activity:
package com.example.LocationTracker;
import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button;
public class LocationTracker extends Activity{ /** Called when the activity is first created. */
Button btn_Tracker;
Button btn_Display_Map;
Context context;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
context = getApplicationContext();
btn_Tracker = (Button)findViewById(R.id.btn_Tracker);
btn_Tracker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//setContentView(R.layout.trackeractivity);
Intent myIntent1 = new Intent(view.getContext(), TrackerActivity.class);
context.startActivity(myIntent1);
}});
}
class TrackerActivity extends Activity {
//Your member variable declaration here
// Called when the activity is first created.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.trackeractivity);
}
}
I added everything right in the maniefest file
<activity android:name=".TrackerActivity" android:label="#string/app_name"/>
<activity android:name=".DisplayMapActivity" android:label="#string/app_name"/>
</application>
Any idea?
I think TrackerActivity needs to be public, which means it will need to be in its own file as well.
You shouldn't be using getApplicationContext() to start activities. Every activity is a context, so having a member instance of Context should not be necessary. Try re-writing the onClick method of your OnClickListener like this
public void onClick(View view) {
Intent myIntent1 = new Intent(LocationTracker.this, TrackerActivity.class);
LocationTracker.this.startActivity(myIntent1);
}});
Also, refer to this documentation for when to use the application context.

Categories