2012-03-11 3 views
0

У меня есть программа для Android, которая запускает намерение и передает значение следующей активности. Я делал это раньше, и он работал отлично. Но в этом случае он не передает значение. Я использовал тосты, чтобы узнать, что происходит, и я не могу понять, что происходит. Другой вопрос в моей другой программе, что intent.putextra работал кодandroid intent putextra wont pass my value

 Intent i= new Intent(this,SpecialLocationDatabase.class); 

работал, но в этой программе это дало мне ошибку: «Удалить аргументы из намерения», так что я должен был кодировать это нравится:

 Intent i= new Intent(Main.this,SpecialLocationDatabase.class); 

мой код ниже. Есть два вида деятельности Основные и SpecialLocationDataBase:

public class Main extends Activity { 
    /** The activity that launches the intent and passes the value. */ 

TextView tv; 

private SpecialLocationDatabaseHelper dbIngredientHelper=null; 
private static final int ACTIVITY_CREATE=0; 



@Override 
    public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    dbIngredientHelper = new SpecialLocationDatabaseHelper(this); 
    dbIngredientHelper.createDatabase(); 


    final Button button1 = (Button) findViewById(R.id.button1); 
    button1.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
      // Perform action on click 
      long choice=1; 
      Intent i= new Intent(Main.this,SpecialLocationDatabase.class); 
      i.putExtra("choice", choice); 
      //Main.this.startActivity(i); 
      startActivityForResult(i, ACTIVITY_CREATE); 

      Toast.makeText(Main.this, 
        "Here is your choice " + choice + " clicked", 
        Toast.LENGTH_LONG).show(); 




     } 
    }); 

    final Button button2 = (Button) findViewById(R.id.button2); 
    button2.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
      // Perform action on click 
      long choice=2; 
      Intent i= new Intent(Main.this,SpecialLocationDatabase.class); 
      i.putExtra("choice", choice); 
      Main.this.startActivity(i); 


     } 
    }); 

    final Button button3 = (Button) findViewById(R.id.button3); 
    button3.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
      // Perform action on click 
      long choice=3; 
      Intent i= new Intent(Main.this,SpecialLocationDatabase.class); 
      i.putExtra("choice", choice); 
      Main.this.startActivity(i); 


     } 
    }); 

    final Button button4 = (Button) findViewById(R.id.button4); 
    button4.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
      // Perform action on click 
      long choice=4; 
      Intent i= new Intent(Main.this,SpecialLocationDatabase.class); 
       i.putExtra("choice", choice); 
      Main.this.startActivity(i); 


     } 
    }); 



    public class SpecialLocationDatabase extends ListActivity { 
    /** The activity that is supposed to get the value. */ 


private static final int ACTIVITY_CREATE=0; 
    private static final int ACTIVITY_EDIT=1; 
    private SpecialLocationDatabaseHelper mDbHelper=null; 

    long choice; 

    private static final int BEGIN_SEARCH_OPTION = Menu.FIRST; 


    @Override 
    public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.specialloction); 

    mDbHelper=new SpecialLocationDatabaseHelper(this); 
    mDbHelper.openRead(); 
    Bundle extras = getIntent().getExtras(); 
    choice = extras.getInt("choice"); 
     Toast.makeText(SpecialLocationDatabase.this, 
       "NOw your choice " + choice + " clicked", 
       Toast.LENGTH_LONG).show(); 
    fillData(choice); 
    registerForContextMenu(getListView()); 

    ListView list = getListView(); 
    list.setOnItemLongClickListener(new OnItemLongClickListener() { 

     @Override 
     public boolean onItemLongClick(AdapterView<?> parent, View view, 
       int position, long id) { 




      return true; 
     } 
    }); 

ответ

3

Вы кладете choice до тех пор, но читать его как int, вам необходимо изменить один из них, например:

long receivedChoice = extras.getLong("choice"); 

Что касается другого вопроса - поскольку второй раз цель была создана внутри внутреннего класса, this должен быть полностью подготовлен (напр., Main.this), чтобы было указано, что вы передаетедеятельности, а не

+0

Это работало !!! Спасибо! – codenamejupiterx

0

Конструктор, который вы используете для намерения, которое вы отправляете, принимает контекст приложения. Как сказал первый респондент, вы должны устранить «это». Обычно я использую getApplicationContext() вместо «this».

Кроме того, нет необходимости приобретать все дополнительные функции одновременно как комплект. Существуют методы получения индивидуальных значений из Экстра в зависимости от их типа. В вашем случае вы можете использовать getLongExtra(). getExtras() предназначен для извлечения целого пакета дополнительных функций, которые были помещены в Intent с помощью putExtras(). В общем случае использование putParceableArrayListExtra() и getParceableArrayListExtra() более прямолинейно для отправки «карты» дополнительных функций одновременно, и они также работают между приложениями.

+0

«Обычно я использую getApplicationContext() вместо« this »» - IMHO, это плохая привычка. Хотя 'getApplicationContext()' возвращает «Контекст», этот «Контекст» не подходит для многих вещей, особенно связанных с пользовательским интерфейсом. IMHO, используйте только 'getApplicationContext()', когда вы точно знаете * почему * 'getApplicationContext()' - правильный ответ для данной ситуации. В противном случае «это» обычно является правильным ответом. Он также увеличивается быстрее (без вызова метода). – CommonsWare