Adding multiple items to a listview with each item received from another intent on a button click

huangapple go评论66阅读模式
英文:

Adding multiple items to a listview with each item received from another intent on a button click

问题

I'm creating a birthday reminder application, where the app starts on the main activity, goes to a new activity using intent and there the person selects the birthday, and the selected birth day, month and year is returned back to the main activity.
Then in the main activity I've created a new button which retrieves all the information sent by the bday picker activity and tries to display it in a list activity every time I press a button.

The problem I'm facing is if once I run the app, the birthday gets recorded and is shown in the ListView, but if I add another Birthday and try to display it in the ListView, the previous record is removed and I'm left with only the present record.

What I exactly want to know is how can I add items in my ListView so that all my previous birthdays are shown as well.

The code File Provided is as Follows:

activity_main.xml

<!-- ... (layout XML content) ... -->

MainActivity.java

// ... (Java code content) ...

activity_addinglist.xml

<!-- ... (layout XML content) ... -->

addinglist.java

// ... (Java code content) ...

Thanks in advance for taking out time to solve this query.

英文:

I'm creating a birthday reminder application, where the app starts on the main activity, goes to a new activity using intent and there the person selects the birthday, and the selected birth day, month and year is returned back to the main activity.
Then in the main activity I've created a new button which retrieves all the information sent by the bday picker activity and tries to display it in a list activity every time I press a button.

The problem I'm facing is if once I run the app, the birthday gets recorded and is shown in the listview, but if I add another Birthday and try to display it in the listview,the previous record is removed and I'm left with only the present record.

What I exactly want to know is how can I add items in my listView so that all my previous birthdays are shown as well.

The code File Provided is as Follows:
activity_main.xml

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
    xmlns:tools=&quot;http://schemas.android.com/tools&quot;
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;match_parent&quot;
    android:orientation=&quot;vertical&quot;
    android:weightSum=&quot;10&quot;
    tools:context=&quot;.MainActivity&quot;&gt;

    &lt;androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;0px&quot;
        android:layout_weight=&quot;1&quot;
        android:background=&quot;#97B252D5&quot;&gt;

        &lt;TextView
            android:id=&quot;@+id/editText&quot;
            android:layout_width=&quot;213dp&quot;
            android:layout_height=&quot;52dp&quot;
            android:ems=&quot;10&quot;
            android:fontFamily=&quot;sans-serif-black&quot;
            android:text=&quot;Remindro&quot;
            android:textAllCaps=&quot;true&quot;
            android:textAppearance=&quot;@style/TextAppearance.AppCompat.Large&quot;
            android:textSize=&quot;36sp&quot;
            android:textStyle=&quot;bold|italic&quot;
            app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
            app:layout_constraintEnd_toEndOf=&quot;parent&quot;
            app:layout_constraintHorizontal_bias=&quot;0.067&quot;
            app:layout_constraintStart_toStartOf=&quot;parent&quot;
            app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;

        &lt;Button
            android:id=&quot;@+id/newEntry&quot;
            android:layout_width=&quot;wrap_content&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:background=&quot;#C1E6E60F&quot;
            android:fontFamily=&quot;sans-serif-black&quot;
            android:onClick=&quot;addNewEntry&quot;
            android:text=&quot;+ADD&quot;
            android:textAppearance=&quot;@style/TextAppearance.AppCompat.Large&quot;
            android:textSize=&quot;30sp&quot;
            app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
            app:layout_constraintEnd_toEndOf=&quot;parent&quot;
            app:layout_constraintHorizontal_bias=&quot;0.88&quot;
            app:layout_constraintStart_toEndOf=&quot;@+id/editText&quot;
            app:layout_constraintTop_toTopOf=&quot;parent&quot;
            app:layout_constraintVertical_bias=&quot;0.48&quot; /&gt;
    &lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;

    &lt;androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;0px&quot;
        android:layout_weight=&quot;9&quot;
        android:background=&quot;#A071D4ED&quot;&gt;


        &lt;ListView
            android:id=&quot;@+id/list&quot;
            android:layout_width=&quot;410dp&quot;
            android:layout_height=&quot;596dp&quot;
            app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
            app:layout_constraintEnd_toEndOf=&quot;parent&quot;
            app:layout_constraintHorizontal_bias=&quot;0.0&quot;
            app:layout_constraintStart_toStartOf=&quot;parent&quot;
            app:layout_constraintTop_toBottomOf=&quot;@+id/viewRecord&quot;
            app:layout_constraintVertical_bias=&quot;0.0&quot; /&gt;

        &lt;Button
            android:id=&quot;@+id/viewRecord&quot;
            android:layout_width=&quot;0dp&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:layout_marginTop=&quot;16dp&quot;
            android:background=&quot;#9650EC31&quot;
            android:onClick=&quot;viewRecord&quot;
            android:text=&quot;View Record&quot;
            android:textAppearance=&quot;@style/TextAppearance.AppCompat.Large&quot;
            android:textStyle=&quot;bold&quot;
            app:layout_constraintBottom_toTopOf=&quot;@+id/_dynamic&quot;
            app:layout_constraintEnd_toEndOf=&quot;parent&quot;
            app:layout_constraintHorizontal_bias=&quot;0.0&quot;
            app:layout_constraintStart_toStartOf=&quot;parent&quot;
            app:layout_constraintTop_toTopOf=&quot;parent&quot;
            app:layout_constraintVertical_bias=&quot;0.0&quot; /&gt;
    &lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;
&lt;/LinearLayout&gt;

Code file for : MainActivity.java

package com.example.remindro;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.Calendar;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = &quot;&quot;;

    ArrayList&lt;String&gt; listItems = new ArrayList&lt;String&gt;();

    ArrayAdapter&lt;String&gt; adapter;

    Calendar calendar = Calendar.getInstance();
    int thisYear = calendar.get(Calendar.YEAR);
    int thisMonth = calendar.get(Calendar.MONTH) + 1;
    int thisDay = calendar.get(Calendar.DAY_OF_MONTH);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        adapter=new ArrayAdapter&lt;String&gt;(this,
                android.R.layout.simple_list_item_1,
                listItems);
        ListView records = (ListView) findViewById(R.id.list);
        records.setAdapter(adapter);
    }

    public void addNewEntry(View v)
    {
        Intent adding = new Intent();
        adding.setClass(this,addinglist.class);
        startActivity(adding);
        finish();

    }
    public void viewRecord(View v)
    {
        Intent receiver = getIntent();
        int day = receiver.getIntExtra(&quot;day&quot;,0);
        int month = receiver.getIntExtra(&quot;month&quot;,0);
        int year = receiver.getIntExtra(&quot;year&quot;,0);
        String name = receiver.getStringExtra(&quot;nameofperson&quot;);
        String choice = receiver.getStringExtra(&quot;radio&quot;);
        String mss = name + &quot; has his &quot; + choice + &quot; on &quot; + day + &quot;/&quot; + month + &quot;/&quot; + year;
        //Toast.makeText(getApplicationContext(),mss,Toast.LENGTH_LONG).show();

        int age = thisYear - year;
        calendar.set(thisYear,thisMonth,thisDay);
        Calendar calendar1 = Calendar.getInstance();
        calendar1.set(thisYear,month,day);

        long milliseconds1 = calendar.getTimeInMillis();
        long milliseconds2 = calendar1.getTimeInMillis();
        long diff = milliseconds2 - milliseconds1;
        int noOfDays = (int) (diff / (24 * 60 * 60 * 1000));
        String msg2 = &quot;Turning &quot; + age + &quot; in &quot; + noOfDays + &quot;days!!&quot;;
//        Toast.makeText(getApplicationContext(),msg2,Toast.LENGTH_LONG).show();


        String finalMsg = mss + &quot; &quot; + msg2;
        listItems.add(finalMsg);
        adapter.notifyDataSetChanged();
    }
}

activity_addinglist.xml

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
    xmlns:tools=&quot;http://schemas.android.com/tools&quot;
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;match_parent&quot;
    android:background=&quot;#8AEC9F18&quot;
    tools:context=&quot;.addinglist&quot;&gt;

    &lt;NumberPicker
        android:id=&quot;@+id/day&quot;
        android:layout_width=&quot;97dp&quot;
        android:layout_height=&quot;131dp&quot;
        android:background=&quot;#B5EA1241&quot;
        android:scaleX=&quot;1.3&quot;
        android:scaleY=&quot;1.3&quot;
        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
        app:layout_constraintStart_toStartOf=&quot;parent&quot;
        app:layout_constraintTop_toTopOf=&quot;parent&quot;
        app:layout_constraintVertical_bias=&quot;0.298&quot;&gt;

    &lt;/NumberPicker&gt;

    &lt;NumberPicker
        android:id=&quot;@+id/month&quot;
        android:layout_width=&quot;97dp&quot;
        android:layout_height=&quot;131dp&quot;
        android:layout_marginStart=&quot;60dp&quot;
        android:layout_marginLeft=&quot;60dp&quot;
        android:background=&quot;#B5EA1241&quot;
        android:scaleX=&quot;1.3&quot;
        android:scaleY=&quot;1.3&quot;
        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
        app:layout_constraintStart_toEndOf=&quot;@+id/day&quot;
        app:layout_constraintTop_toTopOf=&quot;parent&quot;
        app:layout_constraintVertical_bias=&quot;0.298&quot;&gt;

    &lt;/NumberPicker&gt;

    &lt;NumberPicker
        android:id=&quot;@+id/year&quot;
        android:layout_width=&quot;97dp&quot;
        android:layout_height=&quot;131dp&quot;
        android:layout_marginStart=&quot;56dp&quot;
        android:layout_marginLeft=&quot;56dp&quot;
        android:background=&quot;#B5EA1241&quot;
        android:scaleX=&quot;1.3&quot;
        android:scaleY=&quot;1.3&quot;
        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
        app:layout_constraintStart_toEndOf=&quot;@+id/month&quot;
        app:layout_constraintTop_toTopOf=&quot;parent&quot;
        app:layout_constraintVertical_bias=&quot;0.298&quot;&gt;

    &lt;/NumberPicker&gt;

    &lt;Button
        android:id=&quot;@+id/submit&quot;
        android:layout_width=&quot;121dp&quot;
        android:layout_height=&quot;59dp&quot;
        android:layout_marginBottom=&quot;156dp&quot;
        android:background=&quot;#9A7CEF46&quot;
        android:onClick=&quot;addingEvent&quot;
        android:text=&quot;ADD Event&quot;
        android:textAppearance=&quot;@style/TextAppearance.AppCompat.Large&quot;
        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
        app:layout_constraintEnd_toEndOf=&quot;parent&quot;
        app:layout_constraintStart_toStartOf=&quot;parent&quot; /&gt;

    &lt;RadioGroup
        android:id=&quot;@+id/typer&quot;
        android:layout_width=&quot;384dp&quot;
        android:layout_height=&quot;88dp&quot;
        app:layout_constraintBottom_toTopOf=&quot;@+id/submit&quot;
        app:layout_constraintEnd_toEndOf=&quot;parent&quot;
        app:layout_constraintHorizontal_bias=&quot;0.407&quot;
        app:layout_constraintStart_toStartOf=&quot;parent&quot;
        app:layout_constraintTop_toBottomOf=&quot;@+id/month&quot;
        app:layout_constraintVertical_bias=&quot;0.666&quot;&gt;

        &lt;RadioButton
            android:id=&quot;@+id/birthday&quot;
            android:layout_width=&quot;match_parent&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:text=&quot;Birthday&quot;
            android:textAppearance=&quot;@style/TextAppearance.AppCompat.Large&quot; /&gt;

        &lt;RadioButton
            android:id=&quot;@+id/anniversary&quot;
            android:layout_width=&quot;match_parent&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:text=&quot;Anniversary&quot;
            android:textAppearance=&quot;@style/TextAppearance.AppCompat.Large&quot; /&gt;
    &lt;/RadioGroup&gt;

    &lt;EditText
        android:id=&quot;@+id/name&quot;
        android:layout_width=&quot;413dp&quot;
        android:layout_height=&quot;53dp&quot;
        android:textAppearance=&quot;@style/TextAppearance.AppCompat.Large&quot;
        android:hint=&quot;Enter the Name of the Person&quot;
        app:layout_constraintBottom_toTopOf=&quot;@+id/month&quot;
        app:layout_constraintEnd_toEndOf=&quot;parent&quot;
        app:layout_constraintHorizontal_bias=&quot;0.045&quot;
        app:layout_constraintStart_toStartOf=&quot;parent&quot;
        app:layout_constraintTop_toTopOf=&quot;parent&quot;
        app:layout_constraintVertical_bias=&quot;0.475&quot; /&gt;

    &lt;EditText
        android:id=&quot;@+id/resultshower&quot;
        android:layout_width=&quot;412dp&quot;
        android:layout_height=&quot;95dp&quot;
        android:textAppearance=&quot;@style/TextAppearance.AppCompat.Large&quot;
        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
        app:layout_constraintEnd_toEndOf=&quot;parent&quot;
        app:layout_constraintHorizontal_bias=&quot;0.045&quot;
        app:layout_constraintStart_toStartOf=&quot;parent&quot;
        app:layout_constraintTop_toBottomOf=&quot;@+id/submit&quot;
        app:layout_constraintVertical_bias=&quot;0.518&quot; /&gt;

&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;

and addinglist.java


import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.NumberPicker;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Switch;

public class addinglist extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addinglist);
        NumberPicker day = (NumberPicker) findViewById(R.id.day);
        NumberPicker month = (NumberPicker) findViewById((R.id.month));
        NumberPicker year = (NumberPicker) findViewById(R.id.year);
        day.setMinValue(1);
        day.setMaxValue(31);
        month.setMinValue(1);
        month.setMaxValue(12);
        year.setMinValue(1950);
        year.setMaxValue(2020);
    }

    public void addingEvent(View v)
    {
        String name;
        EditText nameEntered = (EditText) findViewById(R.id.name);
        name = nameEntered.getText().toString();
        NumberPicker day = (NumberPicker) findViewById(R.id.day);
        NumberPicker month = (NumberPicker) findViewById((R.id.month));
        NumberPicker year = (NumberPicker) findViewById(R.id.year);
        int day1 = day.getValue();
        int month1 = month.getValue();
        int year1 = year.getValue();
        RadioGroup typer = (RadioGroup) findViewById(R.id.typer);
        int selectedId = typer.getCheckedRadioButtonId();
        RadioButton checked = (RadioButton) findViewById(selectedId);
        String typee = checked.getText().toString();
        EditText resultbox = (EditText) findViewById(R.id.resultshower);
        String Finalmsg = name + &quot; has his &quot; + typee + &quot; on &quot; + day1 + &quot;/&quot; + month1 + &quot;/&quot; + year1;
        resultbox.setText(Finalmsg);
        Intent newintent = new Intent();
        newintent.putExtra(&quot;nameofperson&quot;,name);
        newintent.putExtra(&quot;day&quot;,day1);
        newintent.putExtra(&quot;month&quot;,month1);
        newintent.putExtra(&quot;year&quot;,year1);
        newintent.putExtra(&quot;radio&quot;,typee);
        newintent.setClass(this,MainActivity.class);
        startActivity(newintent);
    }
}

Thanks in advance for taking out time to solve this query.

答案1

得分: 1

以下是翻译好的部分:

要从一个活动中获取结果,您应该使用 startActivityForResult()onActivityResult() API,而不是使用 startActivity()

您可以从教程点提供的简单示例中学习:https://www.tutorialspoint.com/how-to-manage-startactivityforresult-on-android

但是,最新的 Android 开发者文档建议我们使用新的 Activity Result APIs 进行操作。

要学习更多,请参阅 Google 的文档:https://developer.android.com/training/basics/intents/result

以及 Wajahat Karim 的这篇文章:https://wajahatkarim.com/2020/05/activity-results-api-onactivityresult/

我将使用这种新的 Activity Result API 来回答您的问题。

首先,您必须将 AndroidX 的 ActivityFragment 库添加为依赖。

app/build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"

    defaultConfig {
        applicationId "com.lakindu.birthdayreminder"
        minSdkVersion 14
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

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

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

    // 参考 1: https://developer.android.com/training/basics/intents/result
    // 参考 2: https://wajahatkarim.com/2020/05/activity-results-api-onactivityresult/
    implementation 'androidx.activity:activity:1.2.0-alpha04'
    implementation 'androidx.fragment:fragment:1.3.0-alpha04'
}

我将从 addinglist 活动发送一个 Parcelable 对象到 MainActivity 作为结果。

这是 Event 类的实现。

Event.java

import android.os.Parcel;
import android.os.Parcelable;

public class Event implements Parcelable {

    // 人的姓名
    private String nameOfPerson;

    // 日期
    // 使用 byte(8 位),因为日期只能在 1 到 31 之间
    private byte day;

    // 月份
    // 使用 byte(8 位),因为月份只能在 1 到 12 之间
    private byte month;

    // 年份
    // 使用 short(16 位),因为年份只能是实际的公元年
    private short year;

    // 事件类型
    private String eventType;

    // 构造函数(由 Android Studio 自动生成)
    public Event(String nameOfPerson, byte day, byte month, short year, String eventType) {
        this.nameOfPerson = nameOfPerson;
        this.day = day;
        this.month = month;
        this.year = year;
        this.eventType = eventType;
    }

    // 获取每个私有成员字段的 getter 方法(由 Android Studio 自动生成)

    public String getNameOfPerson() {
        return nameOfPerson;
    }

    public byte getDay() {
        return day;
    }

    public byte getMonth() {
        return month;
    }

    public short getYear() {
        return year;
    }

    public String getEventType() {
        return eventType;
    }

    // Parcelable 实现(由 Android Studio 自动生成)

    protected Event(Parcel in) {
        nameOfPerson = in.readString();
        day = in.readByte();
        month = in.readByte();
        year = (short) in.readInt();
        eventType = in.readString();
    }

    public static final Creator<Event> CREATOR = new Creator<Event>() {
        @Override
        public Event createFromParcel(Parcel in) {
            return new Event(in);
        }

        @Override
        public Event[] newArray(int size) {
            return new Event[size];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(nameOfPerson);
        dest.writeByte(day);
        dest.writeByte(month);
        dest.writeInt((int) year);
        dest.writeString(eventType);
    }
}

然后,我们需要创建一个类,用来封装从 MainActivityaddinglist 活动的输入(在此示例中没有),以及从 addinglist 活动返回给 MainActivity 的输出(Event Parcelable 对象)。

这个类是一个 ActivityResultContract,它类似于一个合同,我们给 Android 系统,以便打开一个特定的活动,并为我们从中获取结果。

import android.app.Activity;
import android.content.Context;
import android.content.Intent;

import androidx.activity.result.contract.ActivityResultContract;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class GetEvent extends ActivityResultContract<Void, Event> {

    @NonNull
    @Override
    public Intent createIntent(@NonNull Context context, Void input) {

        // 创建 Intent,用于启动 addinglist 活动以获取结果
        Intent intent = new Intent(context, addinglist.class);

        // 如果您需要将任何输入发送到 addinglist 活动,
        // 您可以将它们作为额外信息放入 intent 中。
        // 例如:intent.putExtra("input", input)
        // 但是目前我们不需要将任何输入发送到 addinglist 活动。

        return intent;
    }

    @Override
    public Event parseResult(int resultCode, @Nullable Intent intent) {

        // 操作被取消?返回 null
        if (Activity.RESULT_OK != resultCode) return null;

        // 没有意图获取输出?返回 null
        if (null == intent) return null;

        // 成功从 addinglist 活动获取结果
        return intent.getExtras().getParcelable("output");
    }
}

以下是如何从 MainActivity 启动 addinglist 活动并获取结果。

MainActivity.java

import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import androidx.activity.ComponentActivity;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.Activity

<details>
<summary>英文:</summary>

To get a result from an activity you should use `startActivityForResult()` and `onActivityResult()` APIs instead of `startActivity()`.

You can learn it from this simple example given by tutorialspoint : https://www.tutorialspoint.com/how-to-manage-startactivityforresult-on-android

But latest Android developer documentation recommends us to use new **Activity Result APIs** for this.

To learn, you can refer to the Google&#39;s documentation : https://developer.android.com/training/basics/intents/result

And this write up by Wajahat Karim : https://wajahatkarim.com/2020/05/activity-results-api-onactivityresult/

I&#39;m trying to give you an answer using this new Activity Result API.

First, you must add AndroidX `Activity` and `Fragment` libraries as dependencies.

app/build.gradle

``` gradle
apply plugin: &#39;com.android.application&#39;

android {
    compileSdkVersion 29
    buildToolsVersion &quot;29.0.2&quot;

    defaultConfig {
        applicationId &quot;com.lakindu.birthdayreminder&quot;
        minSdkVersion 14
        targetSdkVersion 29
        versionCode 1
        versionName &quot;1.0&quot;

        testInstrumentationRunner &quot;androidx.test.runner.AndroidJUnitRunner&quot;
    }

    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile(&#39;proguard-android-optimize.txt&#39;), &#39;proguard-rules.pro&#39;
        }
    }

}

dependencies {
    implementation fileTree(dir: &#39;libs&#39;, include: [&#39;*.jar&#39;])

    implementation &#39;androidx.appcompat:appcompat:1.1.0&#39;
    implementation &#39;androidx.constraintlayout:constraintlayout:1.1.3&#39;
    testImplementation &#39;junit:junit:4.12&#39;
    androidTestImplementation &#39;androidx.test.ext:junit:1.1.1&#39;
    androidTestImplementation &#39;androidx.test.espresso:espresso-core:3.2.0&#39;

    // Reference 1 : https://developer.android.com/training/basics/intents/result
    // Reference 2 : https://wajahatkarim.com/2020/05/activity-results-api-onactivityresult/
    implementation &#39;androidx.activity:activity:1.2.0-alpha04&#39;
    implementation &#39;androidx.fragment:fragment:1.3.0-alpha04&#39;
}

I'm going to send a Parcelable object from the addinglist activity to the MainActivity as the result.

This is the implementation of that Parcelable Event class.

Event.java

import android.os.Parcel;
import android.os.Parcelable;

public class Event implements Parcelable {

    // Name of the person
    private String nameOfPerson;

    // Day of month
    // byte (8 bit) as the type, because day can only have a value from 1 to 31
    private byte day;

    // Month of year
    // byte (8 bit) as the type, because month can only have a value from 1 to 12
    private byte month;

    // Year
    // Short (16 bit) as the type, because year can only have a realistic A.D. year
    private short year;

    // Type of event
    private String eventType;

    // Constructor (auto-generated using Android Studio)
    public Event(String nameOfPerson, byte day, byte month, short year, String eventType) {
        this.nameOfPerson = nameOfPerson;
        this.day = day;
        this.month = month;
        this.year = year;
        this.eventType = eventType;
    }

    // Getters for each private member field (auto-generated using Android Studio)

    public String getNameOfPerson() {
        return nameOfPerson;
    }

    public byte getDay() {
        return day;
    }

    public byte getMonth() {
        return month;
    }

    public short getYear() {
        return year;
    }

    public String getEventType() {
        return eventType;
    }

    // Parcelable implementation (auto-generated using Android Studio)

    protected Event(Parcel in) {
        nameOfPerson = in.readString();
        day = in.readByte();
        month = in.readByte();
        year = (short) in.readInt();
        eventType = in.readString();
    }

    public static final Creator&lt;Event&gt; CREATOR = new Creator&lt;Event&gt;() {
        @Override
        public Event createFromParcel(Parcel in) {
            return new Event(in);
        }

        @Override
        public Event[] newArray(int size) {
            return new Event[size];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(nameOfPerson);
        dest.writeByte(day);
        dest.writeByte(month);
        dest.writeInt((int) year);
        dest.writeString(eventType);
    }
}

Then we have to create a class to encapsulate inputs given to addinglist activity from MainActivity (in this example there's none), and outputs returned from addinglist activity to MainActivity (Event Parcelable object).

This class is an ActivityResultContract, which is like a contract we give to the Android system to open a specific Activity, and get a result from it for us.

import android.app.Activity;
import android.content.Context;
import android.content.Intent;

import androidx.activity.result.contract.ActivityResultContract;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class GetEvent extends ActivityResultContract&lt;Void, Event&gt; {

    @NonNull
    @Override
    public Intent createIntent(@NonNull Context context, Void input) {

        // Create Intent that should be used to start addinglist activity for result
        Intent intent = new Intent(context, addinglist.class);

        // If you need to send any inputs to addinglist activity,
        // you can put them in intent as extras.
        // Eg: intent.putExtra(&quot;input&quot;, input)
        // But for now we don&#39;t have to send any inputs to addinglist activity.

        return intent;
    }

    @Override
    public Event parseResult(int resultCode, @Nullable Intent intent) {

        // Action is cancelled? Return null
        if(Activity.RESULT_OK != resultCode) return null;

        // No intent to get output? Return null
        if(null == intent) return null;

        // Successfully got result from addinglist activity
        return intent.getExtras().getParcelable(&quot;output&quot;);
    }
}

Here is how we launch the addinglist activity from MainActivity and get the result.

MainActivity.java

import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import androidx.activity.ComponentActivity;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;

import java.util.ArrayList;
import java.util.Calendar;

public class MainActivity extends ComponentActivity {

    private static final String TAG = &quot;&quot;;

    ArrayList&lt;String&gt; listItems = new ArrayList&lt;String&gt;();

    ArrayAdapter&lt;String&gt; adapter;

    Calendar calendar = Calendar.getInstance();
    int thisYear = calendar.get(Calendar.YEAR);
    int thisMonth = calendar.get(Calendar.MONTH) + 1;
    int thisDay = calendar.get(Calendar.DAY_OF_MONTH);

    // Holds the latest event received from addinglist activity
    private Event mLatestEvent = null;

    // Register a callback to be called on an event received from addinglist activity
    private ActivityResultLauncher&lt;Void&gt; mGetEvent = registerForActivityResult(
            // Instance that encapsulates input and output when starting addinglist activity for result
            new GetEvent(),

            // Callback to be called when event is received
            new ActivityResultCallback&lt;Event&gt;() {
                @Override
                public void onActivityResult(Event result) {
                    // Save as latest event received
                    mLatestEvent = result;
                }
            }
    );

    private static final Void NO_INPUT = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        adapter=new ArrayAdapter&lt;String&gt;(this,
                android.R.layout.simple_list_item_1,
                listItems);
        ListView records = (ListView) findViewById(R.id.list);
        records.setAdapter(adapter);
    }

    public void addNewEntry(View v)
    {
        // Launch addinglist activity to get an event
        mGetEvent.launch(NO_INPUT);
    }
    public void viewRecord(View v)
    {
        // No latest event? Then nothing to add to list, just return.
        if(null == mLatestEvent) return;

        // Prepare string that is being added to the list.
        // Using a StringBuilder as there are multiple number of immutable strings to be appended.
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(mLatestEvent.getNameOfPerson())
                .append(&quot; has his &quot;)
                .append(mLatestEvent.getEventType())
                .append(&quot; on &quot;)
                .append(mLatestEvent.getDay())
                .append(&quot;/&quot;)
                .append(mLatestEvent.getMonth())
                .append(&quot;/&quot;)
                .append(mLatestEvent.getYear());

        String mss = stringBuilder.toString();
        //Toast.makeText(getApplicationContext(),mss,Toast.LENGTH_LONG).show();

        int age = thisYear - mLatestEvent.getYear();
        calendar.set(thisYear,thisMonth,thisDay);
        Calendar calendar1 = Calendar.getInstance();
        calendar1.set(thisYear, mLatestEvent.getMonth(), mLatestEvent.getDay());

        long milliseconds1 = calendar.getTimeInMillis();
        long milliseconds2 = calendar1.getTimeInMillis();
        long diff = milliseconds2 - milliseconds1;
        int noOfDays = (int) (diff / (24 * 60 * 60 * 1000));
        String msg2 = &quot;Turning &quot; + age + &quot; in &quot; + noOfDays + &quot;days!!&quot;;
//        Toast.makeText(getApplicationContext(),msg2,Toast.LENGTH_LONG).show();


        String finalMsg = mss + &quot; &quot; + msg2;
        listItems.add(finalMsg);
        adapter.notifyDataSetChanged();
    }
}

Note that MainActivity is a ComponentActivity now. Not a AppCompatActivity.

Here is how to send the result from addinglist activity to MainActivity.

addinglist.java

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.NumberPicker;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import androidx.appcompat.app.AppCompatActivity;

public class addinglist extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addinglist);
        NumberPicker day = (NumberPicker) findViewById(R.id.day);
        NumberPicker month = (NumberPicker) findViewById((R.id.month));
        NumberPicker year = (NumberPicker) findViewById(R.id.year);
        day.setMinValue(1);
        day.setMaxValue(31);
        month.setMinValue(1);
        month.setMaxValue(12);
        year.setMinValue(1950);
        year.setMaxValue(2020);
    }

    public void addingEvent(View v)
    {
        String name;
        EditText nameEntered = (EditText) findViewById(R.id.name);
        name = nameEntered.getText().toString();
        NumberPicker day = (NumberPicker) findViewById(R.id.day);
        NumberPicker month = (NumberPicker) findViewById((R.id.month));
        NumberPicker year = (NumberPicker) findViewById(R.id.year);
        byte day1 = (byte) day.getValue();
        byte month1 = (byte) month.getValue();
        short year1 = (short) year.getValue();
        RadioGroup typer = (RadioGroup) findViewById(R.id.typer);
        int selectedId = typer.getCheckedRadioButtonId();
        RadioButton checked = (RadioButton) findViewById(selectedId);
        String typee = checked.getText().toString();
        EditText resultbox = (EditText) findViewById(R.id.resultshower);
        String Finalmsg = name + &quot; has his &quot; + typee + &quot; on &quot; + day1 + &quot;/&quot; + month1 + &quot;/&quot; + year1;
        resultbox.setText(Finalmsg);

        // Prepare the result to output
        Intent newintent = new Intent();
        newintent.putExtra(
                &quot;output&quot;,
                new Event(name, day1, month1, year1, typee)
        );

        // Set the result
        setResult(Activity.RESULT_OK, newintent);

        // Finish the addinglist activity.
        // Then result will be sent to the MainActivity.
        finish();
    }
}

Here is the working app.

Adding multiple items to a listview with each item received from another intent on a button click
Adding multiple items to a listview with each item received from another intent on a button click

huangapple
  • 本文由 发表于 2020年5月5日 01:31:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/61598181.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定