0

Работаю в Android Studio, надо написать приложение. Но, оно вылетает без какой либо ошибки. Задача приложения: во втором активити вводим код коробки (их может быть несколько) и содержимое. В первом вводим код уже сохраненной коробки и получаем её содержимое.

Xml код первого активити:

"<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.mrfair.homesklad.MainActivity">

    <Button
        android:id="@+id/button2"
        android:layout_width="373dp"
        android:layout_height="70dp"
        android:layout_marginRight="16dp"
        android:layout_marginTop="16dp"
        android:onClick="toAc2"
        android:text="изменить содержимое коробки"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="364dp"
        android:layout_height="0dp"
        android:layout_marginBottom="6dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button7"
        app:layout_constraintVertical_bias="1.0" />

    <EditText
        android:id="@+id/editText"
        android:layout_width="192dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="77dp"
        android:layout_marginTop="150dp"
        android:ems="10"
        android:hint="Введите код коробки"
        android:inputType="number"
        app:layout_constraintBottom_toTopOf="@+id/textView"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button7"
        android:layout_width="wrap_content"
        android:layout_height="61dp"
        android:layout_marginBottom="31dp"
        android:layout_marginTop="206dp"
        android:onClick="readFile"
        android:text="Показать содержимое коробки"
        app:layout_constraintBottom_toTopOf="@+id/textView"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>" 

Второго активити:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.mrfair.homesklad.SecondActivity">

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="4dp"
        android:layout_marginTop="4dp"
        android:onClick="toAc1"
        android:text="Назад"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="54dp"
        android:onClick="writefile"
        android:text="Изменить"
        android:visibility="visible"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="59dp"
        android:ems="10"
        android:hint="Код коробки"
        android:inputType="number"
        app:layout_constraintHorizontal_bias="0.502"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button3" />

    <EditText
        android:id="@+id/editText3"
        android:layout_width="329dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="168dp"
        android:ems="10"
        android:inputType="textPersonName"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent" />
</android.support.constraint.ConstraintLayout>

Java код первого активити:

package com.example.mrfair.homesklad;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    public static SharedPreferences sPref;
    EditText code = (EditText)findViewById(R.id.editText);
    TextView content = (TextView)findViewById(R.id.textView);
    final String codetext = code.getText().toString();

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

    public void toAc2 (View v) {
        Intent intent = new Intent(this, SecondActivity.class);
        startActivity(intent);
    }

    public void readFile (View v) {
        sPref = getPreferences(MODE_PRIVATE);
        String saved_text = sPref.getString(codetext, "");
        content.setText(saved_text);
    }
}

Второго:

package com.example.mrfair.homesklad;

import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class SecondActivity extends AppCompatActivity {

    EditText code = (EditText)findViewById(R.id.editText2);
    EditText content = (EditText)findViewById(R.id.editText3);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
    }
    public void toAc1 (View v) {
       Intent intent = new Intent(this, MainActivity.class);
       startActivity(intent);

    }
    public void writefile (View v){
        String codetext = code.getText().toString();
        String conttext = content.getText().toString();
        MainActivity.sPref = getPreferences(MODE_PRIVATE);
        SharedPreferences.Editor et = MainActivity.sPref.edit();
        et.putString(codetext, conttext);
        et.apply();
    }

}

Манифест:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mrfair.homesklad">

    <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=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".SecondActivity">
            <intent-filter>
                <action android:name="com.example.mrfair.homesklad.SecondActivity" />

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

</manifest>

Логи при запуске в .txt файле: https://drive.google.com/open?id=1_8ED-kfzXq5FkBBS7jhc3xiW99aKDtVD

Чего ему надо?

4
  • После чего вылетает?
    – iramm
    9 янв 2018 в 12:03
  • после запуска, не открываясь вылетает, пишет "<имя приложения> has stopped"
    – Ermine
    9 янв 2018 в 12:13
  • После чего? Опишите пожалуйста тесткейс. Что открывалось-нажималось?
    – iramm
    9 янв 2018 в 12:15
  • последовательность действий: 1 запускаю через кнопку run, 2 загружается эмулятор, 3 появляется окно с надписью "<имя приложения> has stopped" и кнопкой "open app again", 4 при нажатии на неё через 1 секунду появляется такое-же окно, но с кнопкой "close app"
    – Ermine
    9 янв 2018 в 12:16

1 ответ 1

1

Попробуйте вызывать команды:

EditText code = (EditText)findViewById(R.id.editText);
TextView content = (TextView)findViewById(R.id.textView);
final String codetext = code.getText().toString();

в методе onCreate() после вызова setContentView(R.layout.activity_main). То же относится и ко второй активности.

6
  • Но тогда я не могу их использовать в методе readfile, или использовать public?
    – Ermine
    9 янв 2018 в 12:25
  • в Java есть такие поля класса. Инициализируете в onCreate(), используете в любом методе класса
    – pavlofff
    9 янв 2018 в 12:27
  • 1
    Оставьте описание полей там же, где раньше. Например, EditText code; а назначайте им значения в onCreate() так: code=(EditText)findViewById(R.id.editText); Тогда к переменной code можно обращаться в любом месте класса.
    – iramm
    9 янв 2018 в 12:28
  • спасибо, перестало вылетать, но не могли бы вы сказать почему оно может не работать как я описал в задаче? И как проверить, сохранились ли preferenses, или нет?
    – Ermine
    9 янв 2018 в 12:39
  • @MrFair61 прочитайте этот ответ, чтобы понять, почему не может работать, как вы написали в вопросе. Насчет преференсов, если у вас другая проблема, создайте другой вопрос с этой проблемой. Не надо в комментриях обсуждать проблемы, не относящиеся к проблеме в вопросе
    – pavlofff
    9 янв 2018 в 12:45

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.