2014-09-21 4 views
0

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

package com.zaki.thenewboston; 

import android.os.Bundle; 
import android.support.v4.app.Fragment; 
import android.support.v7.app.ActionBarActivity; 
import android.view.LayoutInflater; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.view.ViewGroup; 
import android.widget.Button; 
import android.widget.TextView; 

public class MainActivity extends ActionBarActivity { 

    int   counter; 
    Button  add,sub;  //used to reference to xml view ids 
    TextView display;  //used to reference to xml view ids 


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

     if (savedInstanceState == null) { 
      getSupportFragmentManager().beginTransaction() 
        .add(R.id.container, new PlaceholderFragment()) 
        .commit(); 
     } 

      //zaki: this is to wait the R.layout.activity_main to load first other wise the program may crash 
      counter =0; 
      add = (Button) findViewById(R.id.bAdd); 
      // sub = (Button) findViewById(R.id.bSub); 
      display = (TextView) findViewById(R.id.tvDisplay);  
      add.setOnClickListener(new OnClickListener() {    
       @Override 
       public void onClick(View v) { 
        // TODO Auto-generated method stub 
        counter ++; 
        display.setText("Your total is" + counter); 

       } 
      }); 

      /* 
      sub.setOnClickListener(new OnClickListener() { 
       @Override 
       public void onClick(View v) { 
        // TODO Auto-generated method stub 
        counter --; 
        display.setText("Your total is" + counter); 
       } 
      });*/ 



    } 


    @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); 
    } 

    /** 
    * A placeholder fragment containing a simple view. 
    */ 
    public static class PlaceholderFragment extends Fragment { 

     public PlaceholderFragment() { 
     } 

     @Override 
     public View onCreateView(LayoutInflater inflater, ViewGroup container, 
       Bundle savedInstanceState) { 
      View rootView = inflater.inflate(R.layout.fragment_main, container, false); 
      return rootView; 
     } 
    } 

} 

здесь является LogCat: Я думаю, что есть нуль возвращается , но почему? Я не знаю причины. , и я уверен, что проблема в onCreateView

09-21 12:58:37.277: D/AndroidRuntime(1449): Shutting down VM 
09-21 12:58:37.277: W/dalvikvm(1449): threadid=1: thread exiting with uncaught exception (group=0xb2a81ba8) 
09-21 12:58:37.277: E/AndroidRuntime(1449): FATAL EXCEPTION: main 
09-21 12:58:37.277: E/AndroidRuntime(1449): Process: com.zaki.thenewboston, PID: 1449 
09-21 12:58:37.277: E/AndroidRuntime(1449): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.zaki.thenewboston/com.zaki.thenewboston.MainActivity}: java.lang.NullPointerException 
09-21 12:58:37.277: E/AndroidRuntime(1449):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195) 
09-21 12:58:37.277: E/AndroidRuntime(1449):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) 
09-21 12:58:37.277: E/AndroidRuntime(1449):  at android.app.ActivityThread.access$800(ActivityThread.java:135) 
09-21 12:58:37.277: E/AndroidRuntime(1449):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 
09-21 12:58:37.277: E/AndroidRuntime(1449):  at android.os.Handler.dispatchMessage(Handler.java:102) 
09-21 12:58:37.277: E/AndroidRuntime(1449):  at android.os.Looper.loop(Looper.java:136) 
09-21 12:58:37.277: E/AndroidRuntime(1449):  at android.app.ActivityThread.main(ActivityThread.java:5017) 
09-21 12:58:37.277: E/AndroidRuntime(1449):  at java.lang.reflect.Method.invokeNative(Native Method) 
09-21 12:58:37.277: E/AndroidRuntime(1449):  at java.lang.reflect.Method.invoke(Method.java:515) 
09-21 12:58:37.277: E/AndroidRuntime(1449):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 
09-21 12:58:37.277: E/AndroidRuntime(1449):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 
09-21 12:58:37.277: E/AndroidRuntime(1449):  at dalvik.system.NativeStart.main(Native Method) 
09-21 12:58:37.277: E/AndroidRuntime(1449): Caused by: java.lang.NullPointerException 
09-21 12:58:37.277: E/AndroidRuntime(1449):  at com.zaki.thenewboston.MainActivity.onCreate(MainActivity.java:38) 
09-21 12:58:37.277: E/AndroidRuntime(1449):  at android.app.Activity.performCreate(Activity.java:5231) 
09-21 12:58:37.277: E/AndroidRuntime(1449):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) 
09-21 12:58:37.277: E/AndroidRuntime(1449):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159) 
09-21 12:58:37.277: E/AndroidRuntime(1449):  ... 11 more 

файл Activity_main.xml ниже

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:id="@+id/container" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    tools:context="com.zaki.thenewboston.MainActivity" 
    tools:ignore="MergeRootFrame" /> 

и файл fragment_main.xml ниже

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:id="@+id/LinearLayout1" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    tools:context="com.zaki.thenewboston.MainActivity$PlaceholderFragment" > 

    <TextView 
     android:id="@+id/tvDisplay" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_gravity="center" 
     android:text="@string/your_total_is" /> 

    <Button 
    android:layout_width="240dp" 
    android:layout_height="wrap_content" 
    android:layout_gravity="center" 
    android:text="@string/add_one" 
    android:textSize="20sp" 
    android:id="@+id/bAdd" 
    /> 

    <Button 
    android:layout_width="240dp" 
    android:layout_height="wrap_content" 
    android:layout_gravity="center" 
    android:text="@string/subtract_one" 
    android:textSize="20sp" 
    android:id="@+id/bSub" 
    /> 

</LinearLayout> 

также отметить, что i изменил линию

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

быть

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.fragment_main); 

и проблема все еще существует

+0

Скопируйте вставьте его :-) – Nabin

+1

разместить линию номер 38 в своем классе –

+1

Вставьте файл макета (activity_main). Лучше всего догадаться, что файл макета пропускает кнопку. – Psypher

ответ

0

я обнаружил, что проблема заключается не только в перемещении кода в PlaceholderFragment, как я получил новую ошибку компиляции , так как я опубликовал

, а также следующие коды

  add = (Button) findViewById (R.id.bAdd); 
      sub = (Button) findViewById(R.id.bSub); 
      display = (TextView) findViewById(R.id.tvDisplay); 

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

  add = (Button) rootView.findViewById (R.id.bAdd); 
      sub = (Button) rootView.findViewById(R.id.bSub); 
      display = (TextView) rootView.findViewById(R.id.tvDisplay); 

я ценю комментарии с объяснением того, что я сделал

0

переместить это класс фрагмент

counter =0; 
      add = (Button) rootView.findViewById(R.id.bAdd); 

      display = (TextView) rootView.findViewById(R.id.tvDisplay);  
      add.setOnClickListener(new OnClickListener() {    
       @Override 
       public void onClick(View v) { 
        // TODO Auto-generated method stub 
        counter ++; 
        display.setText("Your total is" + counter); 

       } 
      }); 
+0

, когда я это сделал, я получил следующую ошибку: « Невозможно сделать статическую ссылку на нестатический метод findViewById (int) из типа« Активность » –

+0

Удалить статику для фрагмента заполнителя –

+0

У вас возникли проблемы с форматированием кода .. – 2Dee

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