안드로이드 레이아웃 예제

Programming/Android 2013. 3. 16. 16:40 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/page1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Page1" />

        <Button
            android:id="@+id/page2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
             android:text="Page2" />

        <Button
            android:id="@+id/page3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"

 android:text="Page3" />
   </LinearLayout>

    <FrameLayout
        android:id="@+id/frame_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
        <LinearLayout
            android:id="@+id/frame_01"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#ff0000" >
        </LinearLayout>
        <LinearLayout
            android:id="@+id/frame_02"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#00ff00" >
        </LinearLayout>
        <LinearLayout
            android:id="@+id/frame_03"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#0000ff" >
        </LinearLayout>
    </FrameLayout>

</LinearLayout>

 

'Programming > Android' 카테고리의 다른 글

TabActivity 사용법  (0) 2013.03.23
다중 액티비티 예제  (0) 2013.03.23
안드로이드 실습  (0) 2013.03.09
Intent 활용하기  (0) 2013.03.08
ubuntu 에 jdk 간편하게 설치하기  (0) 2013.02.27

안드로이드 실습

Programming/Android 2013. 3. 9. 12:35 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

 

mainActivity.java 에 추가 

 

    @Override

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

       super.onActivityResult(requestCode, resultCode, data);

       if (requestCode == 10001) {

           if (resultCode == SUCCESS) {

              ((TextView) findViewById(R.id.tv_selected_phone)).setText(data

                      .getStringExtra(SELECTED_PHONE));

           } else {

              ((TextView) findViewById(R.id.tv_selected_phone)).setText("");

           }

       }

    }

 

    private void showContactlist() {

       Intent intent = new Intent(MainActivity.this, ContactListActivity.class)

               .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP

                     | Intent.FLAG_ACTIVITY_SINGLE_TOP);

 

       startActivityForResult(intent, 10001);

    }

 

ContactListActivity.java 생성

 

public class ContactListActivity extends Activity {

 

    private ListView lv_contactlist;

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

       super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_contactlist);

       lv_contactlist = (ListView) findViewById(R.id.lv_contactlist);

    }

 

    @Override

    protected void onResume() {

       super.onResume();

   

 

       ContactsAdapter adapter = new ContactsAdapter(ContactListActivity.this,

               R.layout.layout_phonelist, getContactList());

 

       lv_contactlist.setAdapter(adapter);

       lv_contactlist

              .setOnItemClickListener(new AdapterView.OnItemClickListener() {

 

                  public void onItemClick(AdapterView<?> contactlist, View v,

                         int position, long resid) {

                     Contact phonenumber = (Contact) contactlist

                             .getItemAtPosition(position);

 

                     if (phonenumber == null) {

                         return;

                     }

 

                     Intent data = new Intent();

                      data.putExtra(MainActivity.SELECTED_PHONE, phonenumber

                             .getPhonenum().replaceAll("-", ""));

 

                      setResult(MainActivity.SUCCESS, data);

                     finish();

                  }

              });

 

    }

    private ArrayList<Contact> getContactList() {

 

       Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;

 

       String[] projection = new String[] {

           ContactsContract.CommonDataKinds.Phone.CONTACT_ID,

               ContactsContract.CommonDataKinds.Phone.NUMBER,

           ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME };

 

       String[] selectionArgs = null;

 

       String sortOrder = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME

              + " COLLATE LOCALIZED ASC";

 

       Cursor contactCursor = managedQuery(uri, projection, null,

              selectionArgs, sortOrder);

 

       ArrayList<Contact> contactlist = new ArrayList<Contact>();

 

       if (contactCursor.moveToFirst()) {

           do {

              String phonenumber = contactCursor.getString(1).replaceAll("-",

                     "");

              if (phonenumber.length() == 10) {

                  phonenumber = phonenumber.substring(0, 3) + "-"

                        + phonenumber.substring(3, 6) + "-"

                         + phonenumber.substring(6);

             } else if (phonenumber.length() > 8) {

                  phonenumber = phonenumber.substring(0, 3) + "-"

                        + phonenumber.substring(3, 7) + "-"

                         + phonenumber.substring(7);

              }

 

              Contact acontact = new Contact();

               acontact.setPhotoid(contactCursor.getLong(0));

              acontact.setPhonenum(phonenumber);

               acontact.setName(contactCursor.getString(2));

 

              contactlist.add(acontact);

           } while (contactCursor.moveToNext());

       }

 

       return contactlist;

 

    }

 

    private class ContactsAdapter extends ArrayAdapter<Contact> {

 

       private int resId;

       private ArrayList<Contact> contactlist;

       private LayoutInflater Inflater;

       private Context context;

 

       public ContactsAdapter(Context context, int textViewResourceId,

              List<Contact> objects) {

           super(context, textViewResourceId, objects);

           this.context = context;

           resId = textViewResourceId;

           contactlist = (ArrayList<Contact>) objects;

           Inflater = (LayoutInflater) ((Activity) context)

              .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

       }

 

       @Override

       public View getView(int position, View v, ViewGroup parent) {

           ViewHolder holder;

           if (v == null) {

              v = Inflater.inflate(resId, null);

              holder = new ViewHolder();

              holder.tv_name = (TextView) v.findViewById(R.id.tv_name);

              holder.tv_phonenumber = (TextView) v

                      .findViewById(R.id.tv_phonenumber);

              holder.iv_photoid = (ImageView) v.findViewById(R.id.iv_photo);

              v.setTag(holder);

           } else {

              holder = (ViewHolder) v.getTag();

           }

 

           Contact acontact = contactlist.get(position);

 

           if (acontact != null) {

               holder.tv_name.setText(acontact.getName());

           holder.tv_phonenumber.setText(acontact.getPhonenum());

 

              Bitmap bm = openPhoto(acontact.getPhotoid());

              if (bm != null) {

                  holder.iv_photoid.setImageBitmap(bm);

              } else {

              holder.iv_photoid.setImageDrawable(getResources()

                         .getDrawable(R.drawable.ic_launcher));

              }

 

           }

 

           return v;

       }

 

       private Bitmap openPhoto(long contactId) {

           Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI,

                  contactId);

           InputStream input = ContactsContract.Contacts

              .openContactPhotoInputStream(context.getContentResolver(),

                         contactUri);

 

           if (input != null) {

              return BitmapFactory.decodeStream(input);

           }

 

           return null;

       }

 

       private class ViewHolder {

           ImageView iv_photoid;

           TextView tv_name;

           TextView tv_phonenumber;

       }

 

    }

}

 

 

Contact.Java 생성

 

public class Contact {

    long photoid;

    String phonenum;

    String name;

   

    public long getPhotoid() {

       return photoid;

    }

    public void setPhotoid(long photoid) {

       this.photoid = photoid;

    }

    public String getPhonenum() {

       return phonenum;

    }

    public void setPhonenum(String phonenum) {

       this.phonenum = phonenum;

    }

    public String getName() {

       return name;

    }

    public void setName(String name) {

       this.name = name;

    }

}

 

activity_contactlist.xml

<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/lv_contactlist"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

</ListView>


layout_phonelist.xml

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#FFFFFFFF"
        android:gravity="center_vertical"
        android:weightSum="10" >

        <ImageView
            android:id="@+id/iv_photo"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:scaleType="fitXY" />

        <TextView
            android:id="@+id/tv_name"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="4"
            android:singleLine="true"
            android:text="아무개"
            android:textSize="20sp" />

        <TextView
            android:id="@+id/tv_phonenumber"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="6"
            android:singleLine="true"
            android:text="000-0000-0000"
            android:textSize="20sp" />
    </LinearLayout>

</LinearLayout>

 

'Programming > Android' 카테고리의 다른 글

다중 액티비티 예제  (0) 2013.03.23
안드로이드 레이아웃 예제  (0) 2013.03.16
Intent 활용하기  (0) 2013.03.08
ubuntu 에 jdk 간편하게 설치하기  (0) 2013.02.27
R.java import 에러  (0) 2012.11.27

Intent 활용하기

Programming/Android 2013. 3. 8. 19:25 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

//show webapp:

 

Uri uri = Uri.parse("http://www.google.com");

Intent it  = new Intent(Intent.ACTION_VIEW,uri);

startActivity(it);

 

//show maps:

Uri uri = Uri.parse("geo:38.899533,-77.036476");

Intent it = new Intent(Intent.Action_VIEW,uri);

startActivity(it);

 

//show ways

Uri uri = Uri.parse("http://maps.google.com/maps?f=d&saddr=startLat%20startLng&daddr=endLat%20endLng&hl=en");

Intent it = new Intent(Intent.ACTION_VIEW,URI);

startActivity(it);

 

//call dial program

Uri uri = Uri.parse("tel:xxxxxx");

Intent it = new Intent(Intent.ACTION_DIAL, uri); 

startActivity(it); 

 

Uri uri = Uri.parse("tel.xxxxxx");

Intent it =new Intent(Intent.ACTION_CALL,uri);

//don't forget add this config:

<uses-permission id="android.permission.CALL_PHONE" />

 

//send sms/mms

//call sender program

Intent it = new Intent(Intent.ACTION_VIEW);  

it.putExtra("sms_body", "The SMS text");  

it.setType("vnd.android-dir/mms-sms");  

startActivity(it); 

 

//send sms

Uri uri = Uri.parse("smsto:0800000123");  

Intent it = new Intent(Intent.ACTION_SENDTO, uri);  

it.putExtra("sms_body", "The SMS text");  

startActivity(it); 

 

//send mms

Uri uri = Uri.parse("content://media/external/images/media/23");  

Intent it = new Intent(Intent.ACTION_SEND);  

it.putExtra("sms_body", "some text");  

it.putExtra(Intent.EXTRA_STREAM, uri);  

it.setType("image/png");  

startActivity(it);

 

//send email

 

Uri uri = Uri.parse("mailto:xxx@abc.com");

Intent it = new Intent(Intent.ACTION_SENDTO, uri);

startActivity(it);

 

Intent it = new Intent(Intent.ACTION_SEND);  

it.putExtra(Intent.EXTRA_EMAIL, "me@abc.com");  

it.putExtra(Intent.EXTRA_TEXT, "The email body text");  

it.setType("text/plain");  

startActivity(Intent.createChooser(it, "Choose Email Client")); 

 

Intent it=new Intent(Intent.ACTION_SEND);    

String[] tos={"me@abc.com"};    

String[] ccs={"you@abc.com"};    

it.putExtra(Intent.EXTRA_EMAIL, tos);    

it.putExtra(Intent.EXTRA_CC, ccs);    

it.putExtra(Intent.EXTRA_TEXT, "The email body text");    

it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text");    

it.setType("message/rfc822");    

startActivity(Intent.createChooser(it, "Choose Email Client"));  

 

 

//add extra

Intent it = new Intent(Intent.ACTION_SEND);  

it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text");  

it.putExtra(Intent.EXTRA_STREAM, "file:///sdcard/mysong.mp3");  

sendIntent.setType("audio/mp3");  

startActivity(Intent.createChooser(it, "Choose Email Client"));

 

//play media

Intent it = new Intent(Intent.ACTION_VIEW);

Uri uri = Uri.parse("file:///sdcard/song.mp3");

it.setDataAndType(uri, "audio/mp3");

startActivity(it);

 

Uri uri = Uri.withAppendedPath(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, "1");  

Intent it = new Intent(Intent.ACTION_VIEW, uri);  

startActivity(it); 

 

//Uninstall

Uri uri = Uri.fromParts("package", strPackageName, null);  

Intent it = new Intent(Intent.ACTION_DELETE, uri);  

startActivity(it);

 

//uninstall apk

Uri uninstallUri = Uri.fromParts("package", "xxx", null);

returnIt = new Intent(Intent.ACTION_DELETE, uninstallUri);

 

//install apk

Uri installUri = Uri.fromParts("package", "xxx", null);

returnIt = new Intent(Intent.ACTION_PACKAGE_ADDED, installUri);

 

//play audio

Uri playUri = Uri.parse("file:///sdcard/download/everything.mp3");

returnIt = new Intent(Intent.ACTION_VIEW, playUri);

 

//send extra

Intent it = new Intent(Intent.ACTION_SEND); 

it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text"); 

it.putExtra(Intent.EXTRA_STREAM, "file:///sdcard/eoe.mp3"); 

sendIntent.setType("audio/mp3"); 

startActivity(Intent.createChooser(it, "Choose Email Client"));

 

//search

Uri uri = Uri.parse("market://search?q=pname:pkg_name"); 

Intent it = new Intent(Intent.ACTION_VIEW, uri); 

startActivity(it); 

//where pkg_name is the full package path for an application 

 

//show program detail page

Uri uri = Uri.parse("market://details?id=app_id"); 

Intent it = new Intent(Intent.ACTION_VIEW, uri); 

startActivity(it); 

//where app_id is the application ID, find the ID 

//by clicking on your application on Market home 

//page, and notice the ID from the address bar

 

 

//search google

Intent intent = new Intent();

intent.setAction(Intent.ACTION_WEB_SEARCH);

intent.putExtra(SearchManager.QUERY,"searchString")

startActivity(intent);

 


출처 : https://snipt.net/Martin/tag/android/

 

//카카오톡 메세지 Intent

    

    try {

       KakaoLink kakaoLink = KakaoLink

              .getLink(getApplicationContext());

   

       // check, intent is available.

       if (!kakaoLink.isAvailableIntent()) {

           return;

       }

       /**

        * @param activity

        * @param url

        * @param message

        * @param appId

        * @param appVer

        * @param appName

        * @param encoding

        */

       kakaoLink.openKakaoLink(

              MainActivity.this,

              "http://link.kakao.com/?test-android-app",

              "First KakaoLink Message for send url.",

              getPackageName(),

              getPackageManager().getPackageInfo(

                     getPackageName(), 0).versionName,

              "KakaoLink Test App", "UTF-8");

    } catch (Exception e) {

       // TODO Auto-generated catch block

       e.printStackTrace();

    }



KakaoLink.java


'Programming > Android' 카테고리의 다른 글

다중 액티비티 예제  (0) 2013.03.23
안드로이드 레이아웃 예제  (0) 2013.03.16
안드로이드 실습  (0) 2013.03.09
ubuntu 에 jdk 간편하게 설치하기  (0) 2013.02.27
R.java import 에러  (0) 2012.11.27

JAVA 선택정렬

Programming/JAVA,JSP 2013. 3. 3. 16:28 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

public class CarTest3 {

    public static void printAll(int[] array) {

        for (int i = 0; i < array.length; i++) {

           System.out.print(array[i] + " ");

        }

        System.out.println();

    }

 

    public static void sort(int[] array) {

        int[] tempArray = new int[array.length];

        int minIndex;

        int min;

       

        for(int j = 0 ; j < array.length; j++ )

        {

           min = array[j];

           minIndex = j;         

           for( int i = j ; i < array.length ; i++ )

           {

               if( min > array[i] )

               {

                   min = array[i];

                   minIndex = i;

               }

           }

           int temp = array[j];

           array[j] = array[minIndex];

           array[minIndex] = temp;

        }

 

    }

 

    public static void main(String[] args) {

        int[] array = { 35, 26, 21, 1, 100, 150, 200, 700, 3 ,6 };

        printAll(array);

        sort(array);

        printAll(array);

    }

}

'Programming > JAVA,JSP' 카테고리의 다른 글

RESTlet HelloWorld  (0) 2013.04.21
JAVA 로 Word 문서 만들기  (0) 2013.03.29
JAVA 삽입 정렬  (0) 2013.03.03
JAVA JTABLE 사용 예제  (0) 2013.03.03
JAVA executeQuery INSERT DELETE  (0) 2013.03.02

JAVA 삽입 정렬

Programming/JAVA,JSP 2013. 3. 3. 16:24 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

public class CarTest3 {

    public static void printAll(int[] array) {

        for (int i = 0; i < array.length; i++) {

           System.out.print(array[i] + " ");

        }

        System.out.println();

    }

 

    public static void sort(int[] array) {

        int[] tempArray = new int[array.length];

        int minIndex;

        int min;

       

        for(int j = 0 ; j < array.length; j++ )

        {

           min = array[0];

           minIndex = 0;         

           for( int i = 0 ; i < array.length ; i++ )

           {

               if( min > array[i] )

               {

                   min = array[i];

                   minIndex = i;

               }

           }

           tempArray[j] = min;

           array[minIndex] = 1000;

        }

        for( int i = 0 ; i < array.length ; i++ )

        {

           array[i] = tempArray[i];

        }

 

    }

 

    public static void main(String[] args) {

        int[] array = { 35, 26, 21, 1, 100, 150, 200, 700, 3 ,6 };

        printAll(array);

        sort(array);

        printAll(array);

    }

}

'Programming > JAVA,JSP' 카테고리의 다른 글

JAVA 로 Word 문서 만들기  (0) 2013.03.29
JAVA 선택정렬  (0) 2013.03.03
JAVA JTABLE 사용 예제  (0) 2013.03.03
JAVA executeQuery INSERT DELETE  (0) 2013.03.02
JAVA 데이터베이스 실습 예제 UI  (0) 2013.02.24

JAVA JTABLE 사용 예제

Programming/JAVA,JSP 2013. 3. 3. 11:20 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.util.ArrayList;

 

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JTable;

import javax.swing.table.AbstractTableModel;

import javax.swing.table.DefaultTableCellRenderer;

import javax.swing.table.DefaultTableColumnModel;

import javax.swing.table.TableCellRenderer;

import javax.swing.table.TableColumn;

import javax.swing.table.TableColumnModel;

import javax.swing.table.TableModel;

 

class Info {

    public String name;

    public int money;

    public long contentLength = 0L;

    public Info(String name, int money)

    {

        this.name = name;

        this.money = money;

    }

}

 

class InfoTableModel extends AbstractTableModel{

    private static final long serialVersionUID = 7932826462497464190L;

    public ArrayList<Info> pages;

 

    public InfoTableModel(){

        pages = new ArrayList<Info>();

    }

    public int getColumnCount() {

        return 2;

    }

    public int getRowCount() {

        return pages.size();

    }

    public void addInfo(Info page){

        int idx = pages.size();

        pages.add(page);

        fireTableRowsInserted(idx, idx); // 반드시 호출해야한다.

    }

    public Object getValueAt(int rowIndex, int columnIndex) {

        Info info = pages.get(rowIndex);

        switch (columnIndex) {

        case 0 :

            return info.name;

        case 1 :

            return info.money;

        case 2 :

            return info.contentLength;

        default :

                return "invalid";

        }

    }

}

class myFrame extends JFrame {

    JTable table;

 

    public myFrame() {

        // TODO Auto-generated constructor stub

        setSize(600, 400);

        setVisible(true);

 

        InfoTableModel model = new InfoTableModel();

        TableColumnModel columnModel = new DefaultTableColumnModel();

        TableCellRenderer renderer = new DefaultTableCellRenderer() ; // 기본구현

        model.addInfo(new Info("김종명",50000));

        model.addInfo(new Info("김종명",40000));

        model.addInfo(new Info("김종명",60000));

       

 

        TableColumn column = new TableColumn(0);

        column.setCellRenderer(renderer); // 이렇게 하지 않아도 알아서 제공된다.

        column.setHeaderValue("name");

        columnModel.addColumn(column);

       

        column = new TableColumn(1);

        column.setHeaderValue("money");

        columnModel.addColumn(column);

            

        table = new JTable(model, columnModel);

        add(table);

    }

 

}

 

public class CarTest3 {

 

    public static void main(String args[]) {

        new myFrame();

    }

}

'Programming > JAVA,JSP' 카테고리의 다른 글

JAVA 선택정렬  (0) 2013.03.03
JAVA 삽입 정렬  (0) 2013.03.03
JAVA executeQuery INSERT DELETE  (0) 2013.03.02
JAVA 데이터베이스 실습 예제 UI  (0) 2013.02.24
JAVA JDBC 튜토리얼 예제 사이트  (0) 2013.02.24

JAVA executeQuery INSERT DELETE

Programming/JAVA,JSP 2013. 3. 2. 12:25 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

JAVA 에서

executeQuery 는 SELECT 시 사용됨


INSERT, DELETE 는

executeUpdate 를 사용함 


executeQuery 는 resultSet을 생성

executeUpdate 는 resultSet 대신 0과 1로 성공적으로 수행되었는지를 반환


예제 코드

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCEexecuteExample {
       
public static void main(String[] args) throws SQLException {
               
Connection connection = null; // connection reference variable for
                                                                               
// getting
               
// connection
               
Statement statement = null; // Statement reference variable for query
               
// Execution
               
ResultSet resultSet = null; // ResultSet reference variable for saving
                                                                       
// query
               
// result
               
String conUrl = "jdbc:mysql://localhost:3306/";
               
String driverName = "com.mysql.jdbc.Driver";
               
String databaseName = "student";
               
String usrName = "root";
               
String usrPass = "root";
               
try {
                       
// Loading Driver
                       
Class.forName(driverName);
               
} catch (ClassNotFoundException e) {
                       
System.out.println(e.toString());
               
}
               
try {
                       
// Getting Connection
                        connection
= DriverManager.getConnection(conUrl + databaseName,
                                        usrName
, usrPass);
                       
// setting connection autocommit false
                        connection
.setAutoCommit(false);
                       
// Getting reference to connection object
                        statement
= connection.createStatement();
                       
// creating Query String
                       
String updateQuery = "UPDATE student SET NAME='Rajan' WHERE RollNo=1";
                       
String selectQuery = "SELECT * FROM student";
                       
String insertQuery = "INSERT INTO student values(4,'Rohan','MCA','Mumbai')";
                       
String deleteQuery = "DELETE FROM student WHERE RollNo=4";
                       
// Insert Query
                        statement
.executeUpdate(insertQuery);
                       
// Updating Query
                       
int result = statement.executeUpdate(updateQuery);
                       
if (result == 1) {
                               
System.out.println("Table Updated Successfully.......");
                       
}
                       
// Delete Query
                        statement
.executeUpdate(deleteQuery);
                       
// excecuting query
                        resultSet
= statement.executeQuery(selectQuery);
                       
while (resultSet.next()) {
                               
// Didplaying data of tables
                               
System.out.println("Roll No " + resultSet.getInt("RollNo")
                                               
+ ", Name " + resultSet.getString("Name") + ", Course "
                                               
+ resultSet.getString("Course") + ", Address "
                                               
+ resultSet.getString("Address"));
                       
}
               
} catch (Exception e) {
                       
System.out.println(e.toString());
               
} finally {
                       
// Closing connection
                        resultSet
.close();
                        statement
.close();
                        connection
.close();
               
}
       
}
}

'Programming > JAVA,JSP' 카테고리의 다른 글

JAVA 삽입 정렬  (0) 2013.03.03
JAVA JTABLE 사용 예제  (0) 2013.03.03
JAVA 데이터베이스 실습 예제 UI  (0) 2013.02.24
JAVA JDBC 튜토리얼 예제 사이트  (0) 2013.02.24
JAVA 채팅 프로그램 + GUI  (0) 2013.02.23

ubuntu 에 jdk 간편하게 설치하기

Programming/Android 2013. 2. 27. 12:46 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

$ sudo add-apt-repository ppa:webupd8team/java
$ sudo apt-get update
$ sudo apt-get install oracle-java7-installer

$ sudo add-apt-repository ppa:ferramroberto/java
$ sudo apt-get update
$ sudo apt-get install sun-java6-jdk sun-java6-plugin

출처 : http://krroo.blogspot.kr/2013/02/ubuntu-jdk.html

'Programming > Android' 카테고리의 다른 글

다중 액티비티 예제  (0) 2013.03.23
안드로이드 레이아웃 예제  (0) 2013.03.16
안드로이드 실습  (0) 2013.03.09
Intent 활용하기  (0) 2013.03.08
R.java import 에러  (0) 2012.11.27

JAVA 데이터베이스 실습 예제 UI

Programming/JAVA,JSP 2013. 2. 24. 12:51 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

import java.awt.BorderLayout;

import java.awt.GridLayout;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

 

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JList;

import javax.swing.JPanel;


class UI extends JFrame{

    JPanel panel1;

    JPanel panel2;

    JPanel panel3;

    JPanel panel4;

    JList list1;

    JList list2;

    JList list3;

    JList list4;

    JButton updateButton;

   

    public UI()

    {

        JLabel label1 = new JLabel("book_id");

        JLabel label2 = new JLabel("title");

        JLabel label3 = new JLabel("publi");

        JLabel label4 = new JLabel("price");

        String[] listItem1 = { "green", "red", "orange", "dark blue" };

        String[] listItem2 = { "green", "red", "orange", "dark blue" };

        String[] listItem3 = { "green", "red", "orange", "dark blue" };

        String[] listItem4 = { "green", "red", "orange", "dark blue" };

        list1 = new JList(listItem1);

        list2 = new JList(listItem2);

        list3 = new JList(listItem3);

        list4 = new JList(listItem4);

        updateButton = new JButton("Update");

        panel1 = new JPanel(new BorderLayout());

        panel2 = new JPanel(new BorderLayout());

        panel3 = new JPanel(new BorderLayout());

        panel4 = new JPanel(new BorderLayout());

       

        setSize(600,400);

        setVisible(true);

        setLayout(new GridLayout(0, 5));

        add(panel1);

        add(panel2);

        add(panel3);

        add(panel4);

        add(updateButton);

        panel1.add(label1,BorderLayout.NORTH);

        panel2.add(label2,BorderLayout.NORTH);

        panel3.add(label3,BorderLayout.NORTH);

        panel4.add(label4,BorderLayout.NORTH);

        panel1.add(list1,BorderLayout.CENTER);

        panel2.add(list2,BorderLayout.CENTER);

        panel3.add(list3,BorderLayout.CENTER);

        panel4.add(list4,BorderLayout.CENTER);

    }

   

}

public class Test {

       public static Connection makeConnection()

       {

             String url = "jdbc:mysql://localhost/book_db";

             String id = "root";

             String password = "green";

             Connection con = null;

             try {

                    Class.forName("com.mysql.jdbc.Driver");

                    System.out.println("드라이버 적재 성공");

                    con = DriverManager.getConnection(url, id, password);

                    System.out.println("데이터베이스 연결 성공");

             } catch (ClassNotFoundException e) {

                    System.out.println("드라이버를 찾을 없습니다.");

             } catch (SQLException e) {

                    System.out.println("연결에 실패하였습니다.");

             }

             return con;

       }

       public static void main(String arg[]) throws SQLException {

           UI ui = new UI();

           Connection con = makeConnection();

           Statement stmt = con.createStatement();

           ResultSet rs = stmt.executeQuery("SELECT * FROM books");

           while (rs.next()) {

                  int id = rs.getInt("book_id");

                  String title = rs.getString("title");

                  System.out.println(id + " " + title);

           }

       }

}

'Programming > JAVA,JSP' 카테고리의 다른 글

JAVA JTABLE 사용 예제  (0) 2013.03.03
JAVA executeQuery INSERT DELETE  (0) 2013.03.02
JAVA JDBC 튜토리얼 예제 사이트  (0) 2013.02.24
JAVA 채팅 프로그램 + GUI  (0) 2013.02.23
RadioButton exam  (0) 2013.02.03

JAVA JDBC 튜토리얼 예제 사이트

Programming/JAVA,JSP 2013. 2. 24. 10:05 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

JAVA JDBC 튜토리얼 예제 사이트

http://docs.oracle.com/javase/tutorial/jdbc/basics/index.html

http://www.oracle.com/technetwork/java/javase/jdbc/index.html


'Programming > JAVA,JSP' 카테고리의 다른 글

JAVA executeQuery INSERT DELETE  (0) 2013.03.02
JAVA 데이터베이스 실습 예제 UI  (0) 2013.02.24
JAVA 채팅 프로그램 + GUI  (0) 2013.02.23
RadioButton exam  (0) 2013.02.03
[IT]자바의 위기, 한국 IT의 시금석  (0) 2013.02.02