从第二个活动将数据发送到第一个不起作用的Andr​​oid [英] Sending data from a second activity to the first one doesn't work Android

查看:198
本文介绍了从第二个活动将数据发送到第一个不起作用的Andr​​oid的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前工作的一个应用程序,允许你做笔记列表:


  • 名单中的第一个活动查看

  • 新的音符按钮导致与编辑文本和一些文本格式按钮(粗体,斜体,更大的文本,更小的)
  • 第二项活动
  • 应用程序允许您在长途点击,编辑或删除列表中的注意事项。

问题是,当我从一个活动的数据发送到另一个我上记录此错误:


  

显示java.lang.NullPointerException:尝试调用虚函数
  java.lang.String中java.lang.Object.toString()的空对象
  参照


当我尝试将数据发送回的第一个活动,只有发生。当我尝试从按钮内部将其保存在第二个活动同样的方法:

 的getText()的toString()。

工作得很好。这里是code的活动,并与节能方法之间发送/接收数据。

 公共无效的sendMessage(查看视图)
{
    EDITTEXT =(EditText上)findViewById(R.id.add_text);
    字符串消息= editText.getText()的toString()。
    意向意图=新意图(这一点,MainActivity.class);
    intent.putExtra(key_Message,消息);
    startActivity(意向);
}
@覆盖
保护无效onResume(){
    super.onResume();
    意向意图= getIntent();
    字符串消息= intent.getStringExtra(key_Message);
    list.add(消息);
    adapter.notifyDataSetChanged();
}

和这里是保存文本内部(其中正常工作)的方法。请注意,我在的WriteMessage添加SendMessage函数(但评论吧)

 公共无效的WriteMessage(查看视图)
{
    字符串消息= editText.getText()的toString()。
    字符串FILE_NAME =Notes_file;
    尝试{
        FileOutputStream中的FileOutputStream = openFileOutput(FILE_NAME,MODE_PRIVATE);
        fileOutputStream.write(Message.getBytes());
        fileOutputStream.close();
        Toast.makeText(getApplicationContext(),消息已被保存,Toast.LENGTH_SHORT).show();
        //字符串消息= editText.getText()的toString();
        //意向意图=新意图(这一点,MainActivity.class);
        //intent.putExtra(key_Message,消息);
        // startActivity(意向);    }赶上(FileNotFoundException异常五){
        e.printStackTrace();
    }赶上(IOException异常五){
        e.printStackTrace();
    }}

此外另一个小问题,我不能换我的头周围之一:

 公共无效shrinkText(查看视图)
{浮动modifySize = editText.getTextSize();
    modifySize = modifySize - 3;
    editText.setTextSize(modifySize);
}

是从编辑文本,当用户点击一个按钮应该shrinkText小法。它总是增加的文字。有些帮助将是AP preciated。

 公共无效的WriteMessage(查看视图)
{
    字符串消息= editText.getText()的toString()。
    字符串FILE_NAME =Notes_file;
    尝试{
        FileOutputStream中的FileOutputStream = openFileOutput(FILE_NAME,MODE_PRIVATE);
        fileOutputStream.write(Message.getBytes());
        fileOutputStream.close();
        Toast.makeText(getApplicationContext(),消息已被保存,Toast.LENGTH_SHORT).show();
        字符串消息= editText.getText()的toString()。
        意向意图=新的Intent();
        intent.putExtra(key_edit,消息);
        的setResult(RESULT_OK,意向);
        完();
    }赶上(FileNotFoundException异常五){
        e.printStackTrace();
    }赶上(IOException异常五){
        e.printStackTrace();
    }} @覆盖
保护无效的onActivityResult(INT申请code,INT结果code,意图数据){
    super.onActivityResult(要求code,结果code,数据);
    如果(要求code == 1){
        如果(结果code == RESULT_OK){
            串item_tobeadded1;
            item_tobeadded1 = data.getStringExtra(key_edit);
            list.add(item_tobeadded1);
            //adapter.notifyDataSetChanged();
            适配器=新ArrayAdapter<串GT;(这一点,android.R.layout.simple_expandable_list_item_1,清单);
            list_view.setAdapter(适配器);
        }
    }
}


解决方案

由于已经建议你可以做的是开始你的第二个活动与在列表视图中的数据项目你只需点击,当你正在编辑,或当你箱子一​​个新的不传递任何东西。

在这种方式,您将能够编辑以及没有在code做太大的变化建立新的注释。

  INT RESPONSE_ code = 123; //从这个code将将分化,如果
                         //这是我们真正开始的活动做了任务或不    listView.setOnItemClickListener(新AdapterView.OnItemClickListener(){
        @覆盖
        公共无效onItemClick(适配器视图<>母公司,观景,INT位置,长的id){            意向意图=新意图(getApplicationContext(),NoteEditActivity.class);
            intent.putString(PARA1,的arg1);
            intent.putString(PARA2,ARG2);
            intent.putString(para3各个,ARG3);
            intent.putString(para4,ARG4);
            startActivityForResult(意向,RESPONSE_ code);
        }
    });

NoteEditActivity.class 如果有东西,你可以得到你的参数。由于同时创造新的注PARA1,PARA2,para3各个&安培; para4将是空的。但是,如果注意已经存在,你将不得不编辑

 保护无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_main);
    意向myIntent = getIntent();
    字符串ARG1 = myIntent.getStringExtra(PARA1);
    串ARG2 = myIntent.getStringExtra(PARA2);
    串ARG3 = myIntent.getStringExtra(para3各个);
    串ARG4 = myIntent.getStringExtra(para4);
    //在这里你必须检查他们或NOT NULL来区分
    //如果是要创建一个新的注释,或你必须编辑。
    //你应该使用一些另辟蹊径,想出解决办法,我写这个,因为我不会使用它:)}

和一旦你完成创建或编辑你的注意,相关数据附加到的意图和完成活动像这样

 意向意图=新的Intent();
intent.putExtra(PARA1,edited_data_1);
intent.putExtra(PARA2,edited_data_2);
intent.putExtra(para3各个,edited_data_3);
intent.putExtra(para4,edited_data_4);
的setResult(RESULT_OK,意向);
完();

如果任务成功,您将设置结果 RESULT_OK 附加的意图和你做

在previous活动中,你必须覆盖一个名为方法的onActivityResult()这个方法从你已经开始做一些任务活动接收到的数据,

 公共无效的onActivityResult(INT申请code,INT结果code,意图数据){
    super.onActivityResult(要求code,结果code,数据);
    如果(要求code == 1){
         如果(结果code == RESULT_OK){            字符串ARG1 = data.getStringExtra(PARA1);
            串ARG2 = data.getStringExtra(PARA2);
            串ARG3 = data.getStringExtra(para3各个);
            串ARG4 = data.getStringExtra(para4);
            //如果你在这里接收到的数据,
            //你可以添加一个新元素,列出进行 -
            //`ListView`填充,并调用`notifyDataSetChanged()`适配器上。
            //这样`adapter.notifyDataSetChanged();'会更新`listview` -
            //与您从`NoteEditActivity.class`接收到新数据             adapter.notifyDataSetChanged(); //我假设你想更改的项目添加到列表
         }
    }
}


  

更新,我创建了一个虚拟的code为你和它的作品,我已经测试过,我还上传了它在Github上,你可以检查它有


NoteListActivity.java

 公共类NoteListActivity延伸活动{    私人的ListView ListView的;
    私人的ArrayList<串GT;串;
    公共静态最后弦乐NEW_ELEMENT =NEW_ELEMENT;
    公共静态最后弦乐ELEMENT_VALUE =ELEMENT_VALUE;
    公共静态最后弦乐ELEMENT_POSITION =ELEMENT_POSITION;
    私人ArrayAdapter<串GT;适配器;    @覆盖
    保护无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_note_list);        ListView控件=(ListView控件)findViewById(R.id.NoteListActivity_listView);
        listView.setOnItemClickListener(新AdapterView.OnItemClickListener(){
            @覆盖
            公共无效onItemClick(适配器视图<>母公司,观景,INT位置,长的id){
                字符串文本=(字符串)listView.getItemAtPosition(位置);
                意向意图=新意图(getApplicationContext(),NoteEditActivity.class);
                intent.putExtra(NEW_ELEMENT,FALSE);
                intent.putExtra(ELEMENT_POSITION,位置);
                intent.putExtra(ELEMENT_VALUE,文字);
                startActivityForResult(意向,123);
            }
        });        FloatingActionButton FAB =(FloatingActionButton)findViewById(R.id.NoteListActivity_fab);
        fab.setOnClickListener(新View.OnClickListener(){
            @覆盖
            公共无效的onClick(查看视图){
                意向意图=新意图(getApplicationContext(),NoteEditActivity.class);
                intent.putExtra(NEW_ELEMENT,真);
                startActivityForResult(意向,123);
            }
        });        setUpList();        适配器=新ArrayAdapter<串GT;(getApplicationContext(),R.layout.simple_list_item_1,字符串);
        listView.setAdapter(适配器);
    }    @覆盖
    保护无效的onActivityResult(INT申请code,INT结果code,意图数据){
        super.onActivityResult(要求code,结果code,数据);
        Log.d(NoteListActivity1,+ data.getStringExtra(NoteListActivity.ELEMENT_VALUE));        如果(要求code == 123){
            如果(结果code == RESULT_OK){
                Log.d(NoteListActivity2,+ data.getStringExtra(NoteListActivity.ELEMENT_VALUE));
                布尔isNewElement = data.getBooleanExtra(NoteListActivity.NEW_ELEMENT,FALSE);
                如果(isNewElement){
                    strings.add(+ data.getStringExtra(NoteListActivity.ELEMENT_VALUE));
                    adapter.notifyDataSetChanged();
                }其他{
                    strings.set(data.getIntExtra(NoteListActivity.ELEMENT_POSITION,0),+ data.getStringExtra(NoteListActivity.ELEMENT_VALUE));
                    adapter.notifyDataSetChanged();
                }
            }
        }
    }    私人无效setUpList(){
        串=新的ArrayList<>();
        对(INT I = 0; I&下; 4;我++){
            strings.add(Element_1_+ I);
        }
    }
}

activity_note_list.xml

 <?XML版本=1.0编码=UTF-8&GT?;
< android.support.design.widget.CoordinatorLayout的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    的xmlns:工具=htt​​p://schemas.android.com/tool​​s
    机器人:layout_width =match_parent
    机器人:layout_height =match_parent
    机器人:fitsSystemWindows =真
    工具:上下文=com.nimgade.pk.mytutorialapplication.MainActivity>    < LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
        的xmlns:工具=htt​​p://schemas.android.com/tool​​s
        机器人:layout_width =match_parent
        机器人:layout_height =match_parent
        机器人:方向=垂直
        工具:上下文=activities.list.first.NoteListActivity>
        < ListView控件
            机器人:ID =@ + ID / NoteListActivity_listView
            机器人:layout_width =match_parent
            机器人:layout_height =WRAP_CONTENT/>
    < / LinearLayout中>    < android.support.design.widget.FloatingActionButton
        机器人:ID =@ + ID / NoteListActivity_fab
        机器人:layout_width =WRAP_CONTENT
        机器人:layout_height =WRAP_CONTENT
        机器人:layout_gravity =底部|结束
        机器人:layout_margin =@扪/ fab_margin
        机器人:SRC =@机器人:可绘制/ ic_menu_add/>< /android.support.design.widget.CoordinatorLayout>

NoteEditActivity.java

 公共类NoteEditActivity延伸活动{    私人的EditText EDITTEXT;
    私人Button按钮;
    私人布尔isNewElement;
    私人诠释的位置;    @覆盖
    保护无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_note_edit);        EDITTEXT =(EditText上)findViewById(R.id.NoteEditActivity_editText);
        按钮=(按钮)findViewById(R.id.NoteEditActivity_button);        意向myIntent = getIntent();
        isNewElement = myIntent.getBooleanExtra(NoteListActivity.NEW_ELEMENT,FALSE);        如果(!isNewElement){
            editText.setText(+ myIntent.getStringExtra(NoteListActivity.ELEMENT_VALUE));
            位置= myIntent.getIntExtra(NoteListActivity.ELEMENT_POSITION,0);
        }        button.setOnClickListener(新View.OnClickListener(){
            @覆盖
            公共无效的onClick(视图v){
                字符串文本= editText.getText()的toString()。
                如果(文= NULL&放大器;!&安培; text.trim()长()0){
                    意向意图=新的Intent();
                    Log.d(NoteEditActivity,+文字);
                    intent.putExtra(NoteListActivity.ELEMENT_VALUE,文字);
                    intent.putExtra(NoteListActivity.NEW_ELEMENT,isNewElement);
                    如果(!isNewElement){
                        intent.putExtra(NoteListActivity.ELEMENT_POSITION,位置);
                    }
                    的setResult(RESULT_OK,意向);
                    完();
                }其他{
                    Toast.makeText(getApplicationContext(),请写一个有效的元素名称,Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

activity_note_edit.xml

 <?XML版本=1.0编码=UTF-8&GT?;
< LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    的xmlns:工具=htt​​p://schemas.android.com/tool​​s
    机器人:layout_width =match_parent
    机器人:layout_height =match_parent
    机器人:比重=中心
    机器人:方向=垂直
    工具:上下文=activities.list.first.NoteEditActivity>
    <的EditText
        机器人:ID =@ + ID / NoteEditActivity_editText
        机器人:layout_width =match_parent
        机器人:layout_height =WRAP_CONTENT/>    <按钮
        机器人:ID =@ + ID / NoteEditActivity_button
        机器人:layout_width =WRAP_CONTENT
        机器人:layout_height =WRAP_CONTENT
        机器人:文本=保存
        机器人:textAllCaps =FALSE/>
< / LinearLayout中>

I am currently working on an app that allows you to make a list of notes:

  • The list is viewable in the first activity
  • The new note button leads to a second activity with edit text and a few text formatting buttons ( Bold, Italic, bigger text, smaller)
  • The app allows you on long clicks to either edit or delete the notes in the list.

The problem is when I send data from one activity to another I get this error on the logs:

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

And that happens only when I try to send the data back to the first activity. When I try to save it internally from a button in the second activity the same method:

getText().toString() 

works just fine. Here is the code for sending/receiving data between activities and and the saving method.

public void sendMessage(View view)
{
    editText = (EditText) findViewById(R.id.add_text);
    String message = editText.getText().toString();
    Intent intent  = new Intent(this, MainActivity.class);
    intent.putExtra(key_Message, message);
    startActivity(intent);
}


@Override
protected void onResume() {
    super.onResume();
    Intent intent = getIntent();
    String message = intent.getStringExtra(key_Message);
    list.add(message);
    adapter.notifyDataSetChanged();
}

And here is the method for saving text internally ( which works fine). Note that I added the sendMessage function in the writeMessage(but commented it)

 public void writeMessage(View view)
{
    String Message = editText.getText().toString();
    String file_name = "Notes_file";
    try {
        FileOutputStream fileOutputStream = openFileOutput(file_name, MODE_PRIVATE);
        fileOutputStream.write(Message.getBytes());
        fileOutputStream.close();
        Toast.makeText(getApplicationContext(),"Message has been saved", Toast.LENGTH_SHORT).show();
        //String message = editText.getText().toString();
        //Intent intent  = new Intent(this, MainActivity.class);
        //intent.putExtra(key_Message, message);
        //startActivity(intent);

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

Also another small problem I couldn't wrap my head around either:

public void shrinkText(View view)
{   float modifySize = editText.getTextSize();
    modifySize = modifySize - 3;
    editText.setTextSize(modifySize);
}

Is a small method that is supposed to shrinkText from an edit text when the user clicks a button. It always increases text. Some help would be appreciated.

public void writeMessage(View view)
{
    String Message = editText.getText().toString();
    String file_name = "Notes_file";
    try {
        FileOutputStream fileOutputStream = openFileOutput(file_name, MODE_PRIVATE);
        fileOutputStream.write(Message.getBytes());
        fileOutputStream.close();
        Toast.makeText(getApplicationContext(), "Message has been saved", Toast.LENGTH_SHORT).show();
        String message = editText.getText().toString();
        Intent intent  = new Intent();
        intent.putExtra(key_edit, message);
        setResult(RESULT_OK, intent);
        finish();


    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

 @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == 1){
        if(resultCode == RESULT_OK){
            String item_tobeadded1;
            item_tobeadded1 = data.getStringExtra(key_edit);
            list.add(item_tobeadded1);
            //adapter.notifyDataSetChanged();
            adapter = new ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1, list);
            list_view.setAdapter(adapter);
        }
    }
}

解决方案

As already suggested what you can do is start your second activity for with the data on the listview item you just clicked when you are editing, or when you crate a new don't pass anything.

In this manner you would be able to edit as well as create the new Note without making much changes in the code.

int RESPONSE_CODE = 123; // from this code will will differentiate if 
                         // the activity which we started actually did the task or not

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            Intent intent = new Intent(getApplicationContext(), NoteEditActivity.class);
            intent.putString("para1","arg1");
            intent.putString("para2","arg2");
            intent.putString("para3","arg3");
            intent.putString("para4","arg4");
            startActivityForResult(intent, RESPONSE_CODE);
        }
    });

in NoteEditActivity.class you can receive your parameters if there were something. As while creating new Note para1,para2, para3 & para4 would be empty. But if the Note already exist you would have to edit that

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Intent myIntent = getIntent();
    String arg1 = myIntent.getStringExtra("para1");
    String arg2 = myIntent.getStringExtra("para2");
    String arg3 = myIntent.getStringExtra("para3");
    String arg4 = myIntent.getStringExtra("para4");
    // here you have to check that they or not null to differentiate 
    // if it is a new Note to be created OR you have to edit.
    // you should probably use some another way to figure this out, i am writing this because i would not be using it :)

}

And once you are done creating or editing your Note, attach the relevant data to the intent and finish the activity like this

Intent intent = new Intent();
intent.putExtra("para1","edited_data_1");
intent.putExtra("para2","edited_data_2");
intent.putExtra("para3","edited_data_3");
intent.putExtra("para4","edited_data_4");
setResult(RESULT_OK, intent);        
finish(); 

if the Task was successful you will set the result to RESULT_OK attach the intent and you are done

in the previous activity you have to override a method called onActivityResult() this method receives the data from the activity you had started to do some task,

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1) {
         if(resultCode == RESULT_OK){

            String arg1 = data.getStringExtra("para1");
            String arg2 = data.getStringExtra("para2");
            String arg3 = data.getStringExtra("para3");
            String arg4 = data.getStringExtra("para4");
            // if you receive the data here,
            // you can add another element to List from which the -
            //`ListView` is populated and call `notifyDataSetChanged()` on the adapter.
            // like this `adapter.notifyDataSetChanged();` it will update the `listview` -
            //with new data that you received from the `NoteEditActivity.class` 

             adapter.notifyDataSetChanged(); // I am assuming you would add the changed item to the List
         }     
    }
}

Update, I have created a dummy code for you and it does works, i have tested it, I have also uploaded it on Github that you may check it there

NoteListActivity.java

public class NoteListActivity extends Activity {

    private ListView listView;
    private ArrayList<String> strings;
    public static final String NEW_ELEMENT = "NEW_ELEMENT";
    public static final String ELEMENT_VALUE = "ELEMENT_VALUE";
    public static final String ELEMENT_POSITION = "ELEMENT_POSITION";
    private ArrayAdapter<String> adapter;

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

        listView = (ListView) findViewById(R.id.NoteListActivity_listView);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String text = (String) listView.getItemAtPosition(position);
                Intent intent = new Intent(getApplicationContext(), NoteEditActivity.class);
                intent.putExtra(NEW_ELEMENT, false);
                intent.putExtra(ELEMENT_POSITION, position);
                intent.putExtra(ELEMENT_VALUE, text);
                startActivityForResult(intent, 123);
            }
        });

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.NoteListActivity_fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getApplicationContext(), NoteEditActivity.class);
                intent.putExtra(NEW_ELEMENT, true);
                startActivityForResult(intent, 123);
            }
        });

        setUpList();

        adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.simple_list_item_1, strings);
        listView.setAdapter(adapter);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d("NoteListActivity1",""+data.getStringExtra(NoteListActivity.ELEMENT_VALUE));

        if (requestCode == 123) {
            if (resultCode == RESULT_OK) {
                Log.d("NoteListActivity2",""+data.getStringExtra(NoteListActivity.ELEMENT_VALUE));
                boolean isNewElement = data.getBooleanExtra(NoteListActivity.NEW_ELEMENT, false);
                if (isNewElement) {
                    strings.add("" + data.getStringExtra(NoteListActivity.ELEMENT_VALUE));
                    adapter.notifyDataSetChanged();
                } else {
                    strings.set(data.getIntExtra(NoteListActivity.ELEMENT_POSITION, 0), "" + data.getStringExtra(NoteListActivity.ELEMENT_VALUE));
                    adapter.notifyDataSetChanged();
                }
            }
        }
    }

    private void setUpList() {
        strings = new ArrayList<>();
        for (int i = 0; i < 4; i++) {
            strings.add("Element_1_" + i);
        }
    }
}

activity_note_list.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.nimgade.pk.mytutorialapplication.MainActivity">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context="activities.list.first.NoteListActivity">


        <ListView
            android:id="@+id/NoteListActivity_listView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/NoteListActivity_fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_menu_add" />

</android.support.design.widget.CoordinatorLayout>

NoteEditActivity.java

public class NoteEditActivity extends Activity {

    private EditText editText;
    private Button button;
    private boolean isNewElement;
    private int position;

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

        editText = (EditText) findViewById(R.id.NoteEditActivity_editText);
        button = (Button) findViewById(R.id.NoteEditActivity_button);

        Intent myIntent = getIntent();
        isNewElement = myIntent.getBooleanExtra(NoteListActivity.NEW_ELEMENT, false);

        if (!isNewElement) {
            editText.setText("" + myIntent.getStringExtra(NoteListActivity.ELEMENT_VALUE));
            position = myIntent.getIntExtra(NoteListActivity.ELEMENT_POSITION,0);
        }

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String text = editText.getText().toString();
                if (text != null && text.trim().length() > 0) {
                    Intent intent = new Intent();
                    Log.d("NoteEditActivity",""+text);
                    intent.putExtra(NoteListActivity.ELEMENT_VALUE, text);
                    intent.putExtra(NoteListActivity.NEW_ELEMENT, isNewElement);
                    if (!isNewElement) {
                        intent.putExtra(NoteListActivity.ELEMENT_POSITION, position);
                    }
                    setResult(RESULT_OK, intent);
                    finish();
                } else {
                    Toast.makeText(getApplicationContext(), "Kindly write a valid element name", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

activity_note_edit.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    tools:context="activities.list.first.NoteEditActivity">


    <EditText
        android:id="@+id/NoteEditActivity_editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/NoteEditActivity_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Save"
        android:textAllCaps="false" />
</LinearLayout>

这篇关于从第二个活动将数据发送到第一个不起作用的Andr​​oid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆