I have implemented the settings screen of my app using PreferenceFragment.
When the up button in the toolbar of the settings screen is clicked my app returns to the MainActivity screen but the data that was previously entered into the EditTexts (before going to the settings screen) is lost and the EditTexts are all blank.
I tried implementing onSaveInstanceState and onRestoreInstanceState but it is not working because onRestoreInstanceState is not called when clicking the up button in the settings screen toolbar. The savedInstanceState is also null in onCreate.
Would really appreciate it if someone could point out how to go about restoring the data in the EditTexts please? :)
Here's the log for MainActivity:
Clicking on Settings from toolbar menu:
I/LOG: onPause
I/LOG: onSaveInstanceState saving
I/LOG: onStop
Clicking on back button in settings screen toolbar:
I/LOG: onDestroy
I/LOG: onCreate
I/LOG: savedInstanceState is null
I/LOG: onStart
I/LOG: onResume
MainAcitivy.java
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.EditText;
import android.util.Log;
//...
public class MainActivity extends AppCompatActivity {
Toolbar toolbarMain;
EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.i("LOG", "onCreate");
super.onCreate(savedInstanceState);
Log.i("LOG", "savedInstanceState is " + savedInstanceState);
if(savedInstanceState !=null) {
editText.setText(savedInstanceState.getString("ET_KEY"), TextView.BufferType.EDITABLE);
}
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.myEditText);
toolbarMain = (Toolbar) findViewById(R.id.toolbar);
toolbarMain.setTitle(R.string.app_name);
toolbarMain.inflateMenu(R.menu.menu_main);
toolbarMain.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.settings:
startActivity(new Intent(MainActivity.this, SettingsActivity.class));
}
return true;
}
});
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
Log.i("LOG", "onRestoreInstanceState");
super.onRestoreInstanceState(savedInstanceState);
editText.setText(savedInstanceState.getString("ET_KEY"), TextView.BufferType.EDITABLE);
}
#Override
public void onSaveInstanceState(Bundle outState) {
Log.i("LOG", "onSaveInstanceState saving");
outState.putString("ET_KEY", editText.getText().toString());
}
#Override
public void onPause() {
Log.i("LOG", "onPause");
super.onPause();
}
#Override
public void onStop() {
Log.i("LOG", "onStop");
super.onStop();
}
#Override
public void onDestroy() {
Log.i("LOG", "onDestroy");
super.onDestroy();
}
#Override
public void onStart() {
Log.i("LOG", "onStart");
super.onStart();
}
#Override
public void onResume() {
Log.i("LOG", "onResume");
super.onResume();
}
SettingsActivity.java
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
public class SettingsActivity extends AppCompatActivity {
SharedPreferences sharedPref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.preferences_layout);
sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// Display the fragment as the main content.
getFragmentManager().beginTransaction()
.replace(R.id.pref_content, new SettingsFragment())
.commit();
}
}
I found a solution after much searching. Hope the following helps anyone else out there.
Initially, I tried to override the behaviour of the up button. However I was getting a 'cannot resolve symbol' error on MenuItem when trying to override onOptionsItemSelected. Perhaps there is a way to do this but I couldn't figure it out. I gave up on this approach when I noticed this in the Android Developer Docs:
You do not need to catch the up action in the activity's onOptionsItemSelected() method. Instead, that method should call its superclass, as shown in Respond to Actions. The superclass method responds to the Up selection by navigating to the parent activity, as specified in the app manifest.
Solution
A solution that did work for me was to create a custom toolbar so that I could define the behaviour of the up button entirely. Thankfully this only required a few lines of code.
Step 1 - Create a new toolbar layout
res/layout/toolbar_preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/toolbarPreferences"
android:background="#color/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:elevation="4dp"
android:theme="#style/ToolbarTheme"
app:navigationIcon="?attr/homeAsUpIndicator"
app:titleTextColor="#color/white">
</android.support.v7.widget.Toolbar>
Note the line in the above:
app:navigationIcon="?attr/homeAsUpIndicator"
Step 2 - Refer to new toolbar in preferences layout file
In my case, in my preferences_layout.xml:
<include layout="#layout/toolbar_preferences" />
Step 3 - Java code
In SettingsActivity.java, I had to:
First, initiate the new toolbar:
Toolbar toolbarPref = (Toolbar) findViewById(R.id.toolbarPreferences);
setSupportActionBar(toolbarPref);
Second, set click listener and define bahaviour:
toolbarPref.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
Done.
Related
I am working on android activities. I have one main activity and two other activities, these two activities are launched from the main activity. There are back buttons on each of When any of these two activities are launched , on pressing the back button i want the intent to start the resumed main activity, not to relaunch it on other page.
Below is the code for Main Activity
package com.example.nadeemahmad.smartcalculator;
import android.app.Activity;
import android.app.IntentService;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MainActivity extends Activity {
Button show_cam_ctrl,
show_voice_ctrl;
TextView ma_res_txt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Control Buttons
show_cam_ctrl = (Button) findViewById(R.id.show_cam_ctrl);
show_voice_ctrl = (Button) findViewById(R.id.show_voice_ctrl);
show_cam_ctrl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this,cam_calculator.class);
startActivity(i);
}
});
show_voice_ctrl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this,voice_calculator.class);
startActivity(i);
}
});
}
Codes for the two activities
public class voice_calculator extends Activity {
Button back_frm_voice;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_voice_calculator);
back_frm_voice = (Button) findViewById(R.id.back_frm_voice);
back_frm_voice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(voice_calculator.this,MainActivity.class);
startActivity(i);
finish();
}
});
}
}
public class cam_calculator extends Activity {
Fragment cam_fragment;
Button back_frm_came;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cam_calculator);
back_frm_came = (Button) findViewById(R.id.back_frm_came);
back_frm_came.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(cam_calculator.this,MainActivity.class);
startActivity(i);
finish();
}
});
}
}
This is the main activity, having two buttons on top BTN1 and BTN2
The second activity is launched on the BTN1 press, but when i press the back button on the top
This mainactivity is launched, but not the resumed one, when i press the back button on my phone then it get close and the main activity with calculations on screen appears, what i want is , when i press the back button, so the intent should take me to the main activity with resumed calculations.
Just call cam_calculator.this.finish() or voice_calculator.this.finish() from the OnClickListener. Those activities will finish and "automatically" return to the MainActivity.
edit:
If you put a code like this: startActivity(new Intent(this, SomeActivity.class)); you'll directly telling the framework to start an activity.
Just remove that!
Please use the below edited code,
public class voice_calculator extends Activity {
Button back_frm_voice;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_voice_calculator);
back_frm_voice = (Button) findViewById(R.id.back_frm_voice);
back_frm_voice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Intent i = new Intent(voice_calculator.this,MainActivity.class);
//startActivity(i);
finish();
}
});
}
}
public class cam_calculator extends Activity {
Fragment cam_fragment;
Button back_frm_came;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cam_calculator);
back_frm_came = (Button) findViewById(R.id.back_frm_came);
back_frm_came.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Intent i = new Intent(cam_calculator.this,MainActivity.class);
//startActivity(i);
finish();
}
});
}
}
The MainActivity will be in the stack, so when you do finish() in your second activity, the MainActivity will be popped and onResume() will be called instead onCreate()
From what I understand, you're launching two children activities from a parent activity and when you press back, the parent activity is restarting. It's because the Android call stack doesn't know that the parent activity is a parent activity for the two children activities. In your Android Manifest, specify parentActivity for the two child activities like this -
android:parentActivityName="com.example.android.ParentActivity"
Let me know if it still doesn't work. Happy Coding!
i want to add screen rotation support to the activity having a pager view. what i want is when user changes screen orientation, the tab of pager view that was open should be opened in the new orientation. but now activity restarts and every time first tab opens. kindly help me . Thanks in Advance.
package com.example.ali.namallibrary;
import android.app.Fragment;
import android.content.Context;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.Serializable;
public class aboutLibrary extends AppCompatActivity {
CustomAdapter customAdapterpter = null;
TabLayout tabLayout;
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about_library);
customAdapterpter = new CustomAdapter(getSupportFragmentManager(),getApplicationContext());
viewPager = (ViewPager) findViewById(R.id.viewPager);
viewPager.setAdapter(customAdapterpter);
tabLayout = (TabLayout) findViewById(R.id.tabBar);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
});
} // end of oncreate
private class CustomAdapter extends FragmentPagerAdapter {
private String[] fragmentNames = {"About","Collection","Timing","Contact"};
public CustomAdapter(FragmentManager supportFragmentManager, Context applicationContext) {
super(supportFragmentManager);
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
switch (position)
{
case 0 :
return new aboutLibraryFrag();
case 1 :
return new libraryCollectionFrag();
case 2 :
return new libraryTimingFrag();
case 3 :
return new contactUsFrag();
default:
return null;
}
}
#Override
public int getCount() {
return fragmentNames.length;
}
#Override
public CharSequence getPageTitle(int position) {
return fragmentNames[position];
}
}
Whenever your rotate the screen, the activity is completely destroyed and re-created. To deal with this, there is a lifecycle method called onSaveInstanceState. In this method you can save a Bundle object. A Bundle is a bunch of key value pairs that you define, which you want around after the rotation. In that Bundle, you can store the current position of your view pager. I'm haven't worked much with ViewPagers, but getCurrentItem might be what you're looking for. You'd need to make your ViewPager a member variable, and a constant for the key. Then I'm guessing it would look something like:
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putInt(CURRENT_POSITION_KEY, mViewPager.getCurrentItem());
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
The onCreate method takes a Bundle savedInstanceState - if the activity is being restarted from a rotation, this parameter will have everything you saved in onSaveInstanceState. Thus you can do something like this in onCreate:
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
int currentPos = savedInstanceState.getInt(CURRENT_POSITION_KEY);
mViewPager.setCurrentItem(currentPos)
}
More information about loading and saving the state between rotations can be found here: https://developer.android.com/guide/components/activities/activity-lifecycle.html#saras
Another way to deal with screen changes and or rotation is to add android:configChanges to your activity:
<activity android:name="com.example.myactivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize|screenLayout|smallestScreenSize|uiMode" />
The ConfigChanges mentioned will not cause your activity to be detroyed and recreated when they occur instead, Android will simply rotate the screen and then call onConfigurationChanged where you can manually handle the cases yourself.
You can override onConfigurationChanged in your activity to handle the events.
public class myactivity extends Activity
{
//..
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
}
}
}
Read more in the Android documentation here
Pretty new to android world, I am having an issue playing audio when clicking a button. The interesting/weird aspect of it is that same code works on my mainactivity but not on secondactivity that I have set up. I am using the same exact code that works on mainactivity. I used that code on mainactivity just to test it, keep in mind no media player has been declared or defined in mainactivity. I did that just to test to see if code works.
Here is my xml:
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="15sp"
android:layout_marginBottom="15sp" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="press button to play audio"
android:textSize="40sp"
android:textColor="#ffff"
android:fontFamily="cursive"
android:textStyle="bold"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"
/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginBottom="10sp"
android:layout_gravity="center"
>
<Button
android:id="#+id/AudioButton"
android:layout_width="wrap_content"
android:layout_height="50sp"
android:text="play"
android:textSize="22sp"
android:textColor="#ffff"
android:layout_marginRight="10dp"
/>
</LinearLayout>
Here is JAVA:
package nameiscleared;
import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class SecondActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Button start = (Button) findViewById(R.id.AudioButton);
start.setOnClickListener(new View.OnClickListener() {
MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.audioname);
#Override
public void onClick(View view) {
mp.start();
}
});
}
}
It just my assumption, I think you are not releasing the MediaPlayer when you use it in MainActivity. That is why it is not working on secondActivity. Another mistake is, MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.audioname); need to be in onClick, not in View.OnClickListener() bracket. You need to keep in mind that after you used MediaPlayer, you need to release it when it is no longer being used.
A MediaPlayer can consume valuable system resources. Therefore, you should always take extra precautions to make sure you are not hanging on to a MediaPlayer instance longer than necessary. When you are done with it, you should always call release() to make sure any system resources allocated to it are properly released. For example, if you are using a MediaPlayer and your activity receives a call to onStop(), you must release the MediaPlayer, because it makes little sense to hold on to it while your activity is not interacting with the user (unless you are playing media in the background, which is discussed in the next section). When your activity is resumed or restarted, of course, you need to create a new MediaPlayer and prepare it again before resuming playback - Android Developers documentation.
The correct implementation supposed to be like this;
MainActivity
public class MainActivity extends AppCompatActivity{
private Button playBtn, startActivityBtn;
private MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
playBtn = (Button)findViewById(R.id.playBtn);
playBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mediaPlayer = MediaPlayer.create(MainActivity.this, Settings.System.DEFAULT_RINGTONE_URI);
mediaPlayer.start();
}
});
startActivityBtn = (Button)findViewById(R.id.startActivity);
startActivityBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
}
});
}
#Override
protected void onStop() {
super.onStop();
if(null != mediaPlayer){
if(mediaPlayer.isPlaying())
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
}
}
SecondActivity
public class SecondActivity extends AppCompatActivity {
private Button playBtn;
private MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_econd);
playBtn = (Button)findViewById(R.id.playBtn);
playBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mediaPlayer = MediaPlayer.create(SecondActivity.this, Settings.System.DEFAULT_RINGTONE_URI);
mediaPlayer.start();
}
});
}
#Override
protected void onStop() {
super.onStop();
if(null != mediaPlayer){
if(mediaPlayer.isPlaying())
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
}
}
I am not including the layout because both of the layout are very simple. MainActivity has two button, to play and to start another activity. SecondActivity has only play button.
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();
}
}
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;