Reputation: 35
I'm a beginner of Android and new to Stackoverflow. So excuse me for my silly question. However I found no solved solution here, so posting it as a new question.
I've an activity with an Autocompletetextview and a webview. I want on clicking a hyperlink in webview to fill some text in Autocompletetextview. So I've called Javascript in the webpage which in-turn calls Javascript AppInterface. In interface function, I want to update Autocompletetextview text.
I'm able to collect the text from javascript. But while setting the text of Autocompletetextview, my application is crashing.
WebAppInterface.java
public class JsInterface {
@JavascriptInterface
public void NewText(final String text)
{
Log.d("New_Text", "" + text); //Works fine till here.
((Activity)mContext).findViewById(R.id.autoCompleteTextView);
Handler mHandler = new Handler();
mHandler.post(new Runnable() {
@Override
public void run() {
AutoCompleteTextView SearchTextbox = (AutoCompleteTextView) ((Activity)mContext).findViewById(R.id.autoCompleteTextView);
SearchTextbox.setText(text);
}
});
}
}
Error on App Crash
E/AndroidRuntime: FATAL EXCEPTION: JavaBridge
Process: com.test.xxx, PID: 22102
java.lang.ClassCastException: android.app.Application cannot be cast to android.app.Activity
at com.test.xxx.WebAppInterface$1.run(WebAppInterface.java:102)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.os.HandlerThread.run(HandlerThread.java:61)
I want to know if my approach to update UI component is correct? If yes, what changes will resolve the error and will work fine.
Upvotes: 1
Views: 331
Reputation: 29285
The line
java.lang.ClassCastException: android.app.Application cannot be cast to android.app.Activity
is self-explanatory enough. You're casting mContext
to Activity
while it's not an instance of Activity class.
You can add a method called setAutoCompleteTextView
to your JsInterface
class, in which you can hold a reference to that auto complete text view.
public void setAutoCompleteTextView(AutoCompleteTextView textview){
this.mTextView = textview;
}
And in the JavaScript interface method, use it like this.mTextView.set...()
.
Upvotes: 1
Reputation: 4114
The key point is this:
java.lang.ClassCastException: android.app.Application cannot be cast to android.app.Activity
This means your mContext
varible at the problematic line is an Application
object not an Activity
, so refer to the Activity
where you assign it not to the Application
.
Upvotes: 0