[android]Spinner 在主数据 Activity 是丢失后使用 camera 扫描 QR 代码

发布时间: 2017/3/19 18:40:56
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

你好,是新的 Android 编程。

Mainacitivity 加载时我可以从 sql server 中提取数据并填充它在 spinner 。我可以选择一个项目从 spinner 和扫描 qr 码更 / 条码。我一旦停下来 camera 并返回到 MainActivity,我找不到任何数据在 spinner 。请让我知道是否你需要更多的信息有关的问题。我提供了 MainActivity.java 文件中的全部代码。

 package com.example.vxt.barcodescanner;
    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.ProgressBar;import android.widget.Spinner;import android.app.AlertDialog;import android.content.DialogInterface;import com.google.zxing.Result;import me.dm7.barcodescanner.zxing.ZXingScannerView;import java.sql.Connection;import java.sql.ResultSet;import java.sql.PreparedStatement;import java.util.ArrayList;import static com.example.vxt.barcodescanner.R.id.spinner;

    public class MainActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler{
    ConnectionClass connectionClass;
    //ProgressBar pbbar;
    Spinner spinnerProducts;
    private  ZXingScannerView mScannerView;
    ArrayList<String> scanned_data = new ArrayList<String>();
    ArrayList<String> data = new ArrayList<String>();
    String productSelected;
    Button scan, pushToDB;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        connectionClass = new ConnectionClass();
        //pbbar = (ProgressBar) findViewById(R.id.pbbar);
        //pbbar.setVisibility(View.VISIBLE);
        spinnerProducts = (Spinner) findViewById(spinner);
        scan = (Button) findViewById(R.id.button);
        pushToDB = (Button) findViewById(R.id.button3);
        try {
            Connection con = connectionClass.CONN();
            if (con != null) {

                String query = "select * from Products";
                PreparedStatement preparedStatement = con.prepareStatement(query);
                ResultSet rs = preparedStatement.executeQuery();
                data.add("<--- Select a Product --->");
                while(rs.next()){
                    String product = rs.getString("Product");
                    String id = Integer.toString(rs.getInt("Id"));
                    data.add(product + "----" + id);
                }

                ArrayAdapter NoCoreAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, data);
                spinnerProducts.setAdapter(NoCoreAdapter);
                //pbbar.setVisibility(View.GONE);
                scan.setEnabled(false);
                pushToDB.setEnabled(false);
            }
        } catch (Exception ex) {
            //pbbar.setVisibility(View.GONE);
            ex.printStackTrace();
        }
        spinnerProducts.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if(spinnerProducts.getSelectedItemPosition() != 0){
                    scan.setEnabled(true);
                }
                productSelected = spinnerProducts.getSelectedItem().toString();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) { /* do nothing */ }


    public void onClick(View v){
        mScannerView = new ZXingScannerView(MainActivity.this);
        setContentView(mScannerView);
        mScannerView.setResultHandler(this);
        mScannerView.startCamera();
    }

    public void onClickDB(View v){
        //pbbar.setVisibility(View.VISIBLE);
        pushToDB.setEnabled(false);
        try {
            Connection con = connectionClass.CONN();
            if (con != null) {
                String query, query1;
                PreparedStatement preparedStatement, preparedStatement1;  // = con.prepareStatement(query);
                ResultSet rs; // = preparedStatement.executeQuery();
                String[] splArray;
                //SimpleCursorAdapter adapter = (SimpleCursorAdapter) spinnerProducts.getAdapter();
                for (int position = 1; position < scanned_data.size(); position++) {
                    splArray = scanned_data.get(position).split(",");
                    query = "select * from Products_Barcode where ProductId ='" + splArray[1] + "'";
                    preparedStatement = con.prepareStatement(query);
                    rs = preparedStatement.executeQuery();
                    if(rs.next()){
                        query1 = "Update Products_Barcode set Barcode = '" + splArray[2] + "' where ProductId = '" + splArray[1] + "'";
                        preparedStatement1 = con.prepareStatement(query1);
                        preparedStatement1.executeQuery();
                    }
                    else{
                        query1 = "insert into Products_Barcode values ('" + splArray[1] + "','" + splArray[0] + "','" + splArray[2] + "');";
                        preparedStatement1 = con.prepareStatement(query1);
                        preparedStatement1.executeQuery();
                    }
                }
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setMessage("Data tranferred successfully")
                        .setPositiveButton("Yes",new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,int id) {
                                dialog.cancel();
                            }
                        });

                AlertDialog alertDialog = builder.create();
                alertDialog.show();
            }
        } catch (Exception ex) {
            //pbbar.setVisibility(View.GONE);
            ex.printStackTrace();
        }
    }

    @Override
    protected void onPause(){
        super.onPause();
        mScannerView.stopCamera();
    }


    @Override
    public void handleResult(Result result) {
        //if(chk == 0){
        Log.v("handleResult", result.getText());
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        String source_text = result.getText();
        String prod = productSelected.replace("----", ",");
        scanned_data.add(prod + "," + source_text);
        builder.setTitle("Scan Result");
        builder.setMessage("Scan complete")

                //chk = 1;
                .setPositiveButton("Yes",new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int id) {
                        // if this button is clicked, close
                        // current activity
                        dialog.cancel();
                            /*chk = 1;
                            mScannerView.resumeCameraPreview(MainActivity.this);*/
                    }
                });
        spinnerProducts.setSelection(0);
        scan.setEnabled(false);
        if(!pushToDB.isEnabled()){
            pushToDB.setEnabled(true);
        }
        mScannerView.stopCamera();
        setContentView(R.layout.activity_main);
        //pbbar.setVisibility(View.GONE);
        ArrayAdapter NoCoreAdapter = new ArrayAdapter(MainActivity.this,android.R.layout.simple_spinner_item, data);
        NoCoreAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerProducts.setAdapter(NoCoreAdapter);

        AlertDialog alertDialog = builder.create();
        alertDialog.show();

    }
}

解决方法 1:

你需要保存 spinner 内某处的数据 onPause 方法。

@Override
protected void onPause(){
    Data data = spinner.getData(); //Implement your own logic
}

你什么时候回来 MainActivityonResume 调用,你必须将数据回 spinner

@Override
protected void onResume(){
    spinner.setData(data); //Implement your own logic
}

[编辑]

问题是,你使用的 setContentView() 多次是坏的做法。根据 Android 文档

设置 activity 内容以明确 view 。这 view 直接放到activity的 view 层次结构。

如果你想要达到你目前的希望,你应该使用fragment。

总之,不叫 setContentView() 多次。使用 fragment 来显示多个 xml 而无需更改 activity

赞助商