Question

I have recently been working on a program for an android application which is a simple XY-Pad which will display the X and Y coordinates of a users input in set View. The way it works is I have an XML layout for the application which has two TextViews (one to display X values, and one to display Y values), and it also has a View which is where the XY-Pad is located. The problem I keep running into though is when I attempt to send the X and Y coordinates over to the XML's linked class file to set the text of the TextViews, I get an error (a NullPointerException error). Does anyone know what could possibly be wrong with by code?

Here is the XML data:

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"

tools:context=".Start" >

<TextView
    android:id="@+id/theX"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="X:"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
    android:id="@+id/theY"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/button1"
    android:layout_marginBottom="30dp"
    android:layout_toLeftOf="@+id/linearLayout1"
    android:text="Y: "
    android:textAppearance="?android:attr/textAppearanceMedium" />

<view class="com.example.robotcontroller.drawing"
    android:id="@+id/XYpad"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_toRightOf="@+id/button1" />

Here is the 'drawing' class, which is that goes inside of the View in the XML data:

 public class drawing extends View{

  private Paint paint = new Paint();
  private Path path = new Path();

  private float eventX = 0;
  private float eventY = 0;

  public drawing(Context context, AttributeSet attrs) {
    super(context, attrs);
    paint.setAntiAlias(true);
    paint.setStrokeWidth(20f);
    paint.setColor(Color.YELLOW);
    paint.setStyle(Paint.Style.STROKE);
    paint.setStrokeJoin(Paint.Join.ROUND);
  }

  @SuppressLint("DrawAllocation")
@Override
  protected void onDraw(Canvas canvas) {
    canvas.drawPath(path, paint);   
    try{            
         Start itUp = new Start();
         itUp.setXY(eventX, eventY); //The call to the method that is being problematic
        }
        catch(Exception e1){
            Toast.makeText(drawing.this.getContext(), "We have an error!  "+ e1, Toast.LENGTH_LONG).show();
        }
  }


  @Override
  public boolean onTouchEvent(MotionEvent event) {
    try{          
     eventX = event.getX();
     eventY = event.getY();

    switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN:         
      path.moveTo(eventX, eventY);  
      return true;
    case MotionEvent.ACTION_MOVE:
        path.reset();
        path.addCircle(eventX, eventY, 20, Path.Direction.CW);
      break;
    case MotionEvent.ACTION_UP:
        path.reset();
      break;
      default:
          path.reset();
      return false;
    }
    // Schedules a repaint.
    invalidate();
    return true;

  }
    catch(Exception e1){
        return true;
    }
  }


 }

The View can be displayed fine and can track your finger, and it can call another method in another class without a problem. The problem is when I want to create a TextView object to manipulate the two TextView's in the XML, the program just crashes and I get a 'NullPointerException', i don't understand why because the item does exist and it contains text, so why would it be non-existent?

Here is the 'Start' activity which is what contains the 'setXY' method that is being problematic:

 public class Start extends Activity {


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

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.start, menu);
    return true;
}


public void setXY(float x, float y){ //The method where the TextViews are created, and pointing to null objects....
    TextView tv1 = (TextView) findViewById(R.id.theX);
    TextView tv2 = (TextView) findViewById(R.id.theY);
    tv1.setText("X value: "+x);     
    tv2.setText("Y value: "+y);
}




 }

Here is the NPE stack Trace (hope it helps...):

 at android.widget.Toast.show(Toast.java:113)
at com.example.robotcontroller.drawing.onDraw(drawing.java:44)
at android.view.View.draw(View.java:14433)
at android.view.View.draw(View.java:14318)
at android.view.ViewGroup.drawChild(ViewGroup.java:3103)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2940)
at android.view.View.draw(View.java:14316)
at android.view.ViewGroup.drawChild(ViewGroup.java:3103)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2940)
at android.view.View.draw(View.java:14316)
at android.view.ViewGroup.drawChild(ViewGroup.java:3103)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2940)
at android.view.View.draw(View.java:14436)
at android.view.View.draw(View.java:14318)
at android.view.ViewGroup.drawChild(ViewGroup.java:3103)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2940)
at android.view.View.draw(View.java:14436)
at com.android.layoutlib.bridge.impl.RenderSessionImpl.render(RenderSessionImpl.java:584)
at com.android.layoutlib.bridge.Bridge.createSession(Bridge.java:338)
at com.android.ide.common.rendering.LayoutLibrary.createSession(LayoutLibrary.java:334)
at com.android.ide.eclipse.adt.internal.editors.layout.gle2.RenderService.createRenderSession(RenderService.java:451)
at com.android.ide.eclipse.adt.internal.editors.layout.gle2.GraphicalEditorPart.renderWithBridge(GraphicalEditorPart.java:1545)
at com.android.ide.eclipse.adt.internal.editors.layout.gle2.GraphicalEditorPart.recomputeLayout(GraphicalEditorPart.java:1302)
at com.android.ide.eclipse.adt.internal.editors.layout.gle2.GraphicalEditorPart.activated(GraphicalEditorPart.java:1059)
at com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate.delegateActivated(LayoutEditorDelegate.java:743)
at com.android.ide.eclipse.adt.internal.editors.common.CommonXmlEditor.activated(CommonXmlEditor.java:416)
at com.android.ide.eclipse.adt.internal.editors.layout.gle2.LayoutWindowCoordinator.partActivated(LayoutWindowCoordinator.java:379)
at org.eclipse.ui.internal.PartService$6.run(PartService.java:131)
at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
at org.eclipse.ui.internal.PartService.partActivated(PartService.java:129)
at org.eclipse.ui.internal.WorkbenchPage$12.run(WorkbenchPage.java:4462)
at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
at org.eclipse.ui.internal.WorkbenchPage.firePartActivated(WorkbenchPage.java:4460)
at org.eclipse.ui.internal.WorkbenchPage.access$16(WorkbenchPage.java:4440)
at org.eclipse.ui.internal.WorkbenchPage$E4PartListener.partActivated(WorkbenchPage.java:173)
at org.eclipse.e4.ui.internal.workbench.PartServiceImpl$2.run(PartServiceImpl.java:193)
at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
at org.eclipse.e4.ui.internal.workbench.PartServiceImpl.firePartActivated(PartServiceImpl.java:191)
at org.eclipse.e4.ui.internal.workbench.PartServiceImpl.activate(PartServiceImpl.java:596)
at org.eclipse.e4.ui.internal.workbench.PartServiceImpl.activate(PartServiceImpl.java:549)
at org.eclipse.e4.ui.internal.workbench.swt.AbstractPartRenderer.activate(AbstractPartRenderer.java:105)
at org.eclipse.e4.ui.workbench.renderers.swt.StackRenderer$ActivationJob.run(StackRenderer.java:214)
at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35)
at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:135)
at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:4144)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3761)
at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$9.run(PartRenderingEngine.java:1053)
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:942)
at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:86)
at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:588)
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:543)
at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149)
at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:124)
at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:353)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:180)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:629)
at org.eclipse.equinox.launcher.Main.basicRun(Main.java:584)
at org.eclipse.equinox.launcher.Main.run(Main.java:1438)
at org.eclipse.equinox.launcher.Main.main(Main.java:1414)
Était-ce utile?

La solution

I finally figured out how to update the TextViews. The way I did it was by creating two TextView objects in the drawing class like so:

         TextView v1 = (TextView) this.getRootView().findViewById(R.id.textView1);
         TextView v2 = (TextView) this.getRootView().findViewById(R.id.textView2);

The getRootView keyword was what I required to get some data object out of the View which drawing was in. I made the program update the values by setting the X and Y TextViews like so:

  protected void onDraw(Canvas canvas) {
    canvas.drawPath(path, paint);   
    try{            
         TextView v1 = (TextView) this.getRootView().findViewById(R.id.textView1);
         TextView v2 = (TextView) this.getRootView().findViewById(R.id.textView2);
         v1.setText("X: "+eventX);
         v2.setText("Y: "+eventY);
        }
        catch(Exception e1){
            Log.d("myError", e1);
        }
  }
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top