Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > IT форум > Помощь студентам
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 26.04.2018, 14:17   #1
JenquoA
Новичок
Джуниор
 
Регистрация: 26.04.2018
Сообщений: 1
Печаль приложение не сохраняет данные

Добрый день хочу спросить, почему у меня не происходит сохранение данных в приложении, все перепробовал не получается.
Вот код :
Main.java
Код:
package com.example.diplom;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.support.v7.app.AlertDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;

public class Main extends AppCompatActivity{
    public EditText editText;
    public String filename = null;
    private String path = Environment.getExternalStorageDirectory().toString()+"/files/";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        editText = (EditText) findViewById(R.id.editText);
    }
    @Override
    protected void onResume() {
        super.onResume();
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

        float fSize = Float.parseFloat(sharedPreferences.getString(getString(R.string.pref_size),"20"));
        editText.setTextSize(fSize);

        String regular = sharedPreferences.getString(getString(R.string.pref_style),"");
        int typeface = Typeface.NORMAL;

        if(regular.contains("Полужирный"))
            typeface += Typeface.BOLD;

        if(regular.contains("Курсив"))
            typeface += Typeface.ITALIC;

        editText.setTypeface(null, typeface);


        int color = Color.BLACK;
        if(sharedPreferences.getBoolean(getString(R.string.pref_color_red), false))
            color += Color.RED;

        if(sharedPreferences.getBoolean(getString(R.string.pref_color_green), false))
            color += Color.GREEN;

        if(sharedPreferences.getBoolean(getString(R.string.pref_color_blue), false))
            color += Color.BLUE;

        editText.setTextColor(color);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_clear:
                editText.setText("");
                Toast.makeText(getApplicationContext(), "Очищено", Toast.LENGTH_SHORT).show();
                return true;
            case R.id.action_open:
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("имя файла");
                builder.setMessage("Введите имя файла для открытия");
                final EditText input = new EditText(this);
                builder.setView(input);
                builder.setPositiveButton("Открыть", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        editText.setText("");
                        String value = input.getText().toString();
                        filename = value;
                        File file = new File(path+ filename);
                        if(file.exists()&& file.isFile()){
                            editText.setText(openFile(filename));
                        } else{
                            Toast.makeText(Main.this,"Файла не существует", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
                builder.show();
                return true;
                case R.id.action_save:
                AlertDialog.Builder alert = new AlertDialog.Builder(this);
                alert.setTitle("Имя файла");
                alert.setMessage("Введите имя файла для сохранения");
                final EditText input2 = new EditText(this);
                alert.setView(input2);
                alert.setPositiveButton("Сохранить", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    String value = input2.getText().toString();
                    filename = value;
                    saveFile(filename, editText.getText().toString());
                    }
                });
                alert.setNegativeButton("Отмена", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(Main.this,"Вы нажали отмена", Toast.LENGTH_SHORT).show();
                    }
                });
                 alert.show();
                return true;
              case R.id.action_settings:
                  Intent i = new Intent(Main.this,SettingsActivity.class);
                  startActivity(i);
        }
            return super.onOptionsItemSelected(item);
        }
        private void saveFile (String filename, String body) {
        try {
            File root = new File(this.path);
            if(!root.exists()){
                root.mkdirs();
            }
            File file = new File(root, filename);
            FileWriter writer = new FileWriter(file);
            writer.append(body);
            writer.flush();
            writer.close();
            Toast.makeText(Main.this,"Сохранено", Toast.LENGTH_SHORT).show();

        } catch (Exception e){
            e.printStackTrace();
        }
    }

        private String openFile(String filename){
        StringBuilder text = new StringBuilder();
        try{
            File file = new File(this.path, filename);
            BufferedReader br = new BufferedReader(new FileReader(file));
            String line;
            while ((line= br.readLine())!=null){
                text.append(line + "\n");

            }
        } catch (Exception e){
            e.printStackTrace();
        }
        return  text.toString();
        }
}
Вот манифест
Код:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.diplom">
    <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:theme="@style/AppTheme">
        <activity android:name=".Main">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".SettingsActivity">
        </activity>
    </application>
</manifest>

_____
Код программы нужно выделять (форматировать) тегами [CODE] (читать FAQ)
Модератор

Последний раз редактировалось Serge_Bliznykov; 26.04.2018 в 14:19.
JenquoA вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц

Опции темы Поиск в этой теме
Поиск в этой теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
не сохраняет данные с формы в таблицу vasya2704 Microsoft Office Access 1 15.06.2011 09:41
Не сохраняет данные в mysql GreenShuller БД в Delphi 0 27.06.2010 22:37
Скрипт не сохраняет данные Meta2 Microsoft Office Excel 6 28.10.2009 02:55
Не сохраняет данные в таблицу liienna БД в Delphi 18 02.04.2009 15:32
Не сохраняет данные в таблицу! frai БД в Delphi 14 15.09.2007 18:58