mercredi 25 février 2015

Error NullPointerException trying to invoke a method passed

Main Activity there is:



public class Demo {

public void main() {
Class[] paramTypes = new Class[1];
parameterTypes[0] = Integer.Type;// tried also int.class;
Method method1 = Demo.class.getMethod("method1", parameterTypes);

OtherClass.askValue(this, new Demo(), method1, 100);
}

public void method1(int value) {
System.out.println(value);
}

}


In other Class in other java file:



public class OtherClass {

private Context ctx;
private Object obj;
private Method mtd;
private int ris;

public void askValue (Context context, Object object, Method method, int result) {
ctx = context;
obj = object;
mtd = method;
res = result;

AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
builder.setTitle("title");
builder.setMessage("This is the message");
builder.setCancelable(false)
builder.setPositiveButton(R.string.yes, DIonClickPositive);
builder.setNegativeButton(R.string.no,new DInnClickNegative);
AlertDialog alertDialog = builder.create();
alertDialog.show();
}

private DialogInterface.OnClickListener() DIonClickPositive = DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, close

Object[] parameters = new Object[1];
parameters[0] = res;
try {
mtd.invoke(obj, parameters);
} catch (InvocationTargetException ite) {
Toast.makeText (ctx, "EXC ITE ["+ite.getCause()+"]", Toast.LENGTH_SHORT).show();
}

dialog.dismiss();
}
}

private DialogInterface.OnClickListener() DIonClickNegative = DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, close
dialog.dismiss();
}
}

}


When i confirm to the dialog (press positive button), it should invoke the method "method1", but instead it enter in the exception. The getCause() of that exception is "NullPointerException". In the android manual there is written it is caused when the first Object of the invoke is "null". I checked it, but it isn't null.



if (obj == null) Toast.make.Text(ctx, "OBJ NULL !!!", Toast.LENGTH_SHORT).show();


No toast shown, so it isn't null.


How can i resolve ?


Thanksss


PS: i used this example "[click here]", post of Blaise Doughan.






Aucun commentaire:

Enregistrer un commentaire