简体   繁体   中英

Adding new ListView item and get value of item from another activity

I am trying to make a "News App" with Android Studio. I have on my main activity a ListView and a floating button . On my second activity I got two TextViews , two EditViews and one Button . What I'd like to do is the following: First I press on the floating Button from my main Activity. Then the second Activity should pop up and there I write on the two EditText's and then press on the button . After that I should go back to the main activity and there, a new Item should be added to the ListView. The new item should be filled with the text from the second activity's EditTexts.

This is my main activity:

package news;

import android.content.Intent;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Get subject value from addpost Activity
        final String new_value = getIntent().getStringExtra("newSubject");

        String [] new_subject = new String []
                {new_value};

        FloatingActionButton add_post_button = findViewById(R.id.post_btn);
        final ListView post_view = findViewById(R.id.news_feed);
        //Create Adapter to add the new subject to listview
        if (new_subject != null) {
            ArrayAdapter newslist_adapter = new ArrayAdapter(
                    MainActivity.this,
                    android.R.layout.simple_expandable_list_item_1, new_subject);
            post_view.setAdapter(newslist_adapter);
        }
        add_post_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, addpost_activity.class);
                MainActivity.this.startActivity(intent);
            }
        });
    }
}

This is the second activity(addpost_activity):

package news;

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

import java.util.ArrayList;


public class addpost_activity extends AppCompatActivity {

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

        Button post_button = findViewById(R.id.post_btn);
        final EditText subject_text = findViewById(R.id.subject_edit);

        post_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(subject_text.getText() != null) {
                    Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                    intent.putExtra("newSubject", subject_text.getText().toString());
                    startActivity(intent);
                }
            }
        });
    }
}

My problem is now that the app crashes every time I start it. I also get this message from my logs:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference


Solved: Thanks to Munir, the problem was solved.

Here are my activities

MainActivity:

package news;

import android.app.Activity;
import android.content.Intent;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    ArrayAdapter newslist_adapter;
    ArrayList<String> new_subject = new ArrayList<>();

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

        FloatingActionButton add_post_button = findViewById(R.id.post_btn);

        //Create Adapter to add the new subject to listview
        add_post_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, addpost_activity.class);
                startActivityForResult(intent, 1);

            }
        });

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        final ListView post_view = findViewById(R.id.news_feed);
        if (requestCode == 1) {
            if(resultCode == Activity.RESULT_OK){
                String new_value = data.getStringExtra("newSubject");
                new_subject.add(new_value);
                newslist_adapter = new ArrayAdapter(
                        MainActivity.this,
                        android.R.layout.simple_expandable_list_item_1, new_subject);
                post_view.setAdapter(newslist_adapter);

            }
        }
    }
} 

This is my second Activity(addpost_activity):

package news;

import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.content.Intent;
import android.widget.EditText;
import android.widget.ListView;

import java.util.ArrayList;


public class addpost_activity extends AppCompatActivity {

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

        Button post_button = findViewById(R.id.post_btn);
        final EditText subject_text = findViewById(R.id.subject_edit);

        post_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(subject_text.getText() != null) {
                    Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                    intent.putExtra("newSubject", subject_text.getText().toString());
                    setResult(Activity.RESULT_OK, intent);
                    finish();
                }
            }
        });
    }
}

For that purpose I suggest using Fragments instead of two Activities . The MainActivity then holds all your data.

See Fragments guide .

From your MainActivity call the addpost_activity using startActivityForResult() method Instead of startActivity();

In your addpost_activity set the data which you want to return back to FirstActivity

post_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(subject_text.getText() != null) {
                    Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                    intent.putExtra("newSubject", subject_text.getText().toString());
                    setResult(Activity.RESULT_OK,intent );
                   finish();

                }
            }
        });

And in the MainActivity Access the result by overriding onActivityResult()

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == 1) {
        if(resultCode == Activity.RESULT_OK){
            String result=data.getStringExtra("newSubject");
           //Add this value to your adapter and call notifyDataSetChanged();
        }

    }
}

use ArrayList insted of String [] if you want to keep old entry in list change your code like below.

Main Activity

declare this variable as global

ArrayAdapter newslist_adapter;
ArrayList<String> new_subject = new ArrayList<>();

set Adapter like

newslist_adapter = new ArrayAdapter(
                    MainActivity.this,
                    android.R.layout.simple_expandable_list_item_1, new_subject);
            post_view.setAdapter(newslist_adapter);

change startActivity to startActivityForResult

 add_post_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, addpost_activity.class);
                startActivityForResult(intent,100);
            }
        });

Override this method in onActivity

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == 100) {
            String result=data.getStringExtra("newSubject");
new_subject.add(result)
           //Add this value to your adapter and call newslist_adapter.notifyDataSetChanged();

    }
}

And In your addpost_activity set the data which you want to return back

post_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(subject_text.getText() != null) {
                    Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                    intent.putExtra("newSubject", subject_text.getText().toString());
                    setResult(100,intent );
                   finish();

                }
            }
        });

在MainActivity.java中,您应该覆盖一个名为“ onActivityRecsult”的函数,当您从第二个活动返回到第一个活动时,将调用此方法。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM