2015-09-28 3 views
-1

Я попытался найти ответы, но еще не нашел исправления для моей проблемы. У меня есть 2 вида деятельности - лак и Бэкон. Я пытаюсь изучить намерения и данные, проходящие между действиями. Предполагается, что активность яблока передаёт значение, введенное в поле EditText, при нажатии кнопки на операцию бекона, которая просто отображает значение. Я получаю следующее исключение в стекеeditText.getText() возвращает null

Caused by: java.lang.NullPointerException: Attempt to invoke 
virtual method 'android.text.Editable android.widget.EditText.getText()' 
on a null object reference 

Фрагменты кода заключаются в следующем: -

apples.xml

<RelativeLayout 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:paddingLeft="@dimen/activity_horizontal_margin" 
android:paddingRight="@dimen/activity_horizontal_margin" 
android:paddingTop="@dimen/activity_vertical_margin" 
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".Apple" 
android:background="#009900"> 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:textAppearance="?android:attr/textAppearanceLarge" 
    android:text="Apples" 
    android:id="@+id/applesText" 
    android:layout_alignParentTop="true" 
    android:layout_centerHorizontal="true" /> 

<Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Go to Bacon" 
    android:id="@+id/applesButton" 
    android:layout_below="@+id/applesText" 
    android:layout_centerHorizontal="true" 
    android:layout_marginTop="104dp" 
    android:onClick="onClickApples"/> 

<EditText 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:inputType="textPersonName" 
    android:ems="10" 
    android:id="@+id/personName" 
    android:layout_below="@+id/applesText" 
    android:layout_centerHorizontal="true" /> 

Apples.java

package com.example.karan.intentexample; 

import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.content.Intent; 
import android.widget.EditText; 

public class Apple extends AppCompatActivity { 

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

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.menu_apple, menu); 
     return true; 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     // Handle action bar item clicks here. The action bar will 
     // automatically handle clicks on the Home/Up button, so long 
     // as you specify a parent activity in AndroidManifest.xml. 
     int id = item.getItemId(); 

     //noinspection SimplifiableIfStatement 
     if (id == R.id.action_settings) { 
      return true; 
     } 

     return super.onOptionsItemSelected(item); 
    } 

    public void onClickApples(View view){ 

     final EditText applesInput = (EditText)view.findViewById(R.id.personName); 
     String userMessage = applesInput.getText().toString(); 
     Intent i = new Intent(this, Bacon.class); 
     //putExtra takes data in the form of a key-value pair 
     i.putExtra("appleMessage", userMessage); 
     startActivity(i); 
     } 
    } 

Bacon.xml

<RelativeLayout 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:paddingLeft="@dimen/activity_horizontal_margin" 
android:paddingRight="@dimen/activity_horizontal_margin" 
android:paddingTop="@dimen/activity_vertical_margin" 
android:paddingBottom="@dimen/activity_vertical_margin" 
tools:context="com.example.karan.intentexample.Bacon" 
android:background="#72231F"> 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:textAppearance="?android:attr/textAppearanceLarge" 
    android:text="Bacon" 
    android:id="@+id/baconText" 
    android:layout_alignParentTop="true" 
    android:layout_centerHorizontal="true" 
    android:layout_marginTop="39dp" /> 

<Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="New Button" 
    android:id="@+id/baconButton" 
    android:layout_below="@+id/baconText" 
    android:layout_centerHorizontal="true" 
    android:layout_marginTop="99dp" /> 

Bacon.java

package com.example.karan.intentexample; 

import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.widget.TextView; 

public class Bacon extends AppCompatActivity { 

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

     Bundle applesData; 
     applesData = getIntent().getExtras(); 

     //if there is no data in the intent 
     if(applesData==null) 
      return; 

     //get value by using the key in the getString method 
     String appleMessage = applesData.getString("appleMessage"); 
     final TextView baconText = (TextView)findViewById(R.id.baconText); 
     baconText.setText(appleMessage); 

    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.menu_bacon, menu); 
     return true; 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     // Handle action bar item clicks here. The action bar will 
     // automatically handle clicks on the Home/Up button, so long 
     // as you specify a parent activity in AndroidManifest.xml. 
     int id = item.getItemId(); 

     //noinspection SimplifiableIfStatement 
     if (id == R.id.action_settings) { 
      return true; 
     } 

     return super.onOptionsItemSelected(item); 
    } 
} 

ответ

1

Здесь:

final EditText applesInput = (EditText)view.findViewById(R.id.personName); 

view.findViewById вызывая issue.change этом:

final EditText applesInput = (EditText)Apple.this.findViewById(R.id.personName); 

Поскольку EditText с personName идентификатором в деятельности макете вместо внутренней компоновки Button (параметр зрения onClickApples)

1
public class Apple extends AppCompatActivity { 

private EditText applesInput; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_apple); 
    applesInput = (EditText)findViewByID(R.id.personName); 
} 
public void onClickApples(View view){ 

    String userMessage = applesInput.getText().toString(); 
    Intent i = new Intent(this, Bacon.class); 
    //putExtra takes data in the form of a key-value pair 
    i.putExtra("appleMessage", userMessage); 
    startActivity(i); 

    } 
} 
+0

использовать findViewByID в OnCreate, вы должны бросить взгляд на объект EditText, перед использованием это, почему он выбрасывает: «Caused by: java.lang.NullPointerException: попытка вызвать virtual method» android.text.Editable android.widget.EditText.getText() ' по ссылке нулевого объекта " –

+0

Пока этот код может ответить на исходный вопрос OP, несколько строк объяснения помогут нынешним и будущим читателям лучше понять ваш вопрос. – Thom

Смежные вопросы