Thursday, January 23, 2014

Setting the background color on a android TextView

urlTextView.setBackgroundColor(this.getResources().getColor(R.color.error));
view raw gistfile1.java hosted with ❤ by GitHub
<color name="error">#a8206c</color>
view raw gistfile2.xml hosted with ❤ by GitHub

Wednesday, January 22, 2014

Extract value from string using regex in java

So suppose you want to extract values from a string based on a certain regex pattern. The thing that i didn't know was that I needed to use () around the data I wanted to capture.

import java.util.regex.*
Pattern p = Pattern.compile("(.*)/post/(.*)");
def str = "http://home.com/post/56"
Matcher m = p.matcher(str);
if (m.find()) {
println m.group(1);
println m.group(2);
}
view raw gistfile1.java hosted with ❤ by GitHub

Output
http://home.com
56

I dedicate this post to all laymen out there, who get confused with coding and stuff

Listen for text changes on EditText

Assume you want to enable a button only if some changes have been made to a form. You can do this by using android.text.TextWatcher
Simply create a new instance of TextWatcher and implement the required methods
There you have it. For more info checkout http://developer.android.com/reference/android/text/TextWatcher.html

import android.text.TextWatcher;
private void addEditTextChangeListeners() {
TextWatcher textListener = new TextWatcher() {
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {}
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {}
public void afterTextChanged(Editable editable) {
saveButton.setEnabled(editable.length() &gt; 0);
}
};
url.addTextChangedListener(textListener);
}
view raw gistfile1.java hosted with ❤ by GitHub

Tuesday, January 21, 2014

The magic of grep and sed and xargs

You want to get all files that have a certain string

grep -rl "ToMatch" <folder>

You then want to replace that string with another string

grep -rl "ToMatch" | xargs sed -i s/ToMatch/Replaced/g

The xargs command passes the values from "grep -rl "ToMatch" <folder>" to the sed command as arguments

For more info on how to use xargs look at http://unixhelp.ed.ac.uk/CGI/man-cgi?xargs

Friday, January 17, 2014

Delete values from a map through a loop

So you woke up today and you want to delete values from a map, as you loop through the map (For whatever reason). So you right this is groovy

Code
def m = [a:'aa', b:'bb']
def kset = m.keySet()
kset.each{
m.remove(it)
}
println m
Output
[a,b,c]
Wrong !!!!
You actually get a ConcurrentModificationException.... hahaha :D <- This is me laughing at you. So you need to
kset.each{ tempKset << it }
tempKset.each{
m.remove(it)
}

Wednesday, January 15, 2014

Java String.equals versus == [duplicate]

String.equals("some string") checks the contents of the string
"==" checks if the object references are identical