Global Variable class not working - android

I am trying to setup and global variable, but I my app fails after adding the following line to my AndroidManifest.xml
<application android:name=".MyApp"
android:icon="#drawable/icon"
android:label="#string/app_name">
I am using the following code as well:
Class:
package com.mynamecompany.datahelp;
import android.app.Application;
class MyApp extends Application {
private String myState;
public String getState(){
return myState;
}
public void setState(String s){
myState = s;
}
}
Usage:
MyApp appState = ((MyApp)getApplicationContext());
String state = appState.getState();
Toast.makeText(getApplicationContext(), "My Value-" + state, Toast.LENGTH_SHORT).show();
appState.setState("Test");
Toast.makeText(getApplicationContext(), "My Value-" + appState.getState(), Toast.LENGTH_SHORT).show();
The program starts and errors immediately on the Splash screen before the usage code can be called further in the program, on a different Activity.
Any ideas?

You are trying to cast to your class from Context. You have to call getApplication.

What's the package indication in your manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mynamecompany">
<application android:name=".datahelp.MyApp"
android:icon="#drawable/icon" android:label="#string/app_name">
...
Probably you have to change it as I made it above. The rest should just work fine, tried it out on my own project.

Related

Missing logcat messages

I have two classes, A1 and A2. Both inherit from BaseActivity, which, in turn, inherits from AppCompatActivity.
BaseActivity has a boatload of logging statements that track, e.g., activity lifecycle methods. Like this: Log.d(tag, "in onCreate");
Those messages are logged, as expected, from A1 but not from A2! I've tried monitoring logcat both from AS and from command line. I can repeat the problem on several Android emulators and in a couple of dev environments.
If I simply replace, e.g., Log.d(tag, "in onCreate") with System.out.println(tag + ": in onCreate"), all of the expected messages appear.
Totally mystified, at this point. Anybody got any suggestions about where my log messages are going?
Edited to add:
I have replaced all calls to Log.d with calls to the following method:
private void log(String message) {
Log.d("LOGGER", tag);
Log.d(tag, message);
System.out.println(tag + ": " + message);
}
Here is sample output from the two subclasses:
07-09 10:26:42.036 9657-9657/net.callmeike.android.latest D/LOGGER: A1
07-09 10:26:42.036 9657-9657/net.callmeike.android.latest D/A1: in onCreate
07-09 10:26:42.036 9657-9657/net.callmeike.android.latest I/System.out: A1: in onCreate
07-09 10:27:10.837 9657-9657/net.callmeike.android.latest D/LOGGER: A2
07-09 10:27:10.837 9657-9657/net.callmeike.android.latest I/System.out: A2: in onCreate
It appears that the variable tag is, in fact, the thing that drives the issue. Anybody understand why?
FWIW:
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="false"
android:theme="#style/AppTheme"
>
<activity
android:name=".A1"
android:label="#string/a1_name"
android:theme="#style/AppTheme.NoActionBar"
>
</activity>
<activity
android:name=".A2"
android:label="#string/a2_name"
android:theme="#style/AppTheme.NoActionBar"
>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
EDITED to add: Sources for the three Activity-related classes:
public abstract class BaseActivity extends AppCompatActivity {
private final String tag;
private final int layout;
public BaseActivity(String tag, int layout) {
this.tag = tag;
this.layout = layout;
}
protected abstract void test();
#Override
protected final void onCreate(Bundle savedInstanceState) {
Log.d(tag, "in onCreate");
super.onCreate(savedInstanceState);
setContentView(layout);
setSupportActionBar(findViewById(R.id.toolbar));
findViewById(R.id.fab).setOnClickListener(this::makeSnackbar);
}
final void makeSnackbar(View v) {
Snackbar.make(v, R.string.action_test, Snackbar.LENGTH_LONG)
.setAction(R.string.action_test, v1 -> test())
.show();
}
// blah blah blah
}
// BaseActivity logs show up in logcat
public class A1 extends BaseActivity {
private static final String TAG = "A1";
public A1() {
super(TAG, R.layout.activity_a1);
}
#Override
protected void test() {
// blah blah blah
}
}
// BaseActivity logs do not show up in logcat
public class A2 extends BaseActivity {
private static final String TAG = "A2";
public A2() {
super(TAG, R.layout.activity_a2);
}
#Override
protected void test() {
// blah blah blah
}
}
I've had a similar issue - some of my log messages were not shown by the Log command.
I've found out that there are some "illegal" tags that the logcat won't show.
In my case it was "SMS" tag. Try to change the bad tags with other ones.
You can take a look here - LogCat won't show my logs.
I've searched the documentation, but could not find any list of "illegal" tags.

How to assign initial value to a String in Android

i don´t know where i have to setup the initial value of this variable:
mySharedPreferences.putStringValue("hello", "400");
And it don´t be reset if it is changed every time i open the app.
Thank you!!
The best way to do that is to "set" the default value on get method instead of set it on the first start of your app.
mySharedPreferences.getString("hello", "400");
On this way android checks if there was an value set. If not, it will fallback to the default "400".
Take a look at the documentation:
https://developer.android.com/reference/android/content/SharedPreferences.html#getString(java.lang.String, java.lang.String)
And in application tag
<application
android:name=".YourApplication"
android:allowBackup="true"
android:hardwareAccelerated="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
In Application's onCreate Method. It is best place. It will be executed when your app is created.
public class YourApplication extends Application {
public static Boolean sAppOpened = false;
#Override
public void onCreate() {
super.onCreate();
//Write your code here
sAppOpened = true;
....
}
...
}
Declare your SHARED PREFERENCE file name class-wide like this -
public static final String SHARED_PREFERENCES = "SHARED_PREF";
You can use this in your OnCreate method.
SharedPreferences sharedpreferences = getSharedPreferences(SHARED_PREFERENCES, Context.MODE_PRIVATE);
Editor editor = sharedpreferences.edit();
editor.putString("key", "value");
editor.commit();

BackUpAgentHelperClass is not getting called

I want to backup data in Android using MyBackUpAgent class which extends BackupAgentHelper. I am using SharedPreferences in order to store data.
My mainactivity code is:
public class MainActivity extends Activity {
EditText inputtext;
TextView outputtext;
Button submit;
public static SharedPreferences sharedprefs;
static final String File_Name_Of_Prefrences ="godplay_preferences";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
init();
sharedprefs=getSharedPreferences(File_Name_Of_Prefrences,MODE_PRIVATE);
System.out.println("value="+sharedprefs.getString("Input",""));
outputtext.setText(sharedprefs.getString("Input",""));
submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
populateUI();
}
});
}
public void populateUI()
{
String savedinput=inputtext.getText().toString();
System.out.println("savedinput="+savedinput);
outputtext.setText(savedinput);
sharedprefs=getSharedPreferences(File_Name_Of_Prefrences,MODE_PRIVATE);
Editor editor=sharedprefs.edit();
editor.putString("Input",inputtext.getText().toString());
editor.commit();
requestBackup();
}
private void init() throws ClassCastException
{
inputtext=(EditText) findViewById(R.id.edtInputText);
outputtext=(TextView) findViewById(R.id.txtOutputText);
submit=(Button) findViewById(R.id.btnSubmit);
}
public void requestBackup() {
BackupManager bm = new BackupManager(getApplicationContext());
bm.dataChanged();
}
}
My MyBackUpAgent class:
public class MyBackUpAgent extends BackupAgentHelper{
static final String PREFS_BACKUP_KEY = "backup";
String key_string="Hello World";
#Override
public void onCreate() {
System.out.println("********************");
SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this,MainActivity.File_Name_Of_Prefrences);
addHelper(PREFS_BACKUP_KEY, helper);
}
}
My mainfest.xml file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.godplay"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:restoreAnyVersion="false"
android:backupAgent=".MyBackUpAgent"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.godplay.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data android:name="com.google.android.backup.api_key" android:value="AEdPqrEAAAAIhjloadYCTPUNo3yPsSX6LKmziiumZiQVlEEdBA" />
</application>
</manifest>
So far I have tried with bmgr tool to test, it is executing successfully with bmgr tool. However, on testing on Android device and emulator, back up is not happening, nor restoring.
Also, I have tested this on Android 5.1, Android 4.2, and Android 4.0 but still no luck.
It seems to me that my MyBackUpAgent class is never getting called, and I have tried breakpoints in MyBackUpAgent Class and validated it. Its never get hit.
What am I doing wrong?
Docs mention Conditions For Backup Schedule:
The user has enabled backup on the device in Settings > Backup & Reset.
At least 24 hours have elapsed since the last backup.
The device is idle and charging.
The device is connected to a Wi-Fi network. If the device is never connected to a wifi network, then Auto Backup never occurs.
If backup is working for you with bmgr tool but not on a real device / emulator, it's possible you are not meeting all those conditions, therefore backup never occur.
In your AndroidManifest.xml file, try changing
android:backupAgent=".MyBackUpAgent"
with the fully qualified class name, i.e.
android:backupAgent="com.abh.utils.MyBackUpAgent"
but of course changing "com.abh.utils" with the name of the package MyBackUpAgent.java is in.
I had a similar problem and have searched everywhere with no luck. Finally found the solution.
It seems that the BackupAgent needs to be in the top package with no preceding dot. So try changing:
android:backupAgent=".MyBackUpAgent"
to
android:backupAgent="MyBackUpAgent"
You can refer to developer document,
https://developer.android.com/guide/topics/data/backup.html#PerformingBackup
A backup request does not result in an immediate call to your onBackup() method. Instead, the Backup Manager waits for an appropriate time
you can use "bmgr tool" to initiate immediate backup whiling developing your app.
Make sure you call
adb shell bmgr run
to simulate the backup.
Also try using local transport to backup at any time:
adb shell bmgr transport android/com.android.internal.backup.LocalTransport

Android live wallpaper sample getting force closed , Unable to instantiate service

I trying to run a some tutorial samples for android live wall paper but always got this error
09-28 16:13:30.729: E/AndroidRuntime(408): java.lang.RuntimeException:
Unable to instantiate service
net.markguerra.android.glwallpaperexample.MyWallpaperService:
java.lang.ClassNotFoundException:
net.markguerra.android.glwallpaperexample.MyWallpaperService in loader
dalvik.system.PathClassLoader[/data/app/net.markguerra.android.glwallpaperexample-1.apk]
This is my manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="net.markguerra.android.glwallpaperexample"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="#drawable/icon" android:label="#string/app_name">
<service android:label="#string/service_label" android:name=".MyWallpaperService"
android:permission="android.permission.BIND_WALLPAPER">
<intent-filter>
<action android:name="android.service.wallpaper.WallpaperService" />
</intent-filter>
<meta-data android:name="android.service.wallpaper"
android:resource="#xml/myglwallpaper" />
</service>
</application>
<uses-sdk android:minSdkVersion="7" />
</manifest>
Wallpaper service i created
package net.markguerra.android.glwallpaperexample;
import net.rbgrn.android.glwallpaperservice.*;
// Original code provided by Robert Green
// http://www.rbgrn.net/content/354-glsurfaceview-adapted-3d-live-wallpapers
public class MyWallpaperService extends GLWallpaperService {
public MyWallpaperService() {
super();
}
public Engine onCreateEngine() {
MyEngine engine = new MyEngine();
return engine;
}
class MyEngine extends GLEngine {
MyRenderer renderer;
public MyEngine() {
super();
// handle prefs, other initialization
renderer = new MyRenderer();
setRenderer(renderer);
setRenderMode(RENDERMODE_CONTINUOUSLY);
}
public void onDestroy() {
super.onDestroy();
if (renderer != null) {
renderer.release();
}
renderer = null;
}
}
}
this is my projrct structure
I cant figure out whats going wrong in it, Whats the error ?
Any suggestions will be a great help for me
found some related questions on stack but not related to live wallpaper
You should include GLWallpaperService.jar in libs folder.
it must be libs not lib or am I mistaken? With libs you should see a small a on the folder like res or bin have...

Nothing happens when I configure RoboGuice

I am new to RoboGuice and I am trying to set up my activity to use DI. However, nothing happens when I attempt to use it. I only get a blank black window with no content and no logging in my Activity.onCreate() method after I call "super.onCreate(savedInstanceState);"
See these 2 snippets of code:
public class ClikClokActivity extends RoboActivity{
#Inject
private TileAdapter tileAdapter;
#Inject
private GameLogicService gameLogicService;
#Inject
private GridOperationQueue gridOperationQueue;
private GridView gridView;
#Inject
private Handler handler;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
Log.v(this.getClass().toString(), "Entering onCreate");
super.onCreate(savedInstanceState);
Log.v(this.getClass().toString(), "Never logs this with RoboGuice");
setContentView(R.layout.main);
gridView = (GridView) findViewById(R.id.gridview);
gridView.setNumColumns(Constants.GRID_WIDTH);
gridView.setAdapter(tileAdapter);
Log.v(this.getClass().toString(), "GridView initialized");
gridOperationQueue.start();
Log.v(this.getClass().toString(), "Completed onCreate");
}
and
public class ClikClokApplication extends RoboApplication{
#Override
protected void addApplicationModules(List<Module> modules) {
modules.add(new ClikClokModule());
}
}
and
public class ClikClokModule extends AbstractAndroidModule {
#Override
protected void configure() {
}
}
and
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.clikclok"
android:versionCode="1"
android:versionName="1.0">
<application android:name="com.clikclok.ClikClokApplication" android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".ClikClokActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
If you look at the above code, I never get the second logging. However, if I was to extend from Activity instead and remove the android:name="com.clikclok.ClikClokApplication" attribute from my manifest then I do get the second logging (albeit fails with NullPointers as there is no initialization performed).
So what may be happening in super.onCreate(savedInstanceState); that is causing my application not to work?
Thanks
Update from the above:
I've spent quite a bit of time investigating this and using Eclipse's debugger can now see where my code seems to hang within RoboGuice.
The following code is from the InjectorImpl class:
public void injectMembers(Object instance) {
// Reaches here but...
MembersInjector membersInjector = getMembersInjector(instance.getClass());
// ....this comment is never reached
membersInjector.injectMembers(instance);
}
So I dug into the Guice 3.0 code using my debugger and into the FailableCache class:
public V get(K key, Errors errors) throws ErrorsException {
// Reaches here....
Object resultOrError = delegate.get(key);
// ...but not here
if (resultOrError instanceof Errors) {
errors.merge((Errors) resultOrError);
throw errors.toException();
} else {
#SuppressWarnings("unchecked") // create returned a non-error result, so this is safe
V result = (V) resultOrError;
return result;
}
}
How could this be that it just hangs while retrieving a key from a map? I'm not familiar enough with the code and it is quite confusing to troubleshoot.
Any advice is appreciated.
Try to add some bindings in your configure method.
You can also try to inject your grid view like this
#InjectView(R.id.gridview)
GridView gridView;
I hope this will help you.
Regards.
This was caused by me attempting to inject my Activity class into a service class.
So I was attempting to #Inject an instance of "ClikClokActivity" instead of "Activity".
Once I removed this injection attempt, everything worked fine. Not sure if this exposes some other issue with RoboGuice or Guice itself.

Categories

Resources