将数据从第二个活动发送到第一个活动并不适用于Android

时间:2016-01-06 16:07:57

标签: java android android-intent

我目前正在制作一个允许您制作笔记列表的应用程序:

  • 该列表可在第一个活动中查看
  • 新的音符按钮会导致第二个活动,包含编辑文本和一些文本格式按钮(粗体,斜体,更大的文字,更小)
  • 该应用程序允许您长时间点击以编辑或删除列表中的备注。

问题是当我将数据从一个活动发送到另一个活动时,我在日志中收到此错误:

  

java.lang.NullPointerException:尝试调用虚方法   ' java.lang.String java.lang.Object.toString()'在null对象上   参考

只有当我尝试将数据发送回第一个活动时才会发生这种情况。当我尝试从第二个活动中的按钮内部保存它时,方法相同:

getText().toString() 

工作得很好。以下是在活动和保存方法之间发送/接收数据的代码。

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();
}

这是内部保存文本的方法(工作正常)。请注意,我在writeMessage中添加了sendMessage函数(但注释了它)

 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();
    }

}

另一个我无法解决的小问题:

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

当用户单击按钮时,是一种应该从编辑文本中收缩文本的小方法。它总是增加文本。一些帮助将不胜感激。

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);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

正如已经建议的那样,您可以使用您在编辑时刚刚点击的listview项目上的数据开始第二项活动,或者当您创建新项目时不要传递任何内容。

通过这种方式,您既可以编辑也可以创建新的Note,而无需对代码进行太多更改。

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);
        }
    });

NoteEditActivity.class中,如果有任何内容,您可以收到参数。正如创建新的Note para1,para2,para3&amp; para4将是空的。但如果说明已存在,则必须编辑

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 :)

}

完成创建或编辑笔记后,将相关数据附加到意图并完成此活动

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(); 

如果任务成功,您将结果设置为RESULT_OK附加意图并且您已完成

在上一个活动中,您必须覆盖名为onActivityResult()的方法,此方法会从您开始执行某项任务的活动中接收数据,

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
         }     
    }
}
  

更新,我已经为你创建了一个虚拟代码,它确实有效,我已经测试过了,我也在Github上传了它你可以在那里查看

<强> 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>