сложение двух массивов полученых из 2 файлов
есть 2 кнопки по нажатию на которые читаю и обрабатываю файлы, на каждую кнопку свой файл. Для чтения и обработки на 2 кнопки, 1 метод для чтения и 1 метод для формирования массива. После чтения двух файлов нужно сложить 2 полученных массива, но метод сложения вызывается в методе формирования массива, а это происходит 2 раза поэтому массивы не складываются как решить эту проблему
private static String TAG = "myLog";
final String DIR_SD = "MyFiles";
final String FILENAME1 = "Appeals.txt";
final String FILENAME2 = "PKK.txt";
ArrayList <String> list;
private String [] otv;
private ArrayList <String> AppealsMass;
private ArrayList <String> PkkMass;
private int appealSiz;
private int pkkSiz;
private static final int PERMISSION_REQUEST_CODE = 123;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.btn);
Button btn_open = (Button) findViewById(R.id.btn_open);
btn_open.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (hasPermissions()){
String name = "Appeals";
readFileSD(FILENAME1, name);
// Log.d(TAG, "доступ получен");
}
else {
//our app doesn't have permissions, So i m requesting permissions.
requestPermissionWithRationale();
// Log.d(TAG, "доступ не получен");
}
}
});
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (hasPermissions()){
String name = "PKK";
readFileSD(FILENAME2, name);
//Log.d(TAG, "доступ получен");
}
else {
//our app doesn't have permissions, So i m requesting permissions.
requestPermissionWithRationale();
// Log.d(TAG, "доступ не получен");
}
}
});
}
private boolean hasPermissions(){
int res = 0;
//string array of permissions,
String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE};
for (String perms : permissions){
res = checkCallingOrSelfPermission(perms);
if (!(res == PackageManager.PERMISSION_GRANTED)){
return false;
}
}
return true;
}
private void requestPerms(){
String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
requestPermissions(permissions,PERMISSION_REQUEST_CODE);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
boolean allowed = true;
switch (requestCode){
case PERMISSION_REQUEST_CODE:
for (int res : grantResults){
// if user granted all permissions.
allowed = allowed && (res == PackageManager.PERMISSION_GRANTED);
}
break;
default:
// if user not granted permissions.
allowed = false;
break;
}
if (allowed){
//user granted all permissions we can perform our task.
// makeFolder();
// btnCheckUsbDevClick();
}
else {
// we will give warning to user that they haven't granted permissions.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)){
Toast.makeText(this, "Storage Permissions denied.", Toast.LENGTH_SHORT).show();
} else {
showNoStoragePermissionSnackbar();
}
}
}
}
public void showNoStoragePermissionSnackbar() {
Snackbar.make(MainActivity.this.findViewById(R.id.activity_view), "Storage permission isn't granted" , Snackbar.LENGTH_LONG)
.setAction("SETTINGS", new View.OnClickListener() {
@Override
public void onClick(View v) {
openApplicationSettings();
Toast.makeText(getApplicationContext(),
"Open Permissions and grant the Storage permission",
Toast.LENGTH_SHORT)
.show();
}
})
.show();
}
public void openApplicationSettings() {
Intent appSettingsIntent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.parse("package:" + getPackageName()));
startActivityForResult(appSettingsIntent, PERMISSION_REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PERMISSION_REQUEST_CODE) {
// makeFolder();
//btnCheckUsbDevClick();
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
public void requestPermissionWithRationale() {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
final String message = "Storage permission is needed to show files count";
Snackbar.make(MainActivity.this.findViewById(R.id.activity_view), message, Snackbar.LENGTH_LONG)
.setAction("GRANT", new View.OnClickListener() {
@Override
public void onClick(View v) {
requestPerms();
}
})
.show();
} else {
requestPerms();
}
}
void writeFileSD(String file, String type) {
// проверяем доступность SD
if (!Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
Log.d(TAG, "SD-карта не доступна: " + Environment.getExternalStorageState());
return;
}
// получаем путь к SD
File sdPath = Environment.getExternalStorageDirectory();
// добавляем свой каталог к пути
sdPath = new File(sdPath.getAbsolutePath() + "/" + DIR_SD);
// создаем каталог
sdPath.mkdirs();
// формируем объект File, который содержит путь к файлу
File sdFile = new File(sdPath, file);
try {
// открываем поток для записи
BufferedWriter bw = new BufferedWriter(new FileWriter(sdFile));
// пишем данные
bw.write("Содержимое файла на SD");
// закрываем поток
bw.close();
Log.d(TAG, "Файл записан на SD: " + sdFile.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
}
void readFileSD(String file, String type) {
// проверяем доступность SD
if (!Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
Log.d(TAG, "SD-карта не доступна: " + Environment.getExternalStorageState());
return;
}
// получаем путь к SD
File sdPath = Environment.getExternalStorageDirectory();
// добавляем свой каталог к пути
sdPath = new File(sdPath.getAbsolutePath() + "/" + DIR_SD);
// формируем объект File, который содержит путь к файлу
if(file == FILENAME1){
TextView Appeals = (TextView) findViewById(R.id.text_Appeals);
Appeals.setText(String.valueOf(sdPath) + "/" + type + ".txt");
}else {
TextView PKK = (TextView) findViewById(R.id.text_PKK);
PKK.setText(String.valueOf(sdPath) + "/" + type + ".txt");
}
File sdFile = new File(sdPath, file);
try {
// открываем поток для чтения
BufferedReader br = new BufferedReader(new FileReader(sdFile));
String str = "";
// читаем содержимое
list = new ArrayList<String>();
while ((str = br.readLine()) != null) {
// Log.d(TAG, str);
list.add(str);
}
// Log.d(TAG, "Прочитали : " + type);
fds(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void fds (String name){
int siz = list.size();
otv = new String[siz];
for(int i =0; i<siz; i++){
String [] fd = list.get(i).split("\t");
if(fd.length >= 2){
String [] ds = fd[1].split(";");
// Log.d(TAG, ds[0]+i);
// al.add(ds[0]);
otv [i] = ds[0];
}else {
// Log.d(TAG, fd[0]);
// al.add(fd[0]);
}
}
ArrayList <String> mass = new ArrayList<String>();
HashMap<String, Integer> wordToCount = new HashMap<>();
for (String word : otv)
{
if (!wordToCount.containsKey(word))
{
wordToCount.put(word, 0);
}
wordToCount.put(word, wordToCount.get(word) + 1);
}
for (String word : wordToCount.keySet())
{
mass.add(word + ":" + wordToCount.get(word));
}
int size = mass.size();
AppealsMass = new ArrayList<>();
PkkMass = new ArrayList<>();
if(name == FILENAME2){
TextView PKK_size = (TextView) findViewById(R.id.pkk_size);
PKK_size.setText(String.valueOf(siz));
pkkSiz = siz;
for(int i = 0; i<size; i++){
PkkMass.add(mass.get(i));
}
}else {
TextView Appeals_size = (TextView) findViewById(R.id.appeals_size);
Appeals_size.setText(String.valueOf(siz));
appealSiz = siz;
for(int i = 0; i<size; i++){
AppealsMass.add(mass.get(i));
}
}
TextView documents = (TextView) findViewById(R.id.documents_size);
documents.setText(String.valueOf(pkkSiz+appealSiz));
table_output();
}
public void table_output() {
int siz = AppealsMass.size();
for (int i = 0; i < siz; i++){
// Log.d(TAG, "ответственные Appeals : " + AppealsMass.get(i));
}
int siz2 = PkkMass.size();
for(int j = 0; j<siz2; j++){
//Log.d(TAG, "ответственные PKK : " + PkkMass.get(j));
}
ArrayList <String> listAB = (ArrayList<String>) ListUtils.union(PkkMass, AppealsMass);
int siz3 = listAB.size();
for(int k = 0; k<siz3;k++){
Log.d(TAG, "Общий массив : " + listAB.get(k));
}
Log.d(TAG, String.valueOf(listAB.size()));
}
}