Got an error using ListPreference in Android - android

I have a question about PreferenceScreen in Android Studio. I used MultiSelectListPreference and did not get an error, however when I used ListPreference, I got an error and does not open setting activity.
<PreferenceCategory
android:title="Time Table Setting">
<ListPreference
android:key="Header_List"
android:entries="#array/setting_header_list"
android:entryValues="#array/setting_header_values"
android:title="Display Dates"
android:summary="Monday to Friday, Saturday or Sunday"/>
</PreferenceCategory>
<Preference
android:key="Restart"
android:title="Save"/>
If you have any suggestions, Please help me out. Thank you
Here is the error message that I've got
2020-03-21 22:06:26.212 14206-14206/com.pythontaro.personaltimetable E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.name, PID: 14206
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.name.appname/com.name.appname.setting.SettingsActivity}: java.lang.ClassCastException: java.util.HashSet cannot be cast to java.lang.String
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
Caused by: java.lang.ClassCastException: java.util.HashSet cannot be cast to java.lang.String
at android.app.SharedPreferencesImpl.getString(SharedPreferencesImpl.java:225)
at androidx.preference.Preference.getPersistedString(Preference.java:1686)
at androidx.preference.ListPreference.onSetInitialValue(ListPreference.java:255)
at androidx.preference.Preference.onSetInitialValue(Preference.java:1614)
at androidx.preference.Preference.dispatchSetInitialValue(Preference.java:1587)
at androidx.preference.Preference.onAttachedToHierarchy(Preference.java:1311)
at androidx.preference.Preference.onAttachedToHierarchy(Preference.java:1326)
at androidx.preference.PreferenceGroup.addPreference(PreferenceGroup.java:249)
at androidx.preference.PreferenceGroup.addItemFromInflater(PreferenceGroup.java:170)
at androidx.preference.PreferenceInflater.rInflate(PreferenceInflater.java:345)
at androidx.preference.PreferenceInflater.rInflate(PreferenceInflater.java:346)
at androidx.preference.PreferenceInflater.inflate(PreferenceInflater.java:157)
at androidx.preference.PreferenceInflater.inflate(PreferenceInflater.java:109)
at androidx.preference.PreferenceManager.inflateFromResource(PreferenceManager.java:216)
at androidx.preference.PreferenceFragmentCompat.addPreferencesFromResource(PreferenceFragmentCompat.java:361)
at com.name.appname.setting.SettingsActivity$SettingsFragment.onCreatePreferences(SettingsActivity.java:28)
at androidx.preference.PreferenceFragmentCompat.onCreate(PreferenceFragmentCompat.java:160)
at androidx.fragment.app.Fragment.performCreate(Fragment.java:2684)
at androidx.fragment.app.FragmentStateManager.create(FragmentStateManager.java:280)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1175)
at androidx.fragment.app.FragmentTransition.addToFirstInLastOut(FragmentTransition.java:1255)
at androidx.fragment.app.FragmentTransition.calculateFragments(FragmentTransition.java:1138)
at androidx.fragment.app.FragmentTransition.startTransitions(FragmentTransition.java:136)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1989)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1947)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1849)
at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2629)
at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:2577)
at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:247)
at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:541)
at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:201)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1248)
at android.app.Activity.performStart(Activity.java:6679)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2609)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756) 
This is code in Setting Activity Class
public class SettingsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_activity);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.settings, new SettingsFragment())
.commit();
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
public static class SettingsFragment extends PreferenceFragmentCompat {
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
addPreferencesFromResource(R.xml.settings);
}
}}
This is code for string value
<!--Setting-->
<string-array name="setting_header_list">
<item>"Friday(default)"</item>
<item>"Saturday"</item>
<item>"Sunday"</item>
</string-array>
<string-array name="setting_header_values">
<item>0</item>
<item>1</item>
<item>2</item>
</string-array>
This is the code of line 225 in SharedPreferencesImpl.java
final StructStat stat;
try {
/*
* Metadata operations don't usually count as a block guard
* violation, but we explicitly want this one.
*/
BlockGuard.getThreadPolicy().onReadFromDisk();
stat = Os.stat(mFile.getPath());
} catch (ErrnoException e) {
return true;
}

From your stack trace this is the key:
Caused by: java.lang.ClassCastException: java.util.HashSet cannot be cast to java.lang.String
you are trying to use a java.util.HashSet where a java.lang.String is in use.
It's at SharedPreferencesImpl.java:225 when getString is being called. This is as far as I can go if you do not share the relevant part of your code.
EDIT
As the asker pointed out here in the comment section, the issue was that double quotation marks were used on string-array items.

Related

Android Checkbox error "on a null object reference" [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I tried to make a checkbox that when it is checked it will strikethrough text field elements in the listview. I'm pretty sure that I did everything correctly including set up the ID for the checkbox in XML and declared it on the class that I wanna use but I still get the Null object error.
I have looked through all the question and answer all over this topic, I also tried them all but I still get an error. Could someone please help me identify where an error might be.
Thank you so much in advance for any help =)
Class file
package com.puyakul.prin.psychic_shopping;
import...
public class MainListView extends AppCompatActivity {
//================DATABASE=====================//
private ShoppingListDatabase databaseConnection;
private SQLiteDatabase db;
public ListView ListView_mainListView;
public ArrayList<ShoppingList> lists;
public AppCompatCheckBox checkBox_doneCheck;
public TextView textView_listname;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//================DATABASE Connection================//
databaseConnection = new ShoppingListDatabase(this);
db = databaseConnection.open();
//important!!!
setContentView(R.layout.activity_main_list_view);
getLists();
}
public void getLists(){
....
******Original here, but I delete by acident******
checkBox_doneCheck = findViewById(R.id.checkBox_doneCheck);
checkBox_doneCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if (checkBox_doneCheck.isChecked()) {
textView_listname.setPaintFlags(textView_listname.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
else{
textView_listname.setPaintFlags(textView_listname.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG);
}
}
});
}
XML file
<android.support.v7.widget.AppCompatCheckBox
android:id="#+id/checkBox_doneCheck"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:checked="false"/>
Error log
Process: com.puyakul.prin.psychic_shopping, PID: 19958
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.puyakul.prin.psychic_shopping/com.puyakul.prin.psychic_shopping.MainListView}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.AppCompatCheckBox.setOnCheckedChangeListener(android.widget.CompoundButton$OnCheckedChangeListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.AppCompatCheckBox.setOnCheckedChangeListener(android.widget.CompoundButton$OnCheckedChangeListener)' on a null object reference
at com.puyakul.prin.psychic_shopping.MainListView.getLists(MainListView.java:107)
at com.puyakul.prin.psychic_shopping.MainListView.onCreate(MainListView.java:67)
at android.app.Activity.performCreate(Activity.java:6662)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756) 
You never initialize checkBox_doneCheck, try this instead in onCreate:
setContentView(R.layout.activity_main_list_view);
checkBox_doneCheck = (AppCompatCheckBox) findViewById(R.id.checkBox_doneCheck);
getLists();
You may also want to do something similar with those variables:
ListView_mainListView
textView_listnameist item
You are missing the association between the xml and java code.
Add this line:
checkBox_doneCheck = findViewById(R.id.checkBox_doneCheck)
Thats why you are having the NullPointerException.

Exception when trying to compile project inside Android studio

I have the following error when I try to compile my project; any body knows what I can do with this error.
FATAL EXCEPTION: main
Process: com.bignerdranch.android.criminalintent, PID: 15284
java.lang.NoSuchMethodError: No static method
getFont(Landroid/content/Context;ILandroid/util/TypedValue;ILandroid/widget/TextView;)Landroid/graphics/Typeface;
in class Landroid/support/v4/content/res/ResourcesCompat; or its super
classes (declaration of
'android.support.v4.content.res.ResourcesCompat' appears in
/data/app/com.bignerdranch.android.criminalintent-sYwk5YXA0Ap8nyn-79YvKg==/base.apk)
at
android.support.v7.widget.TintTypedArray.getFont(TintTypedArray.java:119)
at
android.support.v7.widget.AppCompatTextHelper.updateTypefaceAndStyle(AppCompatTextHelper.java:208)
at
android.support.v7.widget.AppCompatTextHelper.loadFromAttributes(AppCompatTextHelper.java:110)
at
android.support.v7.widget.AppCompatTextHelperV17.loadFromAttributes(AppCompatTextHelperV17.java:38)
at
android.support.v7.widget.AppCompatTextView.(AppCompatTextView.java:81)
at
android.support.v7.widget.AppCompatTextView.(AppCompatTextView.java:71)
at
android.support.v7.widget.AppCompatTextView.(AppCompatTextView.java:67)
at android.support.v7.widget.Toolbar.setTitle(Toolbar.java:753)
at
android.support.v7.widget.ToolbarWidgetWrapper.setTitleInt(ToolbarWidgetWrapper.java:261)
at
android.support.v7.widget.ToolbarWidgetWrapper.setWindowTitle(ToolbarWidgetWrapper.java:243)
at
android.support.v7.widget.ActionBarOverlayLayout.setWindowTitle(ActionBarOverlayLayout.java:621)
at
android.support.v7.app.AppCompatDelegateImplV9.onTitleChanged(AppCompatDelegateImplV9.java:631)
at
android.support.v7.app.AppCompatDelegateImplV9.ensureSubDecor(AppCompatDelegateImplV9.java:328)
at
android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:284)
at
android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
at
com.bignerdranch.android.criminalintent.SingleFragmentActivity.onCreate(SingleFragmentActivity.java:21)
at android.app.Activity.performCreate(Activity.java:6999)
at android.app.Activity.performCreate(Activity.java:6990)
at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Here is the part it says it is failing in the log
public abstract class SingleFragmentActivity extends AppCompatActivity
{
protected abstract Fragment createFragment();//abstract method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
***setContentView(R.layout.activity_fragment);***
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragment_container);
if (fragment == null) {
fragment = createFragment();
fm.beginTransaction()
.add(R.id.fragment_container,fragment)
.commit();
}
}
}
Always try to read and understand what Android Studio is telling you. In this case it tells you quite plainly that there is no such method as getFont() in the current context. You probably wanted/should've used ResourcesCompat.getFont(context, R.font.your_font); but there is no way to know because you didn't post a sample of your code. Please review Stack Overflow's posting guidelines. This will save everyone a lot of time.

Runtime Exception in Preference Fragment

I have a preference fragment with the following files
preference.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<EditTextPreference
android:defaultValue="0000"
android:key="#string/pin"
android:summary="Set Pin for Notes"
android:title="Password" />
</PreferenceScreen>
Preference Activity
public class PreferenceActivity extends AppCompatActivity {
#BindView(R.id.toolbar_settings)
Toolbar toolbarSettings;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
ButterKnife.bind(this);
setSupportActionBar(toolbarSettings);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
}
and finally
Preference Fragment
public class PreferenceFragment extends PreferenceFragmentCompat {
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
addPreferencesFromResource(R.xml.preference);
}
}
But here when the addPreferencesFromResources is called, I am getting a runtime exception.
Here is the log stack
Exception
02-21 22:23:36.574 8813-8813/in.snotes.snotes E/AndroidRuntime: FATAL EXCEPTION: main
Process: in.snotes.snotes, PID: 8813
java.lang.RuntimeException: Unable to start activity ComponentInfo{in.snotes.snotes/in.snotes.snotes.settings.PreferenceActivity}: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2659)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
Caused by: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class fragment
Caused by: android.view.InflateException: Binary XML file line #0: Error inflating class fragment
Caused by: java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
at android.app.SharedPreferencesImpl.getString(SharedPreferencesImpl.java:225)
at android.support.v7.preference.Preference.getPersistedString(Preference.java:1601)
at android.support.v7.preference.EditTextPreference.onSetInitialValue(EditTextPreference.java:92)
at android.support.v7.preference.Preference.dispatchSetInitialValue(Preference.java:1517)
at android.support.v7.preference.Preference.onAttachedToHierarchy(Preference.java:1245)
at android.support.v7.preference.Preference.onAttachedToHierarchy(Preference.java:1257)
at android.support.v7.preference.PreferenceGroup.addPreference(PreferenceGroup.java:194)
at android.support.v7.preference.PreferenceGroup.addItemFromInflater(PreferenceGroup.java:126)
at android.support.v7.preference.PreferenceInflater.rInflate(PreferenceInflater.java:355)
at android.support.v7.preference.PreferenceInflater.inflate(PreferenceInflater.java:162)
at android.support.v7.preference.PreferenceInflater.inflate(PreferenceInflater.java:112)
at android.support.v7.preference.PreferenceManager.inflateFromResource(PreferenceManager.java:138)
at android.support.v7.preference.PreferenceFragmentCompat.addPreferencesFromResource(PreferenceFragmentCompat.java:432)
at in.snotes.snotes.settings.PreferenceFragment.onCreatePreferences(PreferenceFragment.java:12)
at android.support.v7.preference.PreferenceFragmentCompat.onCreate(PreferenceFragmentCompat.java:224)
at android.support.v4.app.Fragment.performCreate(Fragment.java:2246)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1377)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1650)
at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1906)
at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:3698)
at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:111)
at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:350)
at android.support.v4.app.BaseFragmentActivityApi14.onCreateView(BaseFragmentActivityApi14.java:39)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:67)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:777)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:858)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
at android.view.LayoutInflater.inflate(LayoutInflater.java:377)
02-21 22:23:36.575 8813-8813/in.snotes.snotes E/AndroidRuntime: at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
at in.snotes.snotes.settings.PreferenceActivity.onCreate(PreferenceActivity.java:21)
at android.app.Activity.performCreate(Activity.java:6672)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1140)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2612)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
I had a switch preference before the edit text preference and that worked fine. Once i replaced the switch preference with edit text preference, this error is thrown.
How do I fix this?
Can you try the code below?
strings.xml
<string name="pin_default_value">0000</string>
preference.xml
<EditTextPreference
android:defaultValue="#string/pin_default_value"
android:key="#string/pin"
android:summary="Set Pin for Notes"
android:title="Password" />
Android is trying to set default value but it is reading 0000 as an Integer and not as a String Main reason is that android:defaultValue is not directly handled as String. This way, to avoid this int to Stringconversion error, you must explicit use a String value (by using some string from strings.xml.
Note
You may need to clear your app data since that wrong default value may be stored in cached files already.

My application in android keeps on crashing

I keep on getting this error in my logcat and don't know why. I don't seem to have any errors in code either. Any help will be greatly appreciated.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.admin.trainyourmath, PID: 26931
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.admin.trainyourmath/com.example.admin.trainyourmath.MainActivity}: java.lang.ClassCastException: com.example.admin.trainyourmath.MainActivity cannot be cast to android.view.View$OnClickListener
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2434)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2494)
at android.app.ActivityThread.access$900(ActivityThread.java:157)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1356)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5551)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
Caused by: java.lang.ClassCastException: com.example.admin.trainyourmath.MainActivity cannot be cast to android.view.View$OnClickListener
at com.example.admin.trainyourmath.MainActivity.onCreate(MainActivity.java:31)
at android.app.Activity.performCreate(Activity.java:6272)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2494) 
at android.app.ActivityThread.access$900(ActivityThread.java:157) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1356) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5551) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620) 
You are using your MainActivity as a OnClickListener which it does not implement properly. Add implements View.OnClickListener to the end of your MainActivity class declaration if it's not already there. Should look something like:
public class MainActivity extends AppCompatActivity implements View.OnClickListener
You also need to implement all the methods of the View.OnClickListener so inside your MainActivity class add:
#Override
public void onClick(View v) {
// Do stuff
}

Android: Crash when setting up media route button

I'm having pretty much the same problem as Android: Cast SDK v3 Crashing in Release build only.
The key difference is that my project does it while i'm just debugging and does it on this line
CastButtonFactory.setUpMediaRouteButton(getApplicationContext(), mMediaRouteButton);
I have tried making all my variables public but that doesn't do anything. The full code is
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMediaRouteButton = (MediaRouteButton) findViewById(R.id.media_route_button);
CastButtonFactory.setUpMediaRouteButton(getApplicationContext(), mMediaRouteButton);
mCastContext = CastContext.getSharedInstance(this);
mSelector = new MediaRouteSelector.Builder()
// These are the framework-supported intents
.addControlCategory(MediaControlIntent.CATEGORY_LIVE_AUDIO)
.addControlCategory(MediaControlIntent.CATEGORY_LIVE_VIDEO)
.addControlCategory(MediaControlIntent.CATEGORY_REMOTE_PLAYBACK)
.build();
mMediaRouter = MediaRouter.getInstance(this);
}
Also I find it worth mentioning that this code worked and I can not for the life of me figure out what caused it to stop working. As far as I can tell it stopped working when I invalidated the cache in Android Studio.
This is the error I'm getting
java.lang.RuntimeException: Unable to start activity ComponentInfo{mypackage.package/mypackage.package.MainActivity}: java.lang.IllegalStateException: Failed to initialize CastContext.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.IllegalStateException: Failed to initialize CastContext.
at com.google.android.gms.cast.framework.CastContext.zzbb(Unknown Source)
at com.google.android.gms.cast.framework.CastContext.getSharedInstance(Unknown Source)
at com.google.android.gms.cast.framework.CastButtonFactory.setUpMediaRouteButton(Unknown Source)
at mypackage.package.MainActivity.onCreate(MainActivity.java:51)
at android.app.Activity.performCreate(Activity.java:6664)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
Caused by: java.lang.IllegalAccessException: java.lang.Class<mypackage.package.CastOptionsProvider> is not accessible from java.lang.Class<com.google.android.gms.cast.framework.CastContext>
at java.lang.Class.newInstance(Native Method)
at com.google.android.gms.cast.framework.CastContext.zzbb(Unknown Source) 
at com.google.android.gms.cast.framework.CastContext.getSharedInstance(Unknown Source) 
at com.google.android.gms.cast.framework.CastButtonFactory.setUpMediaRouteButton(Unknown Source) 
at mypackage.package.MainActivity.onCreate(MainActivity.java:51) 
at android.app.Activity.performCreate(Activity.java:6664) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
There might be an issue on how you initialize media CastContext, to properly initialize CastContext, the application must have the implements OptionsProvider interface:
package com.example.app;
public class CastOptionsProvider implements OptionsProvider {
#Override
public CastOptions getCastOptions(Context appContext) {
...
}
}
and specify its fully qualified class name in the AndroidManifest.xml with the key OPTIONS_PROVIDER_CLASS_NAME_KEY:
...
<meta-data
android:name="com.google.android.gms.cast.framework.OPTIONS_PROVIDER_CLASS_NAME"
android:value="com.example.app.CastOptionsProvider" />
...
Note: All public methods must be called from the main thread.
I did some research and found this related SO ticket which discuss how to initialize CastContext: How to initialize CastContext outside of onCreate method
This was fixed by making the CastOptionsProvider public. I don't know why this problem occurred to begin with, because it was working fine when it wasn't public until it didn't. I didn't touch the CastOptionsProvider on the build where it started failing.
My CastOptionsProvider now looks like this
public class CastOptionsProvider implements OptionsProvider {
#Override
public CastOptions getCastOptions(Context appContext) {
CastOptions castOptions = new CastOptions.Builder()
.setReceiverApplicationId(appContext.getString(R.string.app_id))
.build();
return castOptions;
}
#Override
public List<SessionProvider> getAdditionalSessionProviders(Context context) {
return null;
}
}
If this is happening only in release buildtype then it is related to proguard. Please add the CastOptionsProvider class to the proguard file and recheck
-keep class abc.xyz.videocast.CastOptionsProvider { *; }
For more safety these classes can also be added
-keep class android.support.** { *; }
-keep class com.google.** { *; }

Categories

Resources