2013-09-10 3 views
1

Я студент, и это задание. Я следил за указаниями для этой программы, но когда я запускаю свое приложение, он падает. Основываясь на трассе стека, я считаю, что проблема заключается в намерении. Но я не знаю точно. Может ли кто-нибудь проверить мой код и объяснить, что не так и почему.Как остановить приложение для Android от сбоев в эмуляторе?

Основным видом деятельности, которая вызывает другой вид деятельности

package edu.cvtc.android.activitylab; 

    import android.os.Bundle; 
    import android.app.Activity; 
    import android.content.Intent; 
    import android.view.Menu; 
    import android.view.View; 
    import android.view.View.OnClickListener; 


    public class EnterNameActivity extends Activity implements OnClickListener{ 

    android.widget.EditText nameField; 
    android.widget.Button okButton; 

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

     //EditText nameField = (EditText) findViewById(R.id.editText1); 
     this.nameField.findViewById(R.id.editText1); 
     //Button okButton = (Button) findViewById(R.id.button1); 
     this.okButton.findViewById(R.id.button1); 
     //EditText and Button are used to type cast the variables because 
     //findViewById only returns an object. 

     okButton.setOnClickListener(this); 
    } 

    @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_entername, menu); 
     return true; 
    } 

    @Override 
    public void onClick(View v) { 
     // Get the text value the user entered 
     String tempText = nameField.getText().toString(); 

     //Clear the text field if there is data 
     if(tempText != ""){ 

      nameField.setText(""); 
     } 

     //Create an Intent to call another activity 
     Intent myIntent = new Intent(this, LayoutMainActivity.class); 

     //Passing the user entered name to the main greeting activity 
     myIntent.putExtra("name", tempText); 
     this.startActivity(myIntent); 
    } 

    } 

Другая деятельность

package edu.cvtc.android.activitylab; 

    import android.os.Bundle; 
    import android.app.Activity; 
    import android.view.Menu; 
    import android.widget.TextView; 

    public class LayoutMainActivity extends Activity { 

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

     android.os.Bundle temp = this.getIntent().getExtras(); 

     if(temp != null){ 
      //Extract the username from the bundle 
      String userName = temp.getString("name"); 

      //get the TextView Id to change the text 
      TextView text = (TextView) findViewById(R.id.textView1); 

      text.setText("Hello " + userName); 
     } 
    } 


    @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_layout_main, menu); 
     return true; 
    } 

    } 

манифеста

<?xml version="1.0" encoding="utf-8"?> 
    <manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="edu.cvtc.android.activitylab" 
    android:versionCode="1" 
    android:versionName="1.0" > 

    <uses-sdk 
     android:minSdkVersion="10" 
     android:targetSdkVersion="18" /> 

    <application 
     android:allowBackup="true" 
     android:icon="@drawable/ic_launcher" 
     android:label="@string/app_name" 
     android:theme="@style/AppTheme" > 
     <activity 
      android:name="edu.cvtc.android.activitylab.LayoutMainActivity" 
      android:label="@string/app_name" > 

     </activity> 
     <activity 
      android:name="edu.cvtc.android.activitylab.EnterNameActivity" 
      android:label="@string/title_activity_enter_name" > 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 
    </application> 

    </manifest> 

Стек след от отладки

Thread [<1> main] (Suspended (exception RuntimeException)) 
    <VM does not provide monitor information> 
    ActivityThread.handleLaunchActivity(ActivityThread$ActivityClientRecord, Intent) line: 2261 
    ActivityThread.access$600(ActivityThread, ActivityThread$ActivityClientRecord, Intent) line: 141  
    ActivityThread$H.handleMessage(Message) line: 1256 
    ActivityThread$H(Handler).dispatchMessage(Message) line: 99 
    Looper.loop() line: 137 
    ActivityThread.main(String[]) line: 5103  
    Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method] 
    Method.invoke(Object, Object...) line: 525 
    ZygoteInit$MethodAndArgsCaller.run() line: 737 
    ZygoteInit.main(String[]) line: 553 

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

+0

Pls сообщение The LogCat. –

+0

Все logcat сказал, что устройство отключено. – user1793408

ответ

1

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

Во-первых, вы почти правильно выполнили инициализацию своего View, но вы изменили их.Измените ваш onCreate() от

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

    //EditText nameField = (EditText) findViewById(R.id.editText1); 
    this.nameField.findViewById(R.id.editText1); // this returns an EditText object so it isn't being applied to a variable. 
    //Button okButton = (Button) findViewById(R.id.button1); 
    this.okButton.findViewById(R.id.button1); 
    //EditText and Button are used to type cast the variables because 
    //findViewById only returns an object. 

    okButton.setOnClickListener(this); 
} 

в

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

    EditText nameField = (EditText) findViewById(R.id.editText1); 
    Button okButton = (Button) findViewById(R.id.button1); 

    okButton.setOnClickListener(this); 
} 

также изменить ваш инициализации Intent использовать ActivtyContext путем изменения

//Create an Intent to call another activity 
    Intent myIntent = new Intent(this, LayoutMainActivity.class); 

в

//Create an Intent to call another activity 
    Intent myIntent = new Intent(EnterNameActivity .this, LayoutMainActivity.class); 

Вот еще одна проблема

if(tempText != ""){ 

когда вы сравните String сек таким образом вы сравните, если объекты равны, но не то, что они ссылаются. Он должен быть

if(!"".equals(tempText)){ 

Это говорит о том, если пустая String не равна значению tempText. В качестве альтернативы вы можете увидеть

if (!tempText.equals("")){ 

но первый способ будет защищать от NPE, потому что если tempText является null вы получите NPE вторым способом, так как вы бы вызов функции на объекте, который null

+0

Спасибо, я опубликовал все, что появилось в трассировке стека. Но потом у меня было более 2 часов, когда на эмуляторе не было ничего, и теперь logcat и консоль даже ничего не показывают. В контексте деятельности не «это» уже предоставляет контекст? – user1793408

+0

Когда вы можете, тестирование на самом устройстве всегда лучше. Что касается «Контекста», вам должно быть хорошо, но вам действительно нужно понять, когда использовать «Context», если вы продолжите разработку для Android. [Этот ответ] (http://stackoverflow.com/questions/18704228/is-there-any-difference-between-activityname-this-this/18704355#18704355) должен помочь в этом. Также обратите особое внимание на последнюю часть моего ответа о сравнении «Строки», потому что это поможет вам позже, если вы этого не поймете. – codeMagic

+0

Я внес изменения в оператор if. Разница между сравнением объектов и примитивов - одна из тех вещей, которые еще не застряли. Я прочитал часть другого сообщения и закончу его, но понимаю, что вы сейчас имеете в виду. «this» может относиться к методу, в котором он находится, когда я действительно хочу эту активность. Так много правил, так мало пространства мозга! – user1793408

1

Что вы здесь делаете неправильно, я полагаю:

//EditText nameField = (EditText) findViewById(R.id.editText1); 
     this.nameField.findViewById(R.id.editText1); 
     //Button okButton = (Button) findViewById(R.id.button1); 
     this.okButton.findViewById(R.id.button1); 
     //EditText and Button are used to type cast the variables because 
     //findViewById only returns an object. 

Просто замените:

this.nameField.findViewById(R.id.editText1); 

и

this.okButton.findViewById(R.id.button1); 

By:

nameField = (EditText) findViewById(R.id.editText1); 

и

okButton = (Button) findViewById(R.id.button1); 

Надеется, что это помогает.

+0

Спасибо, что исправил проблему, и все работает сейчас. бы это сработало, если бы я сделал: this.nameField = (EditText) findViewById (R.id.editText1); – user1793408

+1

@ user1793408Если анс помог затем принять его, выполнив отметку –

0
 EditText nameField = (EditText) findViewById(R.id.editText1); 

     Button okButton = (Button) findViewById(R.id.button1); 

     //EditText and Button are used to type cast the variables because 
     //findViewById only returns an object. 

okButton.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View arg0) { 
     // Get the text value the user entered 
     String tempText = nameField.getText().toString(); 

     //Clear the text field if there is data 
     if(tempText != ""){ 

      nameField.setText(""); 
     } 

     //Create an Intent to call another activity 
     Intent myIntent = new Intent(EnterNameActivity.this, LayoutMainActivity.class); 

     //Passing the user entered name to the main greeting activity 
     myIntent.putExtra("name", tempText); 
     startActivity(myIntent); 
} 

Это лучший способ справиться с edittexts, buttons и onClicks.

* удалить onClick из активности и удалить методы использования и кнопки onclick и edittext, которые использовали это.

+0

Почему вы предлагаете изменить способ обработки 'onClick()'? То, как OP это делает, прекрасно и намного чище, ИМХО. Проблема не связана с тем, как обрабатывается 'onClick()', но с инициализацией переменных – codeMagic

0

Попробуйте этот путь

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




      //Extract the username from the bundle 
      String userName = getIntent().getStringExtra("name"); // UPDATE HERE 

      //get the TextView Id to change the text 
      TextView text = (TextView) findViewById(R.id.textView1); 

      text.setText("Hello " + userName!=null?userName:""); // UPDATE HERE 

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