我是安卓的初学者.我将 QR 扫描仪集成到我的应用程序中,但我想拆分字符串并加载到共享首选项



在我的应用程序中,我集成了qr扫描仪。在我的应用程序活动中,我正在使用OnActivity结果方法来显示扫描结果。我正在扫描ABCDEFGH..但我想使用 OnActivityResult 方法将 ABCDEFGH 拆分为两个字符串。将这两个字符串加载到共享首选项。.谁能帮我..下面是我的代码

  @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, 
        data);
                if (scanResult != null) {
                    Toast.makeText(this, " " + scanResult.getContents(), Toast.LENGTH_LONG).show();
                    }
                else
                {
                     Log.d("ScanFragment", "Cancelled scan");
                    Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
                            }

            // This is important, otherwise the result will not be passed to the fragment
                            super.onActivityResult(requestCode, resultCode, data);
                        }

@Override

public void onActivityResult(int requestCode, int resultCode, Intent data) {
       IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
    if (scanResult != null) {
        String part1 = scanResult.getContents().substring(0, 10),
                part2 = scanResult.getContents().substring(4);
        //  System.out.println(" ");
        Toast.makeText(getActivity(), " " + scanResult.getContents(), Toast.LENGTH_LONG).show();
        setCustomerSerialName(part1.toString(), part2.toString());
    } else {
        Log.d("ScanFragment", "Cancelled scan");
        Toast.makeText(getActivity(), "Cancelled", Toast.LENGTH_LONG).show();

    }

    // This is important, otherwise the result will not be passed to the fragment
    super.onActivityResult(requestCode, resultCode, data);
}
private void setCustomerSerialName(String cusSno, String passcode) {
    String customerSNo = IHomeActivity._sharedPreferences.getString("customerSNo", "null");
    Editor editor = IHomeActivity._sharedPreferences.edit();
    editor.putString("customerSNo", cusSno);
    editor.putString("customerPass", passcode);
    if (customerSNo.equals(cusSno)) {
    } else {
        editor.putBoolean("custSNoAuthStatus", false);
    }
    editor.commit();
}

将字符串分成几部分

我想使用 OnActivityResult 方法将 ABCDEFGH 拆分为两个字符串

根据您要拆分此字符串的内容。

  • 如果你在String中有任何特殊字符,那么你可以使用string.split(",")方法来完成(这里,被认为是特殊字符,必须存在于string命名变量中)。

  • 如果您知道必须从多长的长度划分此字符串,则可以使用 string.substring(startIndex, endIndex) 作为第一部分,string.substring(endIndex + 1)作为另一部分来执行此操作。

将字符串存储到SharedPreferences

然后您可以使用如下所示SharedPreferences.Editor将其存储到SharedPreferences

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("part1", part1);
editor.putString("part2", part2);
editor.apply();
String CurrentString = "ABCD,EFGH";
String[] separated = CurrentString.split(",");

separated[0];//这将包含"ABCD"

separated[1];//这将包含"EFGH"

最新更新