2

I have 5 tab in viewpager. Default 1st tab is selected.1st tab open the system default camera.then i move from 1st to 2nd and 2nd to 3rd and so on.. But issue is when i back from 3rd, 4th or 5th to 2nd tab it opens the camera but i don't have camera in 2nd tab. it is on 1st tab.why this happen? I don't Understand...

Please help me...

My Code is like below :

TabsPagerAdapterLoginSuccess.java :

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

public class TabsPagerAdapterLoginSuccess extends FragmentPagerAdapter {
    public TabsPagerAdapterLoginSuccess(FragmentManager supportFragmentManager) {
        super(supportFragmentManager);
    }

    @Override
    public Fragment getItem(int position) {

        switch (position) {
            case 0:
                // Top Rated fragment activity
                return new CameraFragment();
            case 1:
                // Games fragment activity
                return new FriendRequestFragment();

            case 2:
                // Movies fragment activity
                return new FriendFragment();

            case 3:
                // Movies fragment activity
                return new SearchFragment();

            case 4:
                return new ProfileFragment();
        }

        return null;
    }

    @Override
    public int getCount() {
        return 5;
    }
}

LoginSuccess.java

import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

public class LoginSuccess extends AppCompatActivity {

    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bottomtabslider);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar1);
        setSupportActionBar(toolbar);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs1);
        tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.cameraicon1));
        tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.friendrequest));
        tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.friend));
        tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.search));
        tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.profileicon));
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

        final ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager1);
        final TabsPagerAdapterLoginSuccess adapterLoginSuccess = new TabsPagerAdapterLoginSuccess(getSupportFragmentManager());
        viewPager.setAdapter(adapterLoginSuccess);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }
}

CameraFragment.java

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

public class CameraFragment extends Fragment {

    public String mycropimg,encodedImage;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.camerafragment, container, false);
        ((AppCompatActivity)getActivity()).getSupportActionBar().show();

        Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        // intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivityForResult(intent, 0);

        return rootView;

    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == getActivity().RESULT_OK) {
            Bitmap bp = (Bitmap) data.getExtras().get("data");
             String partFilename = "image_" + System.currentTimeMillis()+UUID.randomUUID().toString().substring(0,8) + ".jpg";

            storeCameraPhotoInSDCard(bp, partFilename);

            ByteArrayOutputStream stream = new ByteArrayOutputStream();

            bp.compress(Bitmap.CompressFormat.PNG, 50, stream);
            byte[] byte_arr = stream.toByteArray();

            encodedImage = Base64.encodeToString(byte_arr, 0);
            Intent i=new Intent(getActivity(),CameraPostStatus.class);
            i.putExtra("encoded_image",encodedImage);
            i.putExtra("imgfilename",partFilename);

            startActivity(i);
        }
    }


    private void storeCameraPhotoInSDCard(Bitmap bitmap, String currentDate){
        File outputFile = new File(Environment.getExternalStorageDirectory(), "image_" + System.currentTimeMillis()+UUID.randomUUID().toString().substring(0,8) + ".jpg");
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

1 Answers1

3

you need to do this in your code

 final ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager1);
viewPager.setOffscreenPageLimit(5);

what is happening at the moment is by default ViewPager keeps the current page, the previous page and the next page in memory. However in your case since there are 5 tabs, you can keep all 5 tabs in memory. You can do so by setting offScreenPageLimit.

Junaid Hafeez
  • 1,618
  • 1
  • 16
  • 25
  • it solution for 2nd tab. but 1st tab can not open camera when back to 1st tab. – Hiren Gondaliya Jan 27 '17 at 07:57
  • you need to do the open camera code in `onResume` method of your fragment which you might be doing in `onCreate` at the moment or share you Camera Fragment code. – Junaid Hafeez Jan 27 '17 at 07:58
  • @HirenGondaliya, I have checked your code, there are two options, either add a button and fire intent on button click or secondly if you want to open your camera every time you press this tab, you will have to implement an interface and get a manual `onResume` or `onPause` method `callback` as in case of view pager, all the fragments loads at once, and remain in `onResume()` – Junaid Hafeez Jan 27 '17 at 09:46
  • for interface thing, you may post new question if you could't get, these both are good link btw to follow http://stackoverflow.com/questions/17845641/alternative-for-the-onresume-during-fragment-switching, http://stackoverflow.com/questions/6503189/fragments-onresume-from-back-stack. Also accept and vote-up if previous problem resolved :) – Junaid Hafeez Jan 27 '17 at 09:49
  • if possible than give me code as you say for implement an interface. – Hiren Gondaliya Jan 27 '17 at 09:56
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/134165/discussion-between-hiren-gondaliya-and-junaid-hafeez). – Hiren Gondaliya Jan 27 '17 at 09:57
  • I had the same problem, I followed @JunaidHafeez advice and problem was gone. Thank you :) – Junia Montana Aug 10 '18 at 18:06