1

Updated Problem: My text of the SecondAcitivity is displayed in the recycling view of my MainActivity. However, the text in the Recyclerview will be overwritten. How do I get it that the text in my recycling view is not overwritten, but is displayed in a further field one below the other?

I would like to have a button in my main activity that opens Activity 2. A text should then be entered there, which should then be displayed by clicking a button in the Recyclerview of the main activity. I have already inserted a recylerview adapter, but the text is not output. Where is the problem?

On my XML i got 2 Buttons (one in the MainActivity (floatingActionButton) and one in the Second (sendNewTask))

My MainActivity:

public class MainActivity extends AppCompatActivity {

RecyclerView recyclerView;
FloatingActionButton floatingActionButton;
TaskManager taskManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    taskManager = new TaskManager(this);
    initViews();
    initClickListener();
    receiveIntent();
    setRecyclerView();

}

protected void initViews(){
    floatingActionButton = findViewById(R.id.floating_button);
    recyclerView = findViewById(R.id.recyclerview);

}

protected void initClickListener(){
    floatingActionButton.setOnClickListener(view -> onOpenButtonClicked());
}

protected void setRecyclerView(){
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    recyclerView.setAdapter(new TaskListAdapter(taskManager));
    recyclerView.getAdapter().notifyItemInserted(taskManager.getTaskListCount() - 1);
}

protected void onOpenButtonClicked(){
    Intent i = new Intent(this, TaskActivity.class);
    startActivity(i);
}
protected void receiveIntent(){
    String inputTask = getIntent().getStringExtra("EXTRA_SESSION_TASK");
    Task task = new Task();
    task.setName(inputTask);
    taskManager.addTask(task);
}

}

My SecondActivity:

public class TaskActivity extends AppCompatActivity {

    EditText etAddTask;
    ImageView sendNewTask;

    TaskManager taskManager;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_task);
        taskManager = new TaskManager(this);
        initViews();
        initClickListener();
    }

    protected void initViews(){
        etAddTask = findViewById(R.id.et_new_task);
        sendNewTask = findViewById(R.id.send_new_task);
    }

    protected void initClickListener(){
        sendNewTask.setOnClickListener(view -> onSendButtonClicked());
    }

    protected void onSendButtonClicked(){
        String newTaskName = etAddTask.getText().toString();
        Task task = new Task();
        task.setName(newTaskName);
        taskManager.addTask(task);
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
    }
}

And my RecyclerAdapter & TaskViewHolder:

public class TaskListAdapter extends RecyclerView.Adapter<TaskViewHolder> {

    TaskManager taskManager;

    public TaskListAdapter(TaskManager taskManager){
        this.taskManager = taskManager;
    }

    @NonNull
    @Override
    public TaskViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new TaskViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.task_row, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull TaskViewHolder holder, int position) {
        Task task = taskManager.getTaskList().get(position);
        holder.newTask.setText(task.getName());
    }

    @Override
    public int getItemCount() {
        return taskManager.getTaskListCount();
    }
}


public class TaskViewHolder extends RecyclerView.ViewHolder {

    TextView newTask;

    public TaskViewHolder(@NonNull View itemView) {
        super(itemView);
        newTask = itemView.findViewById(R.id.tv_new_task);
    }
}

TaskManager:

public class TaskManager {

    ArrayList<Task> taskList = new ArrayList<>();

    public TaskManager(Context context){
        Hawk.init(context).build();
        loadTaskList();
    }

    public void addTask(Task task){
        taskList.add(task);
        saveTaskList();
    }

    public void removeTask(Task task){
        taskList.remove(task);
        saveTaskList();
    }

    public ArrayList<Task> getTaskList(){
        return taskList;
    }

    public int getTaskListCount(){
        return taskList.size();
    }

    protected void saveTaskList(){
        Hawk.put("taskList", taskList);
    }

    protected void loadTaskList(){
        Hawk.get("taskList", new ArrayList<>());
    }
}
FloFlo
  • 43
  • 7
  • Does this answer your question? [How do I pass data between Activities in Android application?](https://stackoverflow.com/questions/2091465/how-do-i-pass-data-between-activities-in-android-application) – enzo May 17 '21 at 16:11
  • @Enzo I know that you can pass a string through this method. But how can I transfer this string with the layout to the recycling view with this function? – FloFlo May 17 '21 at 16:26
  • You're creating two task managers where you should keep only one (in the `MainActivity`). When you fetch the name in the second activity, transfer the string (`newTaskName`) to the main activity. In the main activity, receive this string, create a new task and add it to the task manager you're keeping there. – enzo May 17 '21 at 16:32
  • Now it works to put the text with the layout in the recylerview. However, each time i make a new entry, the old text is overwritten. Both texts (in different recyclerview layouts) should be displayed in the recyclerviews. Where is my problem that the text is overwritten? – FloFlo May 17 '21 at 18:53
  • That's a bit harder problem with different solutions. You can use either 1) [an AlertDialog instead of a whole new Activity](https://stackoverflow.com/a/36652295/9997212) to add new tasks, 2) [transfer a ArrayList instead of a String](https://stackoverflow.com/a/6543850/9997212), or 3) [use SharedPreferences](https://stackoverflow.com/a/3624358/9997212). If you want, you can update your question with the new problem and I can add a detailed answer of how it can work. – enzo May 17 '21 at 19:08
  • @Enzo I Updated my Question above the original Question. I also edited my new MainActivity with the new Task and taskManager (i added receiveIntent()). – FloFlo May 17 '21 at 19:57
  • The easiest way would be to transfer an arraylist right? Or which of this solutions would be the easiest? – FloFlo May 17 '21 at 20:01
  • I've added an answer, see if this helps you. I've decided to not include `SharedPreferences` because I thought it would be overkill, but if you want I can add this way too. – enzo May 17 '21 at 22:20

1 Answers1

0

Adding a task using a AlertDialog

If you don't need a whole new activity to just add a new task, you can use an AlertDialog.

public class MainActivity extends AppCompatActivity {
    // ...
    
    protected void onOpenButtonClicked(){
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
       
        // Here you can set the View you want, even a LinearLayout. In this
        // case, I'm adding a text field so user can type the task name
        final EditText edittext = new EditText(this);
        builder.setTitle("Enter the task name");
        builder.setView(edittext);
   
        alert.setPositiveButton("ADD", (dialog, which) -> {
            // When the user clicks the add button of the dialog, here will
            // be the task name the user has typed, so just add it to the 
            // task manager of this activity
            final String newTaskName = edittext.getText().toString();
        });
        alert.setNegativeButton("CANCEL", (dialog, which) -> {
            // When the user clicks the cancel button of the dialog, just
            // dismiss it without doing any action
            dialog.dismiss();
        });

        alert.create().show();
    }

    // ...
}

Keeping the previous tasks passing a StringArrayList

If you do need a new activity, you can keep the previous tasks by using a ArrayList and passing this around.

  • Requesting a new task:
public class MainActivity extends AppCompatActivity {
    // ...

    protected void onOpenButtonClicked(){
        final Intent i = new Intent(this, TaskActivity.class);
        
        // Transform the task list to a string list
        final List<String> taskNames = taskManager.getTaskList().stream()
            .map(task -> task.name).collect(Collesctions.toList());
  
        // Put it into the intent and start a new activity
        i.putStringArrayListExtra("TASK_NAME_LIST", new ArrayList<>(taskNames));
        
        startActivity(i);
    }

    // ...
}
  • Fetching a new task name:
public class TaskActivity extends AppCompatActivity {
    // ...

    ArrayList<String> taskNames;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        // ...
    
        final Intent i = getIntent();
        // Receive the current task names
        taskNames = getIntent().getStringArrayListExtra("TASK_NAME_LIST");
    }

    protected void onOpenButtonClicked() {
        final String newTaskName = etAddTask.getText().toString();        
 
        // Add the new task name to the task names
        taskNames.add(newTaskName);

        // Send it back to the MainActivity
        final Intent i = new Intent(this, MainActivity.class);
        i.putStringArrayListExtra("TASK_NAME_LIST", taskNames);

        startActivity(i);
        finish();
    }

    // ...
}
  • Creating a new task:
public class MainActivity extends AppCompatActivity {
    // ...

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // ...       

        taskManager = new TaskManager(this);
        
        final Intent i = getIntent();
        
        if (i != null) {
            // Receive the new task names
            final List<String> taskNames = getIntent().getStringArrayListExtra("TASK_NAME_LIST");
            
            for (String taskName : taskNames) {
                final Task task = new Task();
                task.setName(taskName);
                taskManager.addTask(task);
            }
        }
    }

    // ...
}

NOTE: Even though in the previous example there are two separate MainActivity methods, you should include both.

enzo
  • 9,861
  • 3
  • 15
  • 38