Skip to content
This repository was archived by the owner on Nov 30, 2021. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .idea/gradle.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions homework6/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/build
33 changes: 33 additions & 0 deletions homework6/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
apply plugin: 'com.android.application'

android {
compileSdkVersion 30
buildToolsVersion "30.0.2"

defaultConfig {
applicationId "com.example.homework6"
minSdkVersion 21
targetSdkVersion 30
versionCode 1
versionName "1.0"

testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}

dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'

}
21 changes: 21 additions & 0 deletions homework6/proguard-rules.pro
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html

# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}

# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable

# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package com.example.homework6;

import android.content.Context;

import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;

import org.junit.Test;
import org.junit.runner.RunWith;

import static org.junit.Assert.*;

/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.example.homework6", appContext.getPackageName());
}
}
28 changes: 28 additions & 0 deletions homework6/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.homework6">

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:permission="android.permission.WRITE_EXTERNAL_STORAGE"
android:theme="@style/AppTheme">

<activity android:name=".CheckActivity"></activity>
<activity android:name=".EditItem" />
<activity android:name=".SecondActivity" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>
32 changes: 32 additions & 0 deletions homework6/src/main/java/com/example/homework6/CheckActivity.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package com.example.homework6;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;

import androidx.appcompat.app.AppCompatActivity;

public class CheckActivity extends AppCompatActivity {
private CheckBox checkStorage;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check);

checkStorage = findViewById(R.id.checkStorage);

findViewById(R.id.backButton).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent backIntent = new Intent();
backIntent.putExtra("ISCHEKED", checkStorage.isChecked());
setResult(Activity.RESULT_OK, backIntent);
finish();
}
});
checkStorage.isChecked();
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

по-моему эта строчка лишняя. ты ничего не делаешь с результатом, который ты получаешь из checkStorage.isChecked();

}
}
40 changes: 40 additions & 0 deletions homework6/src/main/java/com/example/homework6/EditItem.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package com.example.homework6;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class EditItem extends AppCompatActivity {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не совсем удачное имя для класса.

  • Не понятно что это за компонент: активити, элемент списка и что-то еще
  • Лучше к таким классам приписывать слово Activtiy/
    Так вот лучше что-то типа EditTextActivity

EditText fileName;
EditText fileText;
int position;
Comment on lines +13 to +15
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

нет модификаторов доступа

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_item);

Intent intent = getIntent();
fileName = findViewById(R.id.fileName);
fileText = findViewById(R.id.fileText);
fileName.setText(intent.getStringExtra("NAME"));
fileText.setText(intent.getStringExtra("TEXT"));
position = intent.getIntExtra("POSITION", 0);
Comment on lines +21 to +26
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Тут как бы есть небольшая недоработка. Лично я бы передавал бы в эту активити путь к файлу и уже в ней читал бы файл, сохранял и так далее. В общем делал бы все что необходимо в рамках этой активити. Ну и собственно методы по работе с файлами лучше вынести в отдельный класс. Может тут как раз подойдут просто статические методы. Надо пробовать


findViewById(R.id.btnSave2).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent resultIntent = new Intent();
resultIntent.putExtra("NAMESAVE", fileName.getText().toString());
resultIntent.putExtra("TEXTSAVE", fileText.getText().toString());
resultIntent.putExtra("POSITIONSAVE", position);
setResult(Activity.RESULT_OK, resultIntent);
Comment on lines +31 to +35
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Если использовать чтение файла в этой активити, то можно и использовать сохранение файла

finish();
}
});
}
}
99 changes: 99 additions & 0 deletions homework6/src/main/java/com/example/homework6/MainActivity.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
package com.example.homework6;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
private EditText etText;
private EditText writeFileName;
private Button btnSave;
private ArrayList<File> fileArray;
private Button toSecondActivity;
private boolean isCheked;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

etText = (EditText) findViewById(R.id.etText);
writeFileName = findViewById(R.id.writeFileName);
btnSave = (Button) findViewById(R.id.btnSave);
fileArray = new ArrayList<>();
toSecondActivity = findViewById(R.id.toSecondActivity);


btnSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isCheked == false) {
try {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
openFileOutput(writeFileName.getText().toString(), MODE_PRIVATE)));
bw.write(etText.getText().toString());
Toast.makeText(MainActivity.this, "Файл \"" +
writeFileName.getText().toString() + "\" успешно сохранен во внутреннюю память", Toast.LENGTH_SHORT).show();
fileArray.add(new File(writeFileName.getText().toString()));
bw.close();

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else if (isCheked == true) {
File externalPath = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "MyFiles");
externalPath.mkdir();
File externalFile = new File(externalPath, writeFileName.getText().toString());
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(externalFile));
bw.write(etText.getText().toString());
Toast.makeText(MainActivity.this, "Файл \"" +
writeFileName.getText().toString() + "\" успешно сохранен во внешнюю память", Toast.LENGTH_SHORT).show();
fileArray.add(new File(writeFileName.getText().toString()));
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Comment on lines +48 to +78
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Если ты сравнишь код в блоке if и в блоке else if, то ты заметишь, что у тебя большая часть кода совпадает. Как минимум сама логика записи одна и та же. Значит этот код можно выделить в отдельный метод. Так как это работа с файлом, то этот мметод должен быть в другом классе.

});

toSecondActivity.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra(ArrayList.class.getSimpleName(), fileArray);
startActivityForResult(intent, 2000);
}
});
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if (requestCode == 2000 && resultCode == Activity.RESULT_OK && data != null) {
this.fileArray = (ArrayList<File>) data.getExtras().getSerializable(ArrayList.class.getSimpleName());
this.isCheked = data.getBooleanExtra("ISCHEKED", false);
}
super.onActivityResult(requestCode, resultCode, data);
}
}
Loading