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.
Related
I need to show a unit of measure from the product user selection and that when selecting it shows its price at the same time
Alert Dialog with data using floating btn
I don't know if it should be with the ViewModel or the repository in the second, because it must vary from the input of the first
I use the generic MVVM model pattern where I have my dao, entity (POJO) and ViewModel with Repo.
The other problem it's how show with Repository specific columns
I want to use specifics columns from my POJOS using method to string I created, not the toString override.
When this is ready I need this data inside the ActivityHost to check if is empty, don't send the data to the other fragments and the server.
In summary this is all the things:
the final display that I need
Please let me know if there is more data that I could provide.Thanks (I can't use Kotlin btw)
The result I want it's use the data to pass it to a RecycleView and then will go to my ActivityHost of fragmentProduct
This is part of the class:
Fragment Product
//initilization of variables,viewModels and Repos:
...
other functions
...
private void alertAddProducto() {
// build of the MaterialAlertDialog customView
final ArrayAdapter<Productos> dataAdapter = new ArrayAdapter<>(getActivity(),
R.layout.item_listado_layout, new ArrayList<>(0));
tiProducto.setAdapter(dataAdapter);
mProductosRepository.getAllProductosLiveData().observe(requireActivity(), items -> {
assert items != null;
Collections.sort(items, (obj1, obj2) -> obj1.getPRODUCTO_DESCRIPCION().compareToIgnoreCase(obj2.getPRODUCTO_DESCRIPCION()));
dataAdapter.addAll(items);
dataAdapter.notifyDataSetChanged();
});
//the other mRepo that I don't know if is necessary, (should be ViewModel)?
the second AutocompleteView needs the user input and then it should show other fields in my alert
like price ,quantity and subtotal (disabled)
}
ilustrative pictures
DAO
#Dao
public interface ProductosDao {
#Insert
void insert(Productos producto);
#Update
void update(Productos producto);
#Delete
void delete(Productos producto);
#Query("DELETE FROM productos_table")
void deleteAll();
#Query("SELECT * FROM productos_table ORDER BY PRODUCTO_ID DESC")
LiveData<List<Productos>> getAllProductosLiveData();
#Query("SELECT * FROM productos_table ")
LiveData<List<Productos>> getAllUnidadesMedida();
}
TABLE
#Entity(tableName = "productos_table")
public class Productos {
#PrimaryKey(autoGenerate = true)
private int AUTOGENERADO_ID;
private String PRODUCTO_DESCRIPCION;
...
public Productos(int AUTOGENERADO_ID,
...) {
this.AUTOGENERADO_ID = AUTOGENERADO_ID;
this.PRODUCTO_DESCRIPCION = PRODUCTO_DESCRIPCION;
}
...
#Override
public String toString() {
return PRODUCTO_ID + " " + PRODUCTO_DESCRIPCION;
}
public String getStringPRODUCTO_DESCRIPCION() {
return PRODUCTO_DESCRIPCION;
}
}
I want to use this methods not toString in AutocompleteView
ActivityHost
public class ActaHost extends DrawerBaseActivity{
//init variables
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityPacHostBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
FragmentManager fm = getSupportFragmentManager();
adapter = new ActaAdapter(fm, getLifecycle());
...
initViewPager2();
mSharedViewModel = new ViewModelProvider(this).get(ActaSharedViewModel.class);
observable(mSharedViewModel);
}
observable(SharedViewModel mSharedViewModel){
mProductoViewModel.getAllProductos().observe(this, Productos-> {
assert Productos!= null;
Collections.sort(Productos, (obj1, obj2) -> obj1.getProducto().compareToIgnoreCase(obj2.getProducto()));
for (int i = 0; i < Productos.size(); i++) {
ProductosList.add(Productos.get(i));
Log.i("ProductosList", Productos.get(i) + String.valueOf(ProductosList.get(i).getProducto()));
}
Log.i("ProductosList", ProductosList.toString());
});
}
}
Since I'm new to programming Android apps I followed a tutorial on how to use the Android Architecture Components and Firebase for implementing the MVVM (using LiveData, ViewModel, etc.).
The tutorial I followed can be found here:
Part 1
Part 2
Part 3
I'm now left with what I think is a decent implementation of the MVVM, but I can not wrap my head around how I am supposed to pass query parameters to it. Right now I need to hardcode the ID of the document I want to retrieve:
public class AlarmDAO {
private FirebaseFirestore firebaseFirestore = FirebaseFirestore.getInstance();
public AlarmLiveData getFirestoreLiveData() {
DocumentReference documentReference = firebaseFirestore.collection(Collection.ALARMS.name).document("5RxJNuNyhDJlz49wpBkw");
return new AlarmLiveData(documentReference);
}
}
That then gets called by a class extending ViewModel.
public class AlarmViewModel extends ViewModel {
private AlarmDAO DAO = new AlarmDAO();
private AlarmLiveData liveData = null;
public LiveData<Alarm> getAlarmLiveData() {
liveData = DAO.getFirestoreLiveData();
return liveData;
}
public LiveData<Alarm> getAlarm() {
return liveData.alarm;
}
}
And then I observe that data in my activity:
model.getAlarmLiveData().observe(this, Observable -> {});
model.getAlarm().observe(this, alarm -> {
if (alarm != null) {
alarmTextView.setText(alarm.getTest());
else {
Log.d(TAG, "Waiting for data");
}
});
My problem is that I do not see a way of querying for a specific alarm. For instance model.getAlarm("someId"). I am under the impression that it should be done in the DAO and/or the ViewModel, but I can't figure out how. Another thing I do not understand is why I need to observe both model.getAlarmLiveData() and model.getAlarm() in my activity, as using only one does not work. The answer to both of those questions is most likely very simple, but thus far I haven't been able to figure it out.
For completeness: the Alarm class is nothing besides a getter and setter for two strings, and the AlarmLiveData class is below.
public class AlarmLiveData extends LiveData<Alarm> implements EventListener<DocumentSnapshot> {
private static final String TAG = AlarmLiveData.class.getSimpleName();
private Alarm alarmTemp = new Alarm();
private DocumentReference documentReference;
private ListenerRegistration listenerRegistration = () -> {};
public MutableLiveData<Alarm> alarm = new MutableLiveData<>();
public AlarmLiveData(DocumentReference documentReference) {
this.documentReference = documentReference;
}
#Override
protected void onActive() {
listenerRegistration = documentReference.addSnapshotListener(this);
super.onActive();
}
#Override
protected void onInactive() {
listenerRegistration.remove();
super.onInactive();
}
#Override
public void onEvent(#Nullable DocumentSnapshot documentSnapshot, #Nullable FirebaseFirestoreException e) {
if (documentSnapshot != null && documentSnapshot.exists()) {
alarmTemp = new Alarm();
alarmTemp.setId(documentSnapshot.getId());
alarmTemp.setTest(documentSnapshot.get("test").toString());
alarm.setValue(alarmTemp);
} else {
Log.d(TAG, "ERROR");
}
}
}
Thank you for reading, I'm looking forward to the answer(s)!
The reason you have to use both model.getAlarmLiveData() and model.getAlarm() looks to be that your AlarmLiveData class extends LiveData but sets a value for the contained MutableLiveData member variable instead of setting its own class value.
Inside your AlarmLiveData class:
// Comment out/Remove your 'public MutableLiveData<alarm> alarm' member variable from the top.
// You're going to want to set the value of the AlarmLiveData class itself instead.
// ...
// Then inside of your onEvent callback
#Override
public void onEvent(#Nullable DocumentSnapshot documentSnapshot, #Nullable FirebaseFirestoreException e) {
if (documentSnapshot != null && documentSnapshot.exists()) {
alarmTemp = new Alarm();
alarmTemp.setId(documentSnapshot.getId());
alarmTemp.setTest(documentSnapshot.get("test").toString());
// Set the value for the AlarmLiveData class directly
setValue(alarmTemp);
} else {
Log.d(TAG, "ERROR");
}
}
I'm not sure why you're creating a DAO class and I would most likely move that code directly into the AlarmViewModel class.
But, here is how you can alter your current DAO class if you don't want to remove it:
// Pass in the document id you want to create a document reference for
public AlarmLiveData getFirestoreLiveData(String documentId) {
DocumentReference documentReference = firebaseFirestore.collection(Collection.ALARMS.name).document(documentId);
return new AlarmLiveData(documentReference);
}
Your AlarmViewModel class would look something like this:
public class AlarmViewModel extends ViewModel {
private AlarmDAO DAO = new AlarmDAO();
private AlarmLiveData liveData = null;
// Make sure to take in the document id so you can create the corresponding LiveData
public LiveData<Alarm> getAlarmLiveData(String documentId) {
// Only create a new LiveData instance if the current one is null.
// This is helpful if you intend to use this as a Shared ViewModel.
if(liveData == null){
liveData = DAO.getFirestoreLiveData(documentId);
}
return liveData;
}
}
Finally, in your Activity:
// Pass in the document id and observe the ViewModel
model.getAlarmLiveData("MY_DOCUMENT_ID").observe(this, alarm -> {
if (alarm != null) {
alarmTextView.setText(alarm.getTest());
}else{
Log.d(TAG, "Waiting for data");
}
});
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.
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.
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").