7 Ekim 2017 Cumartesi

JAVA JDBC Examples

Oncelikle JDBC i kullanmak icin https://www.oracle.com/technetwork/apps-tech/jdbc-112010-090769.html linkinden ojdbc6.jar i indiriyoruz.

Ve eclipse de yeni bir java projesi olusturup icinde libs adli bir folder olusturuyoruz. Indirdigimiz jar i oraya yapistiriyoruz. Ama bu sekilde yapistirmamiz o jar i kullanmamiza yetmez o yuzden jar a sag tiklayip Build Path -> Add to Build Path secenegine tikliyoruz. Bu sekilde referenced library e jar imiz eklenmis oldu. Artik kullanabiliriz.

JDBC i kullanmak icin temel olarak yapmamiz gerekenler

Connection olustur => Statement olustur => Execute Et => Resultset ile cek.

Statement

Statement icin temelde 2 tip var.

ResultSet executeQuery(String sql) => gordugumuz gibi result set dondurur. select islemleri icin bunu kullaniriz.

int executeUpdate(String sql) => bunu ise insert, update, delete gibi islemlerde kullaniriz ve sonuc olarak islemlerden etkilenen row countu dondurur.


* Ayrica yazdigimiz tum connection, statement ve resultset in kapatilmasi gerekir. bunu tek tek kapatmak yerine try icinde hepsini tamamlarsak otomatik olarak kullanmadiginda kapatilir.

ResultSet Types

3 tip vardir.

Type_Forward_Only : ornegin bir islemde ilk basta 1. rowdayiz ve bunu kullanarak 5. row a gecebiliriz. Ama 5. rowdan 3 e gecemeyiz.Sadece ileri dogru gidebiliriz.

Type_Scroll_Insensitive : bununla hem forward hem backward ilerleyebiliriz. Ama Insensitive oldg icin result olustuktan sonraki degisikliklere duyarsizdir.

Type_Scroll_Sensitive :  bununla hem forward hem backward ilerleyebiliriz. Sensitive oldg icin result olustuktan sonraki degisikliklere duyarlidir.

* hic birini yazmazsak defaultu Type_Forward_Only dir.

ResultSet Concur Types

2 tip vardir.

Concur_Read_Only 

Concur_Updatable 

* defaultu Concur_Read_Only dir.

Asagida hem update hem insert yaptigimiz bir ornek yer almaktadir.



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

public class UpdatableRecords {

 public static void main(String[] args) {
  try (Connection conn = DBUtil.getConnection(DBType.ORADB);
    Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
    ResultSet rs = stmt.executeQuery("select department_id, department_name, manager_id, location_id from departments");
    ) {
   rs.absolute(6);
   rs.updateString("department_name", "Information Technology");
   rs.updateRow();
   
   System.out.println("Record updated successfuly");
   
   rs.moveToInsertRow();
   rs.updateInt("department_id", 999);
   rs.updateString("department_name", "Training");
   rs.updateInt("manager_id", 200);
   rs.updateInt("location_id", 2000);
   rs.insertRow();
   System.out.println("Record inserted succesfully");
   
  } catch(SQLException e){
   DBUtil.showErrorMsg(e);
  }

 }

}



Degisiklikleri sqlplus tan goruntuleyebiliriz.



Simdi de PreparedStatement kullanimina bakalim. Statement in bir alt sinifidir ve sorguya parametre girilecegi zaman kullanilir.

Asagida ornek bir yer almaktadir.



import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class PreparedStatementEx01 {

 public static void main(String[] args) {
  
  Connection conn = null;
  PreparedStatement pstmt = null;
  ResultSet rs = null;
  try {
   String sql = "select * from Employees where SALARY < ? and Department_Id=?";
   
   conn = DBUtil.getConnection(DBType.ORADB);
   pstmt = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
   
   preparedStatement(pstmt, 10000, 50);
   System.out.println("---------------------------");
   
   preparedStatement(pstmt, 3000, 50);
   
   
  } catch(SQLException e){
   DBUtil.showErrorMsg(e);
  }
 }

 private static void preparedStatement(PreparedStatement pstmt, double salary, int department_id) throws SQLException {
  ResultSet rs;
  pstmt.setDouble(1, salary);
  pstmt.setInt(2, department_id);
  rs = pstmt.executeQuery();
  String format = "%-4s%-20s%-25s%-10f\n";
  
  while(rs.next()){
   System.out.format(format, rs.getString("Employee_ID"), rs.getString("First_Name"),
     rs.getString("Last_Name"), rs.getFloat("Salary"));
  }
  rs.last();
  System.out.println("Total num of rows: "+ rs.getRow());
 }
}



INSERT RECORD



import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class InsertRecord {

 public static void main(String[] args) throws SQLException {
  Connection conn = DBUtil.getConnection(DBType.ORADB);
  PreparedStatement pstmt = null;
  
  String empname;
  int salary, empid;
  Date hiredate;
  
  Scanner scan = new Scanner(System.in);
  
  System.out.print("Enter emp id: ");
  empid = Integer.parseInt(scan.nextLine());
  
  System.out.print("Enter emp name: ");
  empname = scan.nextLine();
  
  System.out.println("Enter salary: ");
  salary = Integer.parseInt(scan.nextLine());
  
  System.out.println("Enter hire date: ");
  hiredate = java.sql.Date.valueOf(scan.nextLine());
  
  String sql = "insert into newemp values(?,?,?,?)";
  
  pstmt = conn.prepareStatement(sql);
  
  pstmt.setInt(1, empid);
  pstmt.setString(2, empname);
  pstmt.setInt(3, salary);
  pstmt.setDate(4, hiredate);
  
  int result = pstmt.executeUpdate();
  
  if(result == 1){
   System.out.println("Record inserted");
  } else{
   System.err.println("Error occured when insert.");
  }
  
  scan.close();
  pstmt.close();
  conn.close();
 }

}


UPDATE RECORD


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class UpdateRecord01 {
 public static void main(String[] args) throws SQLException{
  Connection conn = DBUtil.getConnection(DBType.ORADB);
  String sql = "update newemp set empsalary = ? where empid=20";
  
  Scanner scan = new Scanner(System.in);
  System.out.println("Enter new salary : ");
  int salary = scan.nextInt();
  PreparedStatement pstmt  = conn.prepareStatement(sql);
  pstmt.setInt(1, salary);
    
  int result  = pstmt.executeUpdate();
  if(result == 1){
   System.out.println("Succesfully updated");
  } else{
   System.err.println("Error occured");
  }
  scan.close();
  pstmt.close();
  conn.close();
 }
}


DELETE RECORD


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class DeleteRecord01 {

 public static void main(String[] args) throws SQLException {
  Connection conn = DBUtil.getConnection(DBType.ORADB);
  String sql = "Delete from newemp where empid=?";
  
  Scanner scan = new Scanner(System.in);
  System.out.println("Enter id of emp to delete:");
  int empid = scan.nextInt();
  
  PreparedStatement pstmt = conn.prepareStatement(sql);
  pstmt.setInt(1, empid);
  
  int result = pstmt.executeUpdate();
  if(result == 1){
   System.out.println("Succesfully deleted");
  } else{
   System.err.println("Error occured.");
  }
  scan.close();
  pstmt.close();
  conn.close();
 }

}



CALLABLE STATEMENT

Callable Statement ile Stored Procedure e parametre gonderebiliriz.
Bunun icin oncelikle bir stored procedure olusturalim.
SqlPlus i acalim. Ve daha once elimizdeki newemp tablosuna kayit eklememizi saglayacak bir procedure yazalim.

create or replace Procedure AddEmployee
(
eid in NEWEMP.EMPID%TYPE,
ename in NEWEMP.EMPNAME%TYPE,
sal in NEWEMP.EMPSALARY%TYPE,
hdate in NEWEMP.HIREDATE%TYPE
)
is
begin
    insert into NEWEMP values (eid, ename, sal, hdate);
commit;
end;
/

Procedure yukaridaki gibi olmalidir.

Simdi eclipse e gecip kodumuzu yazalim.


import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.Date;
import java.sql.SQLException;
import java.util.Scanner;

public class CallableStatementEx01 {

 public static void main(String[] args) {
  try (Connection conn = DBUtil.getConnection(DBType.ORADB);
    CallableStatement cstmt = conn.prepareCall("{call AddEmployee (?,?,?,?)}"); 
    Scanner scan = new Scanner(System.in); ) {
   
   
   System.out.println("Enter empid: ");
   int empid = Integer.parseInt(scan.nextLine());
   System.out.println("Enter empname: ");
   String empname = scan.nextLine();
   System.out.println("Enter empsalary: ");
   int salary = Integer.parseInt(scan.nextLine());
   System.out.println("Enter hiredate: ");
   Date hdate = java.sql.Date.valueOf(scan.nextLine());
   
   cstmt.setInt(1, empid);
   cstmt.setString(2, empname);
   cstmt.setInt(3, salary);
   cstmt.setDate(4, hdate);
   
   cstmt.execute();
   System.out.println("Added succesfully");
   
  } catch(SQLException ex){
   DBUtil.showErrorMsg(ex);
  }
 }

}


INSERTING MULTIPLE RECORDS

Yukarida yazdigimiz kod ile bir kez insert islemi yapabiliyoruz. Eger 10 kez insert yapmak istesek her bir insert isleminde database e baglanip islem yapmamiz gerekecek ve bu da network trafigini arttiracak. Bu yuzden 10 kez insert yapip bir kez database e baglanmamiz iyi bir yontemdir.



import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.Date;
import java.sql.SQLException;
import java.util.Scanner;

public class InsertMultipleRecords01 {

 public static void main(String[] args) {
  try (Connection conn = DBUtil.getConnection(DBType.ORADB);
    CallableStatement cstmt = conn.prepareCall("{call AddEmployee(?,?,?,?)}");
    Scanner scan = new Scanner(System.in); ) {
   String option;
   do {
   System.out.println("Enter eid: ");
   int eid = Integer.parseInt(scan.nextLine());
   System.out.println("Enter ename: ");
   String ename = scan.nextLine();
   System.out.println("Enter salary: ");
   int sal = Integer.parseInt(scan.nextLine());
   System.out.println("Enter hire date: ");
   Date hdate = java.sql.Date.valueOf(scan.nextLine());
   
   cstmt.setInt(1, eid);
   cstmt.setString(2, ename);
   cstmt.setInt(3, sal);
   cstmt.setDate(4, hdate);
   
   cstmt.addBatch();
   System.out.println("Do you want to add one more record ? yes/no:");
   option = scan.nextLine();
   } while (option.equals("yes"));
   
   int[] updatedRecords = cstmt.executeBatch();
   System.out.println("Total num of updated records: " + updatedRecords.length);
  } catch(SQLException e){
   DBUtil.showErrorMsg(e);
  }

 }

}


Kayitlarin eklenip eklenmedigini kontrol etmek icin SqlPlus ta su query i calistirabiliriz.

select * from newemp where empid in (33, 44, 55);

Bu sekilde eklemis oldugumuz kayitlari gorebiliriz.

STORED PROCEDURE

Stored procedure lar ayni zamanda bir deger de dondurebilir. Bu durumu gorebilecegimiz bir ornek yapalim.
Kullanicidan alacagimiz department id deki calisan sayisni dondurmek isteyelim. Oncelikle bunun icin gerekli stored procedure i yazalim.

create or replace procedure shownum (
dept_id in Employees.Department_Id%Type,
empCount out number
)
as
begin
select count(*) into empCount from Employees
where Department_Id = dept_id;
end;
/



import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Scanner;

public class OutSpEx01 {

 public static void main(String[] args) {
  try (Connection conn = DBUtil.getConnection(DBType.ORADB);
    CallableStatement cstmt = conn.prepareCall("{call shownum (?,?)}");
    Scanner scan = new Scanner(System.in);  ) {
   
   System.err.println("Enter department id: ");
   int deptid = scan.nextInt();
   cstmt.setInt(1, deptid);
   cstmt.registerOutParameter(2, Types.INTEGER);
   cstmt.execute();
   
   int totalCount = cstmt.getInt(2);
   System.out.println("Total number of employees work in department "+ deptid + " is "+ totalCount);
   
  } catch(SQLException e){
   DBUtil.showErrorMsg(e);
  }
 }

}


RETURN MULTIPLE ROWS FROM STORED PROCEDURE

Stored procedure dan multiple row dondurmek istedigimizde data type olarak SYS_REFCURSOR kullanmaliyiz.

Verilen department id de calisanlarin bilgilerini dondurecek bir sp yazalim.

Create or replace procedure GETEMPLOYEES
(
p_deptid in employees.department_id%type,
p_persons out SYS_REFCURSOR
)
as
begin
open p_persons for
select employee_id, first_name || last_name as ename,
email, salary from employees
where department_id = p_deptid
order by employee_id;
end;
/

Simdi ise gerekli kodumuzu yazalim.


import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
import oracle.jdbc.internal.OracleTypes;

public class ReturnMultipleRowsSp01 {
 public static void main(String[] args){
  
  try (Connection conn = DBUtil.getConnection(DBType.ORADB);
    CallableStatement cstmt = conn.prepareCall("{call getemployees(?,?)}");
    Scanner scan = new Scanner(System.in); ) {
   
   System.out.println("Enter deparment id :");
   int deptid = scan.nextInt();
   
   cstmt.setInt(1, deptid);
   cstmt.registerOutParameter(2, OracleTypes.CURSOR);
   cstmt.execute();
   ResultSet rs = ((oracle.jdbc.internal.OracleCallableStatement)cstmt).getCursor(2);
   String format = "%-4s%-20s%-25s%-10f\n";
   while(rs.next()){
    System.out.format(format, rs.getInt("employee_id"), rs.getString("ename"), rs.getString("email"), rs.getDouble("salary"));
   }   
  } catch(SQLException e){
   DBUtil.showErrorMsg(e);
  }
 }
}


1 Ekim 2017 Pazar

Hibernate with H2 Database / H2 Veritabani Hibernate Ornek

Bu yazimda Hibernate ve H2 database kullanarak kullanici ekleme, silme islemlerini anlatacagim.
Bunun icin eclipse de Dynamic Web Project olusturuyoruz.


Ayarlari bu sekilde yaptiktan sonra Configuration kismi icin Modify diyoruz. Ve gelen ekrandan Java Server Faces kismini secili hale getiriyoruz.



Daha sonra Next diyerek devam ediyoruz. Gelen ekrandan Generate web.xml kismini da secili hale getiriyoruz.

Next kismindan User Library ekle diyerek majorra adinda bir library olusturup icine gerekli jarlarimizi ekliyoruz.



Ve Finish diyerek projemizi olusturmus oluyoruz.

H2 database de Person adinda bir tablo olusturuyoruz. Bunun icin su query i kullanalim:

CREATE TABLE Person ( personid int NOT NULL, name varchar(100) NOT NULL, lastname varchar(100) NOT NULL, age int NOT NULL, nationality varchar(100) NOT NULL, PRIMARY KEY(personid))

Burada ise proje structure yer aliyor.

Projem calistiginda ekranim ise su sekilde oluyor.


Projenin kodlari burada yer almaktadir. https://github.com/geallen/javaHibernate

7 Eylül 2017 Perşembe

Date Format Islemleri

Elimizde string formatinda date olsun.
yani su sekilde "201709071826"
gordugumuz gibi bu aslinda hem date hem time iceren bir string. ama bu halde hic bir sey anlasilmiyor. aslinda su sekilde olsa 2017/09/07 18:26 cok daha anlasilir olacak. ama tabiki de bu islemi string olan deger uzerinde yapamayiz. o yuzden once elimizdeki string i date e cevirmemiz lazim. ve simple date format ile var olan formatini parse etmeliyiz yani /siz halini.

Daha sonra elde ettigimiz Date objesi icin / ekleme yapmak amaciyla yeni bir simple date format olusturmaliyiz. Date i ona parse etmeliyiz.





String dateTxt = "201709071826";
Date date = new Date();

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm") ;

try{ 

       date = sdf.parse(dateTxt);
// date eklendi. simdi okunablirligi attirmak amaciyla / eklicez, bunun icin yeni bir simpledateformat olusturcaz

    } catch(ParseException e){

          e.printStackTrace();

    }

SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy/MM/dd HH:mm");

String formattedDate = sdf2.format(date);

System.out.println(formattedDate); // 2017/09/07 18:26 elde ederiz.


30 Ağustos 2017 Çarşamba

JAVA - SETS



package datastructures;

import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.TreeSet;

public class Sets {

 public static void main(String[] args) {
  // hashset is random order
  Set animals = new HashSet();
  animals.add("dog");
  animals.add("pig");
  animals.add("hog");
  animals.add("cow");
  
  System.out.println(animals);
  
  animals.add("hog");
  animals.add("cow");
  animals.add("groose");
  // same elements does not add again
  System.out.println(animals);

  // linked hash set is same order in added
  Set animals1 = new LinkedHashSet();
  animals1.add("chicken");
  animals1.add("pig");
  animals1.add("snake");
  animals1.add("cow");
  
  System.out.println(animals1);
  
  // Difference of animals from animals1
  Set differenceSet = new HashSet(animals);
  differenceSet.removeAll(animals1);
  System.out.println(differenceSet);
  
  // Union of animals from animals1
  Set unionSet = new HashSet(animals);
  unionSet.addAll(animals1);
  System.out.println(unionSet);
    
  
  // tree set is in alphabetical order
  Set animals2 = new TreeSet();
  animals2.add("dog");
  animals2.add("pig");
  animals2.add("hog");
  animals2.add("cow");
  
  System.out.println(animals2);
 }

}


Here is the output:

[hog, cow, dog, pig]
[groose, hog, cow, dog, pig]
[chicken, pig, snake, cow]
[groose, hog, dog]
[groose, hog, chicken, snake, cow, dog, pig]
[cow, dog, hog, pig]

26 Ağustos 2017 Cumartesi

Java Arrays - For and ForEach Loop - Single And Multi Dimensional Arrays


public class Arrays {

 public static void main(String[] args) {
  String[] alphabet = {"a", "b", "c", "d", "e", "f", "g"};
  
  // With for loop
  
  System.out.println("Old fashioned way");
  int size = alphabet.length;
  
  for(int i=0; i< size; i++){
   System.out.print(alphabet[i] + " ");
  }

  // With for-each loop
  System.out.println("\n\nWith For-Each Loop");
  
  for(String letter : alphabet){
   System.out.print(letter + " ");
  }
 }

}


Here is the output:

Old fashioned way
a b c d e f g 

With For-Each Loop
a b c d e f g 

Here with multi dimensional array example



public class Arrays {
      public static void main(String[] args) {
       // Double Arrays
  String[][] users = {
    {"Jon", "Snow", "js@test.com","78965412"},
    {"Dany", "Targeryan", "dt@test.com", "45632101"},
    {"Arya", "Stark", "as@test.com", "12304569"}
   };
  
  int numOfUsers = users.length;
  int numOfFields = users[0].length;
  
  // With old fashioned way
  System.out.println("\n\nWith old Fashoned Way");
  for(int i=0; i< numOfUsers; i++){
   for(int j=0; j< numOfFields; j++){
    System.out.print(users[i][j] + " ");
   }
   System.out.println();
  }
  
  // Little More Intelligent Way
  System.out.println("\n\nLittle More Intelligent Way");
  for(int i=0; i< numOfUsers; i++){
   String name= users[i][0];
   String lastname = users[i][1];
   String mail = users[i][2];
   String phone = users[i][3];
   System.out.println(name+ " " + lastname+ " " + mail + " " + phone);
  }
  
  // With ForEach Loop
  System.out.println("\n\nWith ForEach Loop");
  for(String[] user: users){
   for(String us: user){
    System.out.print(us + " ");
   }
   System.out.println();
  }
 }

}


Here is the output:

With old Fashoned Way
Jon Snow js@test.com 78965412 
Dany Targeryan dt@test.com 45632101 
Arya Stark as@test.com 12304569 


Little More Intelligent Way
Jon Snow js@test.com 78965412
Dany Targeryan dt@test.com 45632101
Arya Stark as@test.com 12304569


With ForEach Loop
Jon Snow js@test.com 78965412 
Dany Targeryan dt@test.com 45632101 
Arya Stark as@test.com 12304569 

Java - Dosyadan Okunan Sayi Telefon Numarasi mi Kontrol Etme

Dosyada yazili olan sayiyi okuyacagiz. Ve bu sayi bir telefon numarasi mi anlamaya calisacagiz.
Okunan sayinin telefon numarasi olmasi belli kritirler var.
Valid phone numbers:

  •  10 digits long 
  • Area code cannot start in 0 or 9 
  • There cannot be 911 in phone number
Bu kosullara uymayanlar icin User defined exception olusturacagiz.


import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class PhoneNumberApp {
 public static void main(String[] args) {
  String filename = "C:\\Users\\Gamze\\Java Udemy\\phoneNumber.txt";
  String phoneNum = null;
  
  File file = new File(filename);
  
  try {
   BufferedReader bf = new BufferedReader(new FileReader(file));
   phoneNum = bf.readLine();
   System.out.println(phoneNum);
   bf.close();
   
  } catch (FileNotFoundException e) {
   System.out.println("ERROR: File is not found "+ filename);
   e.printStackTrace();
  } catch (IOException e) {
   System.out.println("ERROR: Data could not read " +filename);
   e.printStackTrace();
  }
  
  // Valid phone numbers:
  // 10 digits long
  // Area code cannot start in 0 or 9
  // There cannot be 911 in phone number
  
  try{
  if(phoneNum.length() != 10) {
   throw new TenDigitsException(phoneNum);
  } if(phoneNum.substring(0, 1).equals("0") || phoneNum.substring(0,1).equals("9")){
   throw new AreaCodeException(phoneNum);
  } if(phoneNum.contains("911")){
   throw new EmergencyCodeException(phoneNum);
  }
  } catch(TenDigitsException ex){
   System.out.println("ERROR: Phone number is not 10 digits");
  } catch(AreaCodeException ex){
   System.out.println("ERROR: Phone number cannot start with 0 or 9");
  } catch(EmergencyCodeException ex){
   System.out.println("ERROR: Phone number cannot contain emergency code");
  }
 }
}

class TenDigitsException extends Exception{
 String num;
 TenDigitsException(String num) {
  this.num = num;
 }
 public String toString(){
  return ("Ten Digits Exception "+num);
 }
}

class AreaCodeException extends Exception{
 String num;
 AreaCodeException(String num){
  this.num = num;
 }
 public String toString(){
  return ("AreaCodeException "+num);
 }
}
class EmergencyCodeException extends Exception{
 String num;
 EmergencyCodeException(String num){
  this.num = num;
 }
 public String toString(){
  return ("EmergencyCodeException "+ num);
 }
}


Java - Dosya Okuma / Yazma - Error Handling

Okuma Islemi

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class FileOperations1 {

 public static void main(String[] args) {
  // 1. Define the path that we read the file
  // \ younunu ya / yap ya da \\ kullan. 
  // java bu sekilde anliyor.
  String filename = "C:\\Users\\Gamze\\Java Udemy\\FileToRead.txt";
  String text = null;
  
  // 2. Create the file in Java
  File file = new File(filename);
  
  // 3. Open the file
  BufferedReader br;
  
  // alt satirda exception handling lazim.
  //cunku o isimde bir dosya bulunmayabilir.
  try {
   br = new BufferedReader(new FileReader(file));

   
   // 4. Read the file
   // dosya okunmasi sirasinda txt olamyabilir.
   // ppt veya image olabilir. hata handling lazim
   text = br.readLine();
   
   // 5.Close the resources
   br.close();
   
  } catch (FileNotFoundException e) {
   System.out.println("ERROR:File is not found "+ filename);
   e.printStackTrace();
  } catch (IOException e) {
   System.out.println("ERROR:Could not read the data "+ filename);
   e.printStackTrace();
  } finally {
   System.out.println("Finished reading file");
  }
  System.out.println(text);
  
  
 }

}


Here is the output:
Finished reading file
This is the file for reading purpose.

Yazma Islemi

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;

public class FileOperations1_Write {

 public static void main(String[] args) {
  // 1. Define the path
  String filename = "C:\\Users\\Gamze\\Java Udemy\\FileToWrite.txt";
  String text = "I am writing to this file.";
  
  // 2. Create the file in java
  File file = new File(filename);
  
  // 3. Open file writer
  FileWriter fw;
  try {
   fw = new FileWriter(file);
   // 4. Write to file
   fw.write(text);
   
   // 5. Close the file
   fw.close();
   
  } catch (IOException e) {
   System.out.println("ERROR: Could not read the file " + filename);
   e.printStackTrace();
  } finally {
   System.out.println("Closing the file writer.");
  }
  

 }

}


Bu isimde bir dosya olusturulup icine mesaji yazar.

18 Ağustos 2017 Cuma

Php sonuclarini html de gosterme

Mysql ile olusturdugum veritabanindaki kayitlari php cekiyorum. Bunlari android de kullanacagim. Hem bu verileri debug etmek hem de denemek amaciyla sonuclari html de gostermek istedim.

Wamp serverimin www klasorunde loginform01 diye bir klasor olusturdum ve gerekli dosyalari oraya koydum. Simdi ise bana gerekli olan iki dosyayi gosterecegim. ilki init.php. burada veritabani baglantisini olusturuyoruz. Digeri ise xx.php burda da veritabanindaki kayitlari sirasiyla cekiyorum.

init.php

<?php
$host = "localhost";
$db_user = "root";
$db_password = "";
$db_name = "example_test";

$con  = mysqli_connect($host, $db_user, $db_password, $db_name);

if($con){
echo "Connection success ...";
}else{
echo "Connection failed ...";
}

?>


xx.php

<?php
require "init.php";
$sql = "select uname from user";
$result = mysqli_query($con, $sql);
    while ($row = mysqli_fetch_array($result)) {
        ?>
            <div>
 
<p><?php echo $row['fcm_token'] ?></p>
            </div>
        <?php
    }
?>


Bu sekilde veritabanindaki kayitlari ekranda paragraf olarak gostermis oluyoruz.

8 Ağustos 2017 Salı

ANDROID - FIREBASE UPDATE OPERATION

I want to update my record in my firebase database table. I will update order cost as 10 which has primary key as: "20170807192734".




Here is the query I should write to update:



final FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference dbRef = firebaseDatabase.getReference("orders");
String primaryKey = "20170807192734";
dbRef.child(primaryKey).child("cost").setValue("10");


Firebase veritabanimdaki orders tablosundaki "20170807192734" primary key e sahip olan kayitin costunu 10 olarak guncellemek istersem yazmam gereken kodlar yukaridaki gibi olmalidir.

6 Ağustos 2017 Pazar

ANDROID - FIREBASE KULLANIMI

Android uygulamalarimizda veritabani islemleri icin ve bircok islem icin (ornegin bildirim) Firebase kullanabiliriz.

bu uygulamada firebase i uygulamama ekledim. Veritabanina iki tane tablo ekledim. Users ve siparis olmak uzere 2 tablo. bu iki tabloya kayit ekleme ve user tablosundaki kayitlari cekerek list view de gosterme isini yaptim. kodlar github hesabimda yer almaktadir.


27 Temmuz 2017 Perşembe

FRAGMENTLER ARASI VERİ GEÇİŞİ - ANDROID

Fragment sayesinde ayni ekran icinde bir cok islem yapabiliriz. Yeni bir activity olusturmak yerine bir activity icine birden fazla fragment olustururuz. Hem bu sekilde yeniden sayfa yuklenmesine gerek olmadigi icin uygulamamiz daha hizli calisir.

Bu uygulamamizda ust kisimda bir buton olacak ve alt kisimda textbox yer alacak. Butona tiklandikca altta kac defa tiklandigi yazacak. Bunun icin iki tane Fragment olusturacagiz. Ve bu fragmentler arasinda veri tasinmasi gerekiyor. Bu tasinacak veri butona kac defa tiklandigi bilgisi olacak. Fragment B bu bilgiyi alip textview de gosterecek. Bu iki fragment arasinda veri aktarimini interface yardimiyla yapacagiz. Asagiya en sonda ekraninin nasil goruneceginin resmini koyacagim.


Simdi sirasiyla kodlarimi asagiya ekleyecegim.


fragment_a.xml




fragment_b.xml







FragmentA.java


import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

public class FragmentA extends Fragment implements View.OnClickListener {

    Button btnTikla;
    int counter = 0;
    VeriAkisi veriAkisi;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_a, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        btnTikla = ((Button) getActivity().findViewById(R.id.clickMeBtn));
        btnTikla.setOnClickListener(this);
        veriAkisi = ((VeriAkisi) getActivity());
    }

    @Override
    public void onClick(View view) {
        counter++;
        veriAkisi.veriAktar("Butona "+counter+" defa tiklandi");
    }
}



FragmentB.java

import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class FragmentB extends Fragment {

    TextView tikSayisi;
    String text;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_b, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        tikSayisi = (TextView)getActivity().findViewById(R.id.tikSayisi);
    }

    public void tiklanmaSayisiniGoster(String text){
        this.text = text;
        tikSayisi.setText(text);
    }
}



VeriAkisi.java

public interface VeriAkisi {
    public void veriAktar(String data);
}



activity_main.xml




MainActivity.java


import android.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity implements VeriAkisi {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public void veriAktar(String data) {
        FragmentManager manager = getFragmentManager();
        FragmentB fragmentB = (FragmentB) manager.findFragmentById(R.id.fragment5);
        fragmentB.tiklanmaSayisiniGoster(data);
    }
}



Ve uygulamamiz calisir.

kaynak: burada

21 Temmuz 2017 Cuma

HAFIZA ERISIM HIZLARI

Bilgisayarda en hizli erisim sirayla:
Cache
Memory
Harddisk
External diskler
dir. En hizli erisim, hafizanin cache'ine yapilir. Daha sonra hafizanin kendisine, daha sonra harddiske yapilir. Cache ve memory erisimleri arasinda 4-5 kat hiz farki varken, harddisk erisimi, hafiza erisiminden 50-200 kat yavastir. Bu nedenle, en yuksek performans icin mumkun oldugu kadar hafizayi kullanmayi tercih etmelisiniz. Bilgisayarinizin uzun sure acik kaldiktan sonra yavaslamasi bu nedendir (hafiza bilgisayar acildigindan itibaren dolmaya baslar ve bir sure sonra, cok dolu olacagi ve bazen de gereksiz programlar tarafindan isgal edilecegi icin hafizanizdaki bos yer azalir) Bircok programin ayni anda calismasi da, hafizanin cok yogun kullanilip bilgisayarin yavaslamasina bir ornektir. (Network erisimi, USB disk erisimi, CD erisimi, SCSI disk erisimi gibi erisimler harddiskten cogu zaman yavastir.

Kaynak : http://ege-akpinar.blogspot.com/2009/06/javada-inputoutput.html

20 Temmuz 2017 Perşembe

JAVA VERİTABANI BAĞLANTISI - SQL SERVER

Java ile veritabanindan veri listeleme islemi yapacagiz. Bunun icin oncelikle JDBC drivera ihtiyacimiz var. Buradan indirebilirsiniz. .exe uzantili olan linki indirip unzipliyoruz. Daha sonra uygun jar file i kullanabiliriz. Ben sqljdbc4.jar i kullandim.

Eclipse de yeni bir proje olusturup sag tiklayarak -> Properties -> Java Build Path kisminda add external jar diyerek indirdigimiz jar i projemize dahil ediyoruz.

Simdi classimizi olusturup kod kismina gecelim.


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

public class Dbop {

 public static void main(String args[]){
  try{
   Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
   System.out.println("Driver loaded");
   
   String server= "localhost\\sqlexpress";
   int port = 1433;
   String user= "TestUser";
   String pass = "123456";
   String db = "ExampleDb";
   
   String jbcUrl = "jdbc:sqlserver://"+ server+ ":"+port+";user="+user+"; password="+pass +"; databaseName="+db+"";
   
   Connection con = DriverManager.getConnection(jbcUrl);
   System.out.println("connection obtained");
   
   Statement stmt = con.createStatement();
   System.out.println("Statement created");
   
   ResultSet rs = stmt.executeQuery("Select Username, Phone from [User]");
   System.out.println("Query executed");
   
   while(rs.next()){
    System.out.println("Username "+ rs.getString(1) + " Phone "+ rs.getString(2));
   }
   rs.close();
   stmt.close();
   con.close();
   
   System.out.println("Resource released");
   
  }catch(Exception ex){
   System.out.println("Error: " + ex);
  }
  
 }
}



ResultSet sonuclari indeks 1 den baslar. O yuzden Username i gostermek icin getString(1) i kullandik. Istersek indeks yerine sutun adini da yazarak verilere ulasabiliriz.

rs.getString("Username") seklinde.

Outputum su sekilde olacak:


Driver loaded
connection obtained
Statement created
Query executed
Username Mary Phone 05348784250
Username John Phone 05987545123
Username Joe Phone 23654178925
Username Peter Phone 78963254101
Resource released



Yararlandigim kaynak burdadir.

11 Temmuz 2017 Salı

Installation failed with message Failed to finalize session : INSTALL_FAILED_INVALID_APK: Split lib_slice_0_apk was defined multiple times. It is possible that this issue is resolved by uninstalling an existing version of the apk if it is present, and then re-installing. WARNING: Uninstalling will remove the application data!


I get this error on Android Studio. Because I copied my project to another directory. When I run the project in the directory that I copied from, project run without any error.

If we want to run the project that is in new location, then there are some thing we need to do. From top menu, Build -> Clean Project then Build -> Rebuild Project. Then when we run, we do not get any error.

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

Projemi calistirirken Android Studio dan bu sekilde bir hata aldim. Hatayi arastirdigimda buldugum sonuclardan biri benim yasadigim duruma benziyordu. Projemi baska bir lokasyona kopyalamistim. Ve kopyaladigim yerdeki projeyi acinca bu sekilde bir hata aliyordum. Projeyi ilk bulundugu konumdan actigimda ise calistirdigimda hatasiz sekilde calisiyor.

Ancak yeni bulundugu konumdan calistirmak istiyorsak oncelikle ust menude yer alan Build -> Clean Project yapmaliyiz. Daha sonra yine Build -> Rebuild Project yapmaliyiz. Eger hatamiz devam ederse birkac kez tekrar etmeliyiz. Projemiz hatasiz calisacaktir.

8 Temmuz 2017 Cumartesi

ANDROID - SharedPreferences Kullanımı - Using SharedPreferences


Shared Preferences kullanarak uygulama kapansa bile kullanicinin bilgilerini koruyabiliriz. Bu sekilde tekrardan uygulamayi actiginda tekrardan login olmasina gerek olmaz. Bunun icin basit bir uygulama yaptim. Kodlar burada yer almakta. Ekran goruntuleri ise asagidadir.


By using SharedPreferences, even application closes,we can save the user's information. By this way when user again opens the application, there will be no need for user to login again. My code is in here. Screenshots of application is available in below.





28 Haziran 2017 Çarşamba

HELP DISABLED PEOPLE - MAKE EVERYONE VISIBLE

Hello everyone today I am going to talk about the website that I developed for disabled people. Here is the link. Click here for Turkısh version of this post.

Now I am going to explain the aim of the website and how to use it:
  • Helper and disabled person should register to system. If user type is selected as “Disabled” new text box should be appear for disabled to enter her/his story, what is her/his disability, what are her/his needs etc. If conditions are satisfied, operation should be completed succesfully.

  • If user type is selected as helper, they should have 2 pages available. One page for helper is home page. In helpers home page, story of disabled persons should be listed. Below every story there should be button to show comments about story, a button to report the post and a button to mark the post as helped. In the right corner of every post there should be “+” button to add that post to helpers’s list. Helper can write comment to learn more about disabled person.

  • Second page for helper is "My List" page. Helper can add a post to his list to follow disabled. 

  • If helper helped that disabled, he can click "Mark As Helped" button. By this way other helpers can see how many people helped a disabled.

  • Also helper can remove a post from his list.

  • If “helper” wants to report post for some reason (may think disabled person is not disabled in real life etc.),  he can click Report Post button that is placed under the story that he will report. If number of reports about a story becomes five, then disabled users acount becomes disable and that user cannot login to the system.

  • In disabled home page, they can only see their story and comment to their story. They can write comments to their stories also.

Now there are some data for trial purposes. I don't get any money from this project. I just want to make sure we can satisfy disabled person need. I write this here because by this way, many people can see and use it. I am open to any idea.

Thank you for reading. 

ENGELLİ BİREYLERE YARDIM ETMEK

Herkese merhaba bu yazımda tez projem olarak oluşturduğum siteden bahsetmek istiyorum.
Sitemin linki burada yer alıyor.  Click here for English version of this post.

Ben öncelikle işlevinden bahsetmek istiyorum. 
  • Yardıma ihtiyacı olan engelli bireyler, kendileri yapamayacak durumdaysa onlar adına bir kişi, sisteme üye oluyorlar. Üye olurken kendilerinde kısaca hastalıkları ve ihtiyaçları hakkında bilgi girmeleri bekleniyor.

  •  Gönüllü kişiler sisteme giriş yaptıklarında giriş yaptıklarında anasayfalarında engellilerin hikayelerini görüyorlar. Yorum yapıp daha fazla bilgi sahibi olabiliyorlar. Daha yakından takip etmek için kendi listelerine ekleyebiliyorlar. 

  • Gönüllü üyeler yardım ettikleri engelli bireylerin hikayelerini yardım edildi olarak işaretleyip diğer kişilerinde kaç kişi tarafında yardım edildiği konusunda bilgi sahibi olması sağlanıyor. Bu şekilde gönüllü üyelerimiz daha fazla yardıma ihtiyacı olan kişilere yardım edebiliyorlar. 

  • Gönüllü üyeler eğer engelli bireyin hikayesinin gerçek olduğuna inanmıyorsa, engelli kişinin hikayesini şikayet edebilirler. Şikayet sayısı 5 olduğunda engelli kişinin sisteme giriş yapması engelleniyor. 

  • Engelli birey ise sayfasında sadece kendi hikayesini ve yapılan yorumları görebilir. Yorum yapabilir.
Şu an sitede deneme amaçlı veriler yer alıyor. Bu proje üzerinden herhangi bir maddi kazancım yok.  Sadece ihtiyacı olan kişilere ulaşmasını ve yardımcı olmasını istiyorum. Ve buradan mümkün olduğunca çok kişiye duyurmayı amaçlıyorum. Önerilere açığım.

Okuduğunuz için teşekkür ederim.

24 Haziran 2017 Cumartesi

ANDROID - FOTOGRAF VE VIDEO CEKMEK - USING CAMERA AND VIDEO

Bu yazimda fotograf ve video cekmeyi ve bunlari ekranda gostermeyi anlatacagim. Bunun icin camera kullanacagiz.
Projemizi olusturup activity_main.xml layoutumuza iki tane button, imageView ve videoView ekleyecegim. Butonlardan birisi fotograf cekmek, digeri ise video cekmek icin olacak. ImageView resimleri gostermek, videoView ise cekilen videoyu gostermek icin kullanilacak.


activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context="com.example.gamze.cameraandvideoexample.MainActivity">


    <Button        android:id="@+id/imageButton"        android:layout_width="match_parent"        android:layout_height="wrap_content"
        android:text="Take Picture" />

    <Button        android:id="@+id/videoButton"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="Capture Video" />

    <ImageView        android:id="@+id/imageView"        android:layout_width="wrap_content"        android:layout_height="wrap_content" />
    <VideoView
        android:id="@+id/videoView"        android:layout_width="wrap_content"        android:layout_height="wrap_content" />
</LinearLayout>


Simdi ise MainActivity.java dosyamiza gerekli kodlari ekleyelim.


package com.example.gamze.cameraandvideoexample;

import android.content.Intent;
import android.graphics.Bitmap;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.VideoView;

public class MainActivity extends AppCompatActivity {

    private ImageView imageView;
    private VideoView videoView;
    private static final int IMAGE_REQUEST =1;
    private static final int VIDEO_REQUEST = 2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button takePicButton = (Button) findViewById(R.id.imageButton);
        takePicButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                imageView = ((ImageView) findViewById(R.id.imageView));
                Intent pic_intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(pic_intent, IMAGE_REQUEST);
            }
        });
        Button captureVideoButton = ((Button) findViewById(R.id.videoButton));
        captureVideoButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                videoView = (VideoView)findViewById(R.id.videoView);
                Intent video_intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
                startActivityForResult(video_intent,VIDEO_REQUEST);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode != RESULT_OK) return;
        else if(requestCode == IMAGE_REQUEST){
            Bitmap image = (Bitmap)data.getExtras().get("data");
            imageView.setImageBitmap(image);
        }
        else if(requestCode == VIDEO_REQUEST){
            videoView.setVideoURI(data.getData());
            videoView.setMediaController(new MediaController(this));
            videoView.requestFocus();
            videoView.start();
        }
    }
}


Son durumda ekranimiz nasil gorunuyor ona bakalim.




ANDROID WEBVIEW OLUSTURMA - CREATING WEBVIEW

Merhaba, bugunku yazimda Android uygulamalarimizda WebView kullanimini anlatacagim. Oncelikle WebView nedir bunu ogrenelim. WebView sayesinde uygulamalarimiz icinde web sayfalarini acabiliriz. Bu sekilde uygulamamiz kapanmaz ve biz web sayfasina erisebiliriz.

Yeni proje olusturalim.Herseyden once bunu yapabilmemiz icin internete erismemiz gerekir. Yani bunun iznini almaliyiz. Bunun icin izinleri yazdigimiz kisim olan AndroidManifest. xml e internet erisim kodunu eklemeliyiz. Bunun icin application taginin oncesine asagidaki kod satirini eklemeliyiz.

&lt;uses-permission android:name="android.permission.INTERNET" /&gt;

Daha sonra activity_main.xml e gidip ordaki layoutu linear layout a cevirelim ve bir web view ekleyelim.

activity_main.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="com.example.gamze.webwiewexample.MainActivity">


    <WebView        android:id="@+id/webWiewId"        android:layout_width="match_parent"        android:layout_height="match_parent" />
</LinearLayout>

Simdi ise MainActivity.java ya gecip kodlarimizi yazalim. Yapmamiz gereken sey su:

  • Ekledigimiz web view i id ile alacagiz. 
  • Daha sonra javascript kodlarinin eklenmesini sagliyoruz.
  • Acilmasini istedigimiz url i ekliyoruz.
MainActivity.java



package com.example.gamze.webwiewexample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        WebView webView = ((WebView) findViewById(R.id.webWiewId));
        webView.getSettings().setJavaScriptEnabled(true);
        webView.loadUrl("http://gamzesen123.blogspot.com.tr/");
    }
}


Bu sekilde calistirdigimizda verdigimiz url ekranimizda aciliyor. Isterseniz bir buton ekleyip o butona tikladiginda sitenin acilmasini saglayabilirsiniz.

Ekran goruntumuz su sekilde olacaktir.


23 Ocak 2017 Pazartesi

SQL QUERY - GET TODAY'S DATE



DECLARE @FistDate DATETIME = (SELECT DATEADD(m, DATEDIFF(m,0,GETDATE()),0))
DECLARE @TODAY DATETIME = (SELECT GETDATE())

SELECT DATEADD(day, 1, GETDATE()), DATEADD(day, DATEDIFF(day,0,GETDATE()),0), @FistDate,@TODAY


seklinde cikti aliriz.



SELECT DATEADD(m, DATEDIFF(m,0,GETDATE()),0) + ' ' + (select convert(varchar(10), GETDATE(), 108))

ayin ilk gunu ile su an ki zamani birlestirme