ZXing 3.6.0 in portrait mode? - android

I use XZing 3.6.0 to scan QR codes within my Android app.
MainActivity.java
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.zxing.Result;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
public class MainActivity extends AppCompatActivity {
Button btnScan;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnScan = (Button) findViewById(R.id.btn_scan);
tv = (TextView) findViewById(R.id.tv);
btnScan.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
IntentIntegrator scanIntegrator = new IntentIntegrator(MainActivity.this);
scanIntegrator.setOrientationLocked(false);
scanIntegrator.initiateScan();
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
String scanContent = scanningResult.getContents();
tv.setText(scanContent);
}
else {
Toast toast = Toast.makeText(getApplicationContext(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
}
AndroidManifest.xml
<activity
android:name=".MainActivity"
android:screenOrientation="portrait"
>
It works... except the camera is shown in landscape mode. How to change that to portrait mode?

Add this to your Manifest File :
<activity
android:name="com.journeyapps.barcodescanner.CaptureActivity"
android:screenOrientation="portrait"
tools:replace="android:screenOrientation"
android:stateNotNeeded="true"/>

try this in XML file :
<com.journeyapps.barcodescanner.CompoundBarcodeView
android:id="#+id/barcode_scanner"
android:layout_width="match_parent"
android:layout_height="0dp"
app:zxing_viewfinder_mask="#ffffff"
android:layout_weight="40"
>
</com.journeyapps.barcodescanner.CompoundBarcodeView>
and here is the fragment code :
public class ScanFragment extends Fragment {
private String toast;
private LinearLayout qrCameraLayout;
IntentIntegrator intentIntegrator;
private CompoundBarcodeView barcodeView;
private TextView tv_qr_print;
public ScanFragment() {
}
public static ScanFragment newInstance(int page, String title, ViewPager viewPager) {
ScanFragment fragmentFirst = new ScanFragment();
Bundle args = new Bundle();
args.putInt("someInt", page);
args.putString("someTitle", title);
fragmentFirst.setArguments(args);
return fragmentFirst;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
displayToast();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
intentIntegrator = new IntentIntegrator(getActivity());
View view = inflater.inflate(R.layout.screen_scanner, container, false);
qrCameraLayout = (LinearLayout) view.findViewById(R.id.ll_qrcamera);
barcodeView = (CompoundBarcodeView) view.findViewById(R.id.barcode_scanner);
tv_qr_print = (TextView) view.findViewById(R.id.tv_qr_print);
barcodeView.decodeContinuous(callback);
/* View view = inflater.inflate(R.layout.fragment_scan, container, false);*/
CustomButton scan = (CustomButton) view.findViewById(R.id.scan_from_fragment);
scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/* scanFromFragment();*/
}
});
return view;
}
private BarcodeCallback callback = new BarcodeCallback() {
#Override
public void barcodeResult(BarcodeResult result) {
if (result.getText() != null) {
barcodeView.setStatusText(result.getText());
tv_qr_print.setText(result.getText());
displayToast();
}
//Do something with code result
}
#Override
public void possibleResultPoints(List<ResultPoint> resultPoints) {
}
};
public void scanFromFragment() {
intentIntegrator.setOrientationLocked(true);
intentIntegrator.forSupportFragment(this).initiateScan();
}
private void displayToast() {
if(getActivity() != null && toast != null) {
Toast.makeText(getActivity(), toast, Toast.LENGTH_LONG).show();
toast = null;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if(result != null) {
if(result.getContents() == null) {
toast = "Cancelled from fragment";
} else {
toast = "Scanned from fragment: " + result.getContents();
}
// At this point we may or may not have a reference to the activity
displayToast();
}
}
#Override
public void onResume() {
barcodeView.resume();
barcodeView.getViewFinder().setVisibility(View.GONE);
super.onResume();
}
#Override
public void onPause() {
barcodeView.pause();
super.onPause();
}
}

Related

My extra data doesn't appear immediately

In my file Reservation.java I have a function that loads LieuActivity.
So this is the function
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class Reservation extends AppCompatActivity implements View.OnClickListener {
private Button end,deb,lieu,type,cherch;
private TextView type_v ;
private ImageView car;
private View division;
private ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reservation);
end = (Button)findViewById( R.id.btn_fin );
end.setOnClickListener( this);
deb= (Button)findViewById( R.id.deb_btn);
deb.setOnClickListener( this );
lieu = (Button)findViewById( R.id.btn_local);
lieu.setOnClickListener( this );
type = (Button)findViewById( R.id.btn_type);
type.setOnClickListener( this );
cherch= (Button)findViewById( R.id.btn_cherch);
cherch.setOnClickListener( this );
division= (View)findViewById( R.id.div3);
type_v= (TextView)findViewById( R.id.type);
car= (ImageView) findViewById( R.id.pic_car);
list=(ListView)findViewById(R.id.fin_list);
ArrayAdapter<String> mAdapter= new ArrayAdapter<String>(Reservation.this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.values));
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 3 )
{
Intent i = new Intent(view.getContext(),Deb_FinActivity.class);
startActivityForResult(i,3);
}
}
});
list.setAdapter(mAdapter);
}
#Override
public void onClick(View view) {
switch(view.getId())
{
case R.id.deb_btn:
loadDebActivity();
break;
case R.id.btn_fin:
loadFin();
break;
case R.id.btn_local:
loadLieuActivity();
break;
case R.id.btn_type:
loadTypeActivity();
break;
case R.id.btn_cherch:
loadSearch();
break;
}
}
private void loadDebActivity()
{
startActivity(new Intent( this,Deb_FinActivity.class ) );
finish();
}
private void loadFin()
{
lieu.setVisibility( View.INVISIBLE );
type.setVisibility(View.INVISIBLE);
cherch.setVisibility(View.INVISIBLE);
car.setVisibility(View.INVISIBLE);
division.setVisibility(View.INVISIBLE);
type_v.setVisibility(View.INVISIBLE);
list.setVisibility(View.VISIBLE);
}
private void loadLieuActivity()
{
startActivity(new Intent( this,LieuActivity.class ) );
lieu.setText(getIntent().getStringExtra("mytext"));
}
private void loadTypeActivity()
{
startActivity(new Intent( this,TypeActivity.class ) );
finish();
}
private void loadSearch()
{
}
}
In my LieuActivity.java I have this code
public class LieuActivity extends AppCompatActivity {
private EditText lieuu;
private TextView local;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lieu);
addListenerOnButton();
}
public void addListenerOnButton() {
local = (TextView) findViewById(R.id.position);
local.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
EditText lieuu = (EditText)findViewById(R.id.local);
String text =lieuu.getText().toString();
Intent myIntent = new Intent(view.getContext(),Reservation.class);
myIntent.putExtra("mytext",text);
startActivity(myIntent);
}
});
}
}
The problem is when I edit in my LieuActivity and go back to reservation it does not return the extra value until I click another time on the editText so I see the updated data for a second before re-going to LieuActivity and modify it another time .
Put these lines in onCreate() of Reservation activity
String text = getIntent().getStringExtra("mytext");
if (text != null) {
lieu.setText(text);
}
and make this change:
private void loadLieuActivity()
{
startActivity(new Intent( this,LieuActivity.class ) );
finish();
}
Do this in oncreate of Reservation
Bundle extras = getIntent().getExtras();
String string;
if (extras != null) {
string = extras.getString("mytext");
lieu.setText(string);
}
Make changes like this in LieuActivity :-
public class LieuActivity extends AppCompatActivity {
private EditText lieuu;
private TextView local;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lieu);
addListenerOnButton();
}
public void addListenerOnButton() {
local = (TextView) findViewById(R.id.position);
local.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
EditText lieuu = (EditText)findViewById(R.id.local);
String text =lieuu.getText().toString();
Intent myIntent = new Intent(view.getContext(),Reservation.class);
myIntent.putExtra("mytext",text);
setResult(RESULT_OK, myIntent );
});
}
}
In Reservation put onActivityResult()
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class Reservation extends AppCompatActivity implements View.OnClickListener {
private Button end,deb,lieu,type,cherch;
private TextView type_v ;
private ImageView car;
private View division;
private ListView list;
String mNewText="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reservation);
end = (Button)findViewById( R.id.btn_fin );
end.setOnClickListener( this);
deb= (Button)findViewById( R.id.deb_btn);
deb.setOnClickListener( this );
lieu = (Button)findViewById( R.id.btn_local);
lieu.setOnClickListener( this );
type = (Button)findViewById( R.id.btn_type);
type.setOnClickListener( this );
cherch= (Button)findViewById( R.id.btn_cherch);
cherch.setOnClickListener( this );
division= (View)findViewById( R.id.div3);
type_v= (TextView)findViewById( R.id.type);
car= (ImageView) findViewById( R.id.pic_car);
list=(ListView)findViewById(R.id.fin_list);
ArrayAdapter<String> mAdapter= new ArrayAdapter<String>(Reservation.this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.values));
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 3 )
{
Intent i = new Intent(view.getContext(),Deb_FinActivity.class);
startActivityForResult(i,3);
}
}
});
list.setAdapter(mAdapter);
}
#Override
public void onClick(View view) {
switch(view.getId())
{
case R.id.deb_btn:
loadDebActivity();
break;
case R.id.btn_fin:
loadFin();
break;
case R.id.btn_local:
loadLieuActivity();
break;
case R.id.btn_type:
loadTypeActivity();
break;
case R.id.btn_cherch:
loadSearch();
break;
}
}
private void loadDebActivity()
{
startActivity(new Intent( this,Deb_FinActivity.class ) );
finish();
}
private void loadFin()
{
lieu.setVisibility( View.INVISIBLE );
type.setVisibility(View.INVISIBLE);
cherch.setVisibility(View.INVISIBLE);
car.setVisibility(View.INVISIBLE);
division.setVisibility(View.INVISIBLE);
type_v.setVisibility(View.INVISIBLE);
list.setVisibility(View.VISIBLE);
}
private void loadLieuActivity()
{
startActivity(new Intent( this,LieuActivity.class ) );
lieu.setText(mNewText);
}
private void loadTypeActivity()
{
startActivity(new Intent( this,TypeActivity.class ) );
finish();
}
private void loadSearch()
{
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == QUEUE_MSG) {
if (resultCode == RESULT_OK) {
Serializable myText= data.getSerializableExtra("mytext");
if (myText!= null)
mNewText= myText;
}
}
}
}
Hope this may help you

savedInstanceState is null when onCreateView is called in Fragment even though I overrided onSaveInstanceState

I added up button to tool bar to navigate from fragment B to fragment A.
When I click up button, I couldn't restore the member variables of A fragment
Because savedInstanceState was null even though I Overrided
onSaveInstanceState(Bundle) and put all the variables which I wanted to restore later.
I did my best to search the reason, but I couldn't find the reason and the solutoin.
There were differeces between my situation and questions(answers) of other posts.
First, my fragment is hosted dynamically, so I couldn't give an id to my fragment in XML or something.
Second, it works when I rotate my device(savedInstanceState is not null on onCreateView()). I thought both(to rotate the device and to navigate from fragment B to fragment A) is the same situation
in that the fragment A is destroyed and recreated so onSaveInstanceState method
is called first and onCreateView is called after fragment A is recreated.
I have no idea why such situation occured. Please help me. Thanks.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(savedInstanceState != null){
mSubtitleVisible = savedInstanceState.getBoolean(SAVED_SUBTITLE_VISIBLE);
}
View view = inflater.inflate(R.layout.fragment_crime_list, container, false);
mCrimeRecyclerView = (RecyclerView) view.findViewById(R.id.crime_recycler_view);
mCrimeRecyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
updateUI();
return view;
}
...
#Override
public void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
outState.putBoolean(SAVED_SUBTITLE_VISIBLE, mSubtitleVisible);
}
the full code of Fragment B
package com.bignerdranch.android.criminalintent;
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;
/**
* Created by sgc109 on 2017-10-05.
*/
public class CrimeFragment extends android.support.v4.app.Fragment {
private static final String ARG_CRIME_ID = "crime_id";
private static final String DIALOG_DATE = "DialogDate";
private static final String DIALOG_TIME = "DialogTime";
private static final int REQUEST_DATE = 0;
private static final int REQUEST_TIME = 1;
private Crime mCrime;
private EditText mTitleField;
private Button mDateButton;
private Button mTimeButton;
private CheckBox mSolvedCheckBox;
public static CrimeFragment newInstance(UUID crimeId){
Bundle args = new Bundle();
args.putSerializable(ARG_CRIME_ID, crimeId);
CrimeFragment fragment = new CrimeFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
UUID crimeId = (UUID)getArguments().getSerializable(ARG_CRIME_ID);
mCrime = CrimeLab.get(getActivity()).getCrime(crimeId);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.fragment_crime, container, false);
mTitleField = (EditText)v.findViewById(R.id.crime_title);
mTitleField.setText(mCrime.getTitle());
mTitleField.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
mCrime.setTitle(s.toString());
}
#Override
public void afterTextChanged(Editable s) {
}
});
mDateButton = (Button)v.findViewById(R.id.crime_date);
mDateButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
FragmentManager manager = getFragmentManager();
DatePickerFragment dialog = DatePickerFragment.newInstance(mCrime.getDate());
dialog.setTargetFragment(CrimeFragment.this, REQUEST_DATE);
dialog.show(manager, DIALOG_DATE);
}
});
mTimeButton = (Button)v.findViewById(R.id.crime_time);
mTimeButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
FragmentManager manager = getFragmentManager();
TimePickerFragment dialog = TimePickerFragment.newInstance(mCrime.getDate());
dialog.setTargetFragment(CrimeFragment.this, REQUEST_TIME);
dialog.show(manager, DIALOG_TIME);
}
});
updateDateAndTimeButton();
mSolvedCheckBox = (CheckBox)v.findViewById(R.id.crime_solved);
mSolvedCheckBox.setChecked(mCrime.isSolved());
mSolvedCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mCrime.setSolved(isChecked);
}
});
return v;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent){
if(resultCode != Activity.RESULT_OK) {
return;
}
if(requestCode == REQUEST_DATE){
Date date = (Date)intent.getSerializableExtra(DatePickerFragment.EXTRA_DATE);
mCrime.setDate(updateDate(date));
updateDateAndTimeButton();
}
else if(requestCode == REQUEST_TIME){
Date date = (Date)intent.getSerializableExtra(TimePickerFragment.EXTRA_TIME);
mCrime.setDate(updateTime(date));
updateDateAndTimeButton();
}
}
private Date updateDate(Date date){
Calendar calOld = Calendar.getInstance();
calOld.setTime(mCrime.getDate());
Calendar calNew = Calendar.getInstance();
calNew.setTime(date);
calNew.set(Calendar.HOUR_OF_DAY, calOld.get(Calendar.HOUR_OF_DAY));
calNew.set(Calendar.MINUTE, calOld.get(Calendar.MINUTE));
return calNew.getTime();
}
private Date updateTime(Date date){
Calendar calOld = Calendar.getInstance();
calOld.setTime(mCrime.getDate());
Calendar calNew = Calendar.getInstance();
calNew.setTime(date);
calNew.set(Calendar.YEAR, calOld.get(Calendar.YEAR));
calNew.set(Calendar.MONTH, calOld.get(Calendar.MONTH));
calNew.set(Calendar.DAY_OF_MONTH, calOld.get(Calendar.DAY_OF_MONTH));
return calNew.getTime();
}
private void updateDateAndTimeButton() {
mDateButton.setText(mCrime.getDateString());
mTimeButton.setText(mCrime.getTimeString());
}
public void returnResult(){
getActivity().setResult(Activity.RESULT_OK, null);
}
}
Because the Activity created after onCreateView .
You can use onActivityCreated method to restore the fragment's state here .
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
mSubtitleVisible = savedInstanceState.getBoolean(SAVED_SUBTITLE_VISIBLE);
}
Log.e("TAG", "onActivityCreated OK");
Log.e("TAG", savedInstanceState.getBoolean(SAVED_SUBTITLE_VISIBLE) + "");
}
Edit
Change to onViewStateRestored method,and try again .
Add log in onSaveInstanceState and onViewStateRestored ,make sure all of them work .
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
mSubtitleVisible = savedInstanceState.getBoolean(SAVED_SUBTITLE_VISIBLE);
}
Log.e("TAG", "onActivityCreated OK");
Log.e("TAG", "onActivityCreated " + savedInstanceState.getBoolean(SAVED_SUBTITLE_VISIBLE));
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(SAVED_SUBTITLE_VISIBLE, mSubtitleVisible);
Log.e("TAG", "onSaveInstanceState OK");
Log.e("TAG", "onSaveInstanceState" + mSubtitleVisible);
}
Edit
You can save the status in onSaveInstanceState and onDestroyView.
Then,restore the state in onActivityCreated
You can do like this.
Bundle savedState;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Restore State Here
if (!restoreStateFromArguments()) {
// First Time, Initialize something here
onFirstTimeLaunched();
}
}
protected void onFirstTimeLaunched() {
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save State Here
saveStateToArguments();
}
#Override
public void onDestroyView() {
super.onDestroyView();
// Save State Here
saveStateToArguments();
}
private void saveStateToArguments() {
if (getView() != null)
savedState = saveState();
if (savedState != null) {
Bundle b = getArguments();
b.putBundle("savedState", savedState);
}
}
private boolean restoreStateFromArguments() {
Bundle b = getArguments();
savedState = b.getBundle("savedState");
if (savedState != null) {
restoreState();
return true;
}
return false;
}
// Restore Instance State Here
private void restoreState() {
if (savedState != null) {
// For Example
uSelected.setText(savedState.getString("uSelected"));
onRestoreState(savedState);
}
}
protected void onRestoreState(Bundle savedInstanceState) {
}
// Save Instance State Here
private Bundle saveState() {
Bundle state = new Bundle();
// For Example
state.putString("uSelected", uSelected.getText().toString());
onSaveState(state);
return state;
}
protected void onSaveState(Bundle outState) {
}
Fragment life cycle

my fragment showing blank screen after i am having this code

package com.example.mindwareuae;
import java.util.Arrays;
import java.util.List;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.InputFilter.LengthFilter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import com.facebook.widget.LoginButton.UserInfoChangedCallback;
public class FacebokkFragment extends Fragment{
private LoginButton loginBtn;
private Button postImageBtn;
private Button updateStatusBtn;
private TextView userName;
private UiLifecycleHelper uiHelper;
private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (rootView != null) {
ViewGroup parent = (ViewGroup) rootView.getParent();
if (parent != null) {
parent.removeView(rootView);
}
}
try
{
View rootView = inflater.inflate(R.layout.fragment_facebook,container,false);
userName = (TextView)rootView.findViewById(R.id.user_name);
loginBtn = (LoginButton) rootView.findViewById(R.id.fb_login_button);
loginBtn.setUserInfoChangedCallback(new UserInfoChangedCallback() {
#Override
public void onUserInfoFetched(GraphUser user) {
if (user != null) {
userName.setText("Hello, " + user.getName());
} else {
userName.setText("You are not logged");
}
}
});
postImageBtn = (Button)rootView.findViewById(R.id.fbpost_image);
postImageBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
postImage();
}
});
updateStatusBtn = (Button)rootView.findViewById(R.id.fbupdate_status);
updateStatusBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
buttonsEnabled(false);
}catch(Exception e)
{
e.printStackTrace();
}
return rootView;
}
public void buttonsEnabled(boolean isEnabled) {
postImageBtn.setEnabled(isEnabled);
updateStatusBtn.setEnabled(isEnabled);
}
public void postImage() {
if (checkPermissions()) {
Bitmap img = BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher);
Request uploadRequest = Request.newUploadPhotoRequest(
Session.getActiveSession(), img, new Request.Callback() {
#Override
public void onCompleted(Response response) {
Toast.makeText(getActivity(),
"Photo uploaded successfully",
Toast.LENGTH_LONG).show();
}
});
uploadRequest.executeAsync();
} else {
requestPermissions();
}
}
// public void postStatusMessage() {
// if (checkPermissions()) {
// Request request = Request.newStatusUpdateRequest(
// Session.getActiveSession(), message,
// new Request.Callback() {
// #Override
// public void onCompleted(Response response) {
// if (response.getError() == null)
// Toast.makeText(getActivity(),
// "Status updated successfully",
// Toast.LENGTH_LONG).show();
// }
// });
// request.executeAsync();
// } else {
// requestPermissions();
// }
// }
public boolean checkPermissions() {
Session s = Session.getActiveSession();
if (s != null) {
return s.getPermissions().contains("publish_actions");
} else
return false;
}
public void requestPermissions() {
Session s = Session.getActiveSession();
if (s != null)
s.requestNewPublishPermissions(new Session.NewPermissionsRequest(
this, PERMISSIONS));
}
// #Override
// public void onResume() {
// super.onResume();
// uiHelper.onResume();
// buttonsEnabled(Session.getActiveSession().isOpened());
// }
//
// #Override
// public void onPause() {
// super.onPause();
// uiHelper.onPause();
// }
//
// #Override
// public void onDestroy() {
// super.onDestroy();
// if (rootView != null) {
// ViewGroup parentViewGroup = (ViewGroup) rootView.getParent();
// if (parentViewGroup != null) {
// parentViewGroup.removeAllViews();
// }
// }
// uiHelper.onDestroy();
// }
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onSaveInstanceState(Bundle savedState) {
super.onSaveInstanceState(savedState);
uiHelper.onSaveInstanceState(savedState);
}
}
i want login the facbook from this fragment..but i am not getiing any thing my xml file is
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:facebook="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
android:padding="20dp"
android:background="#EEEEEE">
<com.facebook.widget.LoginButton
android:id="#+id/fb_login_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
facebook:confirm_logout="false"
facebook:fetch_user_info="true" />
<TextView
android:id="#+id/fb_user"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="10dp"
android:textSize="18sp" />
<Button
android:id="#+id/fbupdate_status"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="update_status" />
<Button
android:id="#+id/fbpost_image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="post_image" />
</LinearLayout>
it is my xml file why i am not able to get the fragment with my facebook login button.
please any one can explain me.
Create a FragmentActivity and add your fragment to that FragmentActivity
public class MainActivity extends FragmentActivity{
FacebokkFragment fbFragment;
ArrayList<Fragment> fragemetnList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fbFragment = new FacebokkFragment();
fragemetnList = getFragmnetsList();
setContentView(R.layout.activity_main);
}
ArrayList<Fragment> getFragmnetsList() {
ArrayList<Fragment> fragments = new ArrayList<Fragment>();
fragments.add(fbFragment);
// you can also add more fragments here
return fragments;
}
}
Now create an activity_main.xml file into your res/layout directory
Don't forget to make the entry of your MainActivity into AndroidManifest.xml file
May this code will solve your problem
if (rootView != null) {
ViewGroup parent = (ViewGroup) rootView.getParent();
if (parent != null) {
parent.removeView(rootView);
}
}
Is this part of code really required? Try removing this.
Try this
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_facebook, container, false);
...
return rootView;

my In app billing dialog disapears when i tap outside it

I have made a demo in app purchase for android,I have created a test product and purchase it for testing purpose,all is working very fine,But Only issue is when i tap outside the in app billing Dialog,it disappears,I want to do something like "setCancellable(false)" on it,Please suggest me,I need help,My code is as below:
code
package com.medicineqod.activity;
import inapUtils.IabHelper;
import inapUtils.IabHelper.OnConsumeFinishedListener;
import inapUtils.IabHelper.OnIabPurchaseFinishedListener;
import inapUtils.IabHelper.OnIabSetupFinishedListener;
import inapUtils.IabHelper.QueryInventoryFinishedListener;
import inapUtils.IabResult;
import inapUtils.Inventory;
import inapUtils.Purchase;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Locale;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.drm.DrmStore.ConstraintsColumns;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.medicineqod.FragmentAbstractActivity;
import com.medicineqod.R;
import com.medicineqod.DBAdapter.DataBaseHelper;
import com.medicineqod.model.Question;
import com.medicineqod.utility.CommonVariables;
/**
* Created by basheer on 4/26/14.
*/
public class QuestionOFDayActivity extends FragmentAbstractActivity
/* OnIabSetupFinishedListener, OnIabPurchaseFinishedListener */{
// When requested, this adapter returns a WallpaperCollectionFragment,
// representing an object in the collection.
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
ImageView btnNext, btnPrev;
static TextView tvError;
TextView tvDate;
TextView btnHome;
TextView tvTitle;
int mTotalCount;
int mPosition = 0;
int mActivity = 0;
ArrayList<Question> qusList = new ArrayList<Question>();
// edited by jigar
private static final String TAG = "com.medicineqod.inappbilling";
static IabHelper mHelper;
static final String ITEM_SKU = "com.medicineqod.product.one";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quizoftheday);
// ViewPager and its adapters use support library
// fragments, so use getSupportFragmentManager.
// Edited by jigar,....
showCustomeAlertValidation(QuestionOFDayActivity.this);
DataBaseHelper bBase = new DataBaseHelper(this);
mActivity = getIntent().getIntExtra(CommonVariables.ACTIVITY, 0);
if (mActivity == CommonVariables.FavQusAct) {
qusList = bBase.getFavQuestions();
mTotalCount = qusList.size();
} else if (mActivity == CommonVariables.PastQusAct) {
qusList = bBase.getPastQuestions();
mTotalCount = qusList.size();
} else if (mActivity == CommonVariables.QusOfTheDay) {
qusList = bBase.getQuestions();
mTotalCount = qusList.size();
} else {
qusList = bBase.getQuestions();
mTotalCount = qusList.size();
}
if (qusList.size() == 0) {
return;
}
mPosition = getIntent().getIntExtra("postion", 0);
Collections.reverse(qusList);
if (mPosition == -1) {
mPosition = qusList.size() - 1;
}
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setCurrentItem(mPosition);
tvError = (TextView) findViewById(R.id.error_tv);
tvDate = (TextView) findViewById(R.id.topbar_date_tv);
tvTitle = (TextView) findViewById(R.id.topbar_title_tv);
btnNext = (ImageView) findViewById(R.id.bottom_next_img);
btnPrev = (ImageView) findViewById(R.id.bottom_prev_img);
btnNext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (mTotalCount - 1 > mPosition) {
mPosition++;
mViewPager.setCurrentItem(mPosition);
}
}
});
btnPrev.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (0 < mPosition) {
mPosition--;
mViewPager.setCurrentItem(mPosition);
}
}
});
mViewPager
.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
mPosition = position;
btnNext.setVisibility(View.VISIBLE);
btnPrev.setVisibility(View.VISIBLE);
if (mPosition == 0) {
btnPrev.setVisibility(View.INVISIBLE);
} else if (mPosition == mTotalCount - 1) {
btnNext.setVisibility(View.INVISIBLE);
} else {
btnNext.setVisibility(View.VISIBLE);
btnPrev.setVisibility(View.VISIBLE);
}
tvDate.setText("" + qusList.get(position).getDate());
setTiltle(qusList.get(mPosition).getDate());
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
tvDate.setText("" + qusList.get(mPosition).getDate());
setTiltle(qusList.get(mPosition).getDate());
btnHome = (TextView) findViewById(R.id.topbar_left_tv);
if (mActivity == CommonVariables.FavQusAct) {
btnHome.setText("Back");
btnHome.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_back,
0, 0, 0);
} else if (mActivity == CommonVariables.PastQusAct) {
btnHome.setText("Back");
btnHome.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_back,
0, 0, 0);
} else if (mActivity == CommonVariables.QusOfTheDay) {
// btnHome.setText("Back");
// btnHome.setCompoundDrawablesWithIntrinsicBounds(null, null, null,
// null);
}
btnHome.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
overridePendingTransition(R.anim.slide_in_right,
R.anim.slide_out_right);
}
});
// System.out.println(mPosition + "::::" + (mTotalCount - 1));
if (qusList.size() == 0 || qusList.size() == 1) {
btnPrev.setVisibility(View.INVISIBLE);
btnNext.setVisibility(View.INVISIBLE);
} else if (mPosition == 0) {
btnPrev.setVisibility(View.INVISIBLE);
} else if (mPosition == mTotalCount - 1) {
btnNext.setVisibility(View.INVISIBLE);
} else {
btnNext.setVisibility(View.VISIBLE);
btnPrev.setVisibility(View.VISIBLE);
}
}
private void setTiltle(String date) {
if (mActivity == CommonVariables.FavQusAct) {
tvTitle.setText(""
+ getApplication().getResources().getString(
R.string.title_fav_qus));
} else if (getCurrentDate().equals(date)) {
tvTitle.setText(""
+ getApplication().getResources().getString(R.string.qod));
} else {
tvTitle.setText(""
+ getApplication().getResources().getString(
R.string.title_past_qus));
}
}
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
fragment = new QuizCollectionFragment();
Bundle args = new Bundle();
args.putSerializable(QuizCollectionFragment.ARG_OBJECT,
(Serializable) qusList.get(position));
args.putInt(QuizCollectionFragment.QUZI_POSITION, position);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return mTotalCount;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
return "good".toUpperCase(l);
}
}
public void setOnAnswer(String mPerformance, String mAswerView,
String mAswerQue, String mFavourite, int mPosition,
String mPercentage) {
if (qusList.size() > 0 && mPosition < qusList.size()) {
Question mQuizQuestion = qusList.get(mPosition);
mQuizQuestion.setAnsque(mAswerQue);
mQuizQuestion.setPerformance(mPerformance);
mQuizQuestion.setAnsview(mAswerView);
mQuizQuestion.setFavourite(mFavourite);
mQuizQuestion.setPercentage(mPercentage);
qusList.set(mPosition, mQuizQuestion);
}
}
public void refreshTheViewPage(int position) {
if (mActivity == CommonVariables.FavQusAct) {
tvDate.setText("");
qusList.remove(mPosition);
mTotalCount = qusList.size();
mSectionsPagerAdapter.notifyDataSetChanged();
mViewPager.setAdapter(mSectionsPagerAdapter);
if (mTotalCount - 1 < mPosition) {
mPosition = mTotalCount - 1;
}
mViewPager.setCurrentItem(mPosition);
btnNext.setVisibility(View.VISIBLE);
btnPrev.setVisibility(View.VISIBLE);
if (qusList.size() == 0 || qusList.size() == 1) {
btnNext.setVisibility(View.INVISIBLE);
btnPrev.setVisibility(View.INVISIBLE);
} else if (mPosition == 0) {
btnPrev.setVisibility(View.INVISIBLE);
} else if (mPosition == mTotalCount - 1) {
btnNext.setVisibility(View.INVISIBLE);
} else {
btnNext.setVisibility(View.VISIBLE);
btnPrev.setVisibility(View.VISIBLE);
}
}
}
// Popup of subscribing app..
public void showCustomeAlertValidation(final Context context) {
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.popup);
dialog.setCancelable(false);
dialog.getWindow().setBackgroundDrawable(
new ColorDrawable(android.graphics.Color.TRANSPARENT));
final Button btn_subscribe = (Button) dialog
.findViewById(R.id.btn_subscribe);
btn_subscribe.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Subscribing code here...!!!
mHelper.launchPurchaseFlow(QuestionOFDayActivity.this,
ITEM_SKU, 10001, mPurchaseFinishedListener,
"mypurchasetoken");
dialog.dismiss();
}
});
dialog.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (!mHelper.handleActivityResult(requestCode, resultCode, data)) {
super.onActivityResult(requestCode, resultCode, data);
}
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
String base64EncodedPublicKey = "MIIBIjANyOvuqXSF8qd4NAapQdRohAajUA3/N/L9XoD21B7lVqZnICXh1dFEnnVvNyhK+ws1Cr5YsPvIAprHvsQNJ2xtEGypNivk/AA6N91OY0r2dtZJZHGpSxDSsfHTfKk5/4CaW1itbdIo+JiGTieJyHIvMFdWSkLqaxR3JWy+0KwTHvzMrR15oClM9v8fKjNT6M8qxlhnyzLDd7G2/ifBIPTJjfdvWHoXaP/rHa2MbN2acPwvbbwIDAQAB";
mHelper = new IabHelper(this, base64EncodedPublicKey);
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result) {
if (!result.isSuccess()) {
Log.d(TAG, "In-app Billing setup failed: " + result);
} else {
Log.d(TAG, "In-app Billing is set up OK");
}
}
});
}
IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
if (result.isFailure()) {
// Handle error
return;
} else if (purchase.getSku().equals(ITEM_SKU)) {
consumeItem();
System.out
.println(":::::::::::::::::::::Purchase consumed successfuly::::::::::::::::::::");
}
}
};
IabHelper.QueryInventoryFinishedListener mReceivedInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
public void onQueryInventoryFinished(IabResult result,
Inventory inventory) {
if (result.isFailure()) {
// Handle failure
} else {
mHelper.consumeAsync(inventory.getPurchase(ITEM_SKU),
mConsumeFinishedListener);
}
}
};
IabHelper.OnConsumeFinishedListener mConsumeFinishedListener = new IabHelper.OnConsumeFinishedListener() {
public void onConsumeFinished(Purchase purchase, IabResult result) {
if (result.isSuccess()) {
System.out
.println("::::::::::::::::::::::::Purchase consumehas been finished successfully:::::::::::::::::::::");
} else {
// handle error
System.out
.println("::::::::::::::::::::::::Purchase consumehas failed:::::::::::::::::::::");
}
}
};
public void consumeItem() {
mHelper.queryInventoryAsync(mReceivedInventoryListener);
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if (mHelper != null)
mHelper.dispose();
mHelper = null;
}
}
this is what you need to do in order to ristrict that.
dialog.setCanceledOnTouchOutside(false);
this will make sure dialog is not dismissed when touched outside of dialog box area.

zxing onActivityResult not called in Fragment only in Activity

I'm having some issue with zxing onActivityResult().
As you can see in the code I did properly invoke new intent as described in https://code.google.com/p/zxing/wiki/ScanningViaIntent.
The question is how can I catch onActivityResult() in Fragment, since I need this data in my Fragmnet and not in Activity?
package com.example.testingcodereading;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
public class MainFragment extends Fragment {
private Button mButtonXZing;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.fragment_main, parent, false);
mButtonXZing = (Button) v.findViewById(R.id.button_xzing);
mButtonXZing.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
IntentIntegrator integrator = new IntentIntegrator(getActivity());
integrator.initiateScan();
}
});
return v;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
System.out.println("never here");
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanResult != null) {
// handle scan result
}
// else continue with any other code you need in the method
}
}
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fm = getSupportFragmentManager();
Fragment f = fm.findFragmentById(R.id.fragmentContainer);
if(f == null){
f = new MainFragment();
fm.beginTransaction()
.add(R.id.fragmentContainer, f)
.commit();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
System.out.println("the code is catch");
}
}
As Martynnw pointed out the issue is to call fragment.startActivityForResult instead of activity.startActivityForResult. So just use next wrapper:
import android.content.Intent;
import android.support.v4.app.Fragment;
import com.google.zxing.integration.android.IntentIntegrator;
public final class FragmentIntentIntegrator extends IntentIntegrator {
private final Fragment fragment;
public FragmentIntentIntegrator(Fragment fragment) {
super(fragment.getActivity());
this.fragment = fragment;
}
#Override
protected void startActivityForResult(Intent intent, int code) {
fragment.startActivityForResult(intent, code);
}
}
integrator.initiateScan();
Change the above line as
integrator.forSupportFragment(fragment_name.this).initiateScan();
Alternative ZXing Android Embedded, implementation:
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new IntentIntegrator(this).initiateScan(); // `this` is the current Activity
}
Use from a Fragment:
IntentIntegrator.forFragment(this).initiateScan(); // `this` is the current Fragment
// If you're using the support library, use:
// IntentIntegrator.forSupportFragment(this) instead.
Get the results:
#Override
public void onActivityResult(int requestCode, int resultCode,Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if(result != null) {
if(result.getContents() == null) {
Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
more info and options
If any one have the same issue here is my solution.
package com.example.testingcodereading;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment);
FragmentManager fm = getSupportFragmentManager();
Fragment f = fm.findFragmentById(R.id.fragmentContainer);
if (f == null) {
f = MainFragment.newInstance("Start Application");
fm.beginTransaction().add(R.id.fragmentContainer, f).commit();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
System.out.println("the code is catch");
IntentResult scanResult = IntentIntegrator.parseActivityResult(
requestCode, resultCode, intent);
// handle scan result
if (scanResult != null) {
FragmentManager fm = getSupportFragmentManager();
Fragment newFrame = MainFragment.newInstance(scanResult.toString());
fm.beginTransaction().replace(R.id.fragmentContainer, newFrame).commit();
}
}
}
package com.example.testingcodereading;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.test.suitebuilder.annotation.MediumTest;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class MainFragment extends Fragment {
private static final String EXTRA_CODE = "com.example.testingcodereading.code";
private Button mButtonXZing;
private TextView mTextView;
public static MainFragment newInstance(String code) {
Bundle args = new Bundle();
args.putSerializable(EXTRA_CODE, code);
MainFragment fragment = new MainFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.fragment_main, parent, false);
mTextView = (TextView) v.findViewById(R.id.text_code);
mTextView.setText((String) getArguments().getSerializable(EXTRA_CODE));
mButtonXZing = (Button) v.findViewById(R.id.button_xzing);
mButtonXZing.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
IntentIntegrator integrator = new IntentIntegrator(getActivity());
integrator.initiateScan();
}
});
return v;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
System.out.println("never here");
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanResult != null) {
// handle scan result
}
// else continue with any other code you need in the method
}
}
I had this problem and resolved it with below codes:
IntentIntegrator integrator = new IntentIntegrator(getActivity());
integrator.forSupportFragment(MyFragment.this).initiateScan();
Shall call the scan in this way:
IntentIntegrator.forSupportFragment(YourFragment.this)
.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE)
.setBeepEnabled(true/false)
.setPrompt("blahblahblah")
.initiateScan();
Then you can get the scan result in Fragment's onActivityResult
Make sure OnActivityResult in your Activity is calling super.OnActivityResult(). That should ensure it's called on the Fragment as well.
Alternatively, you could modify the IntentIntegrator code so it calls StartActivityResult on the Fragment, either by passing the fragment to the constructor, or passing it to initiateScan.
Try creating IntentIntegrator object in Fragment as below.
val scanIntegrator = IntentIntegrator.forSupportFragment(this#HomeFragment)
scanIntegrator.setPrompt("Scan")
scanIntegrator.setBeepEnabled(true)
//The following line if you want QR code
scanIntegrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES)
scanIntegrator.captureActivity = CaptureActivityAnyOrientation::class.java
scanIntegrator.setOrientationLocked(true)
scanIntegrator.setBarcodeImageEnabled(true)
scanIntegrator.initiateScan()
public void scanCode() {
IntentIntegrator.forSupportFragment(this).
setCaptureActivity(CaptureAct.class).
setOrientationLocked(false)
.setDesiredBarcodeFormats(IntentIntegrator.PRODUCT_CODE_TYPES)
.setPrompt("Scanning code")
.initiateScan();
}
A solution : A basic example of how you can manage it
Main Activity
public static int tapTrick = 0;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//super.onActivityResult(requestCode, resultCode, data);
if(tapTrick!=0 && tapTrick==1) {
Tab1.onActivityResult(requestCode, resultCode, data, MainActivity.this);
}else if (tapTrick!=0 && tapTrick==2){
//Tab2.onActivityResult(requestCode, resultCode, data, MainActivity.this);
}
}
Fragment 1
MainActivity.tapTrick=1; // onCreateView or onClick (load images/files)
public static void onActivityResult(int requestCode, int resultCode, Intent intent, Context context) {
}
Fragment 2
MainActivity.tapTrick=2;
public static void onActivityResult(int requestCode, int resultCode, Intent intent, Context context) {
}
Fragment x
MainActivity.tapTrick=x;
public static void onActivityResult(int requestCode, int resultCode, Intent intent, Context context) {
}

Categories

Resources