2013-10-11 3 views
1

Я последовал за учебник здесь: http://developer.samsung.com/android/technical-docs/Gestures-in-Android Это работает, если я делаю это в отдельный проект, но, когда я пытаюсь реализовать его в другом проекте, как это:Android addOnGesturePerformedListener возвращает NullPointerException

public class Main extends Activity implements OnGesturePerformedListener { 
    int mDay = Calendar.getInstance().get(Calendar.DAY_OF_MONTH); 
    int mMonth = Calendar.getInstance().get(Calendar.MONTH); 
    int mYear = Calendar.getInstance().get(Calendar.YEAR); 
    boolean listHasItems = false; 
    public static String date = ""; 
    ArrayList<String> listNames = new ArrayList<String>(); 
    List<ActivityToDo> acts = System.activities; 
    GestureLibrary gLibrary; 
    GestureOverlayView mView; 

     @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     // Remove title bar 
     this.requestWindowFeature(Window.FEATURE_NO_TITLE); 
     removeActivitesBeforeCurrentDate(); 
     readDB(); 

     gLibrary = GestureLibraries.fromRawResource(this, R.raw.gestures); 
     if (gLibrary != null) { 
      if (!gLibrary.load()) { 
       Log.e("GestureSample", "Gesture library was not loaded…"); 
       finish(); 
      } else { 
       mView = (GestureOverlayView) findViewById(R.id.gestures); 
       mView.addOnGesturePerformedListener(this); 
      } 
     } 

     setContentView(R.layout.main); 
     final Button btnNewAct = (Button) findViewById(R.id.btnNewAct); 

     final DatePicker datep = (DatePicker) findViewById(R.id.datePicker); 
     datep.init(mYear, mMonth, mDay, new OnDateChangedListener() { 
      @Override 
      public void onDateChanged(DatePicker view, int year, 
        int monthOfYear, int dayOfMonth) { 
       mDay = datep.getDayOfMonth(); 
       mMonth = datep.getMonth(); 
       mYear = datep.getYear(); 
       buildList(mDay, mMonth + 1, mYear); 
      } 
     }); 

     btnNewAct.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       Intent i = new Intent(); 
       i.setClass(getApplicationContext(), NewActivity.class); 
       startActivity(i); 
      } 
     }); 

     final ListView listview = (ListView) findViewById(R.id.listview); 

     // listNames.add("Pick date to search activity."); 
     buildList(mDay, mMonth + 1, mYear); 
     ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, 
       android.R.layout.simple_list_item_1, listNames); 
     listview.setAdapter(adapter); 
     registerForContextMenu(listview); 

    } 

    @Override 
    public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) { 
     ArrayList<Prediction> predictions = gLibrary.recognize(gesture); 
     // one prediction needed 
     if (predictions.size() > 0) { 
      Prediction prediction = predictions.get(0); 
      // checking prediction 
      if (prediction.score > 1.0) { 
       // and action 
       Toast.makeText(this, prediction.name,Toast.LENGTH_SHORT).show(); 
      } 
     }  
    } 

MView .addOnGesturePerformedListener (это); возвращает исключение nullPointerException. Даже если я попытаюсь пройти (Main.this), что является решением для этого аналогичного вопроса Android: Nullpointer Exception in addOnGesturePerformedListener.

XML:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:gravity="center_horizontal" 
    android:orientation="vertical" 
    tools:context=".Main" > 

<android.gesture.GestureOverlayView 
    android:id="@+id/gestures" 
    android:layout_width="50dp" 
    android:layout_height="0dip" 
    android:layout_weight="0.5" /> 

<ListView 
    android:id="@+id/listview" 
    android:layout_width="250dp" 
    android:layout_height="200dp" 
    android:layout_weight="0.5" 
    android:background="@drawable/spinnerst" > 
</ListView> 
</LinearLayout> 

Как вы думаете, это проблема? заранее спасибо.

Edit: Это не работает, если я передать слушателю mView.addOnGesturePerformedListener (это):

OnGesturePerformedListener listener=new OnGesturePerformedListener() { 
     @Override 
     public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) { 
      ArrayList<Prediction> predictions = gLibrary.recognize(gesture); 
      // one prediction needed 
      if (predictions.size() > 0) { 
       Prediction prediction = predictions.get(0); 
       // checking prediction 
       if (prediction.score > 1.0) { 
        // and action 
        mostrarToast(prediction.name); 
       } 
      } 
     } 
    }; 
    gLibrary = GestureLibraries.fromRawResource(this, R.raw.gestures); 
    if (gLibrary != null) { 
     if (!gLibrary.load()) { 
      Log.e("GestureSample", "Gesture library was not loaded…"); 
      finish(); 
     } else { 
      mView = (GestureOverlayView) findViewById(R.id.gestures); 
      mView.addOnGesturePerformedListener(listener); 
     } 
    } 
+0

пост StackTrace – njzk2

ответ

0

Вы можете использовать метод findViewById в деятельности, только если у вас есть setContentView(), который определяет макет этой деятельности. В вашем конкретном случае, вы не вызываете setContentView поэтому

(GestureOverlayView) findViewById(R.id.gestures)

возвратит нуль и вызвать NullPointerException при вызове любого метода на MView (в вашем случае mView.addOnGesturePerformedListener (это);)

+0

Супер глупая ошибка: P спасибо большое! – RominaV

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