How to save data from EditTexts in RecyclerView during screen rotation - android

I read that EditText doesn't work well with RecyclerView, but I saw an application where it works well (avito). Now I am trying to understand how it was realized there.
I have a fragment with RecyclerView, in recycler view I have EditTexts only in header holder (only one item with EditTexts). In this header I have about five similar EditTexts and TextViews (city,title,description,price etc.) So as not to duplicate the code for all views, I made a custom view class where I located these views, and this class I show below.
public class CustomEditTextView extends LinearLayout implements TextWatcher {
private LayoutInflater inflater;
private TextView textView;
private final EditText editText;
private TextView tvWarning;
private View view;
private String hint;
private String text ;
private String title;
private String warning;
private boolean isNumber = false;
private SpinnerCitySetupListener spinnerCitySetupListener;
public CustomEditTextView(Context context, AttributeSet attrs) {
super(context, attrs);
inflater = LayoutInflater.from(context);
view = inflater.inflate(R.layout.custom_edittext, this, true);
textView = (TextView) view.findViewById(R.id.mycustom_tvTitle);
editText = (EditText) view.findViewById(R.id.mycustom_etTitle);
tvWarning = (TextView) view.findViewById(R.id.mycustom_tvWarning);
textView.setVisibility(GONE);
tvWarning.setVisibility(GONE);
}
public void setCustomVisibility(View view,boolean isVisible){
view.setVisibility(isVisible?VISIBLE:GONE);
}
public void tuningView() {
editText.addTextChangedListener(this);
if(isNumber)editText.setInputType(InputType.TYPE_CLASS_NUMBER);
}
public void setTitle(String title){
textView.setText(title);
this.title = title;
}
public void setHint(String hint){
editText.setHint(hint);
this.hint = hint;
}
public void setWarning(String warning){
tvWarning.setText(warning);
this.warning = warning;
}
public void setText(String text) {
editText.setText(text);
}
public String getText(){
Log.i("CUSTOM VIEW","GET TEXT FROM VIEW: "+ text);
return text;
}
public TextView getTvWarning(){
return tvWarning;
}
public void setInputType(boolean isNumber){
this.isNumber = isNumber;
}
public void setSpinnerCityListener(SpinnerCitySetupListener listener){
spinnerCitySetupListener = listener;
}
//region TextChangedListener
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
text = charSequence.toString();
}
#Override
public void afterTextChanged(Editable editable) {
if (editable.toString().length()!= 0) {
setCustomVisibility(textView,true);
text = editable.toString();
if(spinnerCitySetupListener!= null) spinnerCitySetupListener.spinnerActivation(false);}
else {setCustomVisibility(textView,false);
if(spinnerCitySetupListener!= null) spinnerCitySetupListener.spinnerActivation(true);}
}
//endregion
}
my manifest:`
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.CALL_PHONE"/>
<!-- <uses-permission android:name="android.permission.SEND_SMS"/>-->
<permission
android:name="com.android.qrz.gcm.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.android.qrz.gcm.permission.C2D_MESSAGE" />
<uses-feature android:name="android.hardware.camera" android:required="true" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<application
android:name="android.support.multidex.MultiDexApplication"
android:allowBackup="true"
android:icon="#drawable/qrz_icon"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<!--android:name=".QRZApp"-->
<meta-data
android:name="AA_DB_NAME"
android:value="QRZ.db" />
<meta-data
android:name="AA_DB_VERSION"
android:value="1" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyBlOgCglvJdnPS476oiF4MRAo3pV3nQ8w8"/>
<receiver
android:name=".receiver.GCMBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="com.android.qrz.receiver" />
</intent-filter>
</receiver>
<receiver
android:name=".receiver.InternetCheckReceiver"
android:label="NetworkConnection" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
<service
android:name=".services.GCMIntentService"
android:process=":remote" />
<activity
android:name=".activity.SplashScreen" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!--<activity-->
<!--android:name=".activity.main_menu.MainMenu"-->
<!--android:label="#string/title_activity_menu" >-->
<!--</activity>-->
<activity
android:name=".activity.main_menu.NewMainMenu"
android:label="#string/title_activity_menu" >
</activity>
<activity
android:name=".activity.LoginActivity"
android:label="#string/title_activity_login" >
</activity>
<!--<activity-->
<!--android:name=".activity.Registration"-->
<!--android:label="#string/title_activity_registration" >-->
<!--</activity>-->
<activity
android:name=".activity.registration.NewRegistration"
android:label="#string/title_activity_registration" >
</activity>
<activity
android:name=".activity.News"
android:label="#string/title_activity_news" >
</activity>
<activity
android:name=".activity.news.DetailNewsActivity"
android:label="#string/title_activity_news" >
</activity>
<!--<activity-->
<!--android:name=".activity.Callbook"-->
<!--android:label="#string/title_activity_callbook" >-->
<!--</activity>-->
<activity
android:name=".activity.NewCallbook"
android:label="Callbook" >
</activity>
<activity
android:name=".activity.PhotoGallery"
android:label="#string/title_activity_photo_gallery" >
</activity>
<!--<activity
android:name=".activity.DiplomsActivity"
android:label="#string/title_activity_diploms" >
</activity>-->
<activity
android:name=".activity.new_diploms.ui.MainDiplomActivity"
android:label="#string/title_activity_new_diploms" >
</activity>
<activity
android:name=".activity.new_diploms.ui.detail_diplom.DiplomDetailActivity"
android:label="#string/title_activity_new_detail_diploms" >
</activity>
<activity
android:name=".activity.new_diploms.ui.searching.SearchingActivity"
android:label="#string/title_activity_searching_diploms" >
</activity>
<activity
android:name=".activity.BirthdaysActivity"
android:label="#string/title_activity_birthdays" >
</activity>
<activity
android:name=".activity.competitions.CompetitionsActivity"
android:label="#string/title_activity_competitions" >
</activity>
<activity
android:name=".activity.DXActivity"
android:label="#string/title_activity_DX" >
</activity>
<activity
android:name=".activity.DXDetailActivity"
android:label="#string/title_activity_DX_detail" >
</activity>
<activity
android:name=".activity.base_of_frequency.BaseFrequencyActivity"
android:label="#string/title_activity_frequency" >
</activity>
<activity
android:name=".activity.qsl.QslActivity"
android:label="#string/title_activity_qsl" >
</activity>
<activity
android:name=".activity.qsl.QSLSearching"
android:label="#string/title_activity_qsl_searching" >
</activity>
<activity
android:name=".activity.declarations.BillboardActivity"
android:label="#string/title_activity_billboard" >
</activity>
<activity
android:name=".activity.declarations.SearchingFilterActivity"
android:label="#string/title_activity_filters_for_search"
>
</activity>
<activity
android:name=".activity.declarations.NewSearchingDeclarationActivity"
android:label="#string/title_activity_searching_declaration" >
</activity>
<activity
android:name=".activity.declarations.ListDeclarationsActivity"
android:label="#string/title_activity_list_declarations" >
</activity>
<activity
android:name=".activity.declarations.DeclarationDetailActivity"
android:label="#string/title_activity_declaration_detail" >
</activity>
<activity
android:name=".activity.personal_activity.PersonalActivity"
android:label="#string/title_activity_personal" >
<intent-filter>
<action android:name="android.intent.action.PICK"></action>
</intent-filter>
</activity>
<activity
android:name=".activity.personal_activity.create_declaration.CreateDeclarationActivity"
android:label="#string/title_activity_create_declaration" >
</activity>
<activity
android:name=".activity.personal_activity.create_qsl_manager.CreateQSLManagerActivity"
android:label="#string/title_activity_create_qsl" >
</activity>
<activity
android:name=".activity.personal_activity.create_dx_reporter.CreateDXReporterActivity"
android:label="#string/title_activity_create_dx_reporter" >
</activity>
<activity
android:name=".activity.personal_activity.create_frequency.CreateFrequencyActivity"
android:label="#string/title_activity_create_frequency" >
</activity>
<activity
android:name=".activity.personal_activity.settings.PersonalSettingsActivity"
android:label="#string/title_activity_settings" >
</activity>
<activity
android:name=".activity.ForumActivity"
android:label="#string/title_activity_forum" >
</activity>
<activity
android:name=".activity.AboutAppActivity"
android:label="#string/title_activity_about_app" >
</activity>
<service
android:name=".rest_service.rest.RestService"
android:enabled="true"
android:exported="true" >
</service><!-- ATTENTION: This was auto-generated to add Google Play services to your project for
App Indexing. See https://g.co/AppIndexing/AndroidStudio for more information. -->
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
</application>
`
My problem is variable "text" in afterTextChanged or in onTextChanged "text" is not empty, in this part of code all works well, but when I want to get this text from my headerHolder I calling customView.getText() for sending this data in fragment for OnSavedInstance and this variable "text" become null, but EditText contains text all this time, why does this happen?

Related

How to update firebasemessagingservice to latest version?

I get an error says "error: class, interface, or enum expected" and I found out its from the firebasemessagingservice needs to be updated and I don't know how to do it. Please help.
import android.util.Log;
import com.google.firebase.iid.FirebaseInstanceId;
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onNewToken(String s) {
super.onNewToken(s);
Log.e("NEW_TOKEN",s);
}
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
}
}
private void sendRegistrationToServer(String token) {
//You can implement this method to store the token on your server
//Not required for current project
}
}
you put an extra " } " in your code. remove it and recompile
Correct code:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onNewToken(String s) {
super.onNewToken(s);
Log.e("NEW_TOKEN",s);
}
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
}
private void sendRegistrationToServer(String token) {
//You can implement this method to store the token on your server
//Not required for current project
}
}
And here is the androidManifest file
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:name=""
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<!-- Disable opening of launcher Activity -->
<meta-data
android:name="com.onesignal.NotificationOpened.DEFAULT"
android:value="DISABLE" />
<activity
android:name=""
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=""
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=""
android:configChanges="orientation|keyboardHidden|screenSize" />
<activity
android:name="com.tools.vactivities.ActivityRecipesDetail"
android:configChanges="orientation|keyboardHidden|screenSize" />
<!--admob-->
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity
android:name="com.google.android.gms.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" />
<!--fcm-->
<service android:name="com.tools.notification.MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service
android:name=".MyFirebaseMessagingService"
android:stopWithTask="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service
android:name="com.tools.notification.NotificationExtenderExample"
android:exported="false"
android:permission="android.permission.BIND_JOB_SERVICE">
<intent-filter>
<action android:name="com.onesignal.NotificationExtender" />
</intent-filter>
</service>
</application>

NoClassDefFoundError for Pojo class in Splash Screen

AndroidManifest.java
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.bidnextjob.bidnextjob">
<!-- Lat lon fetching permission by GPSTracker class start and also use for google map -->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="com.bidnextjob.bidnextjob.permission.C2D_MESSAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- Allows access to the flashlight -->
<permission
android:name="android.permission.FLASHLIGHT"
android:permissionGroup="android.permission-group.HARDWARE_CONTROLS"
android:protectionLevel="normal" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/MyTheme">
<activity android:name=".SplashActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity" />
<activity android:name=".LoginActivity" />
<activity android:name=".RegisterActivity" />
<activity
android:name=".HomeActivity"
android:windowSoftInputMode="stateAlwaysHidden" />
<activity android:name=".FilterActivity" />
<activity android:name=".JobDetailsActivity" />
<activity android:name=".EditProfileActivity"
android:windowSoftInputMode="stateAlwaysHidden"/>
<activity
android:name=".ChatActivity"
android:windowSoftInputMode="stateAlwaysHidden" />
<activity android:name=".AboutUsActivity" />
<activity android:name=".HelpActivity" />
<activity android:name=".ReviewActivity" />
<activity
android:name=".CommentActivity"
android:windowSoftInputMode="stateAlwaysHidden" />
<activity android:name=".ForgetPasswordActivity" />
<activity
android:name=".PlaceBidActivity"
android:windowSoftInputMode="stateAlwaysHidden" />
<activity
android:name=".EditBidActivity"
android:windowSoftInputMode="stateAlwaysHidden" />
<activity android:name=".JobDetails1Activity" />
<activity android:name=".NotificationsActivity" />
<activity android:name=".ChooseCategoryActivity" />
<activity android:name=".BidDetailsActivity" />
<activity android:name=".EditAddressActivity" />
<activity android:name=".UpdateProfileActivity" />
<activity android:name=".GiveRatingActivity" />
<activity android:name=".ArchiveActivity"/>
<activity android:name=".AutoCompleteAddress"/>
<activity
android:name=".SocialLoginActivity"
android:label=".SocialLoginActivity" />
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="#string/facebook_app_id" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="<some api key>" />
<activity
android:name="com.facebook.FacebookActivity"
android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="#string/app_name"
android:theme="#android:style/Theme.Translucent.NoTitleBar" />
<service android:name="utilities.gcm.GcmIntentService" />
<receiver
android:name="utilities.gcm.GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.bidnextjob.bidnextjob" />
</intent-filter>
</receiver>
</application>
</manifest>
I'm accessing a Pojo class having static method for returning value. When I access this static method in my Splash Screen class(Launcher page), I get a NoClassDefFoundError for that Pojo class. How to avoid this exception without making the method non-static?
LogCat
FATAL EXCEPTION: main
Process: com.bidnextjob.bidnextjob, PID: 30515
java.lang.NoClassDefFoundError: shared_pref.SharedStorage
at com.bidnextjob.bidnextjob.SplashActivity.onCreate(SplashActivity.java:21)
at android.app.Activity.performCreate(Activity.java:5280)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1088)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2322)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2410)
at android.app.ActivityThread.access$800(ActivityThread.java:155)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1331)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5388)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:655)
at dalvik.system.NativeStart.main(Native Method)
Pojo class
package shared_pref;
public class SharedStorage {
static SharedPreferences preference;
private static String prefData="ExampleStructApp";
public static String UserId= "UserId";
public static String UserType= "UserType";
public static void setValue(Context context,String key,String data){
preference = context.getSharedPreferences(prefData, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preference.edit();
editor.putString(key,data);
editor.commit();
}
public static String getValue(Context context,String key){
preference = context.getSharedPreferences(prefData, Context.MODE_PRIVATE);
String id = preference.getString(key,"");
return id;
}
public static void resetValue(Context context){
preference = context.getSharedPreferences(prefData, Context.MODE_PRIVATE);
preference.edit().clear().commit();
}
}
Splash Screen class
public class SplashActivity extends AppCompatActivity {
private String user_id = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
// Here I get NoClassDefFoundError
user_id = SharedStorage.getValue(getApplicationContext(),"UserId");
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if(user_id != null && !user_id.isEmpty()){
startActivity(new Intent(SplashActivity.this, HomeActivity.class));
finish();
}else{
startActivity(new Intent(SplashActivity.this, MainActivity.class));
finish();
}
}
}, 3000);
}
}
This is caused when there is a class file that your code depends on and it is present at compile time but not found at runtime. Look for differences in your build time and runtime classpaths.

Firebase notification is not working when the activity is on the foreground

I don't have problem with the notification when my app is in the background. Can someone tell me why?
This is my manifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name=".CrowdWeather"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".FirebaseNotification">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
</application>
This is the FirebaseNotification.java:
public class FirebaseNotification extends FirebaseMessagingService {
public static final String TAG= "Firebase rocks";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d("getFrom",remoteMessage.getFrom()+" ");
Log.d("messageData",remoteMessage.getMessageType()+" ");
Log.d("notificationBody",remoteMessage.getNotification().getBody() +" ");
Log.d("total",remoteMessage.getTtl()+" ");
}
}

Unable to retrieve ads form airpush

Got myself newly registered on AirPush. I integrated bundle SDK with my App. When I tested it for the first time, I got a couple of impressions. It also shows 2 impressions on dashboard.
Now I am unable to fetch the impressions. Did contact the developer team but to no avail.
My code of MainActivity goes like this :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// MMSDK.initialize(this);
// setup a new adView and initialize an adRequest to it.
setupAirPushAdView();
}
#Override
public void onResume() {
super.onResume();
if ((getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK)
== Configuration.SCREENLAYOUT_SIZE_SMALL) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
try {
if (!appStarted) {
setContentView(R.layout.main);
appStarted = true;
}
} catch (Exception e) {
Toast.makeText(this, e.getMessage() + "\n" + e.getClass().toString() + "\n" + e.getLocalizedMessage() + "\n", Toast.LENGTH_LONG).show();
}
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
perform();
}
}, 2000);
}
private void perform() {
setContentView(R.layout.app_home);
if (!appStarted) {
// attachAdView();
attachAirPushAdView();
appStarted = true;
}
...
Other Methods :
private void setupAirPushAdView() {
ma = new MA(this, null, false);
airPushAdView = new AdView(this, AdView.BANNER_TYPE_IN_APP_AD, AdView.PLACEMENT_TYPE_INTERSTITIAL, false, false,
AdView.ANIMATION_TYPE_LEFT_TO_RIGHT);
}
private void attachAirPushAdView() {
LinearLayout outerAdLayout = (LinearLayout) findViewById(R.id.externalAdId);
outerAdLayout.addView(airPushAdView);
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="com.android.browser.permission.READ_HISTORY_BOOKMARKS" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-sdk android:minSdkVersion="9"/>
<!-- android:theme="#android:style/Theme.DeviceDefault.Light" -->
<!-- android:theme="#android:style/Theme.Light.NoTitleBar.Fullscreen" -->
<application android:theme="#style/AppTheme" android:label="#string/app_name" android:icon="#drawable/ic_launcher">
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version"/>
<activity android:name="MainActivity"
android:label="#string/app_name"
android:configChanges="keyboardHidden|orientation"
android:screenOrientation="nosensor"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="differential_activity"
android:configChanges="keyboardHidden|orientation"
android:screenOrientation="nosensor"
>
</activity>
<activity android:name="integral_activity"
android:screenOrientation="portrait"
>
</activity>
<activity android:name="equation_activity"
android:screenOrientation="portrait"
>
</activity>
<activity android:name="com.google.android.gms.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>
<!-- android:configChanges="keyboardHidden|orientation"
android:screenOrientation="nosensor" -->
<!-- for all activities -->
<meta-data android:name="com.google.android.gms.version" android:value="#integer/google_play_services_version" />
<meta-data android:name="com.gyesa.keanp176500.APPID" android:value="206488" />
<meta-data android:name="com.gyesa.keanp176500.APIKEY" android:value="android*1392147786176500813"/>
<activity android:exported="false" android:name="com.gyesa.keanp176500.AdActivity"
android:configChanges="orientation|screenSize"
android:theme="#android:style/Theme.Translucent" />
<activity android:name="com.gyesa.keanp176500.BrowserActivity"
android:configChanges="orientation|screenSize" />
<activity android:name="com.gyesa.keanp176500.VActivity"
android:configChanges="orientation|screenSize" android:screenOrientation="landscape"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen" >
</activity>
<service android:name="com.gyesa.keanp176500.LService" android:exported="false"></service>
<receiver android:name="com.gyesa.keanp176500.BootReceiver" android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
<uses-feature android:name="android.hardware.microphone" android:required="false" />
</manifest>

((ChuckApplication) getActivity().getApplication()).setCurrentGame(c) in Fragment

I'm currently studying a trivia style app and I'm using it in a Fragment. If I use Activities instead of Fragments, the code works:
((ChuckApplication)getApplication()).setCurrentGame(c);
But once I cast it for an activity it keeps on getting an error. The code is:
((ChuckApplication)getActivity().getApplication()).setCurrentGame(c);
The whole code is for this fragment is:
public class Activity_Home_Language extends Fragment implements OnClickListener{
Intent intent;
ImageButton btnToggle;
Button btnExam,btnReview;
TextView txtTitle;
View rootView;
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.layout_home_language, container, false);
btnToggle = (ImageButton) rootView.findViewById(R.id.btnToggle);
btnExam = (Button) rootView.findViewById(R.id.btnExam);
btnReview = (Button) rootView.findViewById(R.id.btnReview);
txtTitle = (TextView) rootView.findViewById(R.id.txtTitle);
btnToggle.setOnClickListener(this);
btnExam.setOnClickListener(this);
btnReview.setOnClickListener(this);
//FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
//transaction.add(R.id.frameContent, new Activity_Home());
//transaction.add(R.id.framePager2, new ViewPagerMunicipalities());
//transaction.add(R.id.frameDestPager, new ViewPagerDes());
//transaction.commit();
//for fading animation
return rootView;
}
#Override
public void onClick(View v) {
if(v==btnToggle){
Activity_Main.mSlideHolder.open();
}
else if(v==btnExam){
FragmentTransaction transaction = getFragmentManager().beginTransaction();
//transaction.addToBackStack(null);
transaction.replace(R.id.frameContent, new Activity_Question_Exam_Home()).commit();
}
else if(v==btnReview){
//enable this to move to move to a Activity or fragment activity
//intent = new Intent(rootView.getContext(), Activity_About.class);
//startActivityForResult(intent,0);
//Get Question set //
List<Question> questions = getQuestionSetFromDb();
//Initialise Game with retrieved question set ///
GamePlay c = new GamePlay();
c.setQuestions(questions);
c.setNumRounds(getNumQuestions());
((ChuckApplication) getActivity().getApplication()).setCurrentGame(c);
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.frameContent, new Activity_Home_Language_Review()).commit();
//transaction.addToBackStack(null);
//transaction.commit();
//FragmentTransaction transaction = getFragmentManager().beginTransaction();
//transaction.addToBackStack(null);
//transaction.replace(R.id.frameContent, new Activity_Question_Review_Home()).commit();
}
else {
}
}
/**
* Method that retrieves a random set of questions from
* the database for the given difficulty
* #return
* #throws Error
*/
private List<Question> getQuestionSetFromDb() throws Error {
int diff = getDifficultySettings();
int numQuestions = getNumQuestions();
DBHelper myDbHelper = new DBHelper(getActivity());
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
List<Question> questions = myDbHelper.getQuestionSet(diff, numQuestions);
//List<Question> questions = myDbHelper.getQuestionSet(diff, 2);
myDbHelper.close();
return questions;
}
/**
* Method to return the difficulty settings
* #return
*/
private int getDifficultySettings() {
SharedPreferences settings = getActivity().getSharedPreferences(Constants.SETTINGS, 0);
int diff = settings.getInt(Constants.DIFFICULTY, Constants.MEDIUM);
return diff;
}
/**
* Method to return the number of questions for the game
* #return
*/
private int getNumQuestions() {
SharedPreferences settings = getActivity().getSharedPreferences(Constants.SETTINGS, 0);
int numRounds = settings.getInt(Constants.NUM_ROUNDS, 20);
return numRounds;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
}
Please help. I'm stuck at that line.
Here's the application:
package com.example.civilserviceexamreviewer;
import android.app.Application;
import com.example.civilserviceexamreviewer.quiz.GamePlay;
public class ChuckApplication extends Application{
private GamePlay currentGame;
/**
* #param currentGame the currentGame to set
*/
public void setCurrentGame(GamePlay currentGame) {
this.currentGame = currentGame;
}
/**
* #return the currentGame
*/
public GamePlay getCurrentGame() {
return currentGame;
}
}
Here's the manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.civilserviceexamreviewer"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#android:style/Theme.Black.NoTitleBar.Fullscreen" >
<activity
android:name="com.example.civilserviceexamreviewer.Activity_Splash1"
android:label="#string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.civilserviceexamreviewer.Activity_Splash2"
android:label="#string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".Activity_Main"
android:label="#string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.example.civilserviceexamreviewer.Activity_Question_Review_Home"
android:label="#string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.example.civilserviceexamreviewer.Activity_About"
android:label="#string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.example.civilserviceexamreviewer.Activity_Choices"
android:label="#string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
<application
android:allowBackup="true"
android:name="com.example.civilserviceexamreviewer.ChuckApplication"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name">
</application>
</manifest>
The way that you're accessing the Application (or its subclass) from within your Fragment is fine and correct. Since the error you're getting is a ClassCastException, I think that your problem is that you haven't declared your custom Application subclass in the AndroidManifest.xml's application tag. For this reason, calling .getApplication() will actually return an object of type android.app.Application which cannot be typecast to your custom Application class. Perhaps you did do this in your original Activity-based project, but forgot to do so when creating the Fragments-based project?
Example of how to declare your Application subclass in the manifest file:
<application
android:name="com.example.civilserviceexamreviewer.ChuckApplication"
android:icon="..."
android:label="...">
</application>
So, the complete manifest you posted in your question should actually be:
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:name="com.example.civilserviceexamreviewer.ChuckApplication"
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#android:style/Theme.Black.NoTitleBar.Fullscreen" >
<activity
android:name="com.example.civilserviceexamreviewer.Activity_Splash1"
android:label="#string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.civilserviceexamreviewer.Activity_Splash2"
android:label="#string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".Activity_Main"
android:label="#string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.example.civilserviceexamreviewer.Activity_Question_Review_Home"
android:label="#string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.example.civilserviceexamreviewer.Activity_About"
android:label="#string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.example.civilserviceexamreviewer.Activity_Choices"
android:label="#string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>

Categories

Resources