Convert list to array in Java [duplicate]

Either: Foo[] array = list.toArray(new Foo[0]); or: Foo[] array = new Foo[list.size()]; list.toArray(array); // fill the array Note that this works only for arrays of reference types. For arrays of primitive types, use the traditional way: List<Integer> list = …; int[] array = new int[list.size()]; for(int i = 0; i < list.size(); i++) array[i] = … Read more

Sending Email in Android using JavaMail API without using the default/built-in app

Send e-mail in Android using the JavaMail API using Gmail authentication. Steps to create a sample Project: MailSenderActivity.java: public class MailSenderActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final Button send = (Button) this.findViewById(R.id.send); send.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { try { GMailSender sender = new GMailSender(“username@gmail.com”, “password”); sender.sendMail(“This … Read more

Java: convert List to a join()d String

String.join With Java 8 you can do this without any third party library. If you want to join a Collection of Strings you can use the String.join() method: List<String> list = Arrays.asList(“foo”, “bar”, “baz”); String joined = String.join(” and “, list); // “foo and bar and baz” Collectors.joining If you have a Collection with another … Read more

Why are static variables considered evil?

Static variables represent global state. That’s hard to reason about and hard to test: if I create a new instance of an object, I can reason about its new state within tests. If I use code which is using static variables, it could be in any state – and anything could be modifying it. I … Read more

Ignoring new fields on JSON objects using Jackson [duplicate]

Jackson provides an annotation that can be used on class level (JsonIgnoreProperties). Add the following to the top of your class (not to individual methods): @JsonIgnoreProperties(ignoreUnknown = true) public class Foo { … } Depending on the jackson version you are using you would have to use a different import in the current version it … Read more

How to check internet access on Android? InetAddress never times out

If the device is in airplane mode (or presumably in other situations where there’s no available network), cm.getActiveNetworkInfo() will be null, so you need to add a null check. Modified (Eddie’s solution) below: public boolean isOnline() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); return netInfo != null && netInfo.isConnectedOrConnecting(); } Also add … Read more