3

I've got a little app with some fragments etc. Now everytime I change the orientation of my screen, the action is restarted, meaning that the input gets lost if you turn your device. How can I prevent this? In addition I'd like to keep the possibility to change my orientation and the app changes with it, I just want to keep the content in.

The magic happens in the MainActivity.java, the displaystuff is in the SearchFragment.xml

MainActivity.java:

package mypackage;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import android.view.View;
import android.view.inputmethod.InputMethodManager;


public class MainActivity extends Activity {


public final static String EXTRA_MESSAGE = "mypackage.MESSAGE";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //addListenerOnSpinnerItemSelection();

 // lädt die ActionBar
        ActionBar actionbar = getActionBar();
        actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        actionbar.setDisplayShowHomeEnabled(true);
        actionbar.setDisplayShowTitleEnabled(true);
        actionbar.setDisplayShowCustomEnabled(false);

        // lädt die Tabs in die Actionbar
        String search = getString(R.string.search_fragment);
        String user = getString(R.string.user_fragment);
        String recent = getString(R.string.recent_fragment);

        ActionBar.Tab TabA = actionbar.newTab().setText(search);
        ActionBar.Tab TabB = actionbar.newTab().setText(user);
        ActionBar.Tab TabC = actionbar.newTab().setText(recent);

        // erstellt neue Fragmente
        Fragment fragmentA = new SearchFragment();
        Fragment fragmentB = new UserFragment();
        Fragment fragmentC = new UpdateFragment();

        // Listener werden angelegt
        TabA.setTabListener(new MyTabsListener(fragmentA));
        TabB.setTabListener(new MyTabsListener(fragmentB));
        TabC.setTabListener(new MyTabsListener(fragmentC));

        // Tabs werden in die actionbar geladen
        actionbar.addTab(TabA);
        actionbar.addTab(TabB);
        actionbar.addTab(TabC);

}


public void sendMessage(View view) 
{

    Spinner mySpinner = (Spinner) findViewById(R.id.criterion);
    String text = mySpinner.getSelectedItem().toString();

    //manual initialation of array - later to be created by XML-Parser
    String[][] array = {{"Opel", "Astra", "2010", "120 PS", "12 l/100km", "Blau, Rot, Grün, Braun", "File 1", "File 2"}, 
                        {"Opel", "Corsa", "2012", "80 PS", "8 l/100km", "Grün, Rot, Blau, Gelb, Magenta", "File 1", "File 2", "File 3"},
                        {"Opel","Vectra", "1980", "200 PS" ,"20 l/100km", "Braun", "file 1"},
                        {"Opel", "Astra", "2010", "120 PS", "12 l/100km", "Blau, Rot, Grün, Braun", "File 1", "File 2"}, 
                        {"Opel", "Corsa", "2012", "80 PS", "8 l/100km", "Grün, Rot, Blau, Gelb, Magenta", "File 1", "File 2", "File 3"},
                        {"Opel","Vectra", "1980", "200 PS" ,"20 l/100km", "Braun", "file 1"}    };



//        Intent intent = new Intent(this, DisplayMessageActivity.class);

    EditText editText = (EditText) findViewById(R.id.edit_message);

    String output = "";

    //add Elements of Array on output string
    for(int i = 0; i <array.length; i++)
    {
        int count = 0;

        //Standard values
        for(int j = 0; j<6; j++)
        {
            output = output + array[i][j];
            if(count<5)
            {
                output = output + " - ";
            }
            count++;
        }

        output = output + "\n";

        int count2 = 6;

        //User generated values with diferent length
        for(int k = 6; k <array[i].length; k++)
        {
            output = output + array[i][k];
            if(count2<array[i].length-1)
            {
                output = output + " - ";
            }
            count2++;
        }

        output = output + "\n\n";
    }


    String message = getText(R.string.search_text)+" "+text+": "+ editText.getText().toString() + "\n\n"+output;

   //display results 
   TextView viewText1 = (TextView) findViewById(R.id.showResults);
   viewText1.setText(message);

   //Clear EditText field
   editText.setText("");

   //Hides Softkeyboard on "Send" Button
   InputMethodManager imm = (InputMethodManager)getSystemService(
              Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);

//        intent.putExtra(EXTRA_MESSAGE, message);
//        startActivity(intent);

}


class MyTabsListener implements ActionBar.TabListener {
    public Fragment fragment;

    public MyTabsListener(Fragment fragment) {
        this.fragment = fragment;
    }

    @Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) {
        // wenn das Tab erneut gewŠhlt wird.
    }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        ft.replace(R.id.fragment_container, fragment);
    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        ft.remove(fragment);
    }

}





@Override //creates the action bar menu using the text information from strings.xml and the method menu() from R.java
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.activity_main, menu);
    return true; //number of points in overflow menu or sth like this

}



public boolean onOptionsItemSelected(MenuItem item) {
    switch(item.getItemId()) {
    case R.id.menu_settings:
    {
        Intent intent = new Intent(this, Settings.class);
      startActivity(intent);
      break;
    }
    case R.id.about_section:
    {
        Intent intent = new Intent(this, About.class);
        startActivity(intent);
        break;
    }
    case R.id.faq_section:
    {
        Intent intent = new Intent(this, FAQ.class);
        startActivity(intent);
        break;
    }
    case R.id.search_section:
    {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        break;
    }
    }

  return true;
}
}

SearchFragment.xml

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_gravity="center"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/welcome" />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="70dp"
        android:orientation="horizontal" >

        <EditText
            android:id="@+id/edit_message"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:hint="@string/edit_message" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp" >

        <Spinner
            android:id="@+id/criterion"
            android:layout_width="117dp"
            android:layout_height="wrap_content"
            android:layout_marginRight="5dp"
            android:layout_marginLeft="5dp"
            android:layout_weight="1"
            android:entries="@array/array"
            android:prompt="@string/prompt" />

        <Button
            android:id="@+id/btnSubmit"
            android:layout_width="136dp"
            android:layout_marginRight="5dp"
            android:layout_marginLeft="5dp"
            android:layout_height="match_parent"
            android:layout_gravity="clip_vertical"
            android:onClick="sendMessage"
            android:text="@string/button_send"
            android:background="@drawable/android" />
    </LinearLayout>

    <TextView
        android:id="@+id/showResults"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</LinearLayout>
Cœur
  • 37,241
  • 25
  • 195
  • 267
chrissik
  • 514
  • 2
  • 5
  • 20
  • see here http://stackoverflow.com/questions/5913130/dont-reload-application-when-orientation-changes – StefMa Feb 08 '13 at 08:37

3 Answers3

2

As far as I know there is a listener for this orientation change so that you can do some data save before orientation change,as when orientation changes activity is relauched internally.

Check out http://developer.android.com/reference/android/view/OrientationListener.html

That is the class have a look through there.

Hope that helped.

Shridutt Kothari
  • 7,326
  • 3
  • 41
  • 61
  • 2
    So I looked into your link and I think that's exaktly what I need. Now I've edited the manifest.xml and added the onConfigurationChanged(Configuration) method to my MainActivity.java. But what to write there? Thanks for your help this far :) – chrissik Feb 08 '13 at 09:15
  • 1
    Ok See my below answer for further implementation: And If I am helping please Up vote the answers so we can know that it is helping you...Happy to help.:) – Shridutt Kothari Feb 08 '13 at 09:25
  • 1
    unfortunatelly upvoting is only possible if i have 15 reputation :( – chrissik Feb 08 '13 at 09:26
  • 3
    @chrissik we should always vote the person who helps us, i think when you reach 15 than up vote the answer. –  Feb 08 '13 at 09:31
  • 1
    @chrissik i think you have 18 rep. congrets now you can upvote answers . – Shridutt Kothari Feb 08 '13 at 09:36
2

Using this method: just call Activity.getLastNonConfigurationInstance to retrieve the same object you returned in the onRetainNonConfigurationInstance. Be sure to check for null and cast to the right class (you can return/get any class). Activity.getLastNonConfigurationInstance

A sample usage in pseudo-code would be:

onRetainNonConfigurationInstance:
    return "I need to remember this next time";

onCreate:
    ...
    String messageToShow = null;
    Object data = getLastNonConfigurationInstance();
    if(data != null)
        messageToShow = (String)data;
    else
        messageToShow = "Nothing to show";

So, if you are targetting up to 2.x.x you can use that method. Otherwise, google recommends you to use Fragment.setRetainInstance. This is backwards compatible via the compability package.

Shridutt Kothari
  • 7,326
  • 3
  • 41
  • 61
  • 2
    Sorry for answering that late. I've looked into the Fragment.setRetainInstance method. Where to call that method? In onConfigurationChanged? Hope you can help me. – chrissik Feb 13 '13 at 09:50
  • 1
    I've looked into that example: http://android-er.blogspot.de/2012/08/retain-fragment-instance-across.html but the way the author does it it isn't working for me. – chrissik Feb 13 '13 at 10:03
0

If the layout is the same on horizontal and verticall add the following to the activity in your manifest:

<activity android:name="yourpackage.MainActivity" android:configChanges="orientation"/>

Now the activity will not reset.

PaNaVTEC
  • 2,505
  • 1
  • 23
  • 36