Я все еще работаю над приложением сканнера штрих-кода и все еще борюсь с некоторыми проблемами. Пользователь этого приложения может выбрать файл Excel, который он хочет использовать в качестве базы данных, и он может выбрать файл, в который он хочет поместить данные, которые он отсканировал («Штрих-код») и что он напишет («Количество продукта»). Мои проблема в том, что мое приложение не записывает данные в выбранный Excel.
Итак, мои вопросы: 1. Как я могу решить проблему, что мое приложение не записывает данные в выбранный Excel? 2. Как я могу это сделать? -> Когда пользователь отсканировал «Штрих-код», он запускает функцию «ReadDatas» Java, когда отсканированные данные совпадают с «Базой данных», выбирают из той же строки другие данные ячейки столбца и помещают их в диалоговое окно.
Действия сканера Java:
public class ScanActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler {
private ZXingScannerView zXingScannerView;
public static String resultt;
public static WriteActivity writeActivity;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set the main content layout of the Activity
setContentView(R.layout.activity_barcode_scanner);
ViewGroup contentFrame = (ViewGroup) findViewById(R.id.content_frame);
zXingScannerView = new ZXingScannerView(this);
contentFrame.addView(zXingScannerView);
}
@Override
public void onResume() {
super.onResume();
zXingScannerView.setResultHandler(this);
zXingScannerView.startCamera();
}
@Override
public void onPause() {
super.onPause();
zXingScannerView.stopCamera();
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public void handleResult(Result rawResult) {
zXingScannerView.stopCamera();
Toast.makeText(this, "Contents = " + rawResult.getText() +
", Format = " + rawResult.getBarcodeFormat().toString(), Toast.LENGTH_SHORT).show();
ViewGroup viewGroup = findViewById(android.R.id.content);
View dialogView = LayoutInflater.from(this).inflate(R.layout.result_dialog, viewGroup, false);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(dialogView);
final AlertDialog dialog = builder.create();
Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawable(new ColorDrawable(Color.BLACK));
TextView myAwesomeTextView = (TextView) dialogView.findViewById(R.id.resultname);
myAwesomeTextView.setText(rawResult.getText());
setResultt(rawResult.getText());
dialog.show();
Button resultbutton = (Button) dialog.findViewById(R.id.resultbutton);
resultbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
writeActivity.WritingDatas();
} catch (IOException e) {
e.printStackTrace();
}
dialog.dismiss();
zXingScannerView.startCamera();
}
});
// Note:
// * Wait 2 seconds to resume the preview.
// * On older devices continuously stopping and resuming camera preview can result in freezing the app.
// * I don't know why this is the case but I don't have the time to figure out.
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
zXingScannerView.resumeCameraPreview(ScanActivity.this);
}
}, 2000);
}
public static void setResultt(String resultt) {
ScanActivity.resultt = resultt;
}
public static String getResultt() {
return resultt;
}
}
Второе действие Java
public class SecondActivity extends AppCompatActivity {
public static RelativeLayout relativeLayout;
public static Button buttonsecond;
public static Button opendatabase;
public static Button createnewdatabse;
public static Button openwritabledatabase;
public static String filePath;
public static String createdfilePath;
public static final int REQUEST_CODE = 10;
String[] permissionsall = {
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.CAMERA};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
relativeLayout = findViewById(R.id.activity_second);
relativeLayout.setBackgroundColor(Color.BLACK);
if(checkPermission()){
}else{
}
buttonsecond = findViewById(R.id.ScanBarcode);
buttonsecond.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(SecondActivity.this,ScanActivity.class));
}
});
opendatabase = findViewById(R.id.Opendatabase);
opendatabase.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new MaterialFilePicker()
.withActivity(SecondActivity.this)
.withRequestCode(1000)
.start();
}
});
createnewdatabse = findViewById(R.id.Createnewfile);
createnewdatabse.setOnClickListener(new View.OnClickListener() {
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public void onClick(View v) {
createnewFile();
}
});
openwritabledatabase = findViewById(R.id.Openwritable);
openwritabledatabase.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new MaterialFilePicker()
.withActivity(SecondActivity.this)
.withRequestCode(2000)
.start();
}
});
}
@Override
protected void onActivityResult(int Requestcode , int Result , Intent data){
super.onActivityResult(Requestcode,Result,data);
if(Requestcode == 1000 && Result == RESULT_OK){
String filePathh = data.getStringExtra(FilePickerActivity.RESULT_FILE_PATH);
setFilePath(filePathh);
Toast.makeText(SecondActivity.this, getFilePath(),
Toast.LENGTH_LONG).show();
}
if(Requestcode == 2000 && Result == RESULT_OK){
String writablepath = data.getStringExtra(FilePickerActivity.RESULT_FILE_PATH);
setCreatedfilePath(writablepath);
Toast.makeText(SecondActivity.this, getCreatedfilePath(),
Toast.LENGTH_LONG).show();
}
}
public boolean checkPermission(){
int result;
List<String> listPermissionisNeed = new ArrayList<>();
for(String permission : permissionsall ){
result = ContextCompat.checkSelfPermission(this,permission);
if(result != PackageManager.PERMISSION_GRANTED){
listPermissionisNeed.add(permission);
}
}
if (!listPermissionisNeed.isEmpty()){
ActivityCompat.requestPermissions(this,listPermissionisNeed.toArray(new String[listPermissionisNeed.size()]),REQUEST_CODE);
return false;
}
return true;
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,@NonNull int[] grantResults){
if(requestCode == REQUEST_CODE){
HashMap<String, Integer> permissionResults = new HashMap<>();
int deniedCOunt = 0;
for(int i=0; i<grantResults.length;i++){
if(grantResults[i] == PackageManager.PERMISSION_DENIED){
permissionResults.put(permissions[i],grantResults[i]);
deniedCOunt++;
}
}
if(deniedCOunt == 0)
{
}
else{
for(Map.Entry<String, Integer > entry : permissionResults.entrySet())
{
String permName = entry.getKey();
int permResult = entry.getValue();
if(ActivityCompat.shouldShowRequestPermissionRationale(this,permName)){
shownewDialog();
}else{
showsecondDialog();
}
}
}
}
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public void shownewDialog(){
ViewGroup viewGroup = findViewById(android.R.id.content);
View dialogView = LayoutInflater.from(this).inflate(R.layout.my_dialog, viewGroup, false);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(dialogView);
final AlertDialog dialog = builder.create();
Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawable(new ColorDrawable(Color.BLACK));
dialog.show();
Button dialogokbutton = (Button) dialog.findViewById(R.id.buttonOk);
dialogokbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
checkPermission();
}
});
Button dialogcancelbutton = (Button) dialog.findViewById(R.id.buttonCancel);
dialogcancelbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
showsecondDialog();
}
});
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public void showsecondDialog(){
ViewGroup viewGroup = findViewById(android.R.id.content);
View dialogView = LayoutInflater.from(this).inflate(R.layout.my_second_dialog, viewGroup, false);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(dialogView);
final AlertDialog dialog = builder.create();
Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawable(new ColorDrawable(Color.BLACK));
dialog.show();
Button dialogokbutton = (Button) dialog.findViewById(R.id.secondbuttonOk);
dialogokbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,Uri.fromParts("package",getPackageName(),null));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
Button dialogcancelbutton = (Button) dialog.findViewById(R.id.secondbuttonCancel);
dialogcancelbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
finish();
}
});
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public void createnewFile(){
ViewGroup viewGroup = findViewById(android.R.id.content);
View dialogView = LayoutInflater.from(this).inflate(R.layout.file_creator, viewGroup, false);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(dialogView);
final AlertDialog dialog = builder.create();
Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawable(new ColorDrawable(Color.BLACK));
dialog.show();
final EditText userInput = (EditText) dialog.findViewById(R.id.filecreatortext);
Button filecreatebutton = (Button) dialog.findViewById(R.id.filercreatorcreatebutton);
filecreatebutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Workbook wb=new HSSFWorkbook();
Cell cell=null;
CellStyle cellStyle=wb.createCellStyle();
cellStyle.setFillForegroundColor(HSSFColor.GREEN.index);
cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
Sheet sheet=null;
sheet = wb.createSheet("Products");
Row row =sheet.createRow(0);
cell=row.createCell(0);
cell.setCellValue("Product Name");
cell.setCellStyle(cellStyle);
cell=row.createCell(1);
cell.setCellValue("Barcodenumber");
cell.setCellStyle(cellStyle);
cell=row.createCell(2);
cell.setCellValue("Quantity");
cell.setCellStyle(cellStyle);
sheet.setColumnWidth(0,(10*200));
sheet.setColumnWidth(1,(10*200));
sheet.setColumnWidth(2,(10*200));
File file = new File(getExternalFilesDir(null),userInput.getText()+".xls");
FileOutputStream outputStream =null;
try {
outputStream=new FileOutputStream(file);
wb.write(outputStream);
Toast.makeText(SecondActivity.this,userInput.getText()+" File Created!",Toast.LENGTH_LONG).show();
} catch (java.io.IOException e) {
e.printStackTrace();
Toast.makeText(SecondActivity.this,"Couldn't create the file!",Toast.LENGTH_LONG).show();
try {
outputStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
dialog.dismiss();}
});
}
public void setFilePath(String filePath){
this.filePath = filePath;
}
public static String getFilePath(){
return filePath;
}
public void setCreatedfilePath(String createdfilePath){
this.createdfilePath = createdfilePath;
}
public static String getCreatedfilePath(){
return createdfilePath;
}
}
Чтение Java:
public class ReadActivity extends AppCompatActivity {
private static final String LOG_TAG = "";
public static String cellValue;
public static AssetManager assetManager;
public static HSSFWorkbook myWorkBook;
public static HSSFSheet mySheet;
public static HSSFRow myRow;
public static InputStream inputStream;
public void LoadingDatas() throws IOException {
inputStream = new FileInputStream(SecondActivity.getFilePath());
myWorkBook = new HSSFWorkbook(inputStream);
mySheet = myWorkBook.getSheetAt(0);
Iterator<Row> rowIter = mySheet.rowIterator();
while (rowIter.hasNext()) {
myRow = (HSSFRow) rowIter.next();
Iterator<Cell> cellIter = myRow.cellIterator();
while (cellIter.hasNext()) {
HSSFCell myCell = (HSSFCell) cellIter.next();
if (myCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
cellValue = myCell.getStringCellValue();
} else {
cellValue = String.valueOf(myCell.getNumericCellValue());
}
Log.v(LOG_TAG, cellValue);
}
}
}
}
Запишите Java:
public class WriteActivity extends AppCompatActivity {
public static AssetManager assetManager;
public static HSSFWorkbook myWorkBook;
public static HSSFSheet mySheet;
public static FileInputStream inputStream;
public void WritingDatas() throws IOException {
//inputStream = new FileInputStream(SecondActivity.getCreatedfilePath());
File myFile = new File(SecondActivity.getCreatedfilePath());
inputStream = new FileInputStream(myFile);
myWorkBook = new HSSFWorkbook(inputStream);
mySheet = myWorkBook.getSheetAt(0);
int num = mySheet.getLastRowNum();
Row row = mySheet.createRow(++num);
EditText text = (EditText)findViewById(R.id.resultnumber);
String value = text.getText().toString();
row.createCell(0).setCellValue(ScanActivity.getResultt());
row.createCell(1).setCellValue(value);
FileOutputStream fileOut =new FileOutputStream(myFile);
myWorkBook.write(fileOut);
inputStream.close();
myWorkBook.close();
fileOut.close();
}
}