-2

I have created two activities MainActivity and EditorActivity. I want to take two strings from Editor Activity and display those strings in MainActivity's ListView, whenever the back button from EditorActivity is clicked. My code shows only one item and every time a new List is getting created.

MainActivity.java

package com.example.android.writedown;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private FloatingActionButton addNoteFab;
    private ArrayList<NoteItem> notes = new ArrayList<>();
    NoteAdapter adapter;
    private static final String SHARED_PREF = "pref";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        addNoteFab = (FloatingActionButton) findViewById(R.id.add_note);
        adapter = new NoteAdapter(this, notes);
        addNoteFab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, EditorActivity.class);
                startActivity(intent);
            }
        });
        SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
        String title = sharedPreferences.getString("title",  null);
        String desc = sharedPreferences.getString("note", null);
        notes.add(new NoteItem(title, desc));
        ListView list = (ListView) findViewById(R.id.list_view);
        adapter.notifyDataSetChanged();
        list.setAdapter(adapter);
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".MainActivity">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <ListView
            android:id="@+id/list_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        </ListView>
    </LinearLayout>

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/add_note"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:layout_margin="16dp" />

</RelativeLayout>

EditorActivity.java

package com.example.android.writedown;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.EditText;

import java.util.ArrayList;

public class EditorActivity extends AppCompatActivity {
    private EditText edit_title;
    private EditText edit_note;
    private SharedPreferences sharedPreferences;
    private static final String SHARED_PREF = "pref";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_editor);
        edit_title = (EditText) findViewById(R.id.edit_title);
        edit_note = (EditText) findViewById(R.id.edit_note);
        sharedPreferences = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
    }

    @Override
    public void onBackPressed() {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("title", edit_title.getText().toString());
        editor.putString("note", edit_note.getText().toString());
        editor.commit();
        Intent intent = new Intent(EditorActivity.this, MainActivity.class);
        startActivity(intent);
    }
}

activity_editor.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".EditorActivity">

    <EditText
        android:id="@+id/edit_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/editor_title"/>

    <EditText
        android:id="@+id/edit_note"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:hint="@string/editor_note"
        android:gravity="start"/>

</LinearLayout>

Custom Data type - NoteItem.java

package com.example.android.writedown;

import android.widget.TextView;

public class NoteItem {
    private String title, note;
    private TextView titleView, descView;
    public NoteItem(String mTitle, String mNote) {
        title = mTitle;
        note = mNote;
    }

    public String getNote() { return note; }

    public String getTitle() { return title; }
}

Custom Adapter - NoteAdapter.java

package com.example.android.writedown;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.List;

public class NoteAdapter extends ArrayAdapter<NoteItem> {
    public NoteAdapter(@NonNull Context context, @NonNull List<NoteItem> notes) {
        super(context, 0, notes);
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        View listItemView = convertView;
        if(listItemView == null) {
            listItemView = LayoutInflater.from(getContext()).inflate(R.layout.note_list_item, parent, false);
        }

        NoteItem currNote = getItem(position);
        String title = currNote.getTitle();
        String desc = currNote.getNote();
        TextView note_title = (TextView) listItemView.findViewById(R.id.note_title);
        TextView note_desc = (TextView) listItemView.findViewById(R.id.note_description);

        if(title!=null) {
            note_title.setText(title);
            note_title.setVisibility(View.VISIBLE);
        }

        if(desc!=null) {
            note_desc.setText(desc);
            note_desc.setVisibility(View.VISIBLE);
        }

        return listItemView;
    }
}

note_list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/note_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:fontFamily="sans-serif"
        android:visibility="invisible"/>

    <TextView
        android:id="@+id/note_description"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fontFamily="sans-serif"
        android:visibility="invisible"/>

</LinearLayout>
Yash Joshi
  • 557
  • 7
  • 25

2 Answers2

0

You're getting the SharedPreference with your key and every time replacing the same key values title and note which, as expected, would keep on overwriting the existing values instead of creating a list as per your requirement.

If you just need to save the data in one Activity and show it in a different activity, you can simply save the data as a list in the local storage (or even a remote database, if you prefer) and then get that instance to keep adding new elements to the list.

You can use PaperDB which is an easy-to-use NoSQL-based library for saving data in local storage. Check the link for integration, and once integrated you can simply save a file simply as:

Paper.book().write("editor_list", <you_list_here>);

Create the list like:

ArrayList<NoteItem> noteList = new ArrayList<>();

And then get the list instance from the local file in the EditorActivity as:

ArrayList<NoteItem> noteList = Paper.book().read("editor_list", new ArrayList<>()); // this will give you empty list if there are no existing items.

Then just add your title and note as a separate object of model class NoteItem and add it to the list like:

noteList.add(<your_object_here>)

Then you can use the write function again to pass this updated list and save the changes in the local file. For showing the list in the ListView simply get the file again as a list and pass the list to the adapter.

This should get it done what you're expecting!

Yash Joshi
  • 557
  • 7
  • 25
0

I noticed in your MainActivity everything is written in onCreate method. If you understand the lifecycle of activity, onCreate calls only one time per launch of activity, I suggest to for another method like this How to manage startActivityForResult on Android and you don't require anything extra, just need to change the Intent calling with startActivityForResult and get in MainActivity in onActivityResult

Brendon
  • 1,368
  • 1
  • 12
  • 28
  • Using these methods stores and displays the data but data is getting removed after the app's cache is cleared. – Nikita Chauhan Jun 06 '21 at 16:40
  • Of course it will be cleared. That's how the system works. If you want to keep the data, may be switch to cloud storage and API web service. – Brendon Jun 07 '21 at 04:00