2012년 11월 29일 목요일

How to check if a number has period

if (value > (int) value)) { //value has period

How to add .0 to the end of integer


String pattern = "###.0";
DecimalFormat decimalFormat = new DecimalFormat(pattern);
decimalFormat.format(value);

Cannot access variables in super class

We can not access private variables in super class.

How to remove day picker section on the DatePickerDialog on Android



public static void displayDatePickerDialogWithoutDaySection( Context context, final TextView datePicker) { // 날짜가 표시합니다 // 오늘 날짜를 가져옵니다 Calendar c = Calendar.getInstance(); final int cyear = c.get(Calendar.YEAR); final int cmonth = c.get(Calendar.MONTH); final int cday = c.get(Calendar.DAY_OF_MONTH); MyDatePickerDialog.OnDateSetListener mDateSetListener = new MyDatePickerDialog.OnDateSetListener() { public void onDateSet(android.widget.DatePicker view, int year, int monthOfYear, int dayOfMonth) { String date_selected = String.valueOf(year) + "-" + String.valueOf(monthOfYear + 1); datePicker.setText(date_selected); } }; MyDatePickerDialog datePickerDialog = new MyDatePickerDialog(context, mDateSetListener, cyear, cmonth, cday); datePickerDialog.show(); DatePicker dp = findDatePicker((ViewGroup) datePickerDialog.getWindow() .getDecorView()); try { Field f[] = dp.getClass().getDeclaredFields(); for (Field field : f) { if (field.getName().equals("mDaySpinner") || field.getName().equals("mDayPicker")) { field.setAccessible(true); Object dayPicker = new Object(); dayPicker = field.get(dp); ((View) dayPicker).setVisibility(View.GONE); } } } catch (SecurityException e) { Log.d("ERROR", e.getMessage()); } catch (IllegalArgumentException e) { Log.d("ERROR", e.getMessage()); } catch (IllegalAccessException e) { Log.d("ERROR", e.getMessage()); } String currentDate = String.valueOf(cyear) + "년 " + String.valueOf(cmonth + 1) + "월"; datePickerDialog.setTitle(currentDate); }




-------------------------------------------------------------------------------

<MyDatePickerDialog.java>






package kr.co.ht.smartsales.utils; import java.util.Calendar; import android.app.DatePickerDialog; import android.content.Context; import android.content.DialogInterface; import android.text.format.DateUtils; import android.widget.DatePicker; public class MyDatePickerDialog extends DatePickerDialog { public MyDatePickerDialog(Context context, OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) { super(context, callBack, year, monthOfYear, dayOfMonth); // TODO Auto-generated constructor stub } @Override public void onDateChanged(DatePicker view, int year, int month, int day) { view.init(year, month, day, this); updateTitle(year, month, day); } private void updateTitle(int year, int month, int day) { String chosenDate = String.valueOf(year) + "년 " + String.valueOf(month + 1) + "월"; setTitle(chosenDate); } }


Re-installation failed due to different application signatures.

If you don't have the app in your device but still have that error message, remove the app using adb on the terminal.

Open the terminal(window 7) and type "adb uninstall <your app package name>".

2012년 11월 26일 월요일

No such file or directory - Cygwin

Change \ to /. For example, change "cd C:\cygwin\home\Jeonggyu\workspace\HelloAndroid\bin" to "cd C:/cygwin/home/Jeonggyu/workspace/HelloAndroid\bin" in Cygwin terminal.

Cygwin bash_profile location

C:\cygwin\etc\skel

NotificationCompat example





Notification noti = new NotificationCompat.Builder(this)
.setContentTitle(message).setContentText("HTSmartSales")
.setSmallIcon(R.drawable.haitai_logo).setContentIntent(pIntent)
.build();

2012년 11월 22일 목요일

arraylist remove doesn't work

check if you put Integer in the remove method, not int. Arraylist considers Integer as object.

How to sort ArrayList, removing duplicate items

 ArrayList arrayList1 = new ArrayList();
    
  
    
  //Create a HashSet which allows no duplicates
  HashSet hashSet = new HashSet(arrayList1);

  //Assign the HashSet to a new ArrayList
  ArrayList arrayList2 = new ArrayList(hashSet) ;
    
  //Ensure correct order, since HashSet doesn't
  Collections.sort(arrayList2);
    
  for (Object item : arrayList2)
    System.out.println(item);

2012년 11월 21일 수요일

How to disable visual effects and compiz 100%

Type "metacity --replace &" and hit enter on terminal.

Eclipse hangs on loading workbench


Try the following:
  1. Delete your .eclipse directory in your home directory. Launch eclipse. If that doesn't work,
  2. Open eclipse under another user account. If it loads, you know the problem is with your account, not your eclipse installation.
  3. If #2 didn't work your workspace might be screwed up. Delete the .metadata folder in your localworkspace (this is what worked for me). It seems that it contains a .LOCK file that if not properly closed, prevents eclipse from starting properly.

how to install java 1.7 on ubuntu 10.04

Type the following command on terminal.



sudo apt-get install oracle-java7-installer

startActivityForResult


From your FirstActivity call the SecondActivity using startActivityForresult() method
eg:
Intent i = new Intent(this, SeconActivity.class);
startActivityForResult(i, 1);
In your SecondActivity set the data which you want to return back to FirstActivity, If you don't want to return back don't set any.
eg: In secondActivity if you want to send back data
 Intent returnIntent = new Intent();
 returnIntent.putExtra("result",result);
 setResult(RESULT_OK,returnIntent);     
 finish();
if you don't want to return data
Intent returnIntent = new Intent();
setResult(RESULT_CANCELED, returnIntent);        
finish();
Now in your FirstActivity class write following code for onActivityResult() method
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

if (requestCode == 1) {

     if(resultCode == RESULT_OK){

      String result=data.getStringExtra("result");

}

if (resultCode == RESULT_CANCELED) {

     //Write your code on no result return 

}
}//onAcrivityResult


Save ArrayList to SharedPreferences


//save the task list to preference
        SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);
        Editor editor = prefs.edit();
        try {
            editor.putString(TASKS, ObjectSerializer.serialize(currentTasks));
        } catch (IOException e) {
            e.printStackTrace();
        }
        editor.commit();




//      load tasks from preference
        SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);

        try {
            currentTasks = (ArrayList<task>) ObjectSerializer.deserialize(prefs.getString(TASKS, ObjectSerializer.serialize(new ArrayList<task>())));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }





You can get ObjectSerializer class from Apache Pig project ObjectSerializer.java

The following is OjectSerializer that I modified.

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package kr.co.ht.smartsales.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import org.apache.commons.logging.Log;

public class ObjectSerializer {

    
    public static String serialize(Serializable obj) throws IOException {
        if (obj == null) return "";
        try {
            ByteArrayOutputStream serialObj = new ByteArrayOutputStream();
            ObjectOutputStream objStream = new ObjectOutputStream(serialObj);
            objStream.writeObject(obj);
            objStream.close();
            return encodeBytes(serialObj.toByteArray());
        } catch (Exception e) {
        }
  return null;
    }
    
    public static Object deserialize(String str) throws IOException {
        if (str == null || str.length() == 0) return null;
        try {
            ByteArrayInputStream serialObj = new ByteArrayInputStream(decodeBytes(str));
            ObjectInputStream objStream = new ObjectInputStream(serialObj);
            return objStream.readObject();
        } catch (Exception e) {
        }
  return str;
    }
    
    public static String encodeBytes(byte[] bytes) {
        StringBuffer strBuf = new StringBuffer();
    
        for (int i = 0; i < bytes.length; i++) {
            strBuf.append((char) (((bytes[i] >> 4) & 0xF) + ((int) 'a')));
            strBuf.append((char) (((bytes[i]) & 0xF) + ((int) 'a')));
        }
        
        return strBuf.toString();
    }
    
    public static byte[] decodeBytes(String str) {
        byte[] bytes = new byte[str.length() / 2];
        for (int i = 0; i < str.length(); i+=2) {
            char c = str.charAt(i);
            bytes[i/2] = (byte) ((c - 'a') << 4);
            c = str.charAt(i+1);
            bytes[i/2] += (c - 'a');
        }
        return bytes;
    }

}

2012년 11월 20일 화요일

java split period doesn't work

Q: split(".") return null.



A:"." is a metacharacter so if you want to match it literally use
s.split("\\.")

can not instaniate Handler

Check if you imported android.os.Handler, not java.util.logging.Handler.

can not see parent package in the Package Explorer

Click a small triangle at the right side of top in the Package Explorer, click Filters and uncheck Empty packages and Empty parent packages.

can not get registration id with GCM(Google Cloud Messageing)

If you followed all the directions about GCM, then check if you put GCMIntentService in the
 default package, not sub folder of that package.

2012년 11월 18일 일요일

how to install openoffice on ubuntu 10.04


Installation Steps

  1. Review the System Requirements
  2. Download your favorite Linux version of Apache OpenOffice
  3. Review helpful information and installation options in the Setup Guide.
  4. Unpack the downloaded image to prepare for installation.
    The following command should work: tar -xvzf "linux package name".tar.gz
    where "linux package name" is the beginning part of the archive you just downloaded.

    This will create an installation directory.
    The name of the installation directory will likely be the language abbreviation for the install set, e.g., en-US.
  5. su to root, if necessary, and navigate to Apache OpenOffice installation directory (the unpacked archive).
    You will likely need to be root to run the deb command to install the software.
  6. cd into the DEBS subdirectory of the installation directory.
    You should see a lot of debs here and one sub-directory called "desktop-integration".
  7. Install this new version by typing sudo dpkg -i *.deb.
    By default, this will install/update Apache OpenOffice in your /opt directory.

    Alternatively, you can use a GUI package installer, reference the installation directory, and install all debs at the top level. This may also aid you in determing any dependency problems if they exist.
  8. Install the desktop integration features for your setup.
    cd to desktop-integration in the installation directory,
    and, depending on your package manager/system, install the appropriate desktop interface using dpkg.
  9. Finally, start up Apache OpenOffice 3.4.x to insure it's working.

How to install LibreOffice on Ubuntu 10.04


How to remove OpenOffice.org?

Open the terminal and type the following command:
sudo apt-get purge "openoffice*.*"
You will be asked for your password, type your password and press the Enter key on your keyboard to continue. When asked, “If you want to remove the OpenOffice.org package,” type “Y” and press the Enter key. Wait for the OpenOffice.org packages to be removed.

How to add the LibreOffice PPA repository?

To add the PPA, add ppa:libreoffice/ppa to your software sources or open the terminal and type the following command:
sudo add-apt-repository ppa:libreoffice/ppa
You will be asked for your password, type your password and press the Enter key on your keyboard to continue.

How to install LibreOffice?

Open a new Terminal session and run the following commands:
sudo apt-get update && sudo apt-get install libreoffice
You will be asked for your password, type your password and press the Enter key on your keyboard to continue.
Now, Ubuntu users should run the following command:
sudo apt-get install libreoffice-gnome
Kubuntu users should run the following command:
sudo apt-get install libreoffice-kde
That’s it! LibreOffice is now completely installed in your Ubuntu machine. If you have any problems, do not hesitate to comment below!

Unable to open the service 'Tomcat6' on Windows Vista or Windows 7

 this is likely caused by Windows User Access Control (UAC). To solve the problem, run Tomcat as an administrator (either by logging into Windows as an administrator or by right-clicking on the Tomcat Monitor and running this as an administrator. Alternatively, disabling UAC should also solve the problem.

can not download files on server with filezilla

Your folder on local site is not writable. Change folder.

output folder is not shown on project explorer on eclise -- jsp project


If you want to display output folder on project manager, click the triangle on project manager and select Customize View... and remove the click on Java output folders
alt text

2012년 11월 16일 금요일

how to uninstall ant on ubuntu

Type the following on the terminal.


sudo apt-get remove ant

Exception in thread "main" java.lang.NoClassDefFoundError


The cause of this is that there is an old version of ant somewhere in the class path or configuration.
A version of this problem happens with jars that are in the classpath that include an embedded copy of ant classes. An example of this is some copies of weblogic.jar.
One can check if this is the case by doing (on unix/sh):
        unset CLASSPATH
        ant -version

how to install tomcat 7 perfectly on ubuntu 10.10

http://diegobenna.blogspot.kr/2011/01/install-tomcat-7-in-ubuntu-1010.html

2012년 11월 15일 목요일

how to install tomcat7 manually on Ubuntu 10.04


Troubleshooting with apache Tomcat 7 steps should be followed ....
after downloading apache-Tomcat 7 // open terminal go to that downloading file folder in which tar.gz file is still.
Untar the tar file
  • tar -xzvf filename.tar.gz
    move a extracted directory of apache-Tomcat7 in current path
  • sudo mv Directory_Name(Extracted eg.apache-Tomcat 7.0.32) /usr/local/Tomcat7
to set environment variable for Tomcat7
  • sudo nano /usr/local/Tomcat7/bin/setenv.sh
then Nano editor will open ..
 JAVA_HOME =/usr/lib/jvm/java-6-sun
 export CATALINA_OPTS="$CATALINA_OPTS -Xms128m -Xmx1024m -XX:MaxPermSize=256m
after hit ctrl+X to save file
  • to set the role and username and password.
sudo nano /usr/local/Tomcat7/conf/./tomcat-users.xml
<role rolename="manager-gui" />
<role rolename="manager-script" />
<role rolename="manager-jmx" />
<role rolename="manager-status" />
<user username="admin" password="admin" roles="manager-gui,manager-script,manager-jmx,manager-status"/>
Ctrl+X to save file
  • If Port no confliction comes in a way then open file to change the port no.
sudo nano /usr/local/Tomcat7/conf/./server.xml
then change the connector port as you want....

how to make jsp project

use eclipse ee version.

Target runtime Apache Tomcat v7.0 is not defined

Click right button of mouse on the project on package explorer. Choose Properties. Go to the Targeted Runtimes. Press New and configure your tomcat environment.

Java compiler level does not match the version of the installed Java project facet

http://help.eclipse.org/indigo/index.jsp?topic=%2Forg.eclipse.jst.j2ee.doc.user%2Ftopics%2Ftchangejavalevel.html

2012년 11월 11일 일요일

how to display multiple lines of text on a button

In layout xml file, add the following.

&#10;

for example, android:text="Hi&#10;Hello"







In coding,  just use '\n'.


how to solve problem that java file is opened in gedit, not java editor in eclipse.

Right click on the file on the package manager, and go to  "open with" menu. Choose default editor, not system editor.

how to solve javahl error in Ubuntu

I installed sublicpse and got javahl error whenever I started eclipse. The following is how to solve that error.


1. type "sudo apt-get install libsvn-java" in the terminal.



2. Type "gedit ~/.eclipse/eclipserc" in the terminal and add the line VMARGS="-Djava.library.path=/usr/lib/jni" on the file, and save it.



3. add this line to your eclipse.ini



-Djava.library.path=/usr/lib/jni

2012년 11월 4일 일요일

how to fix "NoClassDefFoundError"

check if the folder name where jar library file is located is "libs", not "lib". if the folder name is "lib", then change the name to "libs". Then it will work, and the error will be gone.