简体   繁体   English

添加新的ListView项目并从另一个活动中获取项目的价值

[英]Adding new ListView item and get value of item from another activity

I am trying to make a "News App" with Android Studio. 我正在尝试使用Android Studio创建“新闻应用程序”。 I have on my main activity a ListView and a floating button . 我的主要活动有一个ListView和一个floating button On my second activity I got two TextViews , two EditViews and one Button . 在第二个活动中,我得到了two TextViewstwo EditViewsone Button What I'd like to do is the following: First I press on the floating Button from my main Activity. 我要执行的操作如下:首先,我从主“活动”中按下floating Button Then the second Activity should pop up and there I write on the two EditText's and then press on the button . 然后第二个活动应该弹出,在那儿我写two EditText's ,然后按一下button After that I should go back to the main activity and there, a new Item should be added to the ListView. 之后,我应该回到主要活动,在那里,应该将新的Item添加到ListView。 The new item should be filled with the text from the second activity's EditTexts. 新项目应填充第二个活动的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): 这是第二个活动(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 java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“ java.lang.String java.lang.Object.toString()”


Solved: Thanks to Munir, the problem was solved. 已解决:感谢Munir,问题得以解决。

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): 这是我的第二个活动(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 . 为此,我建议使用Fragments而不是两个Activities The MainActivity then holds all your data. 然后, MainActivity将保存您的所有数据。

See Fragments guide . 请参阅片段指南

From your MainActivity call the addpost_activity using startActivityForResult() method Instead of startActivity(); 从您的MainActivity调用使用startActivityForResult()方法而不是startActivity();addpost_activity startActivity();

In your addpost_activity set the data which you want to return back to FirstActivity 在您的addpost_activity设置要返回到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() MainActivity ,通过覆盖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. 如果要在列表中保留旧条目,请使用由String []插入的ArrayList,如下所示更改代码。

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 将startActivity更改为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 在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 然后在您的addpost_activity中设置要返回的数据

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”的函数,当您从第二个活动返回到第一个活动时,将调用此方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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