2017-02-14 10 views
0

Мой вопрос тот же, что здесь .getExtras()' on a null object referenceКак я могу объявить переменную вне метода, а затем инициализировать ее внутри OnCreate()?

Но я не знаю, как сделать это codeMagic говорит: «Вы должны были бы объявить их вне метода и инициализировать их внутри OnCreate() Это или передать. значения, необходимые для необходимых функций »

Извините, что я очень новичок в мире программирования. `package ejemplo1.listaejemplo;

import android.app.Activity; 
import android.content.Context; 
import android.view.View; 
import android.os.Bundle; 
import android.view.LayoutInflater; 
import android.view.ViewGroup; 

import android.widget.ArrayAdapter; 
import android.widget.ListView; 
import android.widget.TextView; 


public class Lista extends Activity { 

    private ListView lista; 

    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.lista); 

     String elem1 = getIntent().getExtras().getString("Nombre"); 
     String elem2 = getIntent().getExtras().getString("Sexo"); 

     Espacios[] datos = new Espacios[] { 
       new Espacios(elem1, elem2), 
       new Espacios("Nombre2", "Sexo2")}; 

     lista = (ListView)findViewById(R.id.Interesar); 

     Adapta adaptador = new Adapta(this, datos); 
     lista.setAdapter(adaptador); 

    } 
    class Adapta extends ArrayAdapter<Espacios> { 

     String elem1 = getIntent().getExtras().getString("Nombre"); 
     String elem2 = getIntent().getExtras().getString("Sexo"); 

     Espacios[] datos = new Espacios[] { 
       new Espacios(elem1, elem2), 
       new Espacios("Nombre2", "Sexo2")}; 

     public Adapta(Context context, Espacios[] datos) { 
      super(context, android.R.layout.simple_list_item_2, datos); 
     } 

     public View getView(int position, View convertView, ViewGroup parent) { 

      LayoutInflater inflater = LayoutInflater.from(getContext()); 
      View item = inflater.inflate(android.R.layout.simple_list_item_2, null); 

      TextView texto1 = (TextView) item.findViewById(android.R.id.text1); 

      texto1.setText(datos[position].getNombre()); 

      TextView texto2 = (TextView) item.findViewById(android.R.id.text2); 
      texto2.setText(datos[position].getSexo()); 



      return(item); 


     } 

    } 


} 
` 
+0

Возможный дубликат [.getExtras() 'для ссылки на нулевой объект) (http://stackoverflow.com/questions/33192284/getextras-on-a-null-object-reference) – dovetalk

+0

Пожалуйста, добавьте образец код, который у вас есть на данный момент. Это позволяет людям давать конкретные советы. –

+0

Есть мой код, я решаю оригинальную проблему, но мне нужно дублировать переменную «datos» «elem1» «elem2», теперь я хочу знать, существует ли способ устранить первые. Благодаря! – Erick

ответ

0

Объявите переменные elem1 и elem2 в качестве членов класса, так же, как вы сделали для переменной lista. Это позволяет использовать elem1 и elem2 для доступа ко всем методам вашего класса. Как только это будет сделано, присвойте свои значения от getExtras к нему в методе onCreate().

Так, например

public class Lista extends Activity { 

    private ListView lista; 
    //Here we are declaring our elem variables outside the onCreate() method 
    //This means that your "Adapta" class can use them 
    private String elem1; 
    private String elem2; 

    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.lista); 

     //And here we are assigning them the values from getExtras() 
     elem1 = getIntent().getExtras().getString("Nombre"); 
     elem2 = getIntent().getExtras().getString("Sexo"); 

     Espacios[] datos = new Espacios[] { 
      new Espacios(elem1, elem2), 
      new Espacios("Nombre2", "Sexo2") 
     }; 

     lista = (ListView)findViewById(R.id.Interesar); 

     Adapta adaptador = new Adapta(this, datos); 
     lista.setAdapter(adaptador); 
    } 

    class Adapta extends ArrayAdapter<Espacios> { 

     //Notice we have removed elem1 and elem2 from the adapter class 
     Espacios[] datos = new Espacios[] { 
      new Espacios(elem1, elem2), 
      new Espacios("Nombre2", "Sexo2") 
     }; 

     public Adapta(Context context, Espacios[] datos) { 
      super(context, android.R.layout.simple_list_item_2, datos); 
     } 

     public View getView(int position, View convertView, ViewGroup parent) { 
      LayoutInflater inflater = LayoutInflater.from(getContext()); 
      View item = inflater.inflate(android.R.layout.simple_list_item_2, null); 

      TextView texto1 = (TextView) item.findViewById(android.R.id.text1); 

      texto1.setText(datos[position].getNombre()); 

      TextView texto2 = (TextView) item.findViewById(android.R.id.text2); 
      texto2.setText(datos[position].getSexo()); 

      return(item); 
     } 

    } 

} 

Я поставил несколько замечаний в приведенном выше примере, я надеюсь, что это делает вещи немного яснее.