I have a sony smart watch and i'm trying to invoke a vibration intent by using the following:
Intent intentImplicit = new Intent(Control.Intents.CONTROL_VIBRATE_INTENT);
startActivity(intentImplicit);
it says startActivity its not declared in the control extension. How can I fix this?
I found this online "You can get a Context object from the Constructor for the Control and save it to a member variable then just call context.startActivity()." but i'm unsure on how to do this
The Sony SDK documentation says you should use sendBroadcast()
See: http://developer.sonymobile.com/reference/sony-addon-sdk/com/sonyericsson/extras/liveware/aef/control/Control.Intents#CONTROL_VIBRATE_INTENT
So this should work:
context.sendBroadcast(intentImplicit, Registration.HOSTAPP_PERMISSION);
If you used a sample application from Sony as base, the context is already saved as a field of your class. If not, you can get a reference in the constructor of the Extension and save it to a field like this:
public class TestExtension extends ControlExtension
{
private Context context;
TestExtension(final String hostAppPackageName, final Context context, Handler handler)
{
super(context, hostAppPackageName);
this.context = context;
}
}
What is the purpose of trying to send that Intent? If you are just trying to activate the Vibration, there is already a method built into the utilities class to do this. Take a look at the ControlExtension.startVibrator() method in the SmartExtensionUtils project.
Related
I am using the following function in one of my activities of my app:
public static float convertDpToPixel(float dp, Context context){
return dp * ((float) context.getResources().getDisplayMetrics().densityDpi / DisplayMetrics.DENSITY_DEFAULT);
}
What context should I use?
Application Context: tied to the Lifecycle of an Application
Activity Context: tied to the life cycle of activity
Base Context: the base context as set by the constructor or setBaseContext
I have done it like this and it seems to work:
In my_activity.java:
float conversion = convertDpToPixel(10, this);
But also I could do the following:
float conversion = convertDpToPixel(10, getApplicationContext());
And also the following:
float conversion = convertDpToPixel(10, getBaseContext());
I think that in this specific case it doesn't really matter as it will get the resources of the app and it is included in all the contextes types but I would like to ensure what I am saying. Thanks
All of three you can use in this case.
Context usually use to get resource or launch some system service, and I found a context explain in this website https://www.jianshu.com/p/94e0f9ab3f1d, here is the picture he explain when each context can be use:
(不推荐 mean not recommended)
Most of case you can use Application, Activity, and Service context, but beside some scene, like show dialog,start activity, and layout inflation.
A dialog need to build base on a activity, so you can't use other two type context.
This case seems to be load resource values, so you can use all of three.
Other information about context: Difference between Activity Context and Application Context, https://web.archive.org/web/20150329210012/https://possiblemobile.com/2013/06/context/.
I'm currently writing an App, it gets JSON from a website, and then lists the contents in a listview. Now since the API itself only returns names like this: "twisted_castle" instead of "Twisted Castle", I created a new class to substitute the generic names to the right names, which I previously added to the strings.xml.
Now I can get Strings via String test = getString(R.string.key) in the MainActivity, but since I created a new class for the Substitute to happen, I somehow can't use getString somehow.
I already discovered that I'll need to get/use the context of MainActivity somehow, but really any solution I found didn't work, and also I'm a bit irritated on how the whole context thing works.
Anyone can help me with this and maybe has a good explanation on how contexts work?
You can use Context as:
mcontext.getString(R.string.something);
all you have to do is init context in the class some where like:
static Context mcontext;
public void setmContext(Context context){
this.mcontext=context;
}
and call setmContext(this) from your activity or where ever you have context attribute
I want to ask why we get this annotation:
Method invocation getContext.getContentResolver() may produce
NullPointerException
Why is it there and not in other parts of program Fragment/Activity? That approach has been used in tutorial made by Google - here is link for ContentProvider code https://github.com/udacity/Sunshine-Version-2/blob/sunshine_master/app/src/main/java/com/example/android/sunshine/app/data/WeatherProvider.java even if you create an aplication with just a blank activity and put that method in a newly created ContentProvider it is there.
Should we use getContext().getContentResolver().notifyChange(uri, null);outside ContentProvider getting the uri passed and then after the update/insert/delete is finished notifyChange? or maybe we can fix it somehow?
If you look in the source of ContentProvider (just hold SHIFT and click on the classname in Android Studio) then you will find that the implementation is holding an object of type Context as mContext.
Your solution is just the same, which means if mContext of ContentProvider is null, your reference will also be null. So there is no need for this.
To help you out, this is just a warning of your IDE if make such a construct yourself. But in this case there will always be context, because the ContentProvider is generated by your system. To avoid the error in your IDE just write #SuppressWarnings("ConstantConditions") above your class definition like:
...
#SuppressWarnings("ConstantConditions")
public class NoteProvider extends ContentProvider {
...
If you can make sure that getContext() can never be null then you can simply ignore this warning. I think the warning even disappears of you just check for null:
if (getContext() != null) {
getContext().getContentResolver();
}
You just have to keep in mind the code won't be executed if getContext() is null.
Cheers
edit:
Be careful with the answer #Shivani Gupta gave you, because you could get different contexts. See: Difference between getContext() , getApplicationContext() , getBaseContext() and "this"
Write getApplicationContext().getContentResolver()
Hope this will work.
Ok it seems I fixed it myself by declaring Context on the beggining of the class.
public class NoteProvider extends ContentProvider {
Context context;
then initializing it in onCreate()
#Override
public boolean onCreate() {
mSQLiteOpenHelper = new NoteDbHelper(getContext());
context = getContext();
return true;
}
I think that made sure that I always have Context when I use context.getContentResolver().notifyChange(uri, null); or retCursor.setNotificationUri(context.getContentResolver(), uri); in insert/update/delete/query method- retCursor being returned cursor by mentioned methods.
I have run the aplication on my phone and did not have issues yet if I will there will probably be an edit for this post.
EDIT:
It does not make a difference after all - explanationin answer by #Mate, thank you for that I think I get it now :]
According to ContentProvider getContext() docs:
Retrieves the Context this provider is running in. Only available once onCreate() has been called -- this will return null in the constructor.
So the getContext() method does not return null in insert(), update() or delete(), because onCreate() will be called before these calls.
So it's OK to disable that warning for that line if you use it in such case...
//noinspection ConstantConditions
getContext().getContentResolver().notifyChange(uri, null);
Whenever you try to use a member or a method of an object, you can have a runtime exception if the object, whose member/method you try to use is null. Let's suppose you want to use a member/method of an object, obj. If you use it like this:
if (obj != null) {
//use members/methods of obj
}
then you prevented the problem. However, you might want to handle it as an exception, like this:
try {
//use members/methods of obj
} catch (NullPointerException npe) {
//handle the NullPointerException
}
Ok this is a bit more theoretical question.
I have PlayerRepository. This is a class that is used to make actions on my SQLite database. I've implemented there actions like select, insert, update etc.
public PlayerRepository(Context context) {
super(context, com.fixus.portals.model.Player.class);
open();
}
super in constructor is cause PlayerRepository extends Repository which is also my class. The most important part of Repository is this one
public class Repository<T> {
protected static SQLiteDatabase db = null;
protected static MainHelper helper = null;
protected Context context;
private Class<T> type;
public Repository(Context context, Class<T> classz) {
this.type = classz;
this.context = context;
if(helper == null) {
helper = new MainHelper(context.getApplicationContext());
}
}
public static void open() {
if(db == null) {
db = helper.getWritableDatabase();
}
}
}
As you can see when I create the repository I'm opening DB if it wasn't open before. To do that I need to pass the Context of the application/activity. That is not a problem.
BUT sometimes I want to use my repository out side of an activity. In some kind of tool class that need to get data. So I have two ways that I can think about
I get the data in activity and pass it to my tool class/method so I don't need to use repository in it. This is not very flexible
I need to pass context to my tool class/method. But that means that every kind of operation need to receive a context and I'm not sure this is a good way
Am I missing something ? is there any better way to handle it ?
You always need a Context to access the SQLite database so what u could do is change the constructor of that specific tool class and pass a new instance of PlayerRepository as a parameter. This prevents your tool class of needing a context itself.
Imo if u have multiple classes using the database best approach is to create a new class whose only job is doing database actions and put all the needed action inside that one.
Just create an object of this database class with the Context of the current activity the to Tools and PlayerRepository constructors. This way neither your PlayerRepository or Tools classes need Context and both can make actions on the database.
Even if you should really need Context in PlayerRepository it is always best to keep all database related functions centralized in a single class.
I understand that this is an old question but still i'll write for those like me who will pass by this in future.
In order to get rid of the context problem with repository pattern used for accessing database you can implement DI (Dependency Injection) pattern in your project. There are many reasons to do such and that question illustrates one of them.
If you implement DI you would have only one instance of database repository amongst the entire module (or app). This instance would be created in a class which has context, and injected to those classes where needed.
One of the simpliest approaches for using DI is to use Dagger 2 library. All of the related information you could find on their site.
How can I register data (like integer or poco objects) shared by all activity like the id of the user ? Have I to use a simple singleton or is there a special Android way ?
Note : I don't need to make that data persistant (no need of SharedPreferences or sqlite)
Thank you
You can create your own class that implements Application and specify this in your manifest file. In that case, every time you call getApplicationContext you will get a reference of your application that can hold any kind of information.
How to declare global variables in Android?
Sample code:
class MyApplication extends Application {
public void setMethod() {
//
}
}
((MyApplication)getApplicationContext()).setMethod()
The android way is to create a custom Application for your project. Then in onCreate of that application you initialize whatever you need, and for example from an Activity do something like:
((MyApplication) getApplication()).getMyData()
If using roboguice you can use a #Singleton injection which basically does the boilerplate of a singleton for you - that's much nicer.