zxing条形码扫描器没有返回结果

时间:2016-02-10 19:11:45

标签: java android zxing barcode-scanner

我正在尝试使这个应用程序扫描一本书的ISBC,然后发出一个http请求来获取该书的标题和其他细节。

我使用 rootView.findViewById(R.id.scan_button)..... 启动了相机。现在我想记录条形码和代码格式,以确保它在 onActivityResult 中工作,但它没有记录或进行祝酒。在相机对焦代码后相机活动关闭并返回到我有按钮的视图,以启动扫描功能,但不记录任何内容或进行任何烘烤。我之前使用过这个教程 - http://code.tutsplus.com/tutorials/android-sdk-create-a-barcode-reader--mobile-17162 - 看看zXing是如何工作的,教程工作得很好,现在我正在尝试实现一些代码。

        rootView.findViewById(R.id.scan_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                IntentIntegrator scanIntegrator = new IntentIntegrator(getActivity());
                scanIntegrator.setBeepEnabled(true);
                scanIntegrator.setBarcodeImageEnabled(true);
                scanIntegrator.setPrompt("Scan a barcode");
                scanIntegrator.initiateScan();
            }
        });



    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
//retrieve scan result
        IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
        if (scanningResult != null) {
//we have a result
            String scanContent = scanningResult.getContents();
            String scanFormat = scanningResult.getFormatName();
            formatTxt.setText("FORMAT: " + scanFormat);
            contentTxt.setText("CONTENT: " + scanContent);
            Log.i("FORMAT ", scanFormat);
            Log.i("CONTENT", scanContent);
            Log.i("xZing", "contents: "+scanContent+" format: "+scanFormat);

            Toast.makeText(getActivity(), "FORMAT " + scanFormat + " CONTENT " + scanContent, Toast.LENGTH_LONG).show();
        }else{
            Toast toast = Toast.makeText(getActivity(),
                    "No scan data received!", Toast.LENGTH_SHORT);
            toast.show();
        }
    }

完整代码

public class AddBook extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
        private static final String TAG = "INTENT_TO_SCAN_ACTIVITY";
        private EditText ean;
        private final int LOADER_ID = 1;
        private View rootView;
        private final String EAN_CONTENT="eanContent";
        private static final String SCAN_FORMAT = "scanFormat";
        private static final String SCAN_CONTENTS = "scanContents";

        private String mScanFormat = "Format:";
        private String mScanContents = "Contents:";


        private Button scanBtn;
        private TextView formatTxt, contentTxt;



        public AddBook(){
        }

        @Override
        public void onSaveInstanceState(Bundle outState) {
            super.onSaveInstanceState(outState);
            if(ean!=null) {
                outState.putString(EAN_CONTENT, ean.getText().toString());
            }
        }

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

            rootView = inflater.inflate(R.layout.fragment_add_book, container, false);
            ean = (EditText) rootView.findViewById(R.id.ean);
            formatTxt = (TextView)rootView.findViewById(R.id.scan_format);
            contentTxt = (TextView)rootView.findViewById(R.id.scan_content);

            ean.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                    //no need
                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    //no need
                }

                @Override
                public void afterTextChanged(Editable s) {

                    String ean = s.toString();
                    //catch isbn10 numbers
                    if (ean.length() == 10 && !ean.startsWith("978")) {
                        ean = "978" + ean;
                    }
                    if (ean.length() < 13) {
                        clearFields();
                        return;
                    }
                    //Once we have an ISBN, start a book intent
                    Intent bookIntent = new Intent(getActivity(), BookService.class);
                    bookIntent.putExtra(BookService.EAN, ean);
                    bookIntent.setAction(BookService.FETCH_BOOK);
                    getActivity().startService(bookIntent);
                    AddBook.this.restartLoader();


                }
            });

            rootView.findViewById(R.id.scan_button).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    IntentIntegrator scanIntegrator = new IntentIntegrator(getActivity());
                    scanIntegrator.setBeepEnabled(true);
                    scanIntegrator.setBarcodeImageEnabled(true);
                    scanIntegrator.setPrompt("Scan a barcode");
                    scanIntegrator.initiateScan();
                }
            });

            rootView.findViewById(R.id.save_button).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    ean.setText("");
                }
            });

            rootView.findViewById(R.id.delete_button).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent bookIntent = new Intent(getActivity(), BookService.class);
                    bookIntent.putExtra(BookService.EAN, ean.getText().toString());
                    bookIntent.setAction(BookService.DELETE_BOOK);
                    getActivity().startService(bookIntent);
                    ean.setText("");
                }
            });

            if(savedInstanceState!=null){
                ean.setText(savedInstanceState.getString(EAN_CONTENT));
                ean.setHint("");
            }

            return rootView;
        }

        public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    //retrieve scan result
            IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
            if (scanningResult != null) {
    //we have a result
                String scanContent = scanningResult.getContents();
                String scanFormat = scanningResult.getFormatName();
                formatTxt.setText("FORMAT: " + scanFormat);
                contentTxt.setText("CONTENT: " + scanContent);
                Log.i("FORMAT ", scanFormat);
                Log.i("CONTENT", scanContent);
                Log.i("xZing", "contents: "+scanContent+" format: "+scanFormat);

                Toast.makeText(getActivity(), "FORMAT " + scanFormat + " CONTENT " + scanContent, Toast.LENGTH_LONG).show();
            }else{
                Toast toast = Toast.makeText(getActivity(),
                        "No scan data received!", Toast.LENGTH_SHORT);
                toast.show();
            }
        }





        // Checks for network connection
        public boolean checkNetworkConnection(){
            ConnectivityManager cm =
                    (ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            boolean isConnected = activeNetwork != null &&
                    activeNetwork.isConnectedOrConnecting();

            return isConnected;
        }

        private void restartLoader(){
            getLoaderManager().restartLoader(LOADER_ID, null, this);
        }


        @Override
        public android.support.v4.content.Loader<Cursor> onCreateLoader(int id, Bundle args) {
            if(ean.getText().length()==0){
                return null;
            }
            String eanStr= ean.getText().toString();
            if(eanStr.length()==10 && !eanStr.startsWith("978")){
                eanStr="978"+eanStr;
            }
            return new CursorLoader(
                    getActivity(),
                    AlexandriaContract.BookEntry.buildFullBookUri(Long.parseLong(eanStr)),
                    null,
                    null,
                    null,
                    null
            );
        }

        @Override
        public void onLoadFinished(android.support.v4.content.Loader<Cursor> loader, Cursor data) {
            if (!data.moveToFirst()) {
                return;
            }

            String bookTitle = data.getString(data.getColumnIndex(AlexandriaContract.BookEntry.TITLE));
            ((TextView) rootView.findViewById(R.id.bookTitle)).setText(bookTitle);

            String bookSubTitle = data.getString(data.getColumnIndex(AlexandriaContract.BookEntry.SUBTITLE));
            ((TextView) rootView.findViewById(R.id.bookSubTitle)).setText(bookSubTitle);

            String authors = data.getString(data.getColumnIndex(AlexandriaContract.AuthorEntry.AUTHOR));
            String[] authorsArr = authors.split(",");
            ((TextView) rootView.findViewById(R.id.authors)).setLines(authorsArr.length);
            ((TextView) rootView.findViewById(R.id.authors)).setText(authors.replace(",","\n"));
            String imgUrl = data.getString(data.getColumnIndex(AlexandriaContract.BookEntry.IMAGE_URL));
            if(Patterns.WEB_URL.matcher(imgUrl).matches()){
                new DownloadImage((ImageView) rootView.findViewById(R.id.bookCover)).execute(imgUrl);
                rootView.findViewById(R.id.bookCover).setVisibility(View.VISIBLE);
            }

            String categories = data.getString(data.getColumnIndex(AlexandriaContract.CategoryEntry.CATEGORY));
            ((TextView) rootView.findViewById(R.id.categories)).setText(categories);

            rootView.findViewById(R.id.save_button).setVisibility(View.VISIBLE);
            rootView.findViewById(R.id.delete_button).setVisibility(View.VISIBLE);
        }

        @Override
        public void onLoaderReset(android.support.v4.content.Loader<Cursor> loader) {

        }

        private void clearFields(){
            ((TextView) rootView.findViewById(R.id.bookTitle)).setText("");
            ((TextView) rootView.findViewById(R.id.bookSubTitle)).setText("");
            ((TextView) rootView.findViewById(R.id.authors)).setText("");
            ((TextView) rootView.findViewById(R.id.categories)).setText("");
            rootView.findViewById(R.id.bookCover).setVisibility(View.INVISIBLE);
            rootView.findViewById(R.id.save_button).setVisibility(View.INVISIBLE);
            rootView.findViewById(R.id.delete_button).setVisibility(View.INVISIBLE);
        }

        @Override
        public void onAttach(Activity activity) {
            super.onAttach(activity);
            activity.setTitle(R.string.scan);
        }
    }

        enter code here

1 个答案:

答案 0 :(得分:1)

问题在于我使用的是IntentIntegrator scanIntegrator = new IntentIntegrator(getActivity()),它会在onActivityResult上调用Activity / Parent级别。由于onActivityResult没有做任何事情,所以什么也没发生。因为我正在使用片段,所以没有调用子/片段的onActivityResult。

要修复它,我将onClick中的IntentIntegrator scanIntegrator = new IntentIntegrator(getActivity())替换为IntentIntegrator.forSupportFragment(AddBook.this),并在片段中引用“AddBook.this”,以便调用片段中的onActivityResult,而不是活动中的一个。

:)

干杯!