Android - извлечение данных как многострочных (то есть с разрывами строк) из файла данных внутреннего хранилища - PullRequest
1 голос
/ 30 октября 2011

Я абсолютный новичок, когда дело доходит до кодирования Java и Android.Тем не менее, я пытаюсь собрать воедино простой блокнот и приложение.В основном это виджет, который отображает текст заметки в textView и действие, которое можно загрузить, нажав на виджет.В упражнении у меня есть EditText и две кнопки - одна для сохранения текста заметки и одна для отмены и закрытия занятия.

Примером текста заметки, введенного в EditText, может быть:

Купить молокоПоцелуй подругуBother Snape

Когда я сохраняю данные заметок из действия, они сохраняют мои данные заметок во внутреннем файле хранения.Затем он обновляет виджет, и здесь мой текст заметки отображается с переносами строк.Но если я затем открываю свою деятельность для редактирования текста, он загружает текст заметки в виде однострочного файла, а не многострочного файла.

У кого-нибудь из вас есть предложения, что я могу сделать, чтобы загрузить мою заметку?-данные в виде многострочного текста с переносами строк?

Вот мой код активности:

package dk.mfoller.android.basicnote;

import android.app.Activity;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RemoteViews;
import android.widget.Toast;
import android.widget.EditText;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;

import java.io.*;

public class BasicNoteActivity extends Activity {
/** Called when the activity is first created. */
private Button saveBtn;
private Button cancelBtn;
private EditText inputTxt;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // Defines objects
    saveBtn = (Button) findViewById(R.id.basicNoteActivity_save); 
    cancelBtn = (Button) findViewById(R.id.basicNoteActivity_cancel);
    inputTxt = (EditText) findViewById(R.id.basicNoteActivity_input);

    // Calls a function to update/replace the displayed note text
    readNoteData();

    // Creates event handler for the save-button
    saveBtn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // Calls a function to write to a file
            writeToFile();

            // Updates the displayed text in the widget
            String noteinput = inputTxt.getText().toString();
            RemoteViews views = new RemoteViews("dk.mfoller.android.basicnote", R.drawable.main_widget);
            views.setTextViewText(R.id.basicNoteWidget_notetext, noteinput);
            // Updates the actual widget - NOTE: This updates ALL instances of the widget
            ComponentName cn = new ComponentName(getBaseContext(), BasicNoteWidget.class);
            AppWidgetManager.getInstance(getBaseContext()).updateAppWidget(cn, views);


        }
    });

    // Creates event handler for the cancel-button
    cancelBtn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            finish();
        }
    });

}

// A function to write to a file
protected void writeToFile() {
    String FILENAME = "basicNote_data";
    String noteinput = inputTxt.getText().toString();

    try {
        FileOutputStream fos = openFileOutput(FILENAME, MODE_PRIVATE);
        //noteinput.replace("\\r", "\n");
        fos.write(noteinput.getBytes());
        fos.close();

        // Displays a popup
        Toast.makeText(this, "Note saved!", Toast.LENGTH_SHORT).show();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

// A function to read from a file on load
protected void readNoteData() {
    String FILENAME = "basicNote_data";

    try {
        FileInputStream fis = openFileInput(FILENAME);
        InputStreamReader isr = new InputStreamReader(fis);
        BufferedReader br = new BufferedReader(isr);

        // How do I make this load as multiline text?!?!
        String line = null;
        String output = "";

        while((line = br.readLine()) != null) {
            output += line;
        }
        // Updates/replaces the displayed note text
        if(output != "") {
            inputTxt.setText(output);
        }
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

}

Заранее спасибо!.. о, и, пожалуйста, будьте очень конкретны.Как я уже сказал: я полный новичок:)

1 Ответ

1 голос
/ 30 октября 2011

readLine() вызов не включает символы конца строки.

Самое быстрое решение - изменить цикл чтения в readNoteData:

while((line = br.readLine()) != null) {
    output += line + "\n";
}

Вы также можете просто прочитать весь файл и пропустить этот шаг, но сначала запустите его.

См. Информацию в документах BufferedReader.readLine () .

...