I've failed to show lists of a RecyclerView - android

I am building my first android app using WiFi Direct to transfer
text, image, and media files to peers.I am using a RecyclerView
and a Fragment. I hope to show peers's list on a framelayout
(a simple textview) and then click the views to form a group
to send files. I am stuck at the first stage of making the list shown
on the parent's view. I would appreciate your help on what I did wrong.
I am just a beginner. Any advice or resources would be welcome even besides the pending problem. The followings are three classes and two xmls I've made fumbling around many sources and Android Developer's guide.
public class MainActivity extends FragmentActivity {
public static String TAG="test";
IntentFilter mIntentFilter;
WifiP2pManager.Channel mChannel;
WifiP2pManager mManager;
BroadcastReceiver mReceiver;
public static boolean setIsWifiP2pEnable;
Button open, connect, file, image, media;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
open = (Button) findViewById(R.id.wifi_open);
connect = (Button) findViewById(R.id.connect);
file = (Button) findViewById(R.id.file);
image = (Button) findViewById(R.id.gallery);
media = (Button) findViewById(R.id.media);
open.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
startActivity(intent);
}
});
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mChannel = mManager.initialize(this, getMainLooper(), null);
mReceiver = new WiFiDirectBroadcastReceiver(mManager, mChannel, this);
checkWiFi();
connect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
Log.d (TAG, "search start");
}
#Override
public void onFailure(int reasonCode) {
Log.d (TAG, "search failed");
}
});
}
});
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragment_container);
if (fragment == null) {
fragment = new DeviceFragment();
fm.beginTransaction()
.add(R.id.fragment_container, fragment)
.commit();
Log.d (TAG, "fragment_activated");
}
}
#Override
protected void onResume () {
super.onResume();
mReceiver = new WiFiDirectBroadcastReceiver(mManager, mChannel, this);
registerReceiver(mReceiver, mIntentFilter);
}
#Override
protected void onPause () {
super.onPause();
unregisterReceiver(mReceiver);
}
public void checkWiFi(){
if(setIsWifiP2pEnable==true){
Toast.makeText(MainActivity.this, "WiFi Direct connected", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "Open WiFi Direct in settings", Toast.LENGTH_LONG).show();
}
}
}
public class WiFiDirectBroadcastReceiver extends BroadcastReceiver {
public static WifiP2pManager mManager;
public static WifiP2pManager.Channel mChannel;
private MainActivity mActivity;
public static List<WifiP2pDevice> peers = new ArrayList<>();
public WiFiDirectBroadcastReceiver(WifiP2pManager manager, WifiP2pManager.Channel channel,
MainActivity activity) {
super();
this.mManager = manager;
this.mChannel = channel;
this.mActivity = activity;
}
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
int state = intent.getIntExtra(mManager.EXTRA_WIFI_STATE, -1);
if (state==mManager.WIFI_P2P_STATE_ENABLED){
Log.d (MainActivity.TAG, "WiFi_enabled");
mActivity.setIsWifiP2pEnable=true;
mActivity.checkWiFi();
} else {
Log.d (MainActivity.TAG, "WiFi_failed");
mActivity.setIsWifiP2pEnable=false;
mActivity.checkWiFi();
}
} else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
if (mManager != null) mManager.requestPeers(mChannel, new WifiP2pManager.PeerListListener() {
#Override
public void onPeersAvailable(WifiP2pDeviceList peerList) {
Log.d (MainActivity.TAG, "peers_found");
peers.clear();
peers.addAll(peerList.getDeviceList());
if(peers.size() ==0){
Log.d (MainActivity.TAG, "No_Peers_found");
return;
}
}
});
} else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
// Respond to new connection or disconnections
if (mManager==null) {
return;
}
NetworkInfo networkInfo = (NetworkInfo) intent
.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);
if (networkInfo.isConnected()){
mManager.requestConnectionInfo(mChannel, new WifiP2pManager.ConnectionInfoListener() {
#Override
public void onConnectionInfoAvailable(WifiP2pInfo info) {
InetAddress groupOwnerAddress = info.groupOwnerAddress;
String s=groupOwnerAddress.getHostAddress();
if (info.groupFormed && info.isGroupOwner) {
} else if (info.groupFormed) {
}
}
});
}
} else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
}
}
}
public class DeviceFragment extends Fragment {
private RecyclerView mDeviceRecyclerView;
private DeviceAdapter mAdapter;
private List<WifiP2pDevice> mDevices;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_device_list, container,false);
mDeviceRecyclerView = (RecyclerView) view
.findViewById(R.id.device_recycler_view);
mDeviceRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
updateUI();
return view;
}
private void updateUI(){
mDevices = WiFiDirectBroadcastReceiver.peers;
mAdapter = new DeviceAdapter(mDevices);
mDeviceRecyclerView.setAdapter(mAdapter);
Log.d (MainActivity.TAG, "adapter_connected");
}
private class DeviceHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView mTitleTextView;
public DeviceHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
mTitleTextView = (TextView) itemView;
Log.d(MainActivity.TAG, "Item_Click_try");
}
#Override
public void onClick(View v) {
Toast.makeText(getActivity(),"Click Succeeded", Toast.LENGTH_LONG).show();
int i = (int) v.getTag();
WifiP2pDevice device = mDevices.get(i);
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = device.deviceAddress;
config.wps.setup = WpsInfo.PBC;
WiFiDirectBroadcastReceiver.mManager.connect(WiFiDirectBroadcastReceiver.mChannel, config, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
Log.d (MainActivity.TAG, "Click_Success!!");
}
#Override
public void onFailure(int reason) {
Log.d (MainActivity.TAG, "Click_Failed!!");
}
});
}
}
private class DeviceAdapter extends RecyclerView.Adapter<DeviceHolder>{
private List<WifiP2pDevice> Devices;
public DeviceAdapter(List<WifiP2pDevice> devices){
Devices=devices;
Log.d (MainActivity.TAG, "device_list");
}
#Override
public DeviceHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
View view=layoutInflater
.inflate(android.R.layout.simple_list_item_1, parent, false);
Log.d (MainActivity.TAG, "simple_list");
return new DeviceHolder(view);
}
#Override
public void onBindViewHolder(DeviceHolder holder, int position) {
WifiP2pDevice device = Devices.get(position);
holder.mTitleTextView.setTag(position);
holder.mTitleTextView.setText(device.deviceName);
Log.d (MainActivity.TAG, "Device_bound");
}
#Override
public int getItemCount() {
return mDevices.size();
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="wrap_content"
tools:context="com.moon.android.wifidirectproject_moon.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/wifi_open"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="WiFi_Direct" />
<Button
android:id="#+id/connect"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Connect" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/file"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="file" />
<Button
android:id="#+id/gallery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="gallery" />
<Button
android:id="#+id/media"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="media" />
</LinearLayout>
The Other Layout:
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/device_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

I think I have made some (not complete) progress on my question. I suspected that the ArrayList information is not properly delivered to my fragment class. So I wrote the following code in OnCreate method in MainActivity:
DeviceFragment df = new DeviceFragment();
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("bundle",WiFiDirectBroadcastReceiver.peers);
df.setArguments(bundle);
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragment_container);
if (fragment == null) {
fragment = df;
fm.beginTransaction()
.add(R.id.fragment_container, fragment)
.commit();
Log.d (TAG, "fragment_activated");
}
I put the following code in my fragment class:
mDevices = getArguments().getParcelableArrayList("bundle");
and revised Adapter class as follows:
public DeviceAdapter(List<WifiP2pDevice> devices){
Devices=devices;
notifyDataSetChanged();
Log.d (MainActivity.TAG, "device_list");
}
It worked. But I met with one more problem. The textviews on screen are refreshed only when I turned off and on again (not powered on/off). So, I want to make a "refresh button" in MainActivity so that I can refresh the list like when turning on/off. But I have no idea how I can refresh the RecyclerView's fragment in MainActivity. I think I should work on fragmentManager and transaction. Could anybody help me deal with this issue?

Related

how to synchronise Between class controller contains AsyncTask and fragment

I am very very tired
I can't change visibility or an object in the fragment from the class controller
exmple addIteamsAutomatic.progressBar.setVisibility(View.GONE); return nullpointer
FragmentAddIteamsAutomatic :
public class FragmentAddIteamsAutomatic extends Fragment {
private EditText ssid, paswd;
public TextView afichage;
public Button parainage;
public Button validation;
public ProgressBar progressBar ;
public LinearLayout linearLayoutParm;
public static String sSSID,pWD;
private ControllerAddIteam controleAdd=null;
public FragmentAddIteamsAutomatic()
{
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.add_iteams_automatic, container, false);
controleAdd.getInstance(getActivity());
progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
ssid = (EditText) view.findViewById(R.id.ssid);
paswd = (EditText) view.findViewById(R.id.password);
parainage = (Button) view.findViewById(R.id.btnParainage);
validation = (Button) view.findViewById(R.id.btnValid);
afichage = (TextView) view.findViewById(R.id.affichage);
linearLayoutParm = (LinearLayout) view.findViewById(R.id.linearLayParam);
progressBar.setVisibility(View.GONE);
afichage.setVisibility(View.GONE);
validation.setVisibility(View.GONE);
parainage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sSSID = ssid.getText().toString();
pWD = paswd.getText().toString();
if (sSSID.equals(""))
Toast.makeText(getActivity(), "Vous Dever Remplir Tous les champs", Toast.LENGTH_LONG).show();
else
parainer();
}
});
validation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
controleAdd.addSwitchToBase();
Intent intent = new Intent(getActivity(), MainActivity.class);
startActivity(intent);
ControllerAddIteam.accesDistant.send("getIteams", new JSONArray());
// finish();
}
});
return view;
}
private void parainer(){
controleAdd.getInstanceExecuteHandle();
}
}
ControllerAddIteam :
public class ControllerAddIteam {
private static ControllerAddIteam instanceAdd = null;
private static Context context;
private static WifiUtils wifiUtils;
public static String SSID = null;
public static AccesDistant accesDistant;
public static Handler mHandler;
public static final ControllerAddIteam getInstance(Context context) {
if (context != null)
ControllerAddIteam.context = context;
if (ControllerAddIteam.instanceAdd == null) {
ControllerAddIteam.instanceAdd = new ControllerAddIteam();
accesDistant = new AccesDistant();
}
return ControllerAddIteam.instanceAdd;
}
public static void getInstanceExecuteHandle() {
new ParainageHandle().execute();
}
static class ParainageHandle extends AsyncTask<String, String, String> {
FragmentAddIteamsAutomatic addIteamsAutomatic=new FragmentAddIteamsAutomatic();
#Override
protected void onPreExecute() {
super.onPreExecute();
addIteamsAutomatic.progressBar.setVisibility(View.GONE);
addIteamsAutomatic.afichage.setVisibility(View.GONE);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
addIteamsAutomatic.progressBar.setVisibility(View.GONE);
if(s.equals("valid"))
{
addIteamsAutomatic.linearLayoutParm.setVisibility(View.GONE);
addIteamsAutomatic.validation.setVisibility(View.VISIBLE);
addIteamsAutomatic.parainage.setVisibility(View.GONE);
}
else if(s.equals("notvalid"))
{
addIteamsAutomatic.parainage.setVisibility(View.VISIBLE);
}
}
#Override
protected void onProgressUpdate(String... values) {
addIteamsAutomatic.afichage.setVisibility(View.VISIBLE);
addIteamsAutomatic.progressBar.setVisibility(View.VISIBLE);
if (values[0].equals("actwifi")) {
if (values[1].equals("true"))
addIteamsAutomatic.afichage.setText("WIFI DEJA ACTIVEE");
else
addIteamsAutomatic.afichage.setText("ACTIVATION WIFI EN COURS...");
} else if (values[0].equals("scan"))
addIteamsAutomatic.afichage.setText("START SCAN FOR Iteams STiTo ... Please Wait");
else if (values[0].equals("find"))
addIteamsAutomatic.afichage.setText("STiTo : "+getTypeFromSsid(SSID)+" DETECTEE : "+SSID);
else if (values[0].equals("connect"))
addIteamsAutomatic.afichage.setText("CONNECTION WITH " + SSID + "En cours ...");
else if (values[0].equals("connectOk"))
addIteamsAutomatic.afichage.setText("CONNECTION WITH " + SSID + "ETABLISHED");
else if (values[0].equals("connectKo"))
addIteamsAutomatic.afichage.setText("PROBLEM OF CONNECTION WITH " + SSID);
else if (values[0].equals("config")) {
addIteamsAutomatic.afichage.setText("SENDING OF CONFIGURATION TO: "+getTypeFromSsid(SSID)+"AND SAVING DATA");
accesDistant.sendConfig(addIteamsAutomatic.sSSID,addIteamsAutomatic.pWD);
....
You declare fragment in AsyncTask and doesn't call replace or add, it mean this fragment never show and it not call onCreateView
FragmentAddIteamsAutomatic addIteamsAutomatic=new FragmentAddIteamsAutomatic();
Maybe you should pass reference addIteamsAutomatic to class ControllerAddIteam. but please make sure it will be call on MainThread, because AsyncTask has method doInBackground in background Thread. best practice is wrap fragment reference by WeakReference
public class AddIteamActivity extends AppCompatActivity {
ViewPager pager;
TabLayout tab;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_iteam);
pager = findViewById(R.id.pager);
tab = findViewById(R.id.tab);
AddIteamsAdapter viewPagerAdapter = new AddIteamsAdapter(getSupportFragmentManager());
pager.setAdapter(viewPagerAdapter);
tab.setupWithViewPager(pager);
}
}

Android check box tik mark disappear randomly when moving from one fragment to another using android-material-stepper

Instead of getting checkbox like this(i am getting it only few times randomly when moving from on fragment to another).
I am getting like this(checkbox is still true but only tik mark is missing randomly)
I am using onSaveInstanceState and onViewStateRestored. The problem is the checkbox tik mark only disappears and comes back few times but the state of checkbox is still selected i see blue color around all the selected check boxes that selected color doesn't go away only the tik mark goes away and comes back randomly.
Layout:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<CheckBox
android:id="#+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:drawableLeft="#drawable/ic_tv"
android:text="TV"
android:theme="#style/CheckBoxTheme"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="Tv" />
</android.support.constraint.ConstraintLayout>
</ScrollView>
My Fragment:
public class StepFragmentTwo extends Fragment implements BlockingStep {
private static final String CLICKS_KEY = "clicks";
private static final String TAG = "ADERVERTISMENT";
private int i = 0;
FragmentManager fm = getFragmentManager();
CheckBox c;
Boolean tv = false ;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(getLayoutResId(), container, false);
c = (CheckBox)v.findViewById(R.id.checkBox);
//initialize your UI
return v;
}
protected int getLayoutResId() {
return getArguments().getInt(String.valueOf(R.layout.step2));
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putInt(CLICKS_KEY, i);
super.onSaveInstanceState(outState);
if(outState!=null) {
outState.putBoolean("c", c.isChecked());
}
}
#Override
public void onViewStateRestored(#Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
if(savedInstanceState!=null) {
tv = savedInstanceState.getBoolean("c");
}
}
#Override
public void onResume() {
super.onResume();
c.setChecked(tv);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
public void onNextClicked(final StepperLayout.OnNextClickedCallback callback) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (c.isChecked()) {
tv = true;
}
SharedPreferences shared = getActivity().getSharedPreferences("Mypref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = shared.edit();
editor.putBoolean("tv", tv);
editor.apply(); // This line is IMPORTANT !!!
callback.goToNextStep();
}
}, 200L);
}
#Override
#UiThread
public void onCompleteClicked(final StepperLayout.OnCompleteClickedCallback callback) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
callback.complete();
}
}, 2000L);
}
public static StepFragmentTwo newInstance(#LayoutRes int layoutResId) {
Bundle args = new Bundle();
args.putInt(String.valueOf(R.layout.step2), layoutResId);
StepFragmentTwo fragment = new StepFragmentTwo();
fragment.setArguments(args);
return fragment;
}
#Override
public VerificationError verifyStep() {
//return null if the user can go to the next step, create a new VerificationError instance otherwise
return null;
}
#Override
public void onSelected() {
//update UI when selected
}
#Override
public void onError(#NonNull VerificationError error) {
//handle error inside of the fragment, e.g. show error on EditText
}
public void onBackClicked(StepperLayout.OnBackClickedCallback callback) {
//Toast.makeText(this.getContext(), "Your custom back action. Here you should cancel currently running operations", Toast.LENGTH_SHORT).show();
callback.goToPrevStep();
}
}
In short you can do,
#Override
public void onResume() {
super.onResume();
SharedPreferences shared = getActivity().getSharedPreferences("Mypref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = shared.edit();
tv = editor.getBoolean("tv", tv);
c.setChecked(tv);
}

How to make 500 Questions Quiz in android with single activity?

I am creating an android app, where I'll be asking for multiple types of questions using RadioButtons. I don't want to make multiple Activities for these questions. Can anyone please tell me how to do that with a short example, of at least two questions?
You can use multiples fragments... or call the activity itself multiple times...
I did an app like yours and i choose the first method!
This is some fragment of a project that i wrote, and the activity that manipulate it, you will have to change it according to your needs.
Activity
public class CollectActivity extends FragmentActivity {
MyPageAdapter pageAdapter;
NonSwipeableViewPager pager;
SpringIndicator springIndicator;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_collect);
List<Fragment> fragments = getFragments();
pager = (NonSwipeableViewPager) findViewById(R.id.view_pager);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
PagerModelManager manager = new PagerModelManager();
manager.addCommonFragment(fragments, getTitles());
ModelPagerAdapter adapter = new ModelPagerAdapter(getSupportFragmentManager(), manager);
pager.setAdapter(adapter);
springIndicator = (SpringIndicator) findViewById(R.id.indicator);
springIndicator.setViewPager(pager);
springIndicator.setOnTabClickListener(new TabClickListener() {
#Override
public boolean onTabClick(int position) {
return false;
}
});
}
private List<Fragment> getFragments() {
List<Fragment> fList = new ArrayList<Fragment>();
fList.add(CollectFragment.newInstance("Fragment 1"));
fList.add(CollectFragment.newInstance("Fragment 2"));
fList.add(CollectFragment.newInstance("Fragment 3"));
//add your fragments with a loop
return fList;
}
private List<String> getTitles() {
return Lists.newArrayList("1", "2", "3");
}
public void swipeFragment() {
pager.setCurrentItem(pager.getCurrentItem() + 1);
}
public int getFragment() {
return pager.getCurrentItem();
}
}
Fragment
public class CollectFragment extends Fragment {
private Button openButton;
private Button confirmationCloseButton;
private Button yesRenew;
private Button noRenew;
private BroadcastReceiver udpMessages;
public static final String EXTRA_MESSAGE = "EXTRA_MESSAGE";
public static final CollectFragment newInstance(String message) {
CollectFragment f = new CollectFragment();
Bundle bdl = new Bundle(1);
bdl.putString(EXTRA_MESSAGE, message);
f.setArguments(bdl);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String message = getArguments().getString(EXTRA_MESSAGE);
View v = null;
if (message.compareTo("Fragment 1") == 0) {
v = inflater.inflate(R.layout.fragment_collect_open, container, false);
openButton = (Button) v.findViewById(R.id.open_button);
openButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i2 = new Intent();
i2.setComponent(new ComponentName("qira.com.locker", "qira.com.locker.Service.MessageService"));
i2.putExtra("Message", "CONFIRM_LOCKER_1_CLOSED");
getContext().startService(i2);
}
});
}
if (message.compareTo("Fragment 2") == 0) {
v = inflater.inflate(R.layout.fragment_collect_close, container, false);
confirmationCloseButton = (Button) v.findViewById(R.id.confirmation_close_button);
confirmationCloseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i2 = new Intent();
i2.setComponent(new ComponentName("qira.com.locker", "qira.com.locker.Service.MessageService"));
i2.putExtra("Message", "OPEN_LOCKER_1");
getContext().startService(i2);
}
});
}
if (message.compareTo("Fragment 3") == 0) {
v = inflater.inflate(R.layout.fragment_collect_renew, container, false);
yesRenew = (Button) v.findViewById(R.id.yes_button);
noRenew = (Button) v.findViewById(R.id.no_button);
yesRenew.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
((CollectActivity) getActivity()).swipeFragment();
}
});
noRenew.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getContext(), ReserveActivity.class);
startActivity(i);
}
});
}
return v;
}
#Override
public void onResume() {
super.onResume();
udpMessages = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction() != null && intent.getAction().equals("UDP.MESSAGES.COLLECT")) {
if (intent.getExtras().getString("Type").compareTo("OPEN_LOCKER_1-LOCKER_OPENED") == 0) {
if (((CollectActivity) getActivity()).getFragment() != 0) { // onCreateView called twice, dont know why... workaround to solve this problem
((CollectActivity) getActivity()).swipeFragment();
}
}
if (intent.getExtras().getString("Type").compareTo("CONFIRM_LOCKER_1_CLOSED-TRUE") == 0) {
if (((CollectActivity) getActivity()).getFragment() != 1) { // onCreateView called twice, dont know why... workaround to solve this problem
((CollectActivity) getActivity()).swipeFragment();
}
}
}
}
};
getContext().registerReceiver(udpMessages, new IntentFilter("UDP.MESSAGES.COLLECT"));
}
#Override
public void onPause() {
super.onPause();
getContext().unregisterReceiver(udpMessages);
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
}

Error saving image from camera(cwac camera)

I am trying to implement the cwac camera library for taking picture and storing them. When i tested the code on htc desire hd there were few complications. This is the screenshot of camera preview.
And when I take picture it shows image preview as.
The codes I have for this are as follows.
This is Activity for implementing camera preview fragment.
public class Camera extends ActionBarActivity implements CameraPreviewFragment.Contract {
private static final String STATE_SINGLE_SHOT="single_shot";
private static final String STATE_LOCK_TO_LANDSCAPE=
"lock_to_landscape";
private static final int CONTENT_REQUEST=1337;
private CameraPreviewFragment std=null;
private CameraPreviewFragment ffc=null;
private CameraPreviewFragment current=null;
private boolean hasTwoCameras=(android.hardware.Camera.getNumberOfCameras() > 1);
private boolean singleShot=false;
private boolean isLockedToLandscape=false;
private Toolbar mToolbar;
private void setToolBar(int toolbarId){
mToolbar = (Toolbar) findViewById(toolbarId);
if (mToolbar != null) {
setSupportActionBar(mToolbar);
getSupportActionBar().setLogo(R.drawable.ic_launcher);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
setToolBar(R.id.toolbar);
if (savedInstanceState == null) {
CameraPreviewFragment frag = new CameraPreviewFragment();
frag = CameraPreviewFragment.newInstance(false);
getFragmentManager().beginTransaction()
.add(R.id.container, frag)
.commit();
}
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
setSingleShotMode(savedInstanceState.getBoolean(STATE_SINGLE_SHOT));
isLockedToLandscape=
savedInstanceState.getBoolean(STATE_LOCK_TO_LANDSCAPE);
if (current != null) {
current.lockToLandscape(isLockedToLandscape);
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean(STATE_SINGLE_SHOT, isSingleShotMode());
outState.putBoolean(STATE_LOCK_TO_LANDSCAPE, isLockedToLandscape);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_menu_camera, 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);
}
#Override
public boolean isSingleShotMode() {
return true;
}
#Override
public void setSingleShotMode(boolean mode) {
}
}
And here is my camera preview fragment.(to load camera and has button for taking image)
public class CameraPreviewFragment extends CameraFragment implements SeekBar.OnSeekBarChangeListener, View.OnClickListener{
private static final String DEBUG = CameraPreviewFragment.class.getSimpleName();
private static final String KEY_USE_FFC=
"com.commonsware.cwac.camera.demo.USE_FFC";
private MenuItem singleShotItem=null;
private boolean singleShotProcessing=false;
private static final int FLASH_ALWAYS_OFF = 0;
private static final int FLASH_ALWAYS_ON = 1;
private static final int FLASH_AUTO_MODE = 2;
private SeekBar zoom=null;
private View mCameraView;
private ImageButton mTakePicture;
private Button mFlashButton;
private Button mGridButton;
private ImageView mGridLines;
private long lastFaceToast=0L;
private int flashState = 2;
String flashMode=null, autoFlashMode=null, noFlashMode= null;
private DemoCameraHost cameraHost;
static CameraPreviewFragment newInstance(boolean useFFC) {
CameraPreviewFragment f=new CameraPreviewFragment();
Bundle args=new Bundle();
args.putBoolean(KEY_USE_FFC, useFFC);
f.setArguments(args);
return(f);
}
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
setHasOptionsMenu(true);
cameraHost = new DemoCameraHost(getActivity());
SimpleCameraHost.Builder builder=
new SimpleCameraHost.Builder(cameraHost);
setHost(builder.useFullBleedPreview(true).build());
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
mCameraView=
super.onCreateView(inflater, container, savedInstanceState);
View results=inflater.inflate(R.layout.fragment_camera, container, false);
mCameraView.setOnClickListener(this);
mGridLines = (ImageView) results.findViewById(R.id.ivGridLines);
mTakePicture = (ImageButton) results.findViewById(R.id.ibCaptureButton);
mTakePicture.setOnClickListener(this);
mFlashButton = (Button) results.findViewById(R.id.bFlash);
mFlashButton.setOnClickListener(this);
mGridButton = (Button) results.findViewById(R.id.bGrid);
mGridButton.setOnClickListener(this);
((ViewGroup) results.findViewById(R.id.camera)).addView(mCameraView);
zoom=(SeekBar)results.findViewById(R.id.sbZoomControl);
zoom.setKeepScreenOn(true);
return(results);
}
#Override
public void onPause() {
super.onPause();
getActivity().invalidateOptionsMenu();
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_camera, menu);
singleShotItem=menu.findItem(R.id.single_shot);
singleShotItem.setChecked(getContract().isSingleShotMode());
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.single_shot:
item.setChecked(!item.isChecked());
getContract().setSingleShotMode(item.isChecked());
return(true);
case R.id.show_zoom:
item.setChecked(!item.isChecked());
zoom.setVisibility(item.isChecked() ? View.VISIBLE : View.GONE);
return(true);
}
return(super.onOptionsItemSelected(item));
}
boolean isSingleShotProcessing() {
return(singleShotProcessing);
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if (fromUser) {
zoom.setEnabled(false);
zoomTo(zoom.getProgress()).onComplete(new Runnable() {
#Override
public void run() {
zoom.setEnabled(true);
}
}).go();
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// ignore
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// ignore
}
Contract getContract() {
return((Contract)getActivity());
}
void takeSimplePicture() {
if (singleShotItem!=null && singleShotItem.isChecked()) {
singleShotProcessing=true;
mTakePicture.setEnabled(false);
}
PictureTransaction xact=new PictureTransaction(getHost());
xact.flashMode(getFlashMode());
takePicture(xact);
}
#Override
public void onClick(View v) {
if(v == mTakePicture){
takeSimplePicture();
}
if(v == mFlashButton){
if(flashState == FLASH_ALWAYS_OFF){
//flash to be always on
flashState = FLASH_ALWAYS_ON;
setFlashMode(flashMode);
Toast.makeText(getActivity(), "Flash! on", Toast.LENGTH_SHORT).show();
}else if(flashState == FLASH_ALWAYS_ON){
flashState = FLASH_AUTO_MODE;
setFlashMode(autoFlashMode);
Toast.makeText(getActivity(), "Flash! auto", Toast.LENGTH_SHORT).show();
}else if(flashState == FLASH_AUTO_MODE){
flashState = FLASH_ALWAYS_OFF;
setFlashMode(noFlashMode);
Toast.makeText(getActivity(), "Flash! off", Toast.LENGTH_SHORT).show();
}
}
if(v == mCameraView){
Log.i(DEBUG,"OnClick autofocus");
autoFocus();
}
if(v == mGridButton){
if(mGridLines.getVisibility() == View.VISIBLE){
mGridLines.setVisibility(View.GONE);
}else if(mGridLines.getVisibility() == View.GONE){
mGridLines.setVisibility(View.VISIBLE);
}
}
}
interface Contract {
boolean isSingleShotMode();
void setSingleShotMode(boolean mode);
}
class DemoCameraHost extends SimpleCameraHost implements
android.hardware.Camera.FaceDetectionListener {
boolean supportsFaces=false;
public DemoCameraHost(Context _ctxt) {
super(_ctxt);
}
#Override
protected File getPhotoDirectory() {
return CameraUtility.getOutputDirectory(CameraUtility.DIRECTORY_TYPE_CAMERA);
}
#Override
public boolean useFrontFacingCamera() {
if (getArguments() == null) {
return(false);
}
return(getArguments().getBoolean(KEY_USE_FFC));
}
#Override
public boolean useSingleShotMode() {
if (singleShotItem == null) {
return(false);
}
return(singleShotItem.isChecked());
}
#Override
public Camera.Size getPictureSize(PictureTransaction xact, Camera.Parameters parameters) {
return super.getPictureSize(xact, parameters);
}
#Override
public void saveImage(PictureTransaction xact, byte[] image) {
if (useSingleShotMode()) {
singleShotProcessing=false;
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
mTakePicture.setEnabled(true);
}
});
ImagePreviewActivity.imageToShow=image;
startActivity(new Intent(getActivity(), ImagePreviewActivity.class));
}
else {
String path = getPhotoFilename();
super.saveImage(xact, image);
}
}
#Override
public void autoFocusAvailable() {
if (supportsFaces)
startFaceDetection();
}
#Override
public void autoFocusUnavailable() {
stopFaceDetection();
}
#Override
public void onCameraFail(CameraHost.FailureReason reason) {
super.onCameraFail(reason);
Toast.makeText(getActivity(),
"Sorry, but you cannot use the camera now!",
Toast.LENGTH_LONG).show();
}
#Override
public android.hardware.Camera.Parameters adjustPreviewParameters(android.hardware.Camera.Parameters parameters) {
autoFlashMode =
CameraUtils.findBestFlashModeMatch(parameters,
android.hardware.Camera.Parameters.FLASH_MODE_RED_EYE,
android.hardware.Camera.Parameters.FLASH_MODE_AUTO,
android.hardware.Camera.Parameters.FLASH_MODE_ON);
flashMode = CameraUtils.findBestFlashModeMatch(parameters,
android.hardware.Camera.Parameters.FLASH_MODE_ON);
noFlashMode = CameraUtils.findBestFlashModeMatch(parameters,
Camera.Parameters.FLASH_MODE_OFF);
if (doesZoomReallyWork() && parameters.getMaxZoom() > 0) {
zoom.setMax(parameters.getMaxZoom());
zoom.setOnSeekBarChangeListener(CameraPreviewFragment.this);
}
else {
zoom.setEnabled(false);
}
if (parameters.getMaxNumDetectedFaces() > 0) {
supportsFaces=true;
}
else {
Toast.makeText(getActivity(),
"Face detection not available for this camera",
Toast.LENGTH_LONG).show();
}
return(super.adjustPreviewParameters(parameters));
}
#Override
public void onFaceDetection(android.hardware.Camera.Face[] faces, android.hardware.Camera camera) {
if (faces.length > 0) {
long now= SystemClock.elapsedRealtime();
if (now > lastFaceToast + 10000) {
Toast.makeText(getActivity(), "I see your face!",
Toast.LENGTH_LONG).show();
lastFaceToast=now;
}
}
}
#Override
protected File getPhotoPath() {
return super.getPhotoPath();
}
#Override
#TargetApi(16)
public void onAutoFocus(boolean success, android.hardware.Camera camera) {
super.onAutoFocus(success, camera);
mTakePicture.setEnabled(true);
}
}
}
This one is for viewing the image taken. ImagePreviewActivity
public class ImagePreviewActivity extends ActionBarActivity {
static byte[] imageToShow = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (imageToShow == null) {
Toast.makeText(this, R.string.no_image, Toast.LENGTH_LONG).show();
finish();
} else {
ImageView iv = new ImageView(this);
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inPurgeable = true;
opts.inInputShareable = true;
opts.inMutable = false;
opts.inSampleSize = 2;
iv.setScaleType(ImageView.ScaleType.FIT_CENTER);
iv.setImageBitmap(BitmapFactory.decodeByteArray(imageToShow,
0,
imageToShow.length,
opts));
imageToShow = null;
iv.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
setContentView(iv);
}
}
}
And as for the xml layouts I have:
for CameraPrevirewFragment
<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"
tools:context="com.example.ballard.CWACCamera.Camera$PlaceholderFragment"
android:orientation="vertical"
android:weightSum="4">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="3">
<FrameLayout
android:id="#+id/camera"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#android:drawable/gallery_thumb"
android:id="#+id/ivGridLines"
android:visibility="gone"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1">
<SeekBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/sbZoomControl"
android:layout_alignParentTop="true"
android:background="#null"
android:layout_toLeftOf="#+id/bFlash"
android:layout_alignBottom="#+id/bFlash"
android:layout_toRightOf="#+id/bGrid"
android:layout_toEndOf="#+id/bGrid" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ibCaptureButton"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:src="#android:drawable/ic_menu_camera"
android:background="#null"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Flash"
android:id="#+id/bFlash"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Grid"
android:id="#+id/bGrid"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
</LinearLayout>
and for the camera activity I have
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="#+id/rlHomeLayout"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context="com.example.ballard.Login.Home" tools:ignore="MergeRootFrame"
>
<include
android:id="#+id/toolbar"
layout="#layout/toolbar"/>
<FrameLayout`enter code here`
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/toolbar">
</FrameLayout>
</RelativeLayout>
I am using v7 toolbar as the actionbar and is as follows(toolbar.xml)
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimaryDark"/>
I tried the demo of the library and is working fine on the same mobile set. Also there seems to be no problem while I was testing it on Nexus 5. I am trying this library for the first time and have no clue for solving this

IllegalStateException: Can not perform this action after onSaveInstanceState - after screen rotating

I'm also getting it in a precise context and the solution given here (IllegalStateException: Can not perform this action after onSaveInstanceState with ViewPager) don't work.
Here is the code: Should be a working code for test; I hope.
MainActivity.java
public class MainActivity extends FragmentActivity {
final static int INIT_NETWORK_DONE = 1;
final static int EXIT_APPLICATION = -1;
private Site site = new Site(this);
private WifiManager wifi = null;
Handler mHandler = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
site.setUrls();
if (savedInstanceState == null) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
fragmentTransaction.replace(R.id.frame_container, new Fragment_init(site)).commit();
}
}
. . .
#Override
public void onSaveInstanceState(Bundle saveInstanceState) {
//super.onSaveInstanceState(saveInstanceState);
}
}
Fragment_init.java
public class Fragment_init extends Fragment {
Fragment fragment = null;
private InitTask mInitTask = null;
// Taille maximale du téléchargement
public final static int MAX_SIZE = 100;
// Identifiant de la boîte de dialogue
public final static int ID_DIALOG = 0;
public final static int DO_INIT_WIFI = 1;
private Site site = null;
public Fragment_init() {
}
public Fragment_init(Site _site) {
site = _site;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_init, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (savedInstanceState == null) {
Animation animation = AnimationUtils.loadAnimation(getActivity().getApplicationContext(), R.animator.welcome_anim);
ImageView logoSite = (ImageView)getActivity().findViewById(R.id.imageAvenArmand);
logoSite.startAnimation(animation);
// Do the init
mInitTask = new InitTask(Fragment_init.this, site, getFragmentManager());
// On l'exécute
mInitTask.execute(0);
}
}
// L'AsyncTask est bien une classe interne statique
static class InitTask extends AsyncTask<Integer, Integer, Integer> {
// Référence faible à l'activité
private Fragment_init mActivity = null;
private Site site = null;
Context context = null;
private FragmentManager fragmentManager = null;
public InitTask (Fragment_init pActivity, Site pSite, FragmentManager _fragmentManager) {
mActivity = pActivity;
context = mActivity.getActivity();
site = pSite;
fragmentManager = _fragmentManager;
}
#Override
protected void onPreExecute () {
}
#Override
protected void onPostExecute (Integer result) {
if(result != 1) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mActivity.getActivity());
alertDialog.setTitle(R.string.label_titleAlertInit);
} else {
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
fragmentTransaction.replace(R.id.frame_container, new Fragment_selectLanguage(site)).commitAllowingStateLoss();
}
}
#Override
protected Integer doInBackground (Integer... arg0) {
URL url = null;
BufferedInputStream buf;
ArrayList<Language> languages = null;
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
}
return 1;
}
#Override
protected void onProgressUpdate (Integer... prog) {
}
#Override
protected void onCancelled () {
}
private int processStream(InputStream inputStream) {
// Création du parser XML
XmlPullParserFactory factory;
int lineNumber = 0;
return (1);
}
}
#Override
public void onSaveInstanceState(Bundle saveInstanceState) {
//super.onSaveInstanceState(saveInstanceState);
}
}
activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:screenOrientation="portrait"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.cabbonline.ndguidelt.MainActivity" >
</FrameLayout>
fragment_init.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/fragmentInit"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.cabbonline.ndguidelt.MainActivity" >
<ImageView
android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dp"
android:src="#drawable/launcher_icon" />
</RelativeLayout>
Anyway, I think that not calling super.onSaveInstanceState() should cause problem on context saving no?
so if you rotate the screen when the image is fading, you should get IllegalStateException on call on commit()
So my workaround is to prevent the screen rotation during this transitional screen. Ok that's ok for me but I doubt it could be an answer for most of you. anyway, it could help.
So I call this in onCreateView() in fragment_init().
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
And I then call this in onCreateView() in the next fragment:
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
:-/
Any other idea?
Use commitAllowingStateLoss() instead of commit()
if (savedInstanceState == null) {
FragmentTransaction fragmentTransaction =getSupportFragmentManager().beginTransaction();
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
fragmentTransaction.replace(R.id.frame_container, new Fragment_init(site)).commitAllowingStateLoss();
}
You should see this blog about on how to avoid that exception: http://www.androiddesignpatterns.com/2013/08/fragment-transaction-commit-state-loss.html
So I solved my problem using the wonderfull message handler implementation explained here:
How to handle Handler messages when activity/fragment is paused
Thx to Akagami which pointed me on the post.
Regards,

Categories

Resources