The method findViewById(int) is undefined for the type new Runnable(){}
You need to call findViewById from a class that actually has the method. The good practice is usually to pass around the Activity you're creating this class from. Something like:
public class msgbox extends Plugin {
private static final String SHOW = "show";
private static final int MSG_INDEX = 0;
private String msg;
private final Activity parent;
// constructor
public msgbox(Activity parent) {
this.parent = parent;
}
Then you can do a:
parent.findViewById(R.id.layoutroot)
You construct your msgbox from within an activity by using:
msgbox myMsgBox = new msgbox(this);
Of course, to do that, the R.id.layoutroot
component must be in the activity you passed.
If you're not in an activity when you construct the msgbox, you can replace the constructor injection with a setter:
public void setParent(Activity parent) {
this.parent = parent;
}
Although, to be able to use findViewById within your Runnable
, parent needs to be final, so you'll have to copy it to a final variable (setter injection cannot be final, obviously)
(NB: Also, your class doesn't use standard java naming conventions, it's confusing: call it MsgBox
)
jcrowson
Senior front-end web developer, knows JavaScript and React. Currently teaching people how to become a React and JavaScript expert at Upmostly.com
Updated on June 04, 2022Comments
-
jcrowson almost 2 years
I'm working on making a Phonegap plugin for Android. When I add the
findViewById
method tothis.ctx.runOnUiThread(new Runnable()
I get an error as stated in the title.Here is my code:
package com.company.msgbox; import java.io.File; import org.crossplatform.phonegap.trial.alternativeTo.R; import org.json.JSONArray; import org.json.JSONException; import android.app.AlertDialog; import android.graphics.Bitmap; import android.view.View; import com.phonegap.api.Plugin; import com.phonegap.api.PluginResult; import com.phonegap.api.PluginResult.Status; public class msgbox extends Plugin { private static final String SHOW = "show"; private static final int MSG_INDEX = 0; private String msg; @Override public PluginResult execute(String arg0, final JSONArray arg1, String arg2) { if ( arg0.equals(SHOW) ) { this.ctx.runOnUiThread(new Runnable() { public void run() { // try/catch generated by editor try { msg = arg1.getString(MSG_INDEX); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } AlertDialog alertDialog = new AlertDialog.Builder(ctx).create(); alertDialog.setTitle("Title"); alertDialog.setMessage(msg); alertDialog.show(); View content = findViewById(R.id.layoutroot); Bitmap bitmap = content.getDrawingCache(); File file = new File("/sdcard/test.png"); } }); } return new PluginResult(Status.OK); } }