Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android activity recreate itself

Tags:

My app normally works just fine, until I face a strange problem on specific device. There are 2 activities in App. After I start ActivityB inside of ActivityA, ActivityA starts with no issue. However, after I go back to the ActivityA with pushing back hardware button or calling finish(); inside of closeButton in ActivityB, ActivityA reloads itself. It triggers onCreate() again and reloads all its contents. And I'm not changing orientation of phone. This strange behavior only appears in 15 phones over 1.000 download of app.

This problem only occurs on Galaxy S3 Android OS 4.1.2. And this is also strange.

Do you have any idea why this is happening?

When I start a new Activity inside of button listener like this:

ActivityA.java (MesajlarListViewActivity)

    public class MesajlarListViewActivity extends TrackedActivity {      Context context = null;      // contacts JSONArray     JSONArray contacts = null;      ArrayList<Message> productArray = new ArrayList<Message>();      private ProductAdapter adapter;     private ListView productList;     private Runnable viewOrders;     private HoloProgressIndicator profilInfoProgress = null;      ImageView kapatButton = null;      @Override     public void onCreate(Bundle savedInstanceState)     {         super.onCreate(savedInstanceState);         setContentView(R.layout.mesajlar_list);          context = this;          kapatButton = (ImageView) findViewById(R.id.kapat_button);         /* kapat button onclick listener. */         // =================================================================================================================         kapatButton.setOnClickListener(new View.OnClickListener() {             public void onClick(View view)             {                 // Set vibration on touch.                 KnetGenericClass.vibratePhone(context);                  finish();             }          });         // =================================================================================================================         //Progress bar.         profilInfoProgress = (HoloProgressIndicator) findViewById(R.id.profil_info_progress);          // cheking internet connectivity.         if(KnetGenericClass.checkInternetConnection(context))         {             // start task!             /* internet var ise web service baglantisi kurmaya baslayabiliriz. */             startActivityIndicatorWithThread();         }         else         {             KnetGenericClass.printErrorMessage(context, "Bağlantı Hatası",                     "Lütfen internet bağlantınızı kontrol ediniz.");         }          productList = (ListView) findViewById(R.id.product_list);         adapter = new ProductAdapter(this, R.layout.message_row, productArray);         productList.setAdapter(adapter);          // When user click a view on list view new page is appearing.         productList.setOnItemClickListener(new OnItemClickListener() {             public void onItemClick(AdapterView<?> parent, View view, int position, long id)             {                  // Set vibration on touch.                 KnetGenericClass.vibratePhone(context);                  /* Navigate to message detay activity class with ilan ID. */                 Intent myIntent = new Intent(view.getContext(), MesajDetayActivity.class);                 myIntent.putExtra("messageID", productArray.get(position).getId());                 startActivity(myIntent);                  // setting image of clicked message null.                 RelativeLayout relativeLayout = (RelativeLayout) view;                 ImageView unreadedImageView = (ImageView) relativeLayout.findViewById(R.id.unreaded_image);                 unreadedImageView.setImageResource(0);             }         });     }      public class ProductAdapter extends ArrayAdapter<Message> {         ArrayList<Message> items;          public ProductAdapter(Context context, int textViewResourceId, ArrayList<Message> objects) {             super(context, textViewResourceId, objects);             this.items = objects;         }          @Override         public View getView(int position, View convertView, ViewGroup parent)         {             if(convertView == null)             {                 LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);                 convertView = vi.inflate(R.layout.message_row, null);             }              ImageView unreadedImageView = (ImageView) convertView.findViewById(R.id.unreaded_image);             TextView productName = (TextView) convertView.findViewById(R.id.product_name);             TextView productDetail = (TextView) convertView.findViewById(R.id.product_detail);             // TextView productDate = (TextView)             // convertView.findViewById(R.id.product_date);             TextView sentDate = (TextView) convertView.findViewById(R.id.product_date);              productName.setText(items.get(position).getSender());             productDetail.setText(items.get(position).getTitle());             // String bodyNoHTML = items.get(position).getBody();              if(items.get(position).getIsReaded())             {                 unreadedImageView.setImageResource(0);             }             else             {                 unreadedImageView.setImageResource(R.drawable.bluedot);             }              String dateStr = items.get(position).getSentDate();             try             {                 sentDate.setText(dateStr.substring(6, 8) + "." + dateStr.substring(4, 6) + "." + dateStr.substring(0, 4)                         +" "+dateStr.substring(8, 10)+":"+dateStr.substring(10, 12));             }             catch(Exception e)             {                 sentDate.setText("");             }               return convertView;         }      }// @end of product adapter class.      /* web service'e baglanti kurulan methodu threadin icerisinde cagiriyoruz. */     public void startActivityIndicatorWithThread()     {         // ==============================================================================================         // getting ilan details into arraylist.         // setting up thread.         viewOrders = new Runnable() {             public void run()             {                 getMessageListFromWebService();             }         };         Thread thread = new Thread(null, viewOrders, "MagentoBackground");         thread.start();         profilInfoProgress.start();         // ==============================================================================================         // @end of the thread declaration.     }      public void getMessageListFromWebService()     {         // Creating JSON Parser instance         JSONParser jParser = new JSONParser(context);          // getting JSON string from URL         JSONArray jsonArray = jParser.getAuthorizedInfoFromUrlToJSONArray(                 WebServiceInfo.getKnetWebServiceLink()+"/API/Member/GetInboxMessageList", MainActivity.getAccessToken());          // if json is null then there is a problem.         if(jsonArray == null)         {             // if json array is null then print error message.             runOnUiThread(showAlertMessage);             runOnUiThread(returnRes);             return;         }          try         {             // Eger aranilan kritere gore ilan yok ise hata mesaji basiyoruz.             if(jsonArray.length() == 0)             {                 // if json array is null then print error message.                 runOnUiThread(showAlertIlanYokMessage);                 runOnUiThread(returnRes);                 return;             }              // looping through All Contacts             for (int i = 0; i < jsonArray.length(); i++)             {                 JSONObject c = jsonArray.getJSONObject(i);                  // Storing each json item in variable                 // String id = c.getString(TAG_ID);                 String id = c.getString("Id");                 String sender = c.getString("Sender");                 // String body = c.getString("Body");                 String title = c.getString("Title");                 String sentDate = c.getString("SentDate");                 Boolean isReaded = c.getBoolean("IsRead");                  Message productObject = new Message(id, sender, "", title, sentDate, isReaded);                 productArray.add(productObject);             }         }         catch (Exception e)         {             Log.e("BACKGROUND_PROC", e.getMessage());         }         runOnUiThread(returnRes);     }       // @end of thread.     private Runnable returnRes = new Runnable() {          public void run()         {             profilInfoProgress.stop();             adapter.notifyDataSetChanged();// refreshing data over adapter in                                             // list view.         }     };      // @end of thread.     private Runnable showAlertMessage = new Runnable() {          public void run()         {             // Bu hata genelde linkteki problemden, servera ulasilamamasindan             // veya timeouttan meydana gelir.             Toast.makeText(getApplicationContext(),                     "Mesajlar alınamadı lütfen daha sonra tekrar deneyiniz.",                      Toast.LENGTH_LONG).show();         }     };      private Runnable showAlertIlanYokMessage = new Runnable() {          public void run()         {             // Bu hata aranilan kelimeye gore ilan bulunamazsa gelir.             Toast.makeText(getApplicationContext(),                     "Mesajlar bulunamadı.",                      Toast.LENGTH_LONG).show();         }     };  } 

========================================================================

ActivityB.java (MesajDetayActivity.java)

public class MesajDetayActivity extends TrackedActivity {      private HoloProgressIndicator profilInfoProgress = null;      TextView titleTextView = null;     TextView senderTextView = null;     TextView dateTextView = null;     WebView bodyWebView = null;      Message messageObject = null;      String messageID = null;      ImageView kapatButton = null;      Context context;      @Override     public void onCreate(Bundle savedInstanceState)     {         super.onCreate(savedInstanceState);         setContentView(R.layout.mesajdetaylari);          context = this;          kapatButton = (ImageView) findViewById(R.id.kapat_button);         /* kapat button onclick listener. */         // =================================================================================================================         kapatButton.setOnClickListener(new View.OnClickListener() {             public void onClick(View view)             {                 // Set vibration on touch.                 KnetGenericClass.vibratePhone(context);                  finish();             }          });         // =================================================================================================================         //Progress bar.         profilInfoProgress = (HoloProgressIndicator) findViewById(R.id.profil_info_progress);          Bundle extras = getIntent().getExtras();         if(extras != null)         {             messageID = extras.getString("messageID");         }          titleTextView = (TextView) findViewById(R.id.title_textview);         senderTextView = (TextView) findViewById(R.id.sender_textview);         dateTextView = (TextView) findViewById(R.id.date_textview);         bodyWebView = (WebView) findViewById(R.id.mesaj_webView);          // Show the ProgressDialog on this thread         profilInfoProgress.start();          // Start a new thread that will download all the data         new MakeItTask().execute();      }      // Async task.     private class MakeItTask extends AsyncTask<String, Void, Object> {         protected Object doInBackground(String... args)         {             Log.i("MyApp", "Background thread starting");              // This is where you would do all the work of downloading your data             // getting message detay             /* connect to web service */             getMessageDetayFromWebService();              return null;         }          protected void onPostExecute(Object result)         {             // Pass the result data back to the main activity             // TakipListeActivity.this.data = result;             try             {                 titleTextView.setText("Başlık: " + messageObject.getTitle());                 senderTextView.setText("Gönderen: " + messageObject.getSender());                 dateTextView.setText("Tarih: " + messageObject.getSentDate().substring(6, 8) + "."                         + messageObject.getSentDate().substring(4, 6) + "."                         + messageObject.getSentDate().substring(0, 4));                  if(!messageObject.getBody().contains("img"))                 {                     bodyWebView.loadDataWithBaseURL(null, messageObject.getBody(), "text/html", "UTF-8", null);                 }              }             catch (Exception e)             {                 Log.e(CONNECTIVITY_SERVICE, "Mesaj Detayi bilgileri basilamadi.");             }              profilInfoProgress.stop();         }     }      /* web service'e baglanti kurulan methodu threadin icerisinde cagiriyoruz. */     public void getMessageDetayFromWebService()     {         // Creating JSON Parser instance         JSONParser jParser = new JSONParser(context);          // getting JSON string from URL         JSONObject jsonObject = jParser.getAuthorizedInfoFromUrlToJSONObject(                 WebServiceInfo.getKnetWebServiceLink()+"/API/Member/GetInboxMessage/" + messageID, MainActivity.getAccessToken());          // if json is null then there is a problem.         if(jsonObject == null)         {             return;         }          try         {             String title = jsonObject.getString("Title");             String id = jsonObject.getString("Id");             String sender = jsonObject.getString("Sender");             String date = jsonObject.getString("SentDate");             String body = jsonObject.getString("Body");              messageObject = new Message(id, sender, body, title, date, true);          }         catch (Exception e)         {             Log.e("BACKGROUND_PROC", e.getMessage());         }      }// @end of getIlanDetayFromWebService.  } 

Edit: Not only these two activities have this problem, all the activities acting same behavior on some phones.

like image 227
OzBoz Avatar asked Feb 21 '13 12:02

OzBoz


2 Answers

Check to see whether Don't keep activities under Settings > System > Developer options > Apps is enabled or not.

like image 158
Joe Avatar answered Nov 10 '22 18:11

Joe


The Activity documentation (http://developer.android.com/reference/android/app/Activity.html) says the following about the lifecycle of a background activity:

A background activity (an activity that is not visible to the user and has been paused) is no longer critical, so the system may safely kill its process to reclaim memory for other foreground or visible processes. If its process needs to be killed, when the user navigates back to the activity (making it visible on the screen again), its onCreate(Bundle) method will be called with the savedInstanceState it had previously supplied in onSaveInstanceState(Bundle) so that it can restart itself in the same state as the user last left it.

In other words, ActivityA may or may not be destroyed by the operating system while ActivityB is active, so this situation has to be handled in the code. If ActivityA has been destroyed, onCreate(Bundle) will be called, when the user presses the back button in ActivityB.

like image 35
Mads Frandsen Avatar answered Nov 10 '22 19:11

Mads Frandsen