Update static variable from another class - java

I have an activity on my app where a user can update their registered information stored in a remote database. When the update button is pressed the information in the database is being updated but the static variable is not changing. Here is my code thanks in advance for any help!
btUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String first_name = First_name.getText().toString();
final String last_name = Last_name.getText().toString();
final String email = Email.getText().toString();
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
LoginActivity.first_name = jsonResponse.getString("first_name");
LoginActivity.last_name = jsonResponse.getString("last_name");
LoginActivity.email_address = jsonResponse.getString("email");
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(UpdateInfoActivity.this);
builder.setMessage("Submission Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
UpdateInfoRequest updateInfoRequest = new UpdateInfoRequest(first_name, last_name, email, userID, responseListener);
RequestQueue queue = Volley.newRequestQueue(UpdateInfoActivity.this);
queue.add(updateInfoRequest);
Intent intent = new Intent(UpdateInfoActivity.this, MainActivity.class);
UpdateInfoActivity.this.startActivity(intent);
}
});

Change your code to this
if (success) {
LoginActivity.first_name = first_name;
LoginActivity.last_name = last_name;
LoginActivity.email_address = email;
}
and I wouldn't be using static variables like that if you want to have a global user profile you could do this
class User {
private static User user = null;
public String firstName = "";
private User() {}
public static synchronized User getInstance() {
if (user == null) user = new User();
return user;
}
}
to retrieve data from anywhere in project call this
String name = User.getInstance().firstName;
And to modify the data do this
User.getInstance().firstName = UserName;

First Understand that static variables are shared by all objects and methods of the class.
So we only have one instance of the static variable.
The ways to Update static variable from other class -
1.Through object.
2.Through Class name.
Enclosing the code sample.
class A{
static int val;
public A(){val=0; }
//....
}
class B{
A obj= new A();
public void updateStatic(){
obj.val=10; // updates values through object to 10
A.val=100; //updates values through class name to 100
}
//..
}
Hope it Helps

Transfer of data between activities using the static variable is not a better way in my opinion. It is bad practice. Transferring data using intents or save data in storage media and accessing from there will be the better solution.

but the static variable is not changing.
Should be... You told the code to do that
if (success) {
LoginActivity.first_name = jsonResponse.getString("first_name");
LoginActivity.last_name = jsonResponse.getString("last_name");
LoginActivity.email_address = jsonResponse.getString("email");
}
Just want to mention...
1) You update a String, not any TextView or EditText in your question, so if you expected to see a "visual change" in your app, then no, nothing will happen unless you call setText.
2) That code is wrapped in a try-catch, and could error, so check the logs for a JSONException. If those keys aren't sent back from the server, then sure, they won't update. For example, the JSON is only {"success": true }
Still, SharedPrefences should largely be preferred over static variables here.

Related

Realm invalid type

I tried to use Realm to make a wish list in my android app. I put data from adapter to SinglePost Activity and I try to put them in realm and display in another activity.
In SinglePost Activity I got this error!
Here is my Activity
public class SinglePost extends AppCompatActivity {
String id, image, url, content, video;
Realm realm;
public Adapter adapter;
ModelPost postInfo;
private String postId;
public static final String Key_Post = "ID";
...
id = getIntent().getStringExtra("ID");
postTitle.setText(getIntent().getStringExtra("Title"));
postExpert.setText(getIntent().getStringExtra("Expert"));
image = getIntent().getStringExtra("Image");
postId = getIntent().getStringExtra("ID");
realm = Realm.getDefaultInstance();
RealmResults<ModelPost> result = realm.where(ModelPost.class).equalTo(Key_Post, postId).findAll();
if (result.size() != 0) {
bookmark.setImageResource(R.drawable.ic_bookmark_black_24dp);
} else {
bookmark.setImageResource(R.drawable.ic_bookmark_border_black_24dp);
}
Bookmark();
}
private void Bookmark() {
bookmark.setOnClickListener(v -> realm.executeTransaction(realm -> {
RealmResults<ModelPost> results = realm.where(ModelPost.class).equalTo(Key_Post, id).findAll();
if (results.size() == 0) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
}
realm.copyToRealm(postInfo);
bookmark.setImageResource(R.drawable.ic_bookmark_black_24dp);
Toast.makeText(getApplicationContext(), "Added", Toast.LENGTH_SHORT).show();
} else {
results.get(0).deleteFromRealm();
bookmark.setImageResource(R.drawable.ic_bookmark_border_black_24dp);
Toast.makeText(getApplicationContext(), "Removed", Toast.LENGTH_SHORT).show();
}
}));
}
Model:
Model Class
Config:
public class G extends Application
{
#Override
public void onCreate()
{
super.onCreate();
Realm.init(getApplicationContext());
RealmConfiguration configuration = new RealmConfiguration.Builder()
.name(Realm.DEFAULT_REALM_NAME)
.schemaVersion(0)
.deleteRealmIfMigrationNeeded()
.build();
Realm.setDefaultConfiguration(configuration);
}
}
Error:
java.lang.IllegalArgumentException: Invalid query: field 'ID' in class 'ModelPost' is of invalid type 'INTEGER'.
You are retrieving the required ID from the activity intent extras, as a string. Your model type uses an integer for the ID field. This is why the types do not match and you are getting an error.
Incidentally, you are creating two variables (postId and Id) that appear to have identical uses - are you sure you need both? I would keep one of these, but make it an int field. The rest of this answer assumes you are keeping id.
Firstly, check that this is also how you are adding the value to the intent (i.e. that you are calling intent.putExtra() with a string argument and not an integer). If it is an integer, then you can use getIntExtra() above instead of getStringExtra(), and assign directly to id. If it is indeed a string, then you need to convert to an integer as below.
String idAsString = getIntent().getStringExtra("ID");
id = Integer.valueOf(idAsString).intValue();
Then all should be good.

How to reuse a method from a different class

I have an authenticateID method which searches in the database to find a match and does something. I guess it will take long to explain so here is my code:
public boolean authenticateStudentID() {
boolean success = true;
final String studentID = etStudentID.getText().toString().trim();
final String module = etModule.getText().toString().trim();
final String degree = etDegree.getText().toString().trim();
final String room = etRoom.getText().toString().trim();
final String email = etEmail.getText().toString().trim();
final String fullname = etfullname.getText().toString().trim();
final String loginID = etLoginID.getText().toString().trim();
if (success) {
databaseRef.addListenerForSingleValueEvent(new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) { // wtf is this advanecd for loop
//map string string because our key is a string and value is a string, map has a key and value object
Map<String, String> map = (Map) snapshot.getValue();
if (map != null) { //if the values and keys are not null
String studentIDMatch = map.get("studentID");
// Log.v("E_VALUE", "students ID entered : " + studentIDMatch);
// Log.v("E_VALUE", "students ID from db: " + studentID);
if (studentID.equals(studentIDMatch)) {
String uniqueKey = databaseRef.push().getKey();
NewStudentAccounts sam = new NewStudentAccounts
(studentID, loginID, email, fullname, module, degree, room);
databaseRef.child(uniqueKey).setValue(sam);
Toast.makeText(getApplicationContext(), "Your account registration has been successful!", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), LoginActivity.class));
} else {
Toast.makeText(getApplicationContext(), "Invalid Student Credentials Entered!!", Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
return success;
I want to know how I can reuse this method for another class instead of copy and pasting code. Please guide me, I really appreciate it.
private void addNewStudent() {
findViewById(R.id.buttonAddStudent).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
View addStudentActivityDialog = LayoutInflater.from(LecturerAccount.this).inflate(R.layout.activity_add_student,null);
etStudentName = addStudentActivityDialog.findViewById(R.id.editTextStudentName);
etStudentUserID = addStudentActivityDialog.findViewById(R.id.editTextStudentUserID);
AlertDialog.Builder addStudentBuilder = new AlertDialog.Builder(LecturerAccount.this);
addStudentBuilder.setMessage("STAR").setView(addStudentActivityDialog).setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String studentName = etStudentName.getText().toString();
String studentID = etStudentUserID.getText().toString();
registerActivity = new RegisterActivity(); //calling the instance of the class here
if (registerActivity.authenticateStudentID() == true){
studentarray.add(studentName);
}
}
}).setNegativeButton("cancel", null).setCancelable(false);
AlertDialog newStudentDialog = addStudentBuilder.create();
newStudentDialog.show();
}
});
}
My if statement here calling the function, I am totally clueless here.
Since onDataChange(DataSnapshot dataSnapshot) is an asynchronous callback event from firebase you must implement your own callback method to get notified of the result.
One approach would be to use interfaces.
create a separate class Auth
public class Auth {
public static void authenticateStudentID(final String studentID, final AuthListener listener) {
DatabaseReference databaseRef = FirebaseDatabase.getInstance().getReference("your reference");
databaseRef.addListenerForSingleValueEvent(new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) { // wtf is this advanecd for loop
//map string string because our key is a string and value is a string, map has a key and value object
Map<String, String> map = (Map) snapshot.getValue();
if (map != null) { //if the values and keys are not null
String studentIDMatch = map.get("studentID");
if (studentID.equals(studentIDMatch)) {
if (listener != null)
listener.onAuthSuccess();
} else {
if (listener != null)
listener.onAuthFailure();
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
if (listener != null)
listener.onAuthFailure();
}
});
}
public interface AuthListener {
void onAuthSuccess();
void onAuthFailure();
}
}
And then call it by
Auth.authenticateStudentID(studentId, new Auth.AuthListener() {
#Override
public void onAuthSuccess() {
}
#Override
public void onAuthFailure() {
}
});
wherever required
As the method you want to reuse should be "public" first of all. It simply means that it can be publically accessed among other classes of that project. And after making it public you can simply refer it using the class name.
Here is an example of this :
Class2 instance = new Class2();
instance.publicMehtodToBeAcessedInThisClass(any parameters);
But in your case, you will have to copy and paste the code to another class file only.
Reason: Because you are fetching data from the layout file of your Java file and this will crash the app. Either you should further modularize your code and handle this by making a separate function for fetching all this data. Otherwise, copy pasting only a method from one class to another will not make your application run into any performance issue or lags.
Access modifier is incorrect. Good old java doc will explain better than me:
access modifiers
In order to access it, you have to create an instance like so:
YourClass yourClass = new YourClass();
yourCLass.authenticateStudentID();
The YourClass is usually the name of the file where this code you pasted located in.
From what you've shown, there are two issues you need to deal with:
As noted, having it private doesn't do you much good when it comes to reuse.
It looks like the databaseRef object is a class property. So you'll need to pass this in, rather than rely on the class property for that class, since you want to use it from another class. (Or you can put this method, and the databaseRef property, in a superclass and have your two classes inherit from it.)
In general - think about what your method needs to do, and then what it needs to do that. Those should shape how you make the method more usable from other parts of your code.

Realm findFirst() method returns null

I searched and found FindFirst returns null question but no one answered it. As I'm thinking I am doing something wrong, let me explain my problem with more details.
I'm working on an app that asks the user to sign in first and then lets the user use the app.
My User class looks like this:
public class User extends RealmObject {
#PrimaryKey
#SerializedName("uid")
String id;
#SerializedName("ufname")
String firstName;
#SerializedName("ulname")
String lastName;
String avatar;
int sessions;
int invites;
String nextSessionTime;
String nextSessionTitle;
#SerializedName("lastlogin")
String lastLogin;
String token;
#Override
public String toString() {
return new GsonBuilder().create().toJson(this, User.class);
}
// other setters and getters
}
I store User's object in Realm db after successful login in SigninActivity class:
#Override
public void onSignInResponse(final GeneralResponse response) {
if (response == null) {
Timber.e("response is null");
return;
}
Timber.d(response.toString());
if (response.isSuccess()) {
// Store user's info including Token
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
realm.copyToRealmOrUpdate(response.getUser());
}
});
// Goto main screen
MainVideoActivity.startActivity(this);
this.finish();
} else {
String errorMessage = response.getErrorMessages();
super.displayMessage(errorMessage);
}
}
Once the login is successful, app directs user to MainVideoActivity. I want to find user in realm by following code however I'm getting null.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_video);
// Create the Realm instance
realm = Realm.getDefaultInstance();
User user = realm.where(User.class).findFirst();
// RealmResults<User> user = realm.where(User.class).findAll();
Timber.d(user.toString());
}
user is null in both approaches.
However, I can see my none null user in db.
I'm using classpath "io.realm:realm-gradle-plugin:2.0.2"
There are two things here:
The null values in the debug window. That is a known limitation when using Realm with debugger. Since Realm generated a Proxy class to access values, inspecting the RealmObject's field in the debugger won't go through the proxy class. See more details here
The fields with null values are not printed in the toString() method. Realm annotation processor will generate a toString() method if there is no toString() method defined in the RealmObject. I think the problem here is the a User.toString() ignores null values. Try to remove the toString() method in the User class.
According Realm doc Realm you can try add isNotNull() in your query like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_video);
// Create the Realm instance
realm = Realm.getDefaultInstance();
User user = realm.where(User.class).isNotNull("id").findFirst(); //add in this line isNotNull()
//RealmResults<User> user = realm.where(User.class).findAll();
Timber.d(user.toString());
}
I have not tested yet, but it should work.
Try replacing
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
realm.copyToRealmOrUpdate(response.getUser());
}
});
// Goto main screen
MainVideoActivity.startActivity(this);
this.finish();
with
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
realm.copyToRealmOrUpdate(response.getUser());
}
}, new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
// Goto main screen
MainVideoActivity.startActivity(this);
finish();
}
});
One way to workaround this is to create an unmanaged copy of the object.
Replace:
User user = realm.where(User.class).findFirst();
with
User managed_user = realm.where(User.class).findFirst();
if(user!=null){
User unmanaged_user = realm.copyFromRealm(managed_user)
}
Return unmanaged_user.

Java, Storing JSON Array to class and calling it from other class

I am trying to pull data from class in another class and populate a JPanel with the data, but it is not working for some reason.
Here is the full restConnector class where I pull the JSON data.
As far as I know this works fine.
public class restConnector {
private static final Logger LOGGER = LoggerFactory.getLogger(restConnector.class);
private static final restConnector INSTANCE = new restConnector();
public static restConnector getInstance() {
return restConnector.INSTANCE;
}
private restConnector(){
}
private static String user = "ss";
private static String pwd = "ee
public static String encode(String user, String pwd) {
final String credentials = user+":"+pwd;
BASE64Encoder encoder = new sun.misc.BASE64Encoder();
return encoder.encode(credentials.getBytes());
}
//Open REST connection
public static void init() {
restConnector.LOGGER.info("Starting REST connection...");
try {
Client client = Client.create();
client.addFilter(new LoggingFilter(System.out));
WebResource webResource = client.resource("https://somewebpage.com/
String url = "activepersonal";
ClientResponse response = webResource
.path("api/alerts/")
.queryParam("filter", ""+url)
.header("Authorization", "Basic "+encode(user, pwd))
.header("x-api-version", "1")
.accept("Application/json")
.get(ClientResponse.class);
if (response.getStatus() != 200) {
}else{
restConnector.LOGGER.info("REST connection STARTED.");
}
String output = response.getEntity(String.class);
ObjectMapper mapper = new ObjectMapper();
mapper.setPropertyNamingStrategy(new MyNameStrategy());
try {
List<Alert> alert = mapper.readValue(output, new TypeReference<List<Alert>>(){});
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void close() {
}
}
However, when I try to pull the data in another class it gives me just null values from the system.out.print inside refreshData() method. Here is the code that is supposed to print the data
public class Application{
Alert alerts = new Alert();
public Application() {
refreshData();
}
private void initComponents() {
restConnector.init();
refreshData();
}
private void refreshData() {
System.out.println("appalertList: "+alerts.getComponentAt(0));
}
}
Here is my Alert class
#JsonIgnoreProperties(ignoreUnknown = true)
#JsonInclude(Include.NON_EMPTY)
public class Alert {
private int pasID;
private String status;
private boolean shared;
private String header;
private String desc;
public int getPasID() {
return pasID;
}
public void setPasID(int pasID) {
this.pasID = pasID;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public boolean isShared() {
return shared;
}
public void setShared(boolean shared) {
this.shared = shared;
}
public String getHeader() {
return header;
}
public void setHeader(String header) {
this.header = header;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("\n***** Alert Details *****\n");
sb.append("PasID="+getPasID()+"\n");
sb.append("Status="+getStatus()+"\n");
sb.append("Shared="+isShared()+"\n");
sb.append("Header="+getHeader()+"\n");
sb.append("Description="+getDesc()+"\n");
sb.append("*****************************");
return sb.toString();
}
public String getComponentAt(int i) {
return toString();
}
}
I'm kind a lost with this and been stuck here for a couple of days already so all help would be really appreciated. Thanks for the help in advance.
Edit: Formatted the code a bit and removed the NullPointerException as it was not happening anymore.
As stated in comments:
Me: In your first bit of code you have this try { List<Alert> alert.., but you do absolutely nothing with the newly declared alert List<Alert>. It this where the data is supposed to be coming from?
OP: I'm under the impression that that bit of code is the one that pushes the JSON Array to the Alert.class. Is there something I'm missing there?
Me: And what makes you think it does that? All it does is read the json, and the Alert.class argument is the class type argument, so the mapper know the results should be mapped to the Alert attributes when it creates the Alert objects. That's how doing List<Alert> is possible, because passing Alert.class decribes T in List<T>. The List<Alert> is what's returned from the reading, but you have to determine what to actually do with the list. And currently, you do absolutely nothing with it
You maybe want to change the class just a bit.
Now this is in no way a good design, just an example of how you can get it to work. I would take some time to sit and think about how you want the restConnector to be fully utilized
That being said, you can have a List<Alert> alerts; class member in the restConnector class. And have a getter for it
public class restConnector {
private List<Alert> alerts;
public List<Alert> getAlerts() {
return alerts;
}
...
}
Then when deserializing with the mapper, assign the value to private List<Alert> alerts. What you are doing is declaring a new locally scoped list. So instead of
try {
List<Alert> alert = mapper.readValue...
do this instead
try {
alerts = mapper.readValue
Now the class member is assigned a value. So in the Application class you can do something like
public class Application {
List<Alert> alerts;
restConnector connect;
public Application() {
initComponents();
}
private void initComponents() {
connector = restConnector.getInstance();
connector.init();
alerts = connector.getAlerts();
refreshData();
}
private void refreshData() {
StringBuilder sb = new StringBuilder();
for (Alert alert : alerts) {
sb.append(alert.toString()).append("\n");
}
System.out.println("appalertList: "+ sb.toString());
}
}
Now you have access to the Alerts in the list.
But let me reiterate: THIS IS A HORRIBLE DESIGN. For one you are limiting the init method to one single call, in which it is only able to obtain one and only one resource. What if the rest service needs to access a different resource? You have made the request set in stone, so you cant.
Take some time to think of some good OOP designs where the class can be used for different scenarios.

How do you share variables with other activities easily? [duplicate]

This question already has answers here:
How do I pass data between Activities in Android application?
(53 answers)
Closed 3 months ago.
I am making a card game and I have an activity for discarding cards and an activity for showing the scores. The problem is I want to pass some objects (player and dealer hands) to the other activity so that I can set imageViews in the scores to the cards that are in the players hands. How can I do this? I don't care about security or anything I just want the easiest way.
Using bundles inside the intent isn't about security, it's because the Android guys made it that way plain and simple. In my opinion using bundles and intents to pass larger objects is not a good idea. it gets too complicated to implement, makes you get the object down to the primitives (when using parcelable) and also makes a copy on the other side in memory (you take one object, set everything inside the intent and then re-create it on the other side making a new copy out of it) which for objects that have a bigger memory footprint isn't good.
I would suggest:
either using a singleton store
Using the application class (which also acts like a singleton)
I am often using a singleton which has a hashMap inside where an integer key is generated by me (from atomic Integer) and an object placed inside the map. You just send the ID inside the intent as an extra and retrieve it on the other side by getting the key from the intent and accessing your singleton to retrieve and remove the object (from that map) and use it in your new activity/service.
Here is a sample of something like this:
(Note: this is a part from my lib for rest requests (https://github.com/darko1002001/android-rest-client) in case you want to see more details on how everything is implemented). in your case you will need to strip some of the code and replace it with your own, but the general idea is the same.
/**
* #author Darko.Grozdanovski
*/
public class HttpRequestStore {
public static final String TAG = HttpRequestStore.class.getSimpleName();
public static final String KEY_ID = "id";
public static final String IS_SUCCESSFUL = "isSuccessful";
private static final HashMap<Integer, RequestWrapper> map = new HashMap<Integer, RequestWrapper>();
private final AtomicInteger counter = new AtomicInteger();
private static Class<?> executorServiceClass = HTTPRequestExecutorService.class;
private final Context context;
private static HttpRequestStore instance;
private HttpRequestStore(final Context context) {
this.context = context;
}
public static HttpRequestStore getInstance(final Context context) {
if (instance == null) {
instance = new HttpRequestStore(context.getApplicationContext());
}
return instance;
}
public static void init(final Class<?> executorServiceClass) {
HttpRequestStore.executorServiceClass = executorServiceClass;
}
public Integer addRequest(final RequestWrapper block) {
return addRequest(counter.incrementAndGet(), block);
}
public Integer addRequest(final Integer id, final RequestWrapper block) {
map.put(id, block);
return id;
}
public void removeBlock(final Integer id) {
map.remove(id);
}
public RequestWrapper getRequest(final Integer id) {
return map.remove(id);
}
public RequestWrapper getRequest(final Intent intent) {
final Bundle extras = intent.getExtras();
if (extras == null || extras.containsKey(KEY_ID) == false) {
throw new RuntimeException("Intent Must be Filled with ID of the block");
}
final int id = extras.getInt(KEY_ID);
return getRequest(id);
}
public Integer launchServiceIntent(final HttpRequest block) {
return launchServiceIntent(block, null);
}
public Integer launchServiceIntent(final HttpRequest block, RequestOptions options) {
if (executorServiceClass == null) {
throw new RuntimeException("Initialize the Executor service class in a class extending application");
}
if (isServiceAvailable() == false) {
throw new RuntimeException("Declare the " + executorServiceClass.getSimpleName() + " in your manifest");
}
final Intent service = new Intent(context, executorServiceClass);
final RequestWrapper wrapper = new RequestWrapper(block, options);
final Integer requestId = addRequest(wrapper);
service.putExtra(KEY_ID, requestId);
context.startService(service);
return requestId;
}
public boolean isServiceAvailable() {
final PackageManager packageManager = context.getPackageManager();
final Intent intent = new Intent(context, executorServiceClass);
final List<ResolveInfo> resolveInfo = packageManager.queryIntentServices(intent,
PackageManager.MATCH_DEFAULT_ONLY);
if (resolveInfo.size() > 0) {
return true;
}
return false;
}
}
You can use Bundle to share variables in other activities. If you want to pass your own class object in other activities use Parcelable to your class
Here's an example
public class Person implements Parcelable {
private int age;
private String name;
// Setters and Getters
// ....
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeString(name);
out.writeInt(age);
}
public static final Parcelable.Creator<Person> CREATOR
= new Parcelable.Creator<Person>() {
public Person createFromParcel(Parcel in) {
return new Person(in);
}
public Person[] newArray(int size) {
return new Person[size];
}
};
private Person(Parcel in) {
name = in.readString();
age = in.readInt();
}
}
Insert your Person object in bundle
Intent i = new Intent();
Bundle b = new Bundle();
b.putParcelable("bob", new Person());
Getting Person object
Intent i = getIntent();
Bundle b = i.getExtras();
Person p = (Person) b.getParcelable("bob");
You can use either of Bundles or shared preferences for share variable or save variables for future use.
Example for shared preferences you can find here
Example for bundles you can find here
Singleton will be the best approach
You can use intent extras,
Intent intent = new Intent(getBaseContext(), NewActivity.class);
intent.putExtra("DATA_KEY", data);
startActivity(intent)
The docs for Intents has more information (look at the section titled "Extras").

Categories

Resources