Javadoc extras accepted/required by activity - android

In my code I have some activities that need some extra parameters (passed as a Bundle in the Intent) to work properly. Some other need none, or have some optional extras.
How to document that in Javadoc?

One way to do that is to define public static method in your Activity to take the extra parameters and return the Intent that you're going to use to start your Activity.
Let's say you have an Activity called MainActivity and it takes an integer id and a String name. here's the code to do it.
public class MainActivity extends Activity {
private static final String BUNDLE_KEY_ID = "id";
private static final String BUNDLE_KEY_NAME = "name";
/**
* Write your documentation here
* #param context Required to create new intent
* #param id write description
* #param name write description
*/
public static Intent getIntent(Context context, int id, String name) {
Intent intent = new Intent(context, MainActivity.class);
intent.putExtra(BUNDLE_KEY_ID, id);
intent.putExtra(BUNDLE_KEY_NAME, name);
return intent;
}
}

In Android Studio ==> Type /** above your Method Signature & Hit Enter
Studio will create documentation basics for that particular method.
/**
*
* #param args1
* #param args2
*/
private void doSomething(int args1,float args2){
}
You just need to add explanation.
/**
* Do something will Blahhh ..Blahhh..
* #param args1 Input argument used to do Blahhh ..Blahhh..
* #param args2 Input argument used to do Blahhh ..Blahhh..
*/
private void doSomething(int args1,float args2){
}

Related

intent setFlags error

What's wrong, really marked red?
here is my Intent
public void onBackPressed() {
super.onBackPressed();
Intent i = new Intent(this, MainActivity.class);
i.setFlags(268468224);
startActivity(i);
finish();
finishAffinity();
System.exit(0);
}}
i.setFlags(268468224) marker red, any solution?
Only this couple gives us that result :
Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK
for 0x10008000(i.e.268468224)
Android Intent setFlags() has #Retention(RetentionPolicy.SOURCE) annotation.That's why your line i.setFlags(268468224); marked as red because violation of it's rules.
/**
* Set special flags controlling how this intent is handled. Most values
* here depend on the type of component being executed by the Intent,
* specifically the FLAG_ACTIVITY_* flags are all for use with
* {#link Context#startActivity Context.startActivity()} and the
* FLAG_RECEIVER_* flags are all for use with
* {#link Context#sendBroadcast(Intent) Context.sendBroadcast()}.
*
* <p>See the
* <a href="{#docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back
* Stack</a> documentation for important information on how some of these options impact
* the behavior of your application.
*
* #param flags The desired flags.
* #return Returns the same Intent object, for chaining multiple calls
* into a single statement.
* #see #getFlags
* #see #addFlags
* #see #removeFlags
*/
public #NonNull Intent setFlags(#Flags int flags) {
mFlags = flags;
return this;
}
#Retention(RetentionPolicy.SOURCE)
public #interface Flags {}
/** #hide */
#IntDef(flag = true, prefix = { "FLAG_" }, value = {
FLAG_FROM_BACKGROUND,
FLAG_DEBUG_LOG_RESOLUTION,
FLAG_EXCLUDE_STOPPED_PACKAGES,
FLAG_INCLUDE_STOPPED_PACKAGES,
FLAG_DEBUG_TRIAGED_MISSING,
FLAG_IGNORE_EPHEMERAL,
FLAG_ACTIVITY_NO_HISTORY,
FLAG_ACTIVITY_SINGLE_TOP,
FLAG_ACTIVITY_NEW_TASK,
FLAG_ACTIVITY_MULTIPLE_TASK,
FLAG_ACTIVITY_CLEAR_TOP,
FLAG_ACTIVITY_FORWARD_RESULT,
FLAG_ACTIVITY_PREVIOUS_IS_TOP,
FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS,
FLAG_ACTIVITY_BROUGHT_TO_FRONT,
FLAG_ACTIVITY_RESET_TASK_IF_NEEDED,
FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY,
FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET,
FLAG_ACTIVITY_NEW_DOCUMENT,
FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET,
FLAG_ACTIVITY_NO_USER_ACTION,
FLAG_ACTIVITY_REORDER_TO_FRONT,
FLAG_ACTIVITY_NO_ANIMATION,
FLAG_ACTIVITY_CLEAR_TASK,
FLAG_ACTIVITY_TASK_ON_HOME,
FLAG_ACTIVITY_RETAIN_IN_RECENTS,
FLAG_ACTIVITY_LAUNCH_ADJACENT,
FLAG_RECEIVER_REGISTERED_ONLY,
FLAG_RECEIVER_REPLACE_PENDING,
FLAG_RECEIVER_FOREGROUND,
FLAG_RECEIVER_NO_ABORT,
FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT,
FLAG_RECEIVER_BOOT_UPGRADE,
FLAG_RECEIVER_INCLUDE_BACKGROUND,
FLAG_RECEIVER_EXCLUDE_BACKGROUND,
FLAG_RECEIVER_FROM_SHELL,
FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS,
})

Memory leak for static declaration of context and INSTANCE , how do I alter it?

Currently in my codebase I have the following class(part of it) where it shows me 2 memory leaks with the message " Do not place Android context classes in static fields (static reference to Myclass which has field context pointing to Context); this is a memory leak (and also breaks Instant Run)"
I am not sure what the alternative is. Is this a 100% memory leak ? I get the leak warning on "INSTANCE;" and "static" declaration for context. Any idea how to go about fixing it?
public enum Myclass {
INSTANCE;
public static final boolean TLS_ENABLED = true;
private static final String TAG = Myclass.class.getSimpleName();
private static final String SP = "My_class";
private static Context context;
public void init(Context context, String appKey, String appSecret) {
init(context, null, appKey, appSecret);
}
/**
* Initialize class
*
* #param context Application level context.
* #param apiUrl API url of backend server
* #param appKey Application key
* #param appSecret Application secret
* #throws IllegalArgumentException If activity instance will be passed as the context
* #throws IllegalArgumentException If application key is empty or null
* #throws IllegalArgumentException If application secret is empty or null
*/
public void init(Context context, String apiUrl, String appKey, String appSecret) {
if (null == context) { throw new NullPointerException(); }
if (!(context instanceof Application)) { throw new IllegalArgumentException("Supply my class with application context"); }
// if (TextUtils.isEmpty(apiUrl)) { throw new IllegalArgumentException("Api url can't be null or empty string"); }
if (TextUtils.isEmpty(appKey)) { throw new IllegalArgumentException("App key can't be null or empty string"); }
if (TextUtils.isEmpty(appSecret)) { throw new IllegalArgumentException("App secret can't be null or empty string"); }
this.apiUrl = apiUrl;
this.appKey = appKey;
this.appSecret = appSecret;
this.sp = context.getSharedPreferences(SP, Context.MODE_PRIVATE);
MyClass.context = context;
initManagers();
}
/**
* Initializes managers. This method must be called after constructor
* returns, as the managers during own initialization may use myclass.get()
* method.
*/
private void initManagers() {
accountManager = new AccountManager();
myclassApi = new MyclassApi(context, apiUrl);
contactManager = new ContactManager();
connectionManager = new ConnectionManager();
meetingListManager = new MeetingListManager();
}
/**
* Returns {#link Context} that was passed to
* {#link myclass#init(Context, String, String)}.
*
* #return
*/
public static Context getContext() {
return context;
}
/**
* Returns {#link SharedPreferences} instance.
*
* #return SharedPreferences
*/
public SharedPreferences getSp() {
return this.sp;
}
public static class Event<T> {
private State state = State.SUCCESS;
private Throwable t;
private T data;
private String errorMessage;
/**
* Event state. If event related to network request/response
* operations - state indicates the physical (not logical)
* success or fail of request.
*/
public enum State {
/**
* Indicates that attempt to get data or perform task successful
*/
SUCCESS,
/**
* Indicates that attempt to get data or perform task fails,
* and reason of fail is the incorrect request data
*/
FAIL,
/**
* Indicates that attempt to get data or perform task encounter an error
* mostly due to connection problem
*/
ERROR,
/**
* Indicates that attempt to get data or perform task was ignored
* according to internal state of event producer.
*/
IGNORED
}
}
It's safe to store application context in a static field, you can simple call context.getApplicationContext() on any context reference you get before storing it in a static field.
The application context is a singleton anyway and you cannot leak it.
This seems like warning from IDE if you are making sure that context will store only ApplicationContext, not Activity context you can suppress this warning using annotation.
#SuppressLint("StaticFieldLeak")
If you want to understand more about memory leaks you can check my only blog :) here

How to comment Android's Activities with JavaDoc?

Activities are called in this way (an example):
Intent i = new Intent(context, MyActivity.class);
i.putExtra("par1", "value1");
i.putExtra("par2", 2);
startActivityForResult(i);
How can I comment MyActivity class with JavaDoc like methods?
For example in this case:
/**
* This activity show some data
* #param par1 String value of parameter1
* #param par2 int number of records to show
* #return returnValue boolean true if data is showed, false otherwise
*/
to have an idea of which parameters intent expects and what type of return offers.
Just write the JavaDoc part right in top of the class declaration.
/**
* JavaDoc
*/
public class MyActivity {
Right Click on a Method Name-> Source-> Generate Element Comment.
Shortcut
ALT+SHIFT+J
Declare the parameter constants as public static final String and add javadoc field documentation there.
Use #links to bind things together.
Example:
/**
* String containing foo parameter for {#link #XyzzyActivity}
*/
public static final String EXTRA_FOO = "par1";
/**
* XyzzyActivity
*
* Parameters understood: {#link #EXTRA_FOO}, ...
*
* Returns...
*/
Type /** at the top of your method, then press ENTER key. The comment part will become something like this:
/**
*
* #return
*/
You are also allowed to add
#author – who wrote this code
#version – when was it changed
#param – describe method parameters
#return – describe method return values
#throws – describe exceptions thrown
#see – link to other, related items (e.g. “See also…”)
#since – describe when code was introduced (e.g. API Level)
#deprecated - describe deprecated item and what alternative to use instead

How to keep certain part of my app common in entire application

I want to have a list of certain important things(which I am fetching from server every 15 seconds) which I want to have constant(or common) in my entire application. So when I move to next activity by Intents(or any other methods) I should have the list all the time. Is it possible in android ??
I want different solutions which requires as less work as possible.
Please Help..
EDIT: I think I havent made myself clear. I am not worried about how to store data..I am asking as to how can I achieve a view in which only half of the screen changes(as we move from activity to activity) while other half remains constant(doesnt move). Can it be possible ??
Your application class instance is always accesible from any activity.
All you need to do is create the application class like this:
public class YourApp extends Application {
....
}
And then modify the following line in your app AndroidManifest.xml :
<application
android:name="your.package.YourApp"
Now you can access this class everywhere:
YourApp appInstance = (YourApp)getApplication();
Use the PreferencesManager like the one below, create your POJO to access the PreferencesManager.
// TODO: Auto-generated Javadoc
/**
* The Class PreferenceManager.
*/
public class PreferenceManager {
/** The Constant TAG. */
private static final String TAG = PreferenceManager.class.getSimpleName();
/** The default shared preferences. */
private static SharedPreferences defaultSharedPreferences = null;
/**
* Inits the.
*
* #param context the context
*/
public static final void init(Context context){
defaultSharedPreferences = android.preference.PreferenceManager.getDefaultSharedPreferences(context);
log("Initialize PreferenceManager!");
UserSettings.init(context);
}
/**
* Save.
*
* #param name the name
* #param value the value
*/
static final void save(String name,String value){
if( value != null ){
Editor edit = defaultSharedPreferences.edit();
edit.remove(name);
edit.putString(name, value);
edit.commit();
}else{
Editor edit = defaultSharedPreferences.edit();
edit.remove(name);
edit.commit();
}
}
/**
* Gets the.
*
* #param name the name
* #param defaultValue the default value
* #return the string
*/
public static final String get(String name,String defaultValue){
return defaultSharedPreferences.getString(name, defaultValue);
}
/**
* Save state.
*
* #param name the name
* #param state the state
*/
public static final void saveState(String name,Bundle state){
if( state != null && state.size() > 0 ){
Parcel parcel = Parcel.obtain();
parcel.writeBundle(state);
String encodeToString = Base64.encodeToString(parcel.marshall(), Base64.DEFAULT);
PreferenceManager.save(name, encodeToString);
}else{
PreferenceManager.save(name, null);
}
log("Saved state "+name);
}
/**
* Gets the state.
*
* #param name the name
* #return the state
*/
public static final Bundle getState(String name){
log("Get state "+name);
String encryptedValue = "";
try {
encryptedValue = PreferenceManager.get(name, "");
} catch (NullPointerException e) {
return new Bundle();
}
if( "".equals(encryptedValue) ){
return new Bundle();
}else{
byte[] decode = Base64.decode(encryptedValue, Base64.DEFAULT);
Parcel parcel = Parcel.obtain();
parcel.unmarshall(decode, 0, decode.length);
parcel.setDataPosition(0);
return parcel.readBundle();
}
}
/**
* Log.
*
* #param msg the msg
*/
private static final void log(String msg){
Log.d(TAG, msg);
}
}
/**
* The Class Settings.
*/
public class UserSettings {
/** The settings bundle. */
private final Bundle settingsBundle = new Bundle(1);
/**
* Save.
*/
public final void save() {
PreferenceManager.saveState(SETTINGS_STATE_NAME, settingsBundle);
}
/**
* Restore.
*/
final public void restore() {
settingsBundle.clear();
Bundle state = PreferenceManager.getState(SETTINGS_STATE_NAME);
if (state.size() == 0) {
settingsBundle.putAll(getDefaultValuesSettings());
} else {
settingsBundle.putAll(state);
}
}
final void reset() {
settingsBundle.clear();
}
/**
* Gets the settings.
*
* #return the settings
*/
public static UserSettings getSettings() {
return settings;
}
/**
* Inits the.
*
* #param ctx the ctx
*/
public static final void init(Context ctx) {
settings.restore();
setDeviceUniqueId(ctx, settings);
}
}
Example usage:
public class YourApplication extends Application {
....
onCreate(){
....
PreferenceManager.init(getBaseContext());
}
}
Where you need your data to be stored and retrieved use the methods like below.
UserSettings.getSettings().setUser(responseVal);
UserSettings.getSettings().save();
String response = UserSettings.getSettings().getUser();
If it's large amount of data, you can store your data using Shared Preferences or SQLite DB. If it is less amount of data then you can go for static variables. If you use static variables, when any crash occurs in the app that data may lost. Hence static variables usage is less preferable.
There are lot of ways to do this :
You can store them and put in your application's SQLite database (Data is Persistent till you delete the application or delete through your application code )
See the SQLite usage here
You use Cache them in the phone memory till the time your app runs.
See Cache usage here here
You can use SQLite database to store this data and then create singleton helper to read it.
Or you can use save your data in XML or JSON format as files, then parse them to read.
Or you can create class-container for one entity of your data, make it serializable and store in SharedPreferences as ArrayList<YourDataContainer>

How to set clipboard in android emulator for ice cream sandwich?

I found a command-line solution to set the clipboard text in a Gingerbread AVD, but this command-line doesn't work when I'm running an ICS AVD.
I built a script from this page: Pasting text into Android emulator clipboard using adb shell .
Again, this works fine for writing to the clipboard and reading the contents, if I'm using a Gingerbread AVD, but when I write to the ICS clipboard, the parcel that comes back just says "Unknown package", and when I attempt to read the clipboard, it appears to return an empty string.
I hope this Link of Example will work for your answer .
This project's Build Target: Android 4.0 that will work on Emulator which is ICS .
http://www.edumobile.org/android/android-tutorial/clipboard-example-in-android-development/
This example shows how to use clipboard manager to copy text/intent/url in android.
Here's how to do it:
I use a main method that takes a param oldApi when false uses Android's old Clip APIs and when true uses the new Clip APIs.
Full project: https://github.com/daniel-c05/LightClipper/blob/master/src/com/deadpixels/light/clipper/utils/ClipHelper.java
/**
*
* #param context The context
* #param label The label to show to the user via {#code ClipDescription}
* #param value The actual value to store on the clipboard via {#link ClipHelper#addItemToClipboard(Context, String, String)}
* #param oldAPI Whether or not we are running on pre-HoneyComb API.
*/
public static void addItemToClipboard(final Context context, final String label, final String value, final boolean oldAPI) {
if (oldAPI) {
addTextToClipboard(context, value);
}
else {
addItemToClipboard(context, label, value);
}
}
/**
* This is only called when oldAPi is passed as false on {#link #addItemToClipboard(Context, String, String, boolean)}
* #param context The context, required to get the Cliboard System Service.
* #param label The label to show to the user via {#code ClipDescription}
* #param value The value to store on the clipboard.
*/
#SuppressLint("NewApi")
private static void addItemToClipboard (final Context context, final String label, final String value) {
ClipboardManager manager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData.Item item = new Item(value);
ClipDescription description = new ClipDescription(label, new String [] {ClipDescription.MIMETYPE_TEXT_PLAIN});
ClipData data = new ClipData(description, item);
manager.setPrimaryClip(data);
}
/**
* This is only called when oldAPi is passed as true on {#link #addItemToClipboard(Context, String, String, boolean)}
* #param context The context, required to get the Cliboard System Service.
* #param value The value to store on the clipboard.
*/
#SuppressWarnings("deprecation")
private static void addTextToClipboard (final Context context, final String value) {
android.text.ClipboardManager manager = (android.text.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
manager.setText(value);
}

Categories

Resources