Android Parse how can I use getObjectId(); when setting a ParseUser object? - java

I have a user search and a listview to populate with the results. The results have an "Add Friend" button.
This is what I have for the onClick:
OnClickListener addRequest = new OnClickListener() {
#Override
public void onClick(View v) {
userConnection = new UserConnection();
userConnection.setCurrentUser(User.getCurrentUser());
userConnection.setOtherUser(users.get(position).getObjectId()); ////HELP, this is where I need to get the objectId for the user and set it as OtherUser
userConnection.setFriendRequestStatus(appConstants.FRIENDREQUESTSTATUS.PENDING);
userConnection.setCurrentUserSentRequest(true);
Utils.showOKdialog(context, "Press OK to send friend request");
userConnection.saveInBackground();
Log.d(TAG, "You have sent a friend request to " + userConnection.getOtherUser().getLastName() + " " + userConnection.getOtherUser().getFirstName());
}
};
I have a comment on which line I need help with, the problem I am having is .getObjectId returns a String and .setOtheruser calls for a ParseUser. Any ideas on how to get the objectId which is a String on the user that is at the position of the list view clicked?
I also tried this but it came back with a null reference for .getParseUser("objectId")
userConnection.setOtherUser(users.get(position).getParseUser("objectId"));

Well I figured it out, I was making things too complicated as usual. The solution is just
userConnection.setOtherUser(users.get(position));

Related

Get selected text in webview to highlight it in java

I'd like to allow users to highlight in yellow text in my webview.
So I wanna use some javascript to allow my app to get the selected text:
mWebview.evaluateJavascript("(function(){return window.getSelection().toString()})()",
new ValueCallback<String>()
{
#Override
public void onReceiveValue(String value)
{
Log.v(TAG, "Webview selected text: " + value);
}
});
Ok, this will get the selected text in the webview. Now I need to save this texts in sharedpreferences to remember it next time user open the app, then find all the texts saved to highlight. Any ideas how to do this?

Android studio updated and code too large now

I have a system that has been produced for 2 years now. It is an EMM system for controlling corporate devices.
It uses FireBase to send the functionality executed on the device from the server app to the device.
There are around 400 possible commands you can send to a device and all these commands are handled in one class initially, which overrides the onMessageReceived() from the FireBaseMessagingService class.
The older version of Android studio built the apk which is now in production. I have started to work on version 2 of my system after about a year off. so I updated my Android studio to the latest (4).
The Problem:
when I try to build the project and push onto a device, I get
error: code too large public void onMessageReceived(RemoteMessage remoteMessage) {
As stated before this onMessageReceived method can handle 400 different types of push notifications from the server app, so there are a lot of if/else statements in the method body.
Is there any reason why since the AS upgrade this will not work?
is there any setting I can change in AS to get past this?
What I have tried:
I thought about putting half of the if/else in another service class, to cut down on the method code. This would involve passing the remoteMessageMap to another class to carry on with the if/else processing.
remoteMessageMap from FireBase is a Map and Maps are not serializable as they extend the interface, so can't pass it.
public class MyAndroidFirebaseMsgService extends FirebaseMessagingService {
private static final String TAG = "MyAndroidFCMService";
AppObj appObj;
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.e(TAG, "remoteMessage.getData() = " + remoteMessage.getData());
Map remoteMessageMap = remoteMessage.getData();
String message = (String)remoteMessageMap.get("message");
thanks
[edit1]
else if(message.trim().equalsIgnoreCase("CLEARCACHE_REMOVE_APP_WL")){
Log.e(TAG, "received CLEARCACHE_REMOVE_APP_WL");
String pushGuid = (String)remoteMessageMap.get("pushguid");
Log.e(TAG, "pushGuid = " + pushGuid);
String clearCacheRemoveWhitelist = (String)remoteMessageMap.get("clear_cache_app_names");
Intent intentExecutePushCommand = new Intent( getApplicationContext(), ExecutePushCommandIntentService.class);
intentExecutePushCommand.putExtra("compID", MenuActivity.companyID);
intentExecutePushCommand.putExtra("command", message);
intentExecutePushCommand.putExtra("pushguid", pushGuid);
intentExecutePushCommand.putExtra("clear_cache_app_names", clearCacheRemoveWhitelist);
startService(intentExecutePushCommand);
}else if(message.trim().equalsIgnoreCase("CLEARCACHE_GET_PACKAGENAMES_WL")){
Log.e(TAG, "received CLEARCACHE_GET_PACKAGENAMES_WL");
String pushGuid = (String)remoteMessageMap.get("pushguid");
Log.e(TAG, "pushGuid = " + pushGuid);
Intent intentExecutePushCommand = new Intent( getApplicationContext(), ExecutePushCommandIntentService.class);
intentExecutePushCommand.putExtra("compID", MenuActivity.companyID);
intentExecutePushCommand.putExtra("command", message);
intentExecutePushCommand.putExtra("pushguid", pushGuid);
startService(intentExecutePushCommand);
}else if(message.trim().equalsIgnoreCase("CLEARCACHE_ADD_PACKAGENAME_WL")){
Log.e(TAG, "received CLEARCACHE_ADD_PACKAGENAME_WL");
String pushGuid = (String)remoteMessageMap.get("pushguid");
Log.e(TAG, "pushGuid = " + pushGuid);
String packageName = (String)remoteMessageMap.get("package_name");
Intent intentExecutePushCommand = new Intent( getApplicationContext(), ExecutePushCommandIntentService.class);
intentExecutePushCommand.putExtra("compID", MenuActivity.companyID);
intentExecutePushCommand.putExtra("command", message);
intentExecutePushCommand.putExtra("pushguid", pushGuid);
intentExecutePushCommand.putExtra("package_name", packageName);
startService(intentExecutePushCommand);
}
There is no need to pass the remoteMessageMap to another class. The source of the problem is the limitation in the java method size. Here is a piece of the official documentation of oracle which is related to this problem:
code_length
The value of the code_length item gives the number of bytes in the code array for this method.
The value of code_length must be greater than zero (as the code array must not be empty) and less than 65536.
The point is that your onMessageReceived method is too long, which is bigger than 64KB of compiled code. It is weird why it was compiled fine in previous versions of Android Studio :)
Anyway, the solution is to break the method into smaller fragments. My suggestion is fragmentation by some message types. For example:
private static final String COMMAND_1 = "COMMAND_1";
private static final String COMMAND_2 = "COMMAND_2";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.e(TAG, "remoteMessage.getData() = " + remoteMessage.getData());
Map remoteMessageMap = remoteMessage.getData();
String message = (String) remoteMessageMap.get("message");
String type = extrated_from_received_message;
switch (type) {
case COMMAND_1:
handleCommand1(remoteMessageMap);
break;
case COMMAND_2:
handleCommand2(remoteMessageMap);
break;
// more commands ...
default:
// ...
}
}
private void handleCommand1(Map remoteMessageMap){
// do whatever related to command 1
}
private void handleCommand2(Map remoteMessageMap){
// do whatever related to command 2
}
In this way, the method size would be optimized and the performance of calling it will be far improved.
It seems that you are repeating the same lines of code a lot of times, just put these lines of code and maybe a few more in a separate method that is called on each else if and this will reduce the size of onMessageReceived()
Intent intentExecutePushCommand = new Intent( getApplicationContext(), ExecutePushCommandIntentService.class);
intentExecutePushCommand.putExtra("compID", MenuActivity.companyID);
intentExecutePushCommand.putExtra("command", message);
intentExecutePushCommand.putExtra("pushguid", pushGuid);

What is the error in my code that once I view all I get the message import androidx.appcompat.app.AppCompatActivity? link for the error in the picture [closed]

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 2 years ago.
Improve this question
Main Activity Code, Having an error once I click the view all button, it will show the import androidx.appcompat.aoo.AppCompatActivity. 2 days of debugging still can't see the error.
public void viewAll(){
btView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Cursor res = db.getAllData();
if (res.getCount() == 0) {
showMessage("Error", "No Records Found");
return;
}
StringBuffer buffer = new StringBuffer();
while(res.moveToNext()){
buffer.append("ID : " + res.getString(0));
buffer.append("stdnt_id : " + res.getString(1));
buffer.append("stdnt_name : " + res.getString(2));
buffer.append("stdnt_prog : " + res.getString(3));
}
showMessage("Student Details", buffer.toString());
}
});
}
public void showMessage (String title, String Message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.show();
}
}
Error I get in my alertdialog
End of Code
I think your misteck is in your getAllData()
Function, your put value of student detail from edittext perfectly
For example
Std_name.text.tostring()
If you put std_name.tostring() I will show logical error like you have
try this
res.moveToFirst();
while(!res.isAfterLast()){
buffer.append("ID : " + res.getString(0));
buffer.append("stdnt_id : " + res.getString(1));
buffer.append("stdnt_name : " + res.getString(2));
buffer.append("stdnt_prog : " + res.getString(3));
res.moveToNext();
}
I May be wrong but i think the problem is you never moved the cursor to the first row, and you are just calling moveToNext() is a loop so when the cursor is at last row it still tries to go to the next row .
I will also suggest doing the database operations on the background thread , you're doing it on the main thread so as your database will grow i will take more and more time to fetch that data , and your UI will be non-responding in that time and some day you will crash with ANR
You are not converting edittext object to string.
DO this
String studentName = requireNonNull(studentNameEditText.getText()).toString();
then store studentName to DB.

Android Linkify - Clickable telephone numbers

So I am trying to add the functionality that when you click on a phone number it would take you to the Dialer app with the pre-populated number. I have the code below:
mContactDetailsText.setText(phonetextBuilder.toString());
Pattern pattern = Pattern.compile("[0-9]+\\s+[0-9]+");
Linkify.addLinks(mContactDetailsText, pattern, "tel:");
and the Text is currently "T. 0123 4567890"
The current outcome is just having the above string without it being clickable. I have even tried added the following line, but to no luck:
mContactDetailsText.setAutoLinkMask(0);
Anyone got any ideas or can see what I am doing wrong?
Thanks
The autolink mask needs to include a search for phone numbers:
mContactDetailsText.setAutoLinkMask(Linkify.PHONE_NUMBERS);
Then you'll need to set the links to be clickable:
mContactDetailsText.setLinksClickable(true);
You might also need movement method set like so:
mContactDetailsText.setMovementMethod(LinkMovementMethod.getInstance())
You should be able to accomplish what you want with the other answers,
but this will definitely work and will give you more control over the display of the text and what will happen when you click the number.
String text = "T. ";
StringBuilder stringBuilder = new StringBuilder(text);
int phoneSpanStart = stringBuilder.length();
String phoneNumber = "0123 4567890"
stringBuilder.append(phoneNumber);
int phoneSpanEnd = stringBuilder.length();
ClickableSpan clickableSpan = new ClickableSpan() {
#Override
public void onClick(View textView) {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:" + phoneNumber.replace(" ", "")));
startActivity(intent);
}
public void updateDrawState(TextPaint ds) {// override updateDrawState
ds.setUnderlineText(false); // set to false to remove underline
ds.setColor(Color.BLUE);
}
};
SpannableString spannableString = new SpannableString(stringBuilder);
spannableString.setSpan(clickableSpan, phoneSpanStart, phoneSpanEnd,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
myTextView.setText(spannableString);
myTextView.setMovementMethod(LinkMovementMethod.getInstance());
You need to set an onClickListener() on your TextViews. Then they will respond to clicks.

Fill fields in webview automatically

I have seen this question floating around the internet, but I haven't found a working solution yet. Basically, I want to load my app and press a button; the button action will then fill in a username and password in a website already loaded in the webview (or wait for onPageFinished). Finally, the submit button on the login page will be activated.
From what I understand this can be done by doing a java injection with the loadUrl(javascript), but I don't know what the java commands would be to fill in the fields. The same question was asked for iOS, but the commands are slightly different.
Is it possible to do what I am asking with javascript in a webivew, or do I have to do a http-post without a webview like this or this?
Thank you so much for any help you can give!
Thanks all for your answer, it helped me, but didn't work.
It was allways opening a white page until i found this :
https://stackoverflow.com/a/25606090/3204928
So here complete solution, mixing all infos found here and there :
1) first of all you have to enable DOM storage, if you don't do that, .GetElementByXXX will return nothing (you have to do it before loading the page)
myWebView.getSettings().setDomStorageEnabled(true);
2)Your last Javascript call on GetElementByXXX MUST store the result in a variable
Exemple 1 :
_webview.loadUrl("javascript:var uselessvar =document.getElementById('passwordfield').value='"+password+"';");
here only one call (only one semi-colon) so we immediatly store the result in 'uselessvar'
Example 2 : see user802467 answer
here there is 3 calls (one for login field, one for password field, one to submit button), only the last call need to be store, it's done in 'frms'
Javascript programmers should easily explain this behaviour...
hope this will help
You don't need to use "java commands"... but instead JavaScript... for instance:
String username = "cristian";
webview.loadUrl("javascript:document.getElementById('username').value = '"+username+"';");
So basically, what you have to do is a big string of JavaScript code that will get those fields and put values on them; also, you can enable/disable the submit button from JavaScript.
This worked for me to fill form values and submitting the form:
webView.loadUrl("javascript: {" +
"document.getElementById('username').value = '"+uname +"';" +
"document.getElementById('password').value = '"+password+"';" +
"var frms = document.getElementsByName('loginForm');" +
"frms[0].submit(); };");
Here is complete code which works for me (Bitbucket):
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.loadUrl("http://example.com/");
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
final String password = "password";
final String username = "username";
final String answer = 5;
final String js = "javascript:" +
"document.getElementById('password').value = '" + password + "';" +
"document.getElementById('username').value = '" + username + "';" +
"var ans = document.getElementsByName('answer');" +
"ans[0].value = '" + answer + "';" +
"document.getElementById('fl').click()";
if (Build.VERSION.SDK_INT >= 19) {
view.evaluateJavascript(js, new ValueCallback<String>() {
#Override
public void onReceiveValue(String s) {
}
});
} else {
view.loadUrl(js);
}
}
});
I tried #user802467 solution.But there was a different behaviour in 2 things
If I stored ONLY the last javascript call in a variable, it was not filling in the fields. Instead if I stored all the three calls in variables, it did
For some reason my form was not being submitted using submit(). But instead of submitting the form, if I clicked on the submit button using button.click(), I didnot need to store all the three calls and everything worked perfectly!
Here is what I used (but didnt work)
view.loadUrl("javascript: var x = document.getElementById('username').value = '" + username + "';" +
"var y = document.getElementById('password').value = '" + password + "';" +
"var form1 = document.getElementById('loginform');" +
"form1[0].submit(); ");
Here is the code that worked for me
view.loadUrl("javascript: document.getElementById('username').value = '" + username + "';" +
" document.getElementById('password').value = '" + password + "';" +
"var z = document.getElementById('submitbutton').click();"
);
It works for me
webView.loadUrl("javascript:var uselessvar =document.getElementById('regno').value='"+mob+"';",null);
webView.loadUrl("javascript:var uselessvar =document.getElementById('passwd').value='"+pass+"';",null);

Categories

Resources