How would you save Activity state during a screen rotation?

When your orientation changes, you don’t have to manually change to the landscape layout file. Android does this automatically for you. When orientation changes, Android destroys your current activity and creates a new activity again, this is why you are losing the text.

Basically, whenever Android destroys and recreates your Activity for orientation change, it calls onSaveInstanceState() before destroying and calls onCreate() after recreating. Whatever you save in the bundle in onSaveInstanceState, you can get back from the onCreate() parameter.

private TextView mTextView;
private static final String KEY_TEXT_VALUE = "textValue";
@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  mTextView = (TextView) findViewById(R.id.main);
  
  if (savedInstanceState != null) {
      CharSequence savedText = savedInstanceState.getCharSequence(KEY_TEXT_VALUE);
      mTextView.setText(savedText);
  }
}

@Override
protected void onSaveInstanceState (Bundle outState) {
   super.onSaveInstanceState(outState);
   outState.putCharSequence(KEY_TEXT_VALUE, mTextView.getText());
}

When you choose Fragment over Activity?

  • Activities are designed to represent a single screen of my application, while
  • Fragments are designed to be reusable UI layouts with logic embedded inside of them

Google advises you to always use Fragments. In the simplest case, Fragments are used like containers of activities. Android 4 (ICS) supports both Smartphones and Tablets. This means the same application will be running on a smartphone and a tablet and they are likely to be very different.


Historically each screen in an Android app was implemented as a separate Activity. This creates a challenge in passing information between screens because the Android Intent mechanism does not allow passing a reference type (i.e. object) directly between Activities. By making each screen a separate Fragment, this data passing headache is completely avoided. Fragments always exist within the context of a given Activity and can always access that Activity. By storing the information of interest within the Activity, the Fragment for each screen can simply access the object reference through the Activity.

How to pass data between Activities in Android?

Consider a scenario after login activity , Sign-out button visible in each activity , now we need to keep session ID available of all activities !!

Solution:

The easiest way to do this would be to pass the session id to the signout activity in the Intent you’re using to
start the activity:

Intent intent = new Intent(getBaseContext(), SignoutActivity.class);
intent.putExtra("EXTRA_SESSION_ID", sessionId);
startActivity(intent);

Access that intent on next activity:

String sessionId = getIntent().getStringExtra("EXTRA_SESSION_ID");

What is ConstraintLayout in Android?

ConstraintLayout allows you to create large and complex layouts with a flat view hierarchy (no nested view groups). It’s similar to RelativeLayout in that all views are laid out according to relationships between sibling views and the parent layout, but it’s more flexible than RelativeLayout and easier to use with Android Studio’s Layout Editor.

Intention of ConstraintLayout is to optimize and flatten the view hierarchy of your layouts by applying some rules to each view to avoid nesting.

How fragment get context in Android?

You can use getActivity() , which returns the activity associated with a fragment. The activity is a context (since
Activity extends Context ). You can also override the onAttach() method of fragment:

public static class DummySectionFragment extends Fragment{
...
@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    DBHelper = new DatabaseHelper(activity);
}
}

What is Context on Android ?

The Context class is an Interface to global information about an application environment.

We may assume a Context is a handle to the system; it provides services like resolving resources, obtaining access to databases and preferences, and so on. An Android app has activities. Context is like a handle to the environment your application is currently running in. The activity object inherits the Context object.

Type of Context in android!!

The are mainly two types of context:

  • Application Context: It is an instance that is the singleton and can be accessed in activity via getApplicationContext() . This context is tied to the lifecycle of an application. The application context can be used where you need a context whose lifecycle is separate from the current context or when you are passing a context beyond the scope of activity.
  • Activity Context: This context is tied to the lifecycle of an activity. The activity context should be used when you are passing the context in the scope of an activity or you need the context whose lifecycle is attached to the current context.

Advantage of ViewHolder pattern in Android!!

Every time when the adapter calls getView() method, the findViewById() method is also called. This is a very intensive work for the mobile CPU and so affects the performance of the application and the battery consumption increases. ViewHolder is a design pattern which can be applied as a way around repeated use of findViewById().

A ViewHolder holds the reference to the id of the view resource and calls to the resource will not be required after you “find” them: Thus performance of the application increases.

ViewHolder Class:

private static class ViewHolder {
  final TextView text;
  final TextView timestamp;
  final ImageView icon;
  final ProgressBar progress;

  ViewHolder(TextView text, TextView timestamp, ImageView icon, ProgressBar progress) {
    this.text = text;
    this.timestamp = timestamp;
    this.icon = icon;
    this.progress = progress;
  }
}

GetView to use ViewHolder object using view.getTag to avoid the use of findviewById again and again to improve performance.

public View getView(int position, View convertView, ViewGroup parent) {
  View view = convertView;
  if (view == null) {
    view = // inflate new view
    ViewHolder holder = createViewHolderFrom(view);
    view.setTag(holder);  
  }
  ViewHolder holder = view.getTag();
  // TODO: set correct data for this list item
  // holder.icon.setImageDrawable(...)
  // holder.text.setText(...)
  // holder.timestamp.setText(...)
  // holder.progress.setProgress(...)
  return view;
}

create ViewHolder object :

private ViewHolder createViewHolderFrom(View view) {
    ImageView icon = (ImageView) view.findViewById(R.id.listitem_image);
    TextView text = (TextView) view.findViewById(R.id.listitem_text);
    TextView timestamp = (TextView) view.findViewById(R.id.listitem_timestamp);
    ProgressBar progress = (ProgressBar) view.findViewById(R.id.progress_spinner);

    return new ViewHolder(text, timestamp, icon, progress);
}

View.setTag(Object) allows you to tell the View to hold an arbitrary object. If we use it to hold an instance of our ViewHolder after we do our findViewById(int) calls, then we can use View.getTag() on recycled views to avoid having to make the calls again and again.

source: stackoverflow

How do you handle Bitmaps in Android as it takes too much memory?

There are a number of reasons why loading bitmaps in your Android app is tricky:

  • Bitmaps can very easily exhaust an app’s memory budget.
  • Loading bitmaps on the UI thread can degrade your app’s performance, causing slow responsiveness or even ANR messages.
  • If your app is loading multiple bitmaps into memory, you need to skillfully manage memory and disk caching.

For most cases, Android recommend that you use the Glide library to fetch, decode, and display bitmaps in your app. Glide abstracts out most of the complexity in handling these and other tasks related to working with bitmaps and other images on Android.

source: developer.android.com