Android Activity: Handle Intent after onCreate()? - java

I have a problem with the order in which my Android Activity is intitialized.
Basics:
The Activity contains a ViewPager with contains 3 Fragments. The Activity is opened this way:
Intent foodsActivityIntent = new Intent(getActivity(), FoodsActivity.class);
foodsActivityIntent.putExtra("NavigationPosition", navigationPosition);
foodsActivityIntent.putExtra("SearchQuery", searchQuery);
foodsActivityIntent.putExtra("SelectedDateMillis", _currentDay.toDate().getTime());
startActivityForResult(foodsActivityIntent, 200);
In the onCreate - Method i catch the Intent and do some stuff:
Intent intent = getIntent();
if (intent != null) {
//Some stuff
_foodsPagerAdapter.performSearch();
}
The interesting part here is "_foodsPagerAdapter.performSearch()". With this i want to perform a search in each Fragment.
public void performSearch() {
if (_foodSearchFragment != null)
_foodSearchFragment.performSearch();
if (_foodFavoritesFragment != null)
_foodFavoritesFragment.performSearch();
if (_foodCustomFragment != null)
_foodCustomFragment.performSearch();
}
The Problem:
As you can see, the search method in each Fragment is only called if the Fragment is not null. My problem is that the getItem() - Method(which initializes the Fragments in the Adapter) is called after the onCreate (and onStart) Method finished. So the performSearch - Method for each Fragment is never called.
You can understand this better with this Logcat output:
First performSearch is called and then getItem(). But getItem must be called first for my code to work.
getItem():
#Override
public Fragment getItem(int i) {
Log.i("FoodActivityTest", "call getItem in FragmentPagerAdapter");
Fragment fragment = null;
switch (i) {
case 0:
if (_foodSearchFragment == null)
_foodSearchFragment = new FoodSearchFragment();
fragment = _foodSearchFragment;
break;
case 1:
if (_foodFavoritesFragment == null)
_foodFavoritesFragment = new FoodFavoritesFragment();
fragment = _foodFavoritesFragment;
break;
case 2:
if (_foodCustomFragment == null)
_foodCustomFragment = new FoodCustomFragment();
fragment = _foodCustomFragment;
break;
}
return fragment;
}
What am I doing wrong? Do I need to approach the problem differently?
EDIT 1:
FoodsActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_foods);
//Init some views
_viewPager = findViewById(R.id.viewpager_foods);
_foodsPagerAdapter = new FoodsPagerAdapter(getSupportFragmentManager(), this);
_viewPager.setAdapter(_foodsPagerAdapter);
handleOpenIntent();
//do more stuff (show ads etc.)
Log.i("FoodActivityTest", "onCreate finished");
}
#Override
protected void onStart() {
super.onStart();
Log.i("FoodActivityTest", "onStart finished");
}
private void handleOpenIntent() {
Intent intent = getIntent();
if (intent != null) {
int navigationPosition = intent.getExtras().getInt("NavigationPosition");
String searchQuery = intent.getExtras().getString("SearchQuery");
_viewPager.setCurrentItem(navigationPosition);
_foodsPagerAdapter.performSearch(searchQuery);
}
}
EDIT 2:
FoodsPagerAdapter:
public class FoodsPagerAdapter extends FragmentPagerAdapter {
private Context _context;
private FoodSearchFragment _foodSearchFragment;
private FoodFavoritesFragment _foodFavoritesFragment;
private FoodCustomFragment _foodCustomFragment;
public FoodsPagerAdapter(FragmentManager fm, Context context) {
super(fm);
_context = context;
}
#Override
public Fragment getItem(int i) {
Log.i("FoodActivityTest", "call getItem in FragmentPagerAdapter");
Fragment fragment = null;
switch (i) {
case 0:
if (_foodSearchFragment == null)
_foodSearchFragment = new FoodSearchFragment();
fragment = _foodSearchFragment;
break;
case 1:
if (_foodFavoritesFragment == null)
_foodFavoritesFragment = new FoodFavoritesFragment();
fragment = _foodFavoritesFragment;
break;
case 2:
if (_foodCustomFragment == null)
_foodCustomFragment = new FoodCustomFragment();
fragment = _foodCustomFragment;
break;
}
return fragment;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return _context.getString(R.string.activity_foods_search);
case 1:
return _context.getString(R.string.activity_foods_favorites);
case 2:
return _context.getString(R.string.activity_foods_customfood);
default:
return "Error";
}
}
public void performSearch(String query) {
Log.i("FoodActivityTest", "call performSearch");
if (_foodSearchFragment != null)
_foodSearchFragment.performSearch(query);
if (_foodFavoritesFragment != null)
_foodFavoritesFragment.performSearch(query);
if (_foodCustomFragment != null)
_foodCustomFragment.performSearch(query);
}

You should be able to pull the values out of your intent before you initialize the other objects. From the looks of it currently, you are trying to populate an view with no data, then assign the data later. To solve, you could either better handle the null in your adapter, or move your data assignment. I would probably do the latter.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_foods);
// Added this. Moved part of handleOpenIntent() here, other half is below view init.
String searchQuery = "";
Intent intent = getIntent();
if (intent != null) {
int navigationPosition = intent.getExtras().getInt("NavigationPosition");
searchQuery = intent.getExtras().getString("SearchQuery");
//should probably have some error handling if the SearchQuery is missing or the value is invalid.
}
// End of additions
//Init some views
_viewPager = findViewById(R.id.viewpager_foods);
_foodsPagerAdapter = new FoodsPagerAdapter(getSupportFragmentManager(), this);
_viewPager.setAdapter(_foodsPagerAdapter);
// added this too, moved out of handleOpenIntent()
_viewPager.setCurrentItem(navigationPosition);
_foodsPagerAdapter.performSearch(searchQuery);
// end of additions
//removed
//handleOpenIntent();
//do more stuff (show ads etc.)
Log.i("FoodActivityTest", "onCreate finished");
}

Related

Progressbar is not displaying in fragment

I have created a Firebase application.
Everything so far is working great. I have one issue, however, that I'm unable to fix.
My MainActivity.java is implementing an Interface ProgressDisplay.java
The Interface has two methods:
public interface ProgressDisplay {
public void showProgress();
public void hideProgress();
}
I'm not able to call these 2 methods from sub fragments, I'm unable to set the visibility on and off in the fragments.
ManageAccountFragment.java
package com.company.walt.fragments;
public class ManageAccountFragment extends Fragment {
private EditText mName;
private Button mUpdateBtn;
private ProgressBar mProgressBar;
public ManageAccountFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_manage_account, container, false);
mName = (EditText)view.findViewById(R.id.input_name);
mUpdateBtn = (Button)view.findViewById(R.id.btn_update);
mUpdateBtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view){
if (!isEmpty (mName.getText().toString()))
{
showProgress();
Toast.makeText(getActivity(), "SHOW DIALOG", Toast.LENGTH_SHORT).show();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null)
{
UserProfileChangeRequest profileUpdate = new UserProfileChangeRequest.Builder()
.setDisplayName(mName.getText().toString())
//.setPhotoUri(Uri.parse("https://avatarfiles.alphacoders.com/862/86285.jpg"))
.build();
user.updateProfile(profileUpdate).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful())
{
Log.d(TAG, "onComplete: User Profile updated");
}
}
});
hideProgress();
Toast.makeText(getActivity(), "HIDE DIALOG", Toast.LENGTH_SHORT).show();
}
}
}
});
hideSoftKeyboard();
return view;
}
private boolean isEmpty(String string){
return string.equals("");
}
/**
* Display progressbar
*/
protected void showProgress() {
if (getActivity() instanceof ProgressDisplay) {
((ProgressDisplay) getActivity()).showProgress();
}
}
/**
* Hide progressbar
*/
protected void hideProgress() {
if (getActivity() instanceof ProgressDisplay) {
((ProgressDisplay) getActivity()).hideProgress();
}
}
private void hideSoftKeyboard(){
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
}
MainActivity.java
package com.company.walt.activities;
public class MainActivity extends AppCompatActivity implements ProgressDisplay {
private static final String TAG = "MainActivity";
private static final int USER_PROFILE = 1;
private static final int PROFILE_MANAGE = 2;
private static final int PROFILE_SETTING = 3;
private Toolbar mainToolbar;
private AccountHeader headerResult = null;
private Drawer result = null;
private ProgressBar mProgressBar;
private ToggleButton switcher;
#Override
protected void onCreate(Bundle savedInstanceState) {
if(AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES) { setTheme(R.style.NightTheme); }
else { setTheme(R.style.LightTheme);}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
switchAppTheme();
createToolbar();
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
buildHeader(false, savedInstanceState);
createDrawerBuilder();
getUserDetails();
}
#Override
protected void onResume() {
super.onResume();
checkAuthenticationState();
}
/**
* Used to check if user is authenticated or not
*/
private void checkAuthenticationState()
{
Log.d(TAG, "checkAuthenticationState: checking authentication state.");
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user == null){
Log.d(TAG, "checkAuthenticationState: user is null, navigating back to login screen.");
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
else {
Log.d(TAG, "checkAuthenticationState: user is authenticated.");
}
}
/**
* Used to switch between light and dark mode
*/
public void switchAppTheme() {
switcher = (ToggleButton) findViewById(R.id.switcher);
if(AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES) {
switcher.setChecked(true);
}
switcher.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
restartApp();
} else{
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
restartApp();
}
}
});
}
/**
* Used to create the toolbar on top
*/
private void createToolbar(){
mainToolbar = (Toolbar) findViewById(R.id.main_toolbar);
setSupportActionBar(mainToolbar);
getSupportActionBar().setTitle(R.string.app_name);
}
/**
* small helper method to reuse the logic to build the AccountHeader
* this will be used to replace the header of the drawer with a compact/normal header
*
* #param compact
* #param savedInstanceState
*/
private void buildHeader(boolean compact, Bundle savedInstanceState) {
IProfile profile_1;
//IProfile profile_2;
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null)
{
String uid = user.getUid();
String name = user.getDisplayName();
String email = user.getEmail();
Uri photoUrl = user.getPhotoUrl();
profile_1 = new ProfileDrawerItem()
.withName(name)
.withEmail(email)
.withIcon(photoUrl);
//profile_2 = new ProfileDrawerItem().withName("Isensei").withEmail("itrade#gmail.com").withIcon(getResources().getDrawable(R.drawable.ic_user_58dp));
headerResult = new AccountHeaderBuilder()
.withActivity(this)
.withHeaderBackground(R.drawable.ip_menu_header_bg)
.withCompactStyle(compact)
.addProfiles(
profile_1,
//profile_2,
new ProfileSettingDrawerItem()
.withName("Manage Account")
.withDescription("Manage your details")
.withIcon(new IconicsDrawable(this,GoogleMaterial.Icon.gmd_settings)
.actionBar().colorRes(R.color.material_drawer_dark_primary_text)).withIdentifier(PROFILE_MANAGE),
new ProfileSettingDrawerItem()
.withName("Add Account")
.withDescription("Register new account")
.withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_person_add)
.actionBar().colorRes(R.color.material_drawer_dark_primary_text)).withIdentifier(PROFILE_SETTING)
)
.withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() {
#Override
public boolean onProfileChanged(View view, IProfile profile, boolean current) {
//sample usage of the onProfileChanged listener
//if the clicked item has the identifier 1 add a new profile ;)
if (profile instanceof IDrawerItem && ((IDrawerItem) profile).getIdentifier() == USER_PROFILE)
{
// Navigate to home fragment
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
Fragment fragment = new Fragment();
fragment = new HomeFragment();
transaction.replace(R.id.flContent, fragment);
transaction.commit();
}
if (profile instanceof IDrawerItem && ((IDrawerItem) profile).getIdentifier() == PROFILE_MANAGE)
{
// Navigate to home fragment
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
Fragment fragment = new Fragment();
fragment = new ManageAccountFragment();
transaction.replace(R.id.flContent, fragment);
transaction.commit();
}
else if (profile instanceof IDrawerItem && ((IDrawerItem) profile).getIdentifier() == PROFILE_SETTING)
{
Toast.makeText(MainActivity.this, "ACCOUNT", Toast.LENGTH_SHORT).show();
}
/*
if (profile instanceof IDrawerItem && ((IDrawerItem) profile).getIdentifier() == PROFILE_SETTING) {
IProfile newProfile = new ProfileDrawerItem()
.withNameShown(true)
.withName("Kensei")
.withEmail("kensei#gmail.com")
.withIcon(getResources().getDrawable(R.drawable.ic_user_58dp));
if (headerResult.getProfiles() != null) {
//we know that there are 2 setting elements. set the new profile above them ;)
headerResult.addProfile(newProfile, headerResult.getProfiles().size() - 2);
} else {
headerResult.addProfiles(newProfile);
}
}
*/
//false if you have not consumed the event and it should close the drawer
return false;
}
})
.build();
}
}
/**
* Used to create the drawer with all the icons and items
*/
private void createDrawerBuilder(){
//create the drawer and remember the `Drawer` result object
result = new DrawerBuilder()
.withActivity(this)
.withAccountHeader(headerResult)
.withToolbar(mainToolbar)
.addDrawerItems(
new SecondaryDrawerItem().withName(R.string.drawer_services)
.withIdentifier(1)
.withIconTintingEnabled(true)
.withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_device_hub))
.withTag("Bullhorn"),
new SecondaryDrawerItem().withName(R.string.drawer_products)
.withIdentifier(2)
.withIconTintingEnabled(true)
.withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_shopping_cart))
.withTag("Bullhorn"),
new SecondaryDrawerItem().withName(R.string.drawer_photos)
.withIdentifier(3)
.withIconTintingEnabled(true)
.withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_camera_roll))
.withTag("Bullhorn"),
new SecondaryDrawerItem().withName(R.string.drawer_poem)
.withIdentifier(4)
.withIconTintingEnabled(true)
.withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_content_copy))
.withTag("Bullhorn"),
new SecondaryDrawerItem().withName(R.string.drawer_archives)
.withIdentifier(5)
.withIconTintingEnabled(true)
.withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_folder_open))
.withTag("Bullhorn"),
new SectionDrawerItem().withName(R.string.drawer_section_header).withEnabled(false),
new SecondaryDrawerItem().withName(R.string.drawer_settings)
.withIdentifier(6)
.withIconTintingEnabled(true)
.withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_settings))
.withTag("Bullhorn"),
new SecondaryDrawerItem().withName(R.string.drawer_feedback)
.withIdentifier(7)
.withIconTintingEnabled(true)
.withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_headset_mic))
.withTag("Bullhorn"),
new SecondaryDrawerItem().withName(R.string.drawer_pro)
.withIdentifier(8)
.withIconTintingEnabled(true)
.withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_security))
.withTag("Bullhorn"),
new SecondaryDrawerItem().withName(R.string.drawer_logout)
.withIdentifier(9)
.withIconTintingEnabled(true)
.withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_power_settings_new))
.withTag("Bullhorn")
)
.withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
#Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
navigateDrawerItem((int)drawerItem.getIdentifier(), drawerItem);
return true;
}
})
.addStickyDrawerItems(
new SecondaryDrawerItem().withName(R.string.drawer_all_right_reserved).withIcon(FontAwesome.Icon.faw_copyright).withEnabled(false)
).build();
}
/**
* Used to navigate to drawer fragment items
*/
public void navigateDrawerItem(int ItemId, IDrawerItem drawerItem) {
// Create a new fragment and specify the fragment to show based on nav item clicked
Fragment fragment = null;
Class fragmentClass;
switch(ItemId) {
case 1:
fragmentClass = ServicesFragment.class;
break;
case 2:
fragmentClass = ProductsFragment.class;
break;
case 3:
fragmentClass = PhotosFragment.class;
break;
case 4:
fragmentClass = PoemsFragment.class;
break;
case 5:
fragmentClass = ArchivesFragment.class;
break;
case 6:
fragmentClass = SettingsFragment.class;
break;
default:
fragmentClass = HomeFragment.class;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
result.closeDrawer();
}
/*
private void setUserDetails(){
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null)
{
UserProfileChangeRequest profileUpdate = new UserProfileChangeRequest.Builder()
.setDisplayName("Jsk Zack")
.setPhotoUri(Uri.parse("https://avatarfiles.alphacoders.com/862/86285.jpg"))
.build();
user.updateProfile(profileUpdate).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful())
{
Log.d(TAG, "onComplete: User Profile updated");
getUserDetails();
}
}
});
}
}
*/
private void getUserDetails(){
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null)
{
String uid = user.getUid();
String name = user.getDisplayName();
String email = user.getEmail();
Uri photoUrl = user.getPhotoUrl();
String properties =
"uid: " + uid + "\n" +
"name: " + name + "\n" +
"email: " + email + "\n" +
"photoUrl: " + photoUrl;
Log.d(TAG, "getUserDetails: properties: \n" + properties);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
//add the values which need to be saved from the drawer to the bundle
outState = result.saveInstanceState(outState);
//add the values which need to be saved from the accountHeader to the bundle
outState = headerResult.saveInstanceState(outState);
super.onSaveInstanceState(outState);
}
#Override
public void onBackPressed() {
//handle the back press :D close the drawer first and if the drawer is closed close the activity
if (result != null && result.isDrawerOpen()) {
result.closeDrawer();
} else {
super.onBackPressed();
}
}
/**
* Display progressbar
*/
public void showProgress() {
findViewById(R.id.progressBar).setVisibility(View.VISIBLE);
}
/**
* Hide progressbar
*/
public void hideProgress() {
if(mProgressBar.getVisibility() == View.VISIBLE){
findViewById(R.id.progressBar).setVisibility(View.INVISIBLE);
}
}
/**
* Used to relaunch the application
*/
public void restartApp() {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
finish();
}
}
I don't know why this is not working, am I doing something wrong?
I think its because of this lines of code
findViewById(R.id.progressBar).setVisibility(View.INVISIBLE);
Just instantiate your Progressbar in your main Activity onCreate(){HERE} and use mProgressBar in the Hide and Show functions
public void showProgress() {
mProgressBar .setVisibility(View.VISIBLE);
}
I Hope this helps ;)

Android: take photo with custom camera activity and return it

I'm using a custom camera class in android. I want to take a photo (only one), finish the activity and return this photo, It doesn't matter if i do this with a bitmap or a bytearray. I'm using an Intent to return the picture.
I have tested 2 ways for do it, but in one way the camera being blocked after take a photo (without exception) and in the other way, in activity result, I can't take the picutre (Bitmap or bytearray) that I have put in the Intent (because it's null)
Here 2 classes, MainActivity and GGCameraActivity (the activity that runs the camera and takes the photo).
MAIN ACTIVITY:
public class MainActivity extends ActionBarActivity{
private static final int CAMERA_ACTIVITY_ID = 98;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b1 = (Button)findViewById(R.id.b_empezar);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startButtonClick();
}
});
}
#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 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_configuracion) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int reqCode, int resCode, Intent handler){
switch(reqCode){
case CAMERA_ACTIVITY_ID:
if(resCode == RESULT_OK){
//get the byte array
byte[] b = handler.getExtras().getByteArray(GGCameraActivity.PARAM_PHOTO);
//'b' is null.
}
break;
}
}
private void startButtonClick(){
Intent i = new Intent(this, GGCameraActivity.class);
startActivityForResult(i, CAMERA_ACTIVITY_ID);
}
}
CAMERA ACTIVITY:
public class GGCameraActivity extends Activity {
private Activity context;
private GGCameraPreview preview;
private Camera camera;
private ImageView fotoButton;
public static final String PARAM_PHOTO = "bmp";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ggcamera);
context = this;
fotoButton = (ImageView) findViewById(R.id.photo_button);
fotoButton.setOnClickListener(photoButtonClick);
preview = new GGCameraPreview(this,(SurfaceView) findViewById(R.id.ggcameraFragment));
FrameLayout frame = (FrameLayout) findViewById(R.id.ggcameraPreview);
frame.addView(preview);
preview.setKeepScreenOn(true);
}
#Override
protected void onResume() {
super.onResume();
if (camera == null) {
camera = Camera.open();
camera.startPreview();
camera.setErrorCallback(new ErrorCallback() {
#Override
public void onError(int error, Camera mcamera) {
camera.release();
camera = Camera.open();
Log.d("Camera died", "error camera");
}
});
}
if (camera != null) {
if (Build.VERSION.SDK_INT >= 14)
setCameraDisplayOrientation(context,
CameraInfo.CAMERA_FACING_BACK, camera);
preview.setCamera(camera);
}
}
#Override
protected void onPause() {
if (camera != null) {
camera.stopPreview();
preview.setCamera(null);
camera.release();
camera = null;
}
super.onPause();
}
private void setCameraDisplayOrientation(Activity activity, int cameraId,
android.hardware.Camera camera) {
android.hardware.Camera.CameraInfo info = new android.hardware.Camera.CameraInfo();
android.hardware.Camera.getCameraInfo(cameraId, info);
int rotation = activity.getWindowManager().getDefaultDisplay()
.getRotation();
int degrees = 0;
switch (rotation) {
case Surface.ROTATION_0:
degrees = 0;
break;
case Surface.ROTATION_90:
degrees = 90;
break;
case Surface.ROTATION_180:
degrees = 180;
break;
case Surface.ROTATION_270:
degrees = 270;
break;
}
int result;
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (info.orientation + degrees) % 360;
result = (360 - result) % 360; // compensate the mirror
} else { // back-facing
result = (info.orientation - degrees + 360) % 360;
}
camera.setDisplayOrientation(result);
}
private OnClickListener photoButtonClick = new OnClickListener() {
#Override
public void onClick(View v) {
fotoButton.setClickable(false);
camera.autoFocus(mAutoFocusCallback);
}
};
Camera.AutoFocusCallback mAutoFocusCallback = new Camera.AutoFocusCallback() {
#Override
public void onAutoFocus(boolean success, Camera camera) {
camera.takePicture(null, null, jpegCallback);
}
};
private PictureCallback jpegCallback = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
Intent resultIntent = new Intent();
resultIntent.putExtra(PARAM_PHOTO, data);
context.setResult(RESULT_OK, resultIntent);
context.finish();
}
};
}
NOTE:
I have no errors as exceptions (I mean, the application don't stops cause of an exception), but I have debugged the classes many times and always I think an exception is raised but catched in some place (but not by me) in "Camera.class" (camera class provided by android). I think this because I always enter in a code snippet (in Camera.class) that's to throw an exception. Here this code snippet:
if (msgType!= CAMERA_MSG_PREVIEW_FRAME &&
msgType != CAMERA_MSG_RAW_IMAGE){
throw new IllegalArgumentException("Unsopported message type: "+ msgType);
}
This code snippet is in Camera.class, I always enter it but, if I don't debug the app, just run it (not taking the captured photo from MainActivity) all works well, the app does not crash.
EDIT 1:
I need a custom camera activity, Intent(MediaStore.ACTION_IMAGE_CAPTURE); is not the thing I need.
EDIT 2: I have tested to return a simple integer. I have the same error, the camera blocks after push the button of take photo and never returns to the main activity. Debuggin I can see again the IllegalArgumentException() mentioned above, but app doesn't crash.
Here the code (changes only in callback and onActivityResult for tke integer instead of byte[]):
Callback of takePicture:
private PictureCallback jpegCallback = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
Intent resultIntent = new Intent();
resultIntent.putExtra("int", 5);
setResult(RESULT_OK, resultIntent);
finish();
}
};
onActivityResult in MainActivity
[...]
case CAMERA_ACTIVITY_ID:
if(resCode == RESULT_OK){
int n = handler.getExtras().getInt("int");
}
break;
[...]
EDIT 3: While debugging, I have step into finish method. I have found that this exception is raised:
throw new UnsupportedOperationException(
"startNextMatchingActivity can only be called from a top-level activity");
But, again, the application does not crash.
I have found the problem. I have read that Intents are not very good for handle large objects. I have tested to put a byte[] of 20 components only and there is no problem. But, with the image byte[] (400k size more or less) the app keeps blocked. I have read this things fast and I'm not sure if it's correct 100%.
I have read too that for sharing large objects between activities the best idea is to use static variables (or Parcelables maybe?).
Then when I take the photo, I put it in class with a static varaible and I take it from other activities.
I suppose that the exceptions I was seeing in the debugger (but not thrown) were produced by the fact of put a too large array in the Intent and return it as result (setResult()), but I'm not sure at all.

Cannot parse "#" sign in dialer

I'm making a custom dialer and everything till now was perfect. Now while testing, I saw that the "#" sign was not working properly. It shows on the dialer but while calling, it goes away. For eg, if I dial *121#, it becomes *121 when the call is being made through the stock dialer. Here is the code for my activity-
public class DialPadActivity extends Activity {
private EditText numberField = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initializeButtonArrowClickListeners();
}
public void dialButtonClick(View v) {
int buttonId = v.getId();
putNumberToEditText(buttonId);
}
public void buttonPhone_click(View v) {
if (numberField != null) {
String phone = numberField.getText().toString();
String uriString = "tel:" + phone;
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse(uriString));
startActivity(intent);
}
}
public void putNumberToEditText(int buttonId) {
switch (buttonId) {
case R.id.dial_button0:
putNumber("0");
break;
case R.id.dial_button1:
putNumber("1");
break;
case R.id.dial_button2:
putNumber("2");
break;
case R.id.dial_button3:
putNumber("3");
break;
case R.id.dial_button4:
putNumber("4");
break;
case R.id.dial_button5:
putNumber("5");
break;
case R.id.dial_button6:
putNumber("6");
break;
case R.id.dial_button7:
putNumber("7");
break;
case R.id.dial_button8:
putNumber("8");
break;
case R.id.dial_button9:
putNumber("9");
break;
case R.id.dial_button_s:
putNumber("*");
break;
case R.id.dial_button_p:
putNumber("#");
break;
}
}
public void putNumber(String number) {
if (numberField == null) {
numberField = (EditText) findViewById(R.id.phone_number_field);
}
numberField.append(number);
}
private void initializeButtonArrowClickListeners() {
ImageButton buttonArrow = (ImageButton) findViewById(R.id.button_arrow);
buttonArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (numberField != null && numberField.length() > 0) {
String previousNumbers = numberField.getText().toString();
String numbersMinusTheLast = previousNumbers.substring(0,
numberField.length() - 1);
numberField.setText(numbersMinusTheLast);
}
}
});
buttonArrow.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
if (numberField != null) {
numberField.setText("");
}
return false;
}
});
}
Where am I doing the wrong?
Use URLEncoder.encode(string, "UTF-8");
For example:
String uriString = "tel:" + URLEncoder.encode(phone, "UTF-8");
Replace your # symbol with %23.
That is: *121%2311 instead of *121#11
String uri = "tel:" + "*6133%235345";
Intent intent;
intent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
startActivity(intent);
the output for this is : *6133#5345

AsyncTask using executeOnExcecutor uses too much memory and cause UI To Freeze

I was instructed to use AsyncTask because multi-threads still caused my application to freeze. I do not believe I am using AsyncTask correctly. In the examples, I saw online, they did not have to call the method Complete().
http://examples.javacodegeeks.com/android/core/os/asynctask/android-asynctask-example/
I call Complete() in the case READ_MESSAGE and as expected it crashes my application. I am not sure what steps I need to take to fix this code. AsyncTask using executeOnExcecutor uses too much memory and cause UI To Freeze. I believe I am calling 'Complete()' incorrectly.
BluetoothChat full code
/**
* This is the main Activity that displays the current chat session.
*/
#SuppressLint("HandlerLeak")
public class BluetoothChat extends Activity {
// Debugging
private static final String TAG = "BluetoothChat";
private static final boolean D = true;
// Message types sent from the BluetoothChatService Handler
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_NAME = 4;
public static final int MESSAGE_TOAST = 5;
public static final int THREAD_POOL_SIZE = Integer.MAX;
// Key names received from the BluetoothChatService Handler
public static final String DEVICE_NAME = "device_name";
public static final String TOAST = "toast";
// Intent request codes
private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
private static final int REQUEST_ENABLE_BT = 3;
// Layout Views
private ListView mConversationView;
private EditText mOutEditText;
private Button mSendButton;
public Button mFunctionButton;
public Button seizureResult;
public double [][]stored = new double[8000][1];
public static HjorthClass finalValue;
public int a;
public Handler handler;
public static boolean potato = false;
public String transfer;
public boolean bool;
// Name of the connected device
private String mConnectedDeviceName = null;
// Array adapter for the conversation thread
private ArrayAdapter<String> mConversationArrayAdapter;
// String buffer for outgoing messages
private StringBuffer mOutStringBuffer;
// Local Bluetooth adapter
private BluetoothAdapter mBluetoothAdapter = null;
// Member object for the chat services
private BluetoothChatService mChatService = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
if(D) Log.e(TAG, "+++ ON CREATE +++");
// Set up the window layout
setContentView(R.layout.main);
setTitle("Seizure Detection Helmet Application");
handler = new Handler();
mFunctionButton = (Button)findViewById(R.id.functions);
seizureResult = (Button)findViewById(R.id.SeizureResult);
mFunctionButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent z = new Intent(BluetoothChat.this, MainActivity.class);
startActivity(z);
}
});
seizureResult.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v){
Toast.makeText(getApplicationContext(), "Value =="+bool, Toast.LENGTH_LONG).show();
}
});
// Get local Bluetooth adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// If the adapter is null, then Bluetooth is not supported
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
}
#Override
public void onStart() {
super.onStart();
if(D) Log.e(TAG, "++ ON START ++");
// If BT is not on, request that it be enabled.
// setupChat() will then be called during onActivityResult
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// Otherwise, setup the chat session
} else {
if (mChatService == null) setupChat();
}
}
#Override
public synchronized void onResume() {
super.onResume();
if(D) Log.e(TAG, "+ ON RESUME +");
// Performing this check in onResume() covers the case in which BT was
// not enabled during onStart(), so we were paused to enable it...
// onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
if (mChatService != null) {
// Only if the state is STATE_NONE, do we know that we haven't started already
if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
// Start the Bluetooth chat services
mChatService.start();
}
}
}
private void setupChat() {
Log.d(TAG, "setupChat()");
// Initialize the array adapter for the conversation thread
mConversationArrayAdapter = new ArrayAdapter<String>(this, R.layout.message);
mConversationView = (ListView) findViewById(R.id.in);
mConversationView.setAdapter(mConversationArrayAdapter);
// Initialize the compose field with a listener for the return key
mOutEditText = (EditText) findViewById(R.id.edit_text_out);
mOutEditText.setOnEditorActionListener(mWriteListener);
// Initialize the send button with a listener that for click events
mSendButton = (Button) findViewById(R.id.button_send);
mSendButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Send a message using content of the edit text widget
TextView view = (TextView) findViewById(R.id.edit_text_out);
String message = view.getText().toString();
sendMessage(message);
}
});
// Initialize the BluetoothChatService to perform bluetooth connections
mChatService = new BluetoothChatService(this, mHandler);
// Initialize the buffer for outgoing messages
mOutStringBuffer = new StringBuffer("");
}
#Override
public synchronized void onPause() {
super.onPause();
if(D) Log.e(TAG, "- ON PAUSE -");
}
#Override
public void onStop() {
super.onStop();
if(D) Log.e(TAG, "-- ON STOP --");
}
#Override
public void onDestroy() {
super.onDestroy();
// Stop the Bluetooth chat services
if (mChatService != null) mChatService.stop();
if(D) Log.e(TAG, "--- ON DESTROY ---");
}
private void ensureDiscoverable() {
if(D) Log.d(TAG, "ensure discoverable");
if (mBluetoothAdapter.getScanMode() !=
BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
}
}
private class ProcessData extends AsyncTask<Boolean, Void, Boolean>
{
#Override
protected Boolean doInBackground(Boolean... params)
{
for(int a = 0; a<8000; a++)
{
try
{
if(transfer == null)
{
transfer = "0";
}
double[] convert = new double[1];
for(int z=0; z <1;z++)
{
convert[z]= Double.parseDouble(transfer);
}
for(int j=0; j<1;j++)
{
stored[a][j]= convert[j];
}
}
catch(NumberFormatException e)
{
}
}
finalValue = new HjorthClass(stored);
bool = finalValue.returnSum();
return bool;
}
}
private final ExecutorService mThreadPoolExecutor = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
public void Complete()
{
ProcessData task = new ProcessData();
task.executeOnExecutor(mThreadPoolExecutor,bool);
}
/**
* Sends a message.
* #param message A string of text to send.
*/
private void sendMessage(String message) {
// Check that we're actually connected before trying anything
if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
return;
}
// Check that there's actually something to send
if (message.length() > 0) {
// Get the message bytes and tell the BluetoothChatService to write
byte[] send = message.getBytes();
mChatService.write(send);
// Reset out string buffer to zero and clear the edit text field
mOutStringBuffer.setLength(0);
mOutEditText.setText(mOutStringBuffer);
}
}
// The action listener for the EditText widget, to listen for the return key
private TextView.OnEditorActionListener mWriteListener =
new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
// If the action is a key-up event on the return key, send the message
if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
String message = view.getText().toString();
sendMessage(message);
}
if(D) Log.i(TAG, "END onEditorAction");
return true;
}
};
/** private final void setStatus(int resId) {
final ActionBar actionBar = getActionBar();
actionBar.setSubtitle(resId);
}
private final void setStatus(CharSequence subTitle) {
final ActionBar actionBar = getActionBar();
actionBar.setSubtitle(subTitle);
} **/
// The Handler that gets information back from the BluetoothChatService
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(final Message msg) {
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
if(D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
switch (msg.arg1) {
case BluetoothChatService.STATE_CONNECTED:
//setStatus(getString(R.string.title_connected_to, mConnectedDeviceName));
mConversationArrayAdapter.clear();
break;
case BluetoothChatService.STATE_CONNECTING:
// setStatus(R.string.title_connecting);
break;
case BluetoothChatService.STATE_LISTEN:
case BluetoothChatService.STATE_NONE:
//setStatus(R.string.title_not_connected);
break;
}
break;
case MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
// construct a string from the buffer
String writeMessage = new String(writeBuf);
mConversationArrayAdapter.add("Me: " + writeMessage);
break;
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
String readMessage = new String(readBuf,0,msg.arg1);
transfer = readMessage;
mConversationArrayAdapter.add("Voltage: "+ transfer);
Complete();
break;
case MESSAGE_DEVICE_NAME:
// save the connected device's name
mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
Toast.makeText(getApplicationContext(), "Connected to "
+ mConnectedDeviceName, Toast.LENGTH_SHORT).show();
break;
case MESSAGE_TOAST:
Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
Toast.LENGTH_SHORT).show();
break;
}
}
};
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(D) Log.d(TAG, "onActivityResult " + resultCode);
switch (requestCode) {
case REQUEST_CONNECT_DEVICE_SECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
connectDevice(data, true);
}
break;
case REQUEST_CONNECT_DEVICE_INSECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
connectDevice(data, false);
}
break;
case REQUEST_ENABLE_BT:
// When the request to enable Bluetooth returns
if (resultCode == Activity.RESULT_OK) {
// Bluetooth is now enabled, so set up a chat session
setupChat();
} else {
// User did not enable Bluetooth or an error occurred
Log.d(TAG, "BT not enabled");
Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
finish();
}
}
}
private void connectDevice(Intent data, boolean secure) {
// Get the device MAC address
String address = data.getExtras()
.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
// Get the BluetoothDevice object
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
// Attempt to connect to the device
mChatService.connect(device, secure);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.option_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent serverIntent = null;
switch (item.getItemId()) {
case R.id.secure_connect_scan:
// Launch the DeviceListActivity to see devices and do scan
serverIntent = new Intent(this, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_SECURE);
return true;
case R.id.insecure_connect_scan:
// Launch the DeviceListActivity to see devices and do scan
serverIntent = new Intent(this, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_INSECURE);
return true;
case R.id.discoverable:
// Ensure this device is discoverable by others
ensureDiscoverable();
return true;
}
return false;
}
}
Looks like my initial answer was too short and got converted to a comment :(. As it's actually an answer and not a comment I pasted it once more.
You are creating too many AsyncTasks and the system fails to allocate so many threads. The same question was answered here: java.util.concurrent.RejectedExecutionException: pool=128/128, queue=10/10
RejectedExecutionException you have is caused by the limited capacity of the queue, which keeps waiting tasks (and not by the size of a thread pool).
Default capacity of the queue is 10.
If you want to have more tasks queued run them with executeOnExecutor instead of execute (on android > 3.0):
// create fixed-size thread pool for Executor
private final ExecutorService mThreadPoolExecutor =
Executors.newFixedThreadPool(THREAD_POOL_SIZE);
// then execute your task
task.executeOnExecutor(mThreadPoolExecutor, bool);
In this case queue capacity will be equal to Integer.MAX_VALUE instead of 10 and you won't have tasks rejected (watch out however for not running out of memory submitting too many tasks).
I also recommend renaming your Boolean bool variable, looks very confusing.

Memory not being released when Activity is closed

I have one main activity. It start another sub activities as Tab. On closing sub activities memory isn't released using by sub tab. Memory increases every time on opening other tabs.
After some time my application get crashed:
public class Main extends Activity {
public static Activity activity;
private Bundle saveInstance;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.activity = this;
this.saveInstance = savedInstanceState;
Application app = Application.getSharedInstance();
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public void onBackPressed()
{
// super.onBackPressed();
AlertUtills.showQuitDialog(Main.this);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
final TabHost tabHost = (TabHost) this
.findViewById(android.R.id.tabhost);
LocalActivityManager mLocalActivityManager = new LocalActivityManager(
this, false);
mLocalActivityManager.dispatchCreate(saveInstance);
tabHost.setup(mLocalActivityManager);
switch (item.getItemId())
{
case R.id.create_new:
{
if (CommonUtilities.isTabNotExist(tabHost, "NewProject"))
{
TabSpec spec2 = tabHost.newTabSpec("NewProject");
Intent in = new Intent(this, Activity_cretateNew.class);
in.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
spec2.setContent(in);
spec2.setIndicator("New Project");
tabHost.addTab(spec2);
tabHost.setCurrentTabByTag("NewProject");
}
tabHost.setCurrentTabByTag("NewProject");
}
break;
case R.id.open:
{
OpenDialog dialog = new OpenDialog(this, "Open Project", false,
OpenDialogType.CORELOG_OPEN);
dialog.Show();
}
break;
case R.id.menu_exit:
onBackPressed();
break;
case R.id.import_las:
{
if (isCurrentProjectExist())
{
if (CommonUtilities.isTabNotExist(tabHost, "ImportLas"))
{
TabSpec spec2 = tabHost.newTabSpec("ImportLas");
Intent in = new Intent(this, LASImportWizard.class);
spec2.setContent(in);
spec2.setIndicator("Import Las");
tabHost.addTab(spec2);
}
tabHost.setCurrentTabByTag("ImportLas");
}
}
break;
case R.id.import_coredata:
{
if (isCurrentProjectExist())
{
if (CommonUtilities.isTabNotExist(tabHost, "coredata"))
{
TabSpec spec2 = tabHost.newTabSpec("coredata");
Intent in = new Intent(Main.this,
CoreDataImportWizard.class);
spec2.setContent(in);
spec2.setIndicator("Core Data Import");
tabHost.addTab(spec2);
}
tabHost.setCurrentTabByTag("coredata");
}
}
break;
case R.id.list_Data:
{
if (isProjectHasWell())
{
if (CommonUtilities.isTabNotExist(tabHost, "ListData"))
{
TabSpec spec1 = tabHost.newTabSpec("ListData");
Intent in = new Intent(Main.this, ListDataWindow.class);
// in.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
spec1.setContent(in);
spec1.setIndicator("List Data");
tabHost.addTab(spec1);
}
tabHost.setCurrentTabByTag("ListData");
}
}
break;
case R.id.basemap:
{
if (isCurrentProjectExist())
{
if (CommonUtilities.isTabNotExist(tabHost, "BaseMap"))
{
TabSpec spec2 = tabHost.newTabSpec("BaseMap");
Intent inBasemap = new Intent(Main.this, Basemap.class);
spec2.setContent(inBasemap);
spec2.setIndicator("Base Map");
tabHost.addTab(spec2);
}
tabHost.setCurrentTabByTag("BaseMap");
}
}
break;
case R.id.logPlot:
{
if (isProjectHasWell())
{
if (CommonUtilities.isTabNotExist(tabHost, "LogPlot"))
{
TabSpec spec2 = tabHost.newTabSpec("LogPlot");
Intent intentLogPlot = new Intent(Main.this,
Logplot_Activity.class);
spec2.setContent(intentLogPlot);
spec2.setIndicator("Log Plot");
tabHost.addTab(spec2);
}
tabHost.setCurrentTabByTag("LogPlot");
}
}
break;
case R.id.show_hide_project_explorer:
{
FrameLayout frameLayout = (FrameLayout) activity
.findViewById(R.id.explorerFrame);
if (item.isChecked() == true)
{
item.setChecked(false);
frameLayout.setVisibility(View.GONE);
}
else
{
item.setChecked(true);
frameLayout.setVisibility(View.VISIBLE);
}
break;
}
}
return true;
}
private boolean isCurrentProjectExist()
{
return Application.getSharedInstance().getCurrentProject() == null ? false
: true;
}
private boolean isProjectHasWell()
{
return isCurrentProjectExist()
&& Application.getSharedInstance().getCurrentProject()
.getAllWells().length != 0 ? true : false;
}
public static Activity getMainActivity()
{
return activity;
}
}
Run hprof or another similar profiler. If this is happening, the number of objects of your tab activites will increase. See whats holding onto references to them, and then fix them so they don't.
Its kind of hard to debug this kind of thing without those hprofs.

Categories

Resources