I am new in Android, I have an ArrayList that hobbies of users. I want to store these values into my User class but I don't know how to store.
My intent values:
comp_phoneNumber = getIntent().getStringExtra("userPhone");
user_FirstName = getIntent().getStringExtra("user_FirstName");
user_Gender = getIntent().getStringExtra("user_Gender");
user_Birthdate = getIntent().getStringExtra("user_Birthdate");
My Getter-Setter class:
public class UserHelperClass {
String comp_phoneNumber, user_FirstName, user_Gender, user_Birthdate;
UserHelperClass() {
}
public UserHelperClass(String comp_phoneNumber, String user_FirstName, String user_Gender, String user_Birthdate) {
this.comp_phoneNumber = comp_phoneNumber;
this.user_FirstName = user_FirstName;
this.user_Gender = user_Gender;
this.user_Birthdate = user_Birthdate;
}
public String getComp_phoneNumber() {
return comp_phoneNumber;
}
public void setComp_phoneNumber(String comp_phoneNumber) {
this.comp_phoneNumber = comp_phoneNumber;
}
public String getUser_FirstName() {
return user_FirstName;
}
public void setUser_FirstName(String user_FirstName) {
this.user_FirstName = user_FirstName;
}
public String getUser_Gender() {
return user_Gender;
}
public void setUser_Gender(String user_Gender) {
this.user_Gender = user_Gender;
}
public String getUser_Birthdate() {
return user_Birthdate;
}
public void setUser_Birthdate(String user_Birthdate) {
this.user_Birthdate = user_Birthdate;
}
}
In my Last_Activity, I store these intent values with this code.
public void storeNewUserData() {
rootNode = FirebaseDatabase.getInstance();
reference = rootNode.getReference("Users");
UserHelperClass addNewUser = new UserHelperClass(comp_phoneNumber, user_FirstName, user_Gender, user_Birthdate);
reference.child(comp_phoneNumber).setValue(addNewUser);
}
I want to store my Hobby String Arraylist values with these values. How can I store?
You can simply use a HashMap to store the values as soon as you get them without needing to store them in a class first or going to another activity. Unless that is necessary
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users");
HashMap<String, Object> userMap = new HashMap<>();
userMap. put("comp_phoneNumber", addNewUser.getComp_phoneNumber());
userMap. put("2nd field", value);
userMap. put("3rd field", value);
userMap. put("4th field", value);
ref.child(comp_phoneNumber).updateChildren(userMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(getActivity(), "User added successfully", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getContext(), "Network Error", Toast.LENGTH_SHORT).show();
}
}
});
Like this you should be able to add the details. Although I am confused as to what was that you wanted to say about Hobbies?
Related
here my module
public class SPSOnHand {
#SerializedName("ITEM_CODE")
#Expose
private String ITEM_CODE;
#SerializedName("ITEM_DESCRIPTION")
#Expose
private String ITEM_DESCRIPTION;
public String getITEM_CODE() {
return ITEM_CODE;
}
public void setITEM_CODE(String item_code) {
ITEM_CODE = item_code;
}
public String getITEM_DESCRIPTION() {
return ITEM_DESCRIPTION;
}
public void setITEM_DESCRIPTION(String item_description) {
ITEM_DESCRIPTION = item_description;
}
here my rest service class
public class RestService {
private static final String URL = "http://localhost:58364/";
private retrofit.RestAdapter restAdapter;
//private InstituteService apiService;
private SPInventoryService apiService;
public RestService()
{
restAdapter = new retrofit.RestAdapter.Builder()
.setEndpoint(URL)
.setLogLevel(retrofit.RestAdapter.LogLevel.FULL)
.build();
apiService = restAdapter.create(SPInventoryService.class);
}
public SPInventoryService getService()
{
return apiService;
}
here my service
#GET("/api/SPSOnHand/itemcode/{item_code}")
public void getItemCode(#Path("item_code") String itemcode,
Callback<ArrayList<SPSOnHand>>callback);
here my main activity class
String itemcode;
Intent intent = getIntent();
itemcode =intent.getStringExtra("itemcode");
restService.getService().getItemCode(itemcode, new Callback<ArrayList<SPSOnHand>>() {
#Override
public void success(ArrayList<SPSOnHand> spsOnHands, Response response) {
item_description.setText(String.valueOf(spsOnHands.get(0)));
}
#Override
public void failure(RetrofitError error) {
Toast.makeText(AirJet.this, error.getMessage().toString(),
Toast.LENGTH_LONG).show();
}
});
I want that item_description to contain a word like this
"ID": 167,
"ITEM_CODE": "3020240002",
"ITEM_DESCRIPTION": "CONTROLLER LME22.331c2 (CONTROL BOX)"
thanks in advance, I'm still a newbie in retrofit
Because of String.valueOf(spsOnHands.get(0)) whole item of list converted to String so that's why you are getting wrong format of text.
Use below code for set text in textview:
int id = 0+1;
String itemCode = arrayList.get(0).getITEM_CODE();
String itemDescription = arrayList.get(0).getITEM_CODE();
item_description.setText("\"ID\":"+ id+" \n\"ITEM_CODE\":" + itemCode+" \n\"ITEM_DESCRIPTION\":"+itemDescription);
You can change format of text in textview according to your requirement.
In your case, you receive ArrayList. And if you want to get the item from List then you have to pass index and get value List, like below. It will give you ITEM_DESCRIPTION for the 0th index of your List.
restService.getService().getItemCode(itemcode, new Callback<ArrayList<SPSOnHand>>() {
#Override
public void success(ArrayList<SPSOnHand> spsOnHands, Response response) {
item_description.setText(String.valueOf(spsOnHands.get(0).ITEM_DESCRIPTION));
}
#Override
public void failure(RetrofitError error) {
Toast.makeText(AirJet.this, error.getMessage().toString(),
Toast.LENGTH_LONG).show();
}
});
I am developing an android app (java), I am using Firebase, for each registered user I have a token of the device, how can I send a notification to a specific user using his token ?
For sending a notification to users the only thing required is that user's token. You can send notification using FCM.
Here, I'm sharing my FCM class which can be used for this purpose. It is using Okhttp3 requests, so make sure you add its dependency.
implementation 'com.squareup.okhttp3:okhttp:5.0.0-alpha.2'
After adding this dependency, all you have to do is to use this FCM class.
FCMMessages.java
public class FCMMessages {
private Context context;
public void sendMessageSingle(Context context, final String recipient, final String title, final String body, final Map<String, String> dataMap)
{
this.context = context;
Map<String, Object> notificationMap = new HashMap<>();
notificationMap.put("body", body);
notificationMap.put("title", title);
Map<String, Object> rootMap = new HashMap<>();
rootMap.put("notification", notificationMap);
rootMap.put("to", recipient);
if (dataMap != null)
rootMap.put("data", dataMap);
new SendFCM().setFcm(rootMap).execute();
}
public void sendMessageMulti(Context context, final JSONArray recipients, final String title, final String body, final Map<String, String> dataMap) {
this.context = context;
Map<String, Object> notificationMap = new HashMap<>();
notificationMap.put("body", body);
notificationMap.put("title", title);
Map<String, Object> rootMap = new HashMap<>();
rootMap.put("notification", notificationMap);
rootMap.put("registration_ids", recipients);
if (dataMap != null)
rootMap.put("data", dataMap);
new SendFCM().setFcm(rootMap).execute();
}
#SuppressLint("StaticFieldLeak")
class SendFCM extends AsyncTask<String, String, String> {
private String FCM_MESSAGE_URL = "https://fcm.googleapis.com/fcm/send";
private Map<String, Object> fcm;
SendFCM setFcm(Map<String, Object> fcm) {
this.fcm = fcm;
return this;
}
#Override
protected String doInBackground(String... strings) {
try {
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(JSON, new JSONObject(fcm).toString());
Request request = new Request.Builder()
.url(FCM_MESSAGE_URL)
.post(body)
.addHeader("Authorization","key=" + StaticConfig.myMessagingAuth)
.build();
Response response = new OkHttpClient().newCall(request).execute();
return response.body().string();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(String result) {
try {
JSONObject resultJson = new JSONObject(result);
int success, failure;
success = resultJson.getInt("success");
failure = resultJson.getInt("failure");
//Toast.makeText(context, "Sent: " + success + "/" + (success + failure), Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
// Toast.makeText(context, "Message Failed, Unknown error occurred.", Toast.LENGTH_LONG).show();
}
}
}
}
Make sure you get the messagingAuth from your firebase project settings. To get the messagingAuth token, follow these steps:
Open Firebase Project > Project Settings > Cloud Messaging > Server key
Copy the value of server key and paste it as messagingAuth in your android project.
To send a notification to single user token use sendMessageSingle method. It would be like
String user_token = "wiubd92uhe91dik-q";
String notification_title = "This is notification title";
String notification_des = "This is notification description";
new FCMMessages().sendMessageSingle(MainActivity.this, user_token, notification_title, notification_des, null);
To send a notification to multiple user tokens use sendMessageMulti method. It would be like
ArrayList<String> user_tokens = new ArrayList<>();
user_tokens.add(token_1);
user_tokens.add(token_2);
user_tokens.add(token_3);
String notification_title = "This is notification title";
String notification_des = "This is notification description";
new FCMMessages().sendMessageMulti(MainActivity.this, new JSONArray(user_tokens), notification_title, notification_des, null);
Use this YouTube link here EDMT Dev has implemented the following in his Eat it new series. And kindly mark this as the correct answer if this helps you.
Add the below dependency
`implementation 'io.reactivex.rxjava2:rxandroid:2.1.1`'
Now Create these classes :
Token Model This Model is used to retrieve token data( Token , Phone ). I have also a variable for the phone because I made this class according to my datastructure . Kindly modify the code according to your need
public class TokenModel {
private String phone,token;
public TokenModel() {
}
public TokenModel(String phone, String token) {
this.phone = phone;
this.token = token;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}}
FCM Send Data Model
public class FCMSendData {
private String to;
private Map<String,String> data;
public FCMSendData(String to, Map<String, String> data) {
this.to = to;
this.data = data;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public Map<String, String> getData() {
return data;
}
public void setData(Map<String, String> data) {
this.data = data;
}}
Create FCM Result Model
class FCMResult {
private String message_id;
public FCMResult() {
}
public String getMessage_id() {
return message_id;
}
public void setMessage_id(String message_id) {
this.message_id = message_id;
}}
Create RetrofitFCMClient
public class RetrofitFCMClient {
private static Retrofit instance;
public static Retrofit getInstance()
{
if(instance==null)
{
instance = new Retrofit.Builder().baseUrl("https://fcm.googleapis.com/")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
return instance;
}
return instance;
}}
Now we need to implement an interface
//Authorization key is server key of Cloud Messaging
public interface IFCMService {
#Headers({
"Content-Type:application/json",
"Authorization:key=**YOUR_AUTHORIZATION KEY HERE**"
})
#POST("fcm/send")
Observable<FCMResponse> sendNotification(#Body FCMSendData body);}
Now We are ready to use the firebase messaging just need to put data and use our retrofit to push it
TokenModel tokenModel = dataSnapshot.getValue(TokenModel.class);
//("FCM",tokenModel.getToken());
Map<String, String> notiData = new
HashMap<>();
notiData.put(Common.NOTI_TITLE, "YOUR NOTIFICATION TITLE");
notiData.put(Common.NOTI_CONTENT,"YOUR_NOTFICATION CONTENT );
FCMSendData sendData = new FCMSendData(tokenModel.getToken(),
notiData);
compositeDisposable
.add(ifcmService.sendNotification(sendData)
.subscribeOn(Schedulers.io()).
observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<FCMResponse>() {
#Override
public void accept(FCMResponse
fcmResponse)
throws Exception {
if (fcmResponse.getSuccess()
== 1) {
Toast.makeText(getContext(),
"Success", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getContext(), "Failed
to Notify", Toast.LENGTH_LONG).show();
}
}
}, new Consumer<Throwable>() {
#Override
public void accept(Throwable
throwable) throws Exception {
Toast.makeText(getContext(),
throwable.getMessage(), Toast.LENGTH_LONG).show();
}
}));
Use this YouTube link here EDMT Dev has implemented the following in his Eat it new series
I actually took the data and printed it with print.But when I add to the list, it gives null object exception.How can I solve the problem?I'm getting an error because I'm creating an empty object.I don't understand why.,What should I do for the solution?
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()){
Mac mac = new Mac();
mac.setMackodu(ds.getValue(Mac.class).getMackodu());
mac.setTakimlar(ds.getValue(Mac.class).getTakimlar());
mac.setTahmin(ds.getValue(Mac.class).getTahmin());
System.out.println("macss " + mac.getMackodu());
System.out.println("macss " + mac.getTakimlar());
System.out.println("macss " + mac.getTahmin());
macList.add(mac);
}
myRecyclerAdapter = new MyRecyclerAdapter(getContext(),macList);
recyclerView.setAdapter(myRecyclerAdapter);
myRecyclerAdapter.notifyDataSetChanged();
}
public class Mac{
private String macKodu;
private String takimlar;
private String tahmin;
public Mac() {
}
public Mac(String macKodu, String takimlar, String tahmin) {
this.macKodu = macKodu;
this.takimlar = takimlar;
this.tahmin = tahmin;
}
public String getMacKodu() {
return macKodu;
}
public void setMacKodu(String macKodu) {
this.macKodu = macKodu;
}
public String getTakimlar() {
return takimlar;
}
public void setTakimlar(String takimlar) {
this.takimlar = takimlar;
}
public String getTahmin() {
return tahmin;
}
public void setTahmin(String tahmin) {
this.tahmin = tahmin;
}
Put this two lines
myRecyclerAdapter = new MyRecyclerAdapter(getContext(),macList);
recyclerView.setAdapter(myRecyclerAdapter);
out of
myRef.addValueEventListener
I have a method for get a List of users by its uid:
public void getNeededUsers(List<String> uidList, UsersListCallback usersListCallback) {
CollectionReference users = db.collection(Consts.USERS_DB);
for (String uid: uidList) {
users.whereEqualTo(Consts.UID, uid).get()
.addOnCompleteListener(task -> {
List<FsUser> fsUserList = new ArrayList<>();
for (DocumentSnapshot snapshot : task.getResult().getDocuments()) {
fsUserList.add(snapshot.toObject(FsUser.class));
}
usersListCallback.getUsers(fsUserList);
});
}
}
But it seems that this method doesn`t work properly. When I try to iterate through the List of users in another method, I receive users one by one from callback, instead of getting all, so they are duplicated in my list.
Here is a code of another method:
public void createUserChats(UserChatListCallback userChatListCallback) {
final List<UserChat> userChatList = new ArrayList<>();
getChatAndUidList((chatList, uidList) -> {
getRtUsersAndMessages(uidList, (rtUserList, messageList) -> {
getNeededUsers(uidList, userList -> {
if (!userList.isEmpty()) {
for (int i = 0; i < userList.size(); i++) {
String name = userList.get(i).getName();
String image = userList.get(i).getImage();
String userId = userList.get(i).getUid();
long timeStamp = chatList.get(i).getTimeStamp();
boolean seen = chatList.get(i).getSeen();
String online = rtUserList.get(i).getOnline();
String message = messageList.get(i).getMessage();
long messageTimestamp = messageList.get(i).getTime();
userChatList.add(new UserChat(name, image, timeStamp, seen, userId, online,
message, messageTimestamp));
}
}
userChatListCallback.getUserChatList(userChatList);
});
});
});
}
To get a list of users, please use the following code:
List<Task<DocumentSnapshot>> tasks = new ArrayList<>();
for (String uid: uidList) {
Task<DocumentSnapshot> documentSnapshotTask = users.whereEqualTo(Consts.UID, uid).get();
tasks.add(documentSnapshotTas);
}
Tasks.whenAllSuccess(tasks).addOnSuccessListener(new OnSuccessListener<List<Object>>() {
#Override
public void onSuccess(List<Object> list) {
//Do what you need to do with your users list
for (Object object : list) {
FsUser fsUser = ((DocumentSnapshot) object).toObject(TeacherPojo.class);
Log.d("TAG", fsUser.getName());
}
}
});
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Iam trying to make login activity
I got a problem. My setter doesnt work, i dont know why?
I have 3 classes.
1st one is Data with server data and getters and setters
public class Data{
String addressesURL = "/DataSnap/rest/TServerMethods1/LookupCustomers";
String articlesURL = "/DataSnap/rest/TServerMethods1/LookupArticle";
String invoicesURL = "/DataSnap/rest/TServerMethods1/LookupInvoice";
String invoicesDetailsURL = "/DataSnap/rest/TServerMethods1/LookupInvoicePos";
String invoicesDetailsAddressesURL = "/DataSnap/rest/TServerMethods1/LookupInvoiceAddress";
String ordersURL = "/DataSnap/rest/TServerMethods1/LookupOrders";
String ordersDetailsURL = "/DataSnap/rest/TServerMethods1/LookupOrdersPos";
String ordersDetailsAddressesURL = "/DataSnap/rest/TServerMethods1/LookupOrdersAddress";
public String serverURL;
//String serverURL = "http://10.10.10.75:8081";
String username = "admin";
String password = "admin";
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAddressesURL() {
return addressesURL;
}
public void setAddressesURL(String addressesURL) {
this.addressesURL = addressesURL;
}
public String getArticlesURL() {
return articlesURL;
}
public void setArticlesURL(String articlesURL) {
this.articlesURL = articlesURL;
}
public String getInvoicesURL() {
return invoicesURL;
}
public void setInvoicesURL(String invoicesURL) {
this.invoicesURL = invoicesURL;
}
public String getInvoicesDetailsURL() {
return invoicesDetailsURL;
}
public void setInvoicesDetailsURL(String invoicesDetailsURL) {
this.invoicesDetailsURL = invoicesDetailsURL;
}
public String getInvoicesDetailsAddressesURL() {
return invoicesDetailsAddressesURL;
}
public void setInvoicesDetailsAddressesURL(String invoicesDetailsAddressesURL) {
this.invoicesDetailsAddressesURL = invoicesDetailsAddressesURL;
}
public String getOrdersURL() {
return ordersURL;
}
public void setOrdersURL(String ordersURL) {
this.ordersURL = ordersURL;
}
public String getOrdersDetailsURL() {
return ordersDetailsURL;
}
public void setOrdersDetailsURL(String ordersDetailsURL) {
this.ordersDetailsURL = ordersDetailsURL;
}
public String getOrdersDetailsAddressesURL() {
return ordersDetailsAddressesURL;
}
public void setOrdersDetailsAddressesURL(String ordersDetailsAddressesURL) {
this.ordersDetailsAddressesURL = ordersDetailsAddressesURL;
}
public String getServerURL() {
return serverURL;
}
public void setServerURL(String serverURL) {
this.serverURL = serverURL;
}}
2nd one is where I start my login Activity
public class Settings extends AppCompatActivity {
//declarations
//Edittext fields for username , server, password & port information
EditText edtIpurl, edtPort, edtUsername, edtPassword;
//Textviews that can be clicked
TextView databaseDel, databaseRef, magnumgmbh, contact, support;
//imagebuttons for bottom menu
ImageButton contacts, articles, invoices, orders;
//string for server URL
//String sURL = "http://";
Thread newSettingsThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
setTitle("Settings");
newSettingsThread = new Thread(){
public void run(){
runOnUiThread(new Runnable() {
#Override
public void run() {
String serverURL = "http://rest.magnumgmbh.de";
//edtIpurl = (EditText)findViewById(R.id.edtIpurl);
Data newD = new Data();
newD.setServerURL(serverURL);
}
});
}
};
newSettingsThread.start();
//start activitys if bottom buttons clicked
contacts = (ImageButton) findViewById(R.id.contacts);
//articles activity start
contacts.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//start activity addresses
Intent startAddresses = new Intent(Settings.this, Addresses.class);
startActivity(startAddresses);
}
});
}}
And the next one is where i try to get my new serverURL
public class Address extends AppCompatActivity{
Thread newAddressThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addresses);
//set activity name
setTitle("Addresses");
//new thread for network operations
newAddressesThread = new Thread() {
public void run() {
//make text from json
jsonText = new StringBuilder();
try {
String str;
Data newData = new Data();
//json dates url
String addressesURL = newData.getAddressesURL();
String serverUrl = newData.getServerURL();
String username = newData.getUsername();
String password = newData.getPassword();
URL url = new URL(serverUrl + addressesURL);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//String encoded = Base64.encode("admin:admin");
String encoded = Base64.encodeToString((username+":"+password).getBytes("UTF-8"), Base64.NO_WRAP);
urlConnection.setRequestProperty("Authorization", "Basic " + encoded);
//check http status code
try {
int statusCode = urlConnection.getResponseCode();
System.out.println(statusCode);
} catch (IOException e) {
}
BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
while ((str = in.readLine()) != null) {
jsonText.append(str);
}
//cast stringbuilder to string
addressesJsonStr = jsonText.toString();
//close IOstream
in.close();
} catch (MalformedURLException e1) {
System.out.println(e1.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
};
//start thread
newAddressesThread.start();
}}
Hier in the third one by serverURL I got null and it thow me an exeption "Protocol not found: null/DataSnap/rest/TServerMethods1/LookupCustomers" so that is my problem.
What do I wrong?
you are creating a new Object in the third class, so the url has the initilize value because the url you've setted in the second class is stored in another object.
If you want that all Objects of Type Data have the same adress, make the variable static otherwise you have to access the object you have created in the second class in the third class.