Posts

Showing posts with the label Java

ADB Over Wireless

Answer : Rooting is not required. With USB cable connected, port 5555 opened across all involved firewalls and debug mode enabled adb tcpip 5555 then look into wireless properties of your device and the network you use, to see which IP address have been granted to device (or configure your DHCP always to use the same for the device mac address). Then adb connect 192.168.1.133 (were 192.168.1.133 is a sample IP address). This is all. You can now use adb shell or adb install or adb upload or the like with USB cable plugged out. To switch back to USB mode, adb usb The device may also revert back to USB mode after reboot. This mode is needed for development of applications that use attached USB devices directly (USB port is used by device so cannot be used by ADB). It is briefly covered in the USB debugging section of the Android website. I ran into the same problem today and find that things are fine on my non-rooted 4.2 Galaxy Nexus device, but does not work on m...

Android: GetContext().getContentResolver() Sometimes Gets NullPointerException

Answer : If you look in the source of ContentProvider (just hold SHIFT and click on the classname in Android Studio) then you will find that the implementation is holding an object of type Context as mContext. Your solution is just the same, which means if mContext of ContentProvider is null, your reference will also be null. So there is no need for this. To help you out, this is just a warning of your IDE if make such a construct yourself. But in this case there will always be context, because the ContentProvider is generated by your system. To avoid the error in your IDE just write @SuppressWarnings("ConstantConditions") above your class definition like: ... @SuppressWarnings("ConstantConditions") public class NoteProvider extends ContentProvider { ... If you can make sure that getContext() can never be null then you can simply ignore this warning. I think the warning even disappears of you just check for null: if (getContext() != null) { getCon...

Android Studio - Keystore Was Tampered With, Or Password Was Incorrect

Answer : I had a similar problem while updating my app. The keytool was not reading the correct keystore file and instead pointing to an older keystore file that I created months ago and not used. Searched for some solutions online but didn't find one. Almost gave up but I thought about cleaning the project by clicking Build then Clean Project . This last resort worked for me. Apparently I just found another post posted few months ago that solved my issues I struggled for days... Simply need to change the keystore and key alias password to be the same for it to work. Though I still don't know why the same keystore worked before when I was publishing updates; then not working anymore until I changed the passwords. If anyone has answer for that, please let everyone know! Apparently Google decided to set the default keystore password to be android . The keytool utility prompts you to enter a password for the keystore. The default password for the debug keystore is ...

Can I Replace Groups In Java Regex?

Answer : Use $n (where n is a digit) to refer to captured subsequences in replaceFirst(...) . I'm assuming you wanted to replace the first group with the literal string "number" and the second group with the value of the first group. Pattern p = Pattern.compile("(\\d)(.*)(\\d)"); String input = "6 example input 4"; Matcher m = p.matcher(input); if (m.find()) { // replace first number with "number" and second number with the first String output = m.replaceFirst("number $3$1"); // number 46 } Consider (\D+) for the second group instead of (.*) . * is a greedy matcher, and will at first consume the last digit. The matcher will then have to backtrack when it realizes the final (\d) has nothing to match, before it can match to the final digit. You could use Matcher#start(group) and Matcher#end(group) to build a generic replacement method: public static String replaceGroup(String regex, String source, int groupT...

"Content Is Not Allowed In Prolog" When Parsing Perfectly Valid XML On GAE

Answer : The encoding in your XML and XSD (or DTD) are different. XML file header: <?xml version='1.0' encoding='utf-8'?> XSD file header: <?xml version='1.0' encoding='utf-16'?> Another possible scenario that causes this is when anything comes before the XML document type declaration. i.e you might have something like this in the buffer: helloworld<?xml version="1.0" encoding="utf-8"?> or even a space or special character. There are some special characters called byte order markers that could be in the buffer. Before passing the buffer to the Parser do this... String xml = "<?xml ..."; xml = xml.trim().replaceFirst("^([\\W]+)<","<"); This error message is always caused by the invalid XML content in the beginning element. For example, extra small dot “.” in the beginning of XML element. Any characters before the “ <?xml…. ” will cause above “ org.xml.sax.SAXParseExcept...

Adding Whitespace In Java

Answer : I think you are talking about padding strings with spaces. One way to do this is with string format codes. For example, if you want to pad a string to a certain length with spaces, use something like this: String padded = String.format("%-20s", str); In a formatter, % introduces a format sequence. The - means that the string will be left-justified (spaces will be added on the right of the string). The 20 means the resulting string will be 20 characters long. The s is the character string format code, and ends the format sequence. There's a few approaches for this: Create a char array then use Arrays.fill, and finally convert to a String Iterate through a loop adding a space each time Use String.format

Android Studio Design Editor Is Unavailable Until After A Successful Project Sync

Answer : Just sync your project with gradles. File --> Sync Project with Gradle Files Build -> Clean Project Build -> Rebuild Project File -> Sync project with gradle files . If not worked then try File -> Invalidate Caches / Restart . It's work for me !!!

Can You Split A Stream Into Two Streams?

Answer : A collector can be used for this. For two categories, use Collectors.partitioningBy() factory. This will create a Map from Boolean to List , and put items in one or the other list based on a Predicate . Note: Since the stream needs to be consumed whole, this can't work on infinite streams. And because the stream is consumed anyway, this method simply puts them in Lists instead of making a new stream-with-memory. You can always stream those lists if you require streams as output. Also, no need for the iterator, not even in the heads-only example you provided. Binary splitting looks like this: Random r = new Random(); Map<Boolean, List<String>> groups = stream .collect(Collectors.partitioningBy(x -> r.nextBoolean())); System.out.println(groups.get(false).size()); System.out.println(groups.get(true).size()); For more categories, use a Collectors.groupingBy() factory. Map<Object, List<String>> groups = stream ...

Android OnBackPressed() Is Not Being Called?

Answer : This question is already answered, but I feel to clear something here in this topic. Most comments and answeres point out to use super.onBackPressed() and that this is the cause of the not working method onBackPressed() . But that is not correct and important to let other beginners know. The method onBackPressed() does not need to use super.onBackPressed() . onBackPressed() also works if somebody, for example, comment super.onBackPressed() out. As the questionier has written, he won´t use super.onBackPressed() because it will close the activity. So, the cause of this why it isn´t working, could be seperated into three possible causes: The Log doesn´t work because of a wrong filter in the logcat console The Toast dosn´t work because of the wrong passed context The OS is implemented wrong by the supplier. Usually, the toast works by passing the correct context. In the case of questioner, simply passing this . @Override public void onBackPressed() { Log.d...

Bring JPanel To Front Of Other Objects In Java (SWING)

Answer : So here you have at least two solutions. Either go with what @Geoff and @sthupahsmaht are suggesting. BTW also possible is to use JOptionPane which automatically creates a dialog for you. The other option would be to use a GlassPane from a frame. Or yet another option is to use JLayeredPane as @jzd suggests. EDIT: Example showing how to use GlassPane to capture user selections. Try following steps: 1.Left clicking on the glass pane visible at start. See the output. 2.Right click it. This hides the glass pane. 3.Left clicking on the content pane. See the output. 4.Right click it. Go to point 1. Enjoy. import java.awt.Color; import java.awt.Dimension; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; public class OverPanel extends JPanel { private static void createAndShowGUI() { final JFrame f = new JFrame(); f.setPreferred...

Can We Rely On String.isEmpty For Checking Null Condition On A String In Java?

Answer : No, absolutely not - because if acct is null, it won't even get to isEmpty ... it will immediately throw a NullPointerException . Your test should be: if (acct != null && !acct.isEmpty()) Note the use of && here, rather than your || in the previous code; also note how in your previous code, your conditions were wrong anyway - even with && you would only have entered the if body if acct was an empty string. Alternatively, using Guava: if (!Strings.isNullOrEmpty(acct)) Use StringUtils.isEmpty instead, it will also check for null. Examples are: StringUtils.isEmpty(null) = true StringUtils.isEmpty("") = true StringUtils.isEmpty(" ") = false StringUtils.isEmpty("bob") = false StringUtils.isEmpty(" bob ") = false See more on official Documentation on String Utils. You can't use String.isEmpty() if it is null. Best is to have your own method to check nul...

After Upload A File In Android Firebase Storage How Get The File Download Url? GetDownloadUrl() Not Working

Answer : I had Found 2 solution for my issue. Firebase Google Documentation : //add file on Firebase and got Download Link filePath.putFile(imageUri).continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() { @Override public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception { if (!task.isSuccessful()){ throw task.getException(); } return filePath.getDownloadUrl(); } }).addOnCompleteListener(new OnCompleteListener<Uri>() { @Override public void onComplete(@NonNull Task<Uri> task) { if (task.isSuccessful()){ Uri downUri = task.getResult(); Log.d(TAG, "onComplete: Url: "+ downUri.toString()); } } }); Another solution! It's more easy and small than google Firebase documentation and I'll use it: filePath.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.Task...

Android MVP: What Is An Interactor?

Answer : MVP exists to tackle God Activity problem (An Activity/Fragment that has way too many lines). While it wasn't obligatory (you can code in any pattern that you want), many developers agree that MVP is suitable for Android. It makes your source code cleaner, testable, maintainable and robust. You can think of an interactor as your "Model/Controller". An interactor will fetch data from your database, web services, or any other data source. After getting the data, the interactor will send the data to the presenter. Thus, making changes in your UI. Advantages of using interactor in a separate class is that it will decouple your class, thus making it cleaner and testable. Sure, you can put the interactor in your presenter inner class, but what's the point? The disadvantages of putting the interactor in your presenter is it will make your presenter class bigger and relatively harder to read and manage. Update: Of course this is just an over-simplification...

Converting ISO 8601-compliant String To Java.util.Date

Answer : Unfortunately, the time zone formats available to SimpleDateFormat (Java 6 and earlier) are not ISO 8601 compliant. SimpleDateFormat understands time zone strings like "GMT+01:00" or "+0100", the latter according to RFC # 822. Even if Java 7 added support for time zone descriptors according to ISO 8601, SimpleDateFormat is still not able to properly parse a complete date string, as it has no support for optional parts. Reformatting your input string using regexp is certainly one possibility, but the replacement rules are not as simple as in your question: Some time zones are not full hours off UTC, so the string does not necessarily end with ":00". ISO8601 allows only the number of hours to be included in the time zone, so "+01" is equivalent to "+01:00" ISO8601 allows the usage of "Z" to indicate UTC instead of "+00:00". The easier solution is possibly to use the data type converter in JAXB, since JAXB m...

Conversion Of Nanoseconds To Milliseconds And Nanoseconds < 999999 In Java

Answer : Why not use the built in Java methods. The TimeUnit is part of the concurrent package so built exactly for you needs long durationInMs = TimeUnit.MILLISECONDS.convert(delayNS, TimeUnit.NANOSECONDS); For an ever shorter conversion using java.util.concurrent.TimeUnit , equivalent to what Shawn wrote above, you can use: long durationInMs = TimeUnit.NANOSECONDS.toMillis(delayNS); Just take the divmod of it with 1000000.

Can I Have Macros In Java Source Files

Answer : You can but you shouldn't . The shouldn't part: You shouldn't because using the pre-processor in that way is considered bad practice to start with, and there are better and more Java-idiomatic ways to solve this use case. The can part: (*) Java itself doesn't support macros. On the other hand, you could pipe the source code through the C pre processor (CPP for short) just like the C/C++ compile chain does. Here's a demo: src/Test.java : #define READINT (new java.util.Scanner(System.in).nextInt()) class Test { public static void main(String[] args) { int i = READINT; } } cpp command: $ cpp -P src/Test.java preprocessed/Test.java Result: class Test { public static void main(String[] args) { int i = (new java.util.Scanner(System.in).nextInt()); } } Compile: $ javac preprocessed/Test.java A better workaround: You can write your own utility class with a static method instead: import ja...

Convert XMLGregorianCalendar To Date I.e "MM/DD/YYYY Hh:mm:ss AM"

Answer : You can do this to return a Date : calendar.toGregorianCalendar().getTime() I found that code from this tutorial. From there, you can use a SimpleDateFormat to turn it into a string in the format you want. But, if you're using JDBC to save the date in the database, you probably can pass in the Date directly with this method: preparedStatement.setDate(colNum, myDate); Here is more clear answer: Get instance of Date from XMLGregorianCalendar instance: Date date = xmlCalendar.toGregorianCalendar().getTime(); I found that code from Convert XMLGregorianCalendar to Date in Java Format that Date instance with format "MM/dd/yyyy hh:mm:ss a", you will get MM/DD/YYYY hh:mm:ss AM format DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a"); String formattedDate = formatter.format(date) From Convert Date to String in Java For inserting database you would do what Daniel suggested If you want to insert your date on a database I would first do w...

Android On Text Change Listener

Answer : You can add a check to only clear when the text in the field is not empty (i.e when the length is different than 0). field1.addTextChangedListener(new TextWatcher() { @Override public void afterTextChanged(Editable s) {} @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if(s.length() != 0) field2.setText(""); } }); field2.addTextChangedListener(new TextWatcher() { @Override public void afterTextChanged(Editable s) {} @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if(s.length() != 0) field1.setText(""); } }); Documentation for TextWatcher here. Also please respect naming con...

Could Not Open JPA EntityManager For Transaction; Nested Exception Is Java.lang.IllegalStateException

Answer : The error comes from JpaTransactionManager line 403: TransactionSynchronizationManager.bindResource(getDataSource(), conHolder); The error means that the transaction manager is trying to bind the datasource (not the entity manager) to the thread, but the datasource is already there and this is unexpected. Note that the transaction manager had not started yet to bind the Entity Manager to the thread, that would happen next at JpaTransactionManager line 416: There are two possible explanations: Somebody (another transaction manager?) is adding the datasource to the thread before the transaction manager and this is unexpected. Or noone is adding the datasource to the transaction manager, is just that at the end of the task execution noone cleans the thread before returning it to the pool, maybe due an error or an unhandled exception. One question, does this also happen for only one execution thread, or only when there are several? To find out what the problem is, these are so...

Compiled Vs. Interpreted Languages

Answer : A compiled language is one where the program, once compiled, is expressed in the instructions of the target machine. For example, an addition "+" operation in your source code could be translated directly to the "ADD" instruction in machine code. An interpreted language is one where the instructions are not directly executed by the target machine, but instead read and executed by some other program (which normally is written in the language of the native machine). For example, the same "+" operation would be recognised by the interpreter at run time, which would then call its own "add(a,b)" function with the appropriate arguments, which would then execute the machine code "ADD" instruction. You can do anything that you can do in an interpreted language in a compiled language and vice-versa - they are both Turing complete. Both however have advantages and disadvantages for implementation and use. I'm going to completely ...