2014-10-30 2 views
0

Я разработчик приложений для Android, и я хотел бросить вызов самому себе, создав приложение, в которое вводится пользовательский ввод, преобразуется в целое число и вводится в формулу Фибоначчи. Результат должен отображать все числа фибоначчи, зацикливая формулу определенное пользователем количество раз.Попытка сделать приложение для Android Fibonacci

До сих пор, я думаю, что я выделил проблему для ContentViewer, но потом снова любая помощь будет принята с благодарностью. BTW Я использую Eclipse, Juno, если это помогает

MainActivity.java

package com.example.myfirstapp; 

//importing the API for this app 
import android.app.Activity; 
import android.content.Intent; 
import android.os.Bundle; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.widget.EditText; 


public class MainActivity extends Activity { 
//I based this on the first app I learnt (as I haven't done much app development so far) 
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE"; 

//this method creates a default layout when a "new app" is started 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
} 


@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.main, 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(); 
    if (id == R.id.action_settings) { 
     return true; 
    } 
    return super.onOptionsItemSelected(item); 
} 

//This method sends the information of the user input to a second activity screen, 
//through the use of intents 
/** Called when the user clicks the Send button */ 
public void sendMessage(View view) { 
    // Do something in response to button 
    Intent intent = new Intent(this, DisplayMessageActivity.class); 
    EditText editText = (EditText) findViewById(R.id.edit_message); 
    String message = editText.getText().toString(); 
    intent.putExtra(EXTRA_MESSAGE, message); 
    startActivity(intent); 
} 
} 

вход переходит во второй экран деятельности под названием DisplayMessageActivity.java

package com.example.myfirstapp; 

//import all the relevant API for this app 
import android.app.Activity; 
import android.content.Intent; 
import android.os.Bundle; 
import android.view.MenuItem; 
import android.widget.TextView; 

//main class extending Activity superclass 
public class DisplayMessageActivity extends Activity { 

//This main method is where the fibonacci formula is worked out the result is shown 
//For some reason, the ContentViewer is not working for me. 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_display_message); 
    Intent intent = getIntent(); 
    String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE); 

    int messages = Integer.parseInt(message); 
    int[] fib = new int[messages + 1]; 
    fib[0] = 1; 
    fib[1] = 1; 

    for (int i=2; i <= messages; i++) 
     { 
     fib[i] = fib[i-1] + fib[i-2]; 
     } 

    // Create the text view 
    TextView textView = new TextView(this); 
    textView.setTextSize(60); 
    StringBuilder builder = new StringBuilder(); 
    for (int j : fib) 
    { 
     builder.append(j); 
    } 
    String text = builder.toString(); 
    textView.setText(text); 
    } 


    // Set the text view as the activity layout 
    setContentView(textView); 

@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(); 
    if (id == R.id.action_settings) { 
     return true; 
    } 
    return super.onOptionsItemSelected(item); 
} 
} 

Сообщение об ошибке я получаю is

DisplayMessageActivity.java 
activity_display_message cannot be resolved or is not a field (Line 18) 
Return type for this method is missing (Line 46) 
Syntax error on token "textView", VariableDeclaratorId expected after this token (Line 46) 
textView cannot be resolved to a type (Line 46) 

Надеюсь, что информации достаточно. Как ни странно, я следовал учебнику developer.android.com по созданию первого приложения с трюками, чтобы сделать его Фибоначчи.

Большое спасибо.

Редактировать: Спасибо за ваш быстрый ответ. Я проверил и не было activity_display_message.xml, поэтому я только что создал и скопировал все из Activity_main.xml. Я также переместил textviewer внутри метода onCreate. Теперь я просто убираю все, поэтому спасибо, что освободил меня от бессонной ночи.

+0

activity_display_message этот xml находится в папке макета..log говорит, что его нет – Meenal

+0

вы уверены, что ваш файл 'activity_display_message.xml' на месте? –

+0

Попробуйте использовать addContentView (textView) вместо setContentView (textView). –

ответ

0

вы явно не создали activity_display_message (или другая, менее вероятно, возможность вы имеете в виду файл, который не в папке макетов). Вы устанавливаете представление в файл, который не существует. Также из кода я вижу, что вы помещаете setContentView() в случайном месте. Он должен находиться внутри тела метода (желательно в пределах onCreate() в вашем случае).

0

setContentView(textView); вне сторона метод я имею в виду, это глобальный убедитесь, что он с в методе OnCreate

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