2015-05-01 5 views
0

Это основное действие, из которого я передаю значения классу, выбранному по выбору.Нельзя передавать значения с одного намерения на другое

@Override 
public void onClick(View v) { 
// TODO Auto-generated method stub 

String x=""; 
for(int i=0;i<count;i++) 
{ 
    x+=songf[i]+" "; 
} 
Toast.makeText(getApplicationContext(), x, Toast.LENGTH_SHORT).show(); 
Choice o = new Choice(); 
o.initializeit(songf,sizef,linkf,indexf,count); 
Intent ix=new Intent("com.example.harmony.CHOICE"); 
startActivity(ix); 
} 

/*public void doit() 
{ 
    Choice o = new Choice(); 
    o.initializeit(songf,sizef,linkf,indexf,count); 
} 
*/ 

Это выбор класса

public class Choice extends Activity implements OnClickListener{ 

Button b; 
RadioButton rb1,rb2,rb3,rb4 ; 
RadioGroup rg; 

static String[] songf = new String[19]; 
static Integer[] indexf = new Integer[19]; 
static String[] linkf = new String[19]; 
static double[] sizef = new double[19]; 
static int count; 

public static void initializeit(String[] song, double[] size, String[] link,Integer[] index, int c) { 
    // TODO Auto-generated method stub 
    songf=song; 
    sizef=size; 
    indexf=index; 
    linkf=link; 
    count=c; 
    String x=""; 
    //x+=Integer.toString(count); 
    //Toast.makeText(getApplicationContext(), x, Toast.LENGTH_SHORT).show(); 
    //for(int i=0;i<count;i++) 
    //{ 
    // x+=songf[i]+" "; 
// } 
// Toast.makeText(getApplicationContext(), x, Toast.LENGTH_SHORT).show(); 
} 

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

    b = (Button) findViewById(R.id.download); 
    rg = (RadioGroup) findViewById(R.id.radioGroup1); 
    rb1 = (RadioButton) findViewById(R.id.fcfs); 
    rb2 = (RadioButton) findViewById(R.id.sjf); 
    rb3 = (RadioButton) findViewById(R.id.priority); 
    b.setOnClickListener(this); 
    MainActivity o = new MainActivity(); 
    o.doit(); 

} 

@Override 
public void onClick(View v) { 
    // TODO Auto-generated method stub 
    if(rb1.isChecked()) 
    { 
    for(int i=0;i<count;i++) 
    { 
     for(int j=0;j<count-i-1;j++) 
     { 
      if(indexf[j]>indexf[j+1]) 
      { 
       int temp1=indexf[j]; 
       indexf[j]=indexf[j+1]; 
       indexf[j+1]=temp1; 
       String temp2=linkf[j]; 
       linkf[j]=linkf[j+1]; 
       linkf[j+1]=temp2; 
       String temp3=songf[j]; 
       songf[j]=songf[j+1]; 
       songf[j+1]=temp3; 
       double temp4=sizef[j]; 
       sizef[j]=sizef[j+1]; 
       sizef[j+1]=temp4; 
      } 
     } 
    } 
    String x=""; 
     for(int i=0;i<count;i++) 
     { 
      x+=songf[i]+" "; 
     } 
     Toast.makeText(getApplicationContext(), x, Toast.LENGTH_SHORT).show(); 
    } 
    else if(rb2.isChecked()) 
    { 
     for(int i=0;i<count;i++) 
     { 
      for(int j=0;j<count-i-1;j++) 
      { 
       if(sizef[j]>sizef[j+1]) 
       { 
        double temp1=sizef[j]; 
        sizef[j]=sizef[j+1]; 
        sizef[j+1]=temp1; 
        String temp2=linkf[j]; 
        linkf[j]=linkf[j+1]; 
        linkf[j+1]=temp2; 
        String temp3=songf[j]; 
        songf[j]=songf[j+1]; 
        songf[j+1]=temp3; 
        int temp4=indexf[j]; 
        indexf[j]=indexf[j+1]; 
        indexf[j+1]=temp4; 
       } 
      } 
     } 
     String x=""; 
     for(int i=0;i<count;i++) 
     { 
      x+=songf[i]+" "; 
     } 
     x+=Integer.toString(count)+songf[0]+indexf[0]; 
     Toast.makeText(getApplicationContext(), x, Toast.LENGTH_SHORT).show(); 
    } 
    else if(rb3.isChecked()) 
    { 
     String x=""; 
     for(int i=0;i<count;i++) 
     { 
      x+=songf[i]+" "; 
     } 
     Toast.makeText(getApplicationContext(), x, Toast.LENGTH_SHORT).show(); 

    } 

} 


} 

Строковые значения инициализируются в initializeit не инициализируются и дает мне нулевые значения. Я не могу понять эту проблему. Пожалуйста, помогите мне.

+0

Почему вы не инициализируетесь в конструкторе объекта? –

ответ

0

Использования putExtra() для передачи данных от одного Activity к другим

intent.putExtra("KEY", "DATA_TO_BE_SENT"); 

и в вашей второй деятельности, вы должны получить значение с помощью

getIntent().getStringExtra("KEY"); 

Таким образом, в вашем коде,

Choice o = new Choice(); 
o.initializeit(songf,sizef,linkf,indexf,count); 
Intent ix=new Intent("com.example.harmony.CHOICE"); 
startActivity(ix); 

имеет заменяется на

Intent ix=new Intent("com.example.harmony.CHOICE"); 
intent.putExtra("KEY", "DATA_TO_BE_SENT"); 
startActivity(ix); 
0

Если вы хотите переместить некоторые данные из одной активности в другую, вы должны использовать намерение.

Intent intent = new Intent(this, Choice.class); 
**intent.putExtra()** // insert here your data ! 
startActivity(intent); 

Поиск более примыкают этой intent.putExtra здесь http://developer.android.com/training/basics/firstapp/starting-activity.html

0

Общие элементы должны быть переданы по Intent.putExtra

Отправить:

Intent i = new Intent(this, ActivityTwo.class); 
i.putExtra("Value1", "This value one for ActivityTwo "); 
i.putExtra("Value2", "This value two ActivityTwo"); 

Прием:

Bundle extras = getIntent().getExtras(); 
if (extras != null) { 
    // get data via the key 
    String value1 = extras.getString("Value1");  
    if (value1 != null) { 
     // do something with the data 
    } 
} 
0

Звонок startActivity не запускает экземпляр Choice, который вы создали, вы можете представить его как отправку сообщения в приложение для создания нового действия типа Choice.

Если вы хотите передать информацию на мероприятие, то в «дополнительной» информации в намерениях. Затем вы можете получить информацию из дополнительных функций onCreate of the Choice.

См. documentation.

1

Вы должны передать данные таким образом:

Intent intent = new Intent(this, Choice.class); 
intent.putExtra("fname", "My first name"); 
intent.putExtra("lname", "My last name"); 
startActivity(intent); 

и извлекать данные в Choice.class таким образом:

Intent intent = getIntent(); 
String fName = intent.getStringExtra("fname"); 
String lName = intent.getStringExtra("lname"); 

Используйте метод putExtra("key", value); и getExtra("key"); и вы не должны создать экземпляр любого Activity исключением случаев, когда вы хотите перейти туда. См. Подробности doc.

+0

Чтобы передать массив, просто наберите intent.putExtra ("fname", songf []); ? –

+0

Да, вы можете сделать это точно. Только одно, если вы хотите передать 'Object', вам нужно обернуть его в' Bundle'.http: //developer.android.com/reference/android/os/Bundle.html и пример 'Bundle' http: //stackoverflow.com/questions/768969/passing-a-bundle-on-startactivity – Yurets

+0

Не беспокойтесь об этом. В любом случае. если он решит проблему, примите ответ, поэтому вопрос будет закрыт :) – Yurets

0
Intent ix=new Intent(this ,Choice.class); 

это может сработать. И передать значения, и нужно добавить код follwing

ix.putExtra("key_name",value); 

чем написать ix.startActivity(); для получения вы можете использовать getIntent().getStringExtra("key_name");

0

Вы не пропуская ничего нового вида деятельности открываемой. Вам нужно использовать putExtra перед startActivity, а затем getExtra в вашей OnCreate в другой активности.

Используйте класс Choice, который не расширяет активность и не имеет конструктора и членов.

public class Choice(){ 
//members 
//constructor 
} 

Choice myChoice = new Choice(songf,sizef,linkf,indexf,count); 

Затем вызовите второе действие, как при передаче дополнительного.

Intent ix=new Intent("com.example.harmony.mysecondactivity"); 
ix.putExtra(myChoice, strName); 
startActivity(ix); 

В другой деятельности получить дополнительную назад

private Choice myChoiceFromTheOtherActivity; 

@Override 
    protected void onCreate(Bundle savedInstanceState) { 

     super.onCreate(savedInstanceState); 
     setContentView(R.layout.intent); 
     Intent i= getIntent(); 
     Bundle b = i.getExtras(); 
     myChoiceFromTheOtherActivity = new Choice(); 
     //you may need to parse this i don't remember 
     myChoiceFromTheOtherActivity = extras.getString("myChoice"); 


    } 

http://developer.android.com/reference/android/content/Intent.html

0

Вы пытаетесь передать данные от основной деятельности к деятельности Выбор? Я вас понял? Если это так, я рекомендую использовать методы putExtra/s класса Intent. Затем в операции «Выбор» извлекайте дополнительные функции, вызывая метод getIntent() класса Activity, который возвращает намерение, которое запустило действие. Затем используйте метод getExtra/s класса Intent. Обратите внимание, что в основном вы можете размещать примитивные типы данных, массивы примитивных типов данных и некоторые другие классы, которые я рекомендую вам изучить. Так, в MainActivity:

Intent intent = new Intent(this, SomeOtherActivity.class); 
intent.putExtra(KEY, new String("some data")); //Remember to check out 
// which values you can pass in the Intent documentation 
startActivity(intent); 

И в SomeOtherActivity извлечения данных

Intent intent = getIntent(); 
    String data = intent.getStringExtra(KEY); 
    // Notice that because i passed am String value, I'm using the 
    // corresponding method to retrieve the data. Also in the Intent documentation 

Существует также способ передать костюм объекты, делая их реализовать Serializable класс, и передавая их используя метод putExtra (String key, Serializable value) и извлечение данных путем вызова метода Intent.getSerializableExtra (String key).

Я рекомендую вам ознакомиться с некоторыми учебниками по этому вопросу. Вот один из моих любимых уроков, Vogella tutorials. Intent tutorial. Удачи!

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