Tuesday, April 23, 2013

Difference Between View.GONE && View.INVISIBLE

DIFFERENCE BETWEEN 

VIEW.GONE && VIEW.INVISIBLE


    Nearly all the android widgets that we use have the function that is setVisibility that helps to hide or show them on the surface.
    We can hide or show or remove the view.

Hiding is to changing the content with the blank, for example you can see the default view below(  Note: The White area is the webview)

Now lets make the update map button view.gone as you can see below

Now lets make the update map button view.invisible you can see below




Removing is to deleting the content from view. So hide function will still be in view tree however as a blank view. Remove will not be in view tree more.

Thursday, March 14, 2013

ANDROID SPINNERS

                                      ANDROID SPINNERS

Android has spinner structure like comboboxes in html.

I will explain to create default spinner in 2 ways.
First one is declaring resources as static in xml
Second one is declaring resources as programmatically in Java

First
You should declare your spinner resource in xml layout file such as

<RelativeLayout 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">

    <Spinner
        android:id="@+id/declaredSpinner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="133dp"
        android:entries="@array/resources" />

</RelativeLayout>


And then you should create a resources in strings.xml file
<string-array name="country_arrays">
        <item>Malaysia</item>
        <item>India</item>
        <item>Indonesia</item>
        <item>France</item>
        <item>Italy</item>
        <item>Singapore</item>
        <item>New Zealand</item>
</string-array>

And then you should handle your spinner functions in you activity

Spinner declaredSpinner= (Spinner) findViewById(R.id.declaredSpinner);
declaredSpinner.setOnItemSelectedListener(new yourListener());

you should create your own class as inner in your activity

class YourListener(){

@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Selected", Toast.LENGTH_LONG).show();
}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Not Selected", Toast.LENGTH_LONG).show();
}

}

If you do not want to write inner class you can use class in function
declaredSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});

Second one needs to use adapter because you are creating your resources programmatically and you should
bind them through the spinner resources

So firstly you will declare your layout file such as below
<RelativeLayout 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">

    <Spinner
        android:id="@+id/declaredSpinner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="133dp"
/>

</RelativeLayout>

If you notice it is different according to the first.
Secondly you will open your activity class

1 ) Create your string arrays
String[] ustspinner = new String[5];
for(int i = 0 ; i < 5 ; i++){
ustspinner = ""+i;
}
2 ) create your arrayadapter with your string arrays
ArrayAdapter<String> defaultAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, ustsolspiner);
defaultAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
3 ) then set to your spinner
spinnerReference.setAdapter(defaultAdapter);
4 ) You can define your functions as the previous one.

The best one is creating your own customized spinner.
For example i want an image and then a text in my spinner how can we do?
We must create CustomizedAdapter.
Steps :
1 ) Create your own layout file in layout folder. Such as customizedspinner.xml
2 ) Get a reference to spinner
3 ) Create your own Customized spinners adapter that is extended from ArrayAdapter
4 ) set your adapter object to your spinner reference


-->
<?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="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="0.74" 
        android:background="@drawable/textdrawable">

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

            <ImageView
                android:id="@+id/imageView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/ido"
                android:contentDescription="@string/img" />
        </LinearLayout>

        <TextView
            android:id="@+id/spinerdatetext"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/blankForDate"
            android:textAppearance="?android:attr/textAppearanceMedium" />
    </LinearLayout>

</LinearLayout>


 class SpAD extends ArrayAdapter<String>{

@Override
public int getPosition(String item) {
// TODO Auto-generated method stub
return 4;
}
public SpAD(Context context, int textViewResourceId,   String[] objects) {
            super(context, textViewResourceId, objects);
        }
@Override
        public View getDropDownView(int position, View convertView,ViewGroup parent) {
            return getCustomView(position, convertView, parent);
        }
 
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
   LayoutInflater inflater=getLayoutInflater();
            View row=inflater.inflate(R.layout.spinerdate, parent, false);
            TextView label=(TextView)row.findViewById(R.id.spinerdatetext);
            label.setText(tenDays[position]);
            ImageView icon=(ImageView)row.findViewById(R.id.imageView1);
            icon.setImageResource(R.drawable.ido);
            return row;        
}
}
//Come to your own activity file
String[] days = tenDays();
       SpAD dataAdapter1 = new SpAD(this,R.layout.customizedspinner, days);
spinerdate.setAdapter(dataAdapter1);



Tuesday, March 12, 2013

SQLiteDatabase

                           SQLITE DATABASE



If you want to save your data to your storage of your device it is one of the easiest way to use SQLite
Basically we will use context to open or create a database and then we will use the SQLiteDatabase class to provide table or data to database also query the database
tables at last we will focus on to Cursor to trace the records on tables

context.openOrCreateDatabase("tablename",/*mode of table*/,null);
mode of table is related the permission of the table
as you know databases for the each program is different in device you can look your DDMS data/data/yourpackagename/databases
so if another program wants to reach to another programs database there should be permission for the table defined when it is created
1 ) If you want another program to reach your database your mode should be MODE_WORLD_READABLE or MODE_WORLD_WRITABLE
2 ) If you want another program not to reach your database your mode should be MODE_PRIVATE
now lets move on.

SQLiteDatabase sqlite = this.openOrCreateDatabase("abctable",MODE_PRIVATE,null);
sqlite.execSQL("CREATE TABLE ABC (F1 VARCHAR);");
sqlite.execSQL("INSERT INTO CAN (F1) values ('ABC') ");

--> Now second important class we will look at. That is Cursor which is associated with pointer structure. It enables you to trace your table rows.
Cursor cursor = sqlite.rawQuery("SELECT * FROM ABC");
Then if you use the code below you can be sure the cursor is on the first row
cursor.moveToFirst();
String str = cursor.getString(0);

now you handled the data from database of your device.


package com.example.myxdb;

import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;

public class MainActivity extends Activity {
SQLiteDatabase mydb = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
mydb = this.openOrCreateDatabase("tablename", MODE_PRIVATE, null);
mydb.execSQL("CREATE TABLE ABC  (F1 VARCHAR);");
mydb.execSQL("INSERT INTO ABC (F1) VALUES ('DATABC')");
Cursor cursor = mydb.rawQuery("SELECT * FROM ABC", null);
cursor.moveToFirst();
String str = cursor.getString(0);
} catch (Exception e) {
Log.e("Error In Database Operations ", null);
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

}





Monday, March 4, 2013

Android Customized Toast

                                                ANDROID CUSTOMIZED TOAST

If you want to warn the user or give an information briefly to the user we use toast most of time. Default toast is not enough for some of the situations so you can make your own toast such as showing images in toast or through styled writings. For example lets create a customized toast :

1 ) Create an xml file into the res-->layout folder of your android project give name as customized.xml

!! You can define relativelayout, linearlayout, tablelayout... whatever you want... And drag an imageview into the folder and choose your image from the menu lastly your xml should look like below.

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

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/sdcard" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/imageView1"
        android:layout_centerHorizontal="true"
        android:text="@string/pleaseinsertyoursdcard"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>
@drawable/sdcard you can open a folder as drawable into the res folder and put a picture named as sdcard into that folder.
Then come to your own activity class file that you want to show toast in it.

If you are in class that is extended from Activity you can code such below


 Toast toast = new Toast(getApplicationContext());
                  toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
                  toast.setDuration(Toast.LENGTH_LONG);
                  LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                  toast.setView(inflater.inflate(R.layout.plugsdcard,null));
                  toast.show();

Now your own toast file will be shown. You can change your layout xml according to your needs.

!!!! If you want to show your toast in a class file that is extended from BroadcastReceiver you can code such as below in onReceive(Context context, Intent intent) function:

Toast toast = new Toast(context);
//context is your app act. context equals to getApplicationContext in class that is extended from Activity class
                   toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
                   toast.setDuration(Toast.LENGTH_LONG);
                   LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                   toast.setView(inflater.inflate(R.layout.plugsdcard,null));
                   toast.show();


This small example can help your program being a little customized...

Saturday, March 2, 2013

Android Button Click

                                           ANDROID BUTTON CLICK

If you are developing android you always have to give response to button clicks. As there are lots of handling types of button clicks i would choose the type for the usage in code. For example you can define your Button in layout file xml as well as programmatic way in java. If you do not want to create new class and you do not want to deal with overriding functions you can write your function name into the xml file such as
In Layout Xml File

<Button
        android:id="@+id/writeToFile"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onclick = "writetofile"
        android:text="@string/writeTo" />

In Activity File
public void writetofile(View view){
 // View will be the clicked button
view.getVisibility();
}

I would choose this if i do not want to comply with complex code.

If i do not want to write into the xml file so i will write into the java file there are again 2 types.
Individual one is

Button button = (Button) findViewById(R.id.writeToFile);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
//Handle your code
                        }
}

If you do not want to open unique function for each type of button click you will register for a handler which is the second type in java.

While in activity
button.setOnClickListener(this);
//inside activity you will create the function below
public void onClick(View view)
{  
switch (view.getId()){
                        case R.id.writeToTextFile:
Toast.makeText(view.getContext(), "You pressed to Write To File", Toast.LENGTH_SHORT).show();
break;
                }
         }

So third one is beneficial for the usage of code(less code and more efficient function)

Thursday, February 28, 2013

Android Data Passing between Activities

                          PASSING DATA BETWEEN ANDROID ACTIVITES
This is very basic knowledge to pass data from one activity to another activity, first we will create an android project then its activity and we will create an layout xml and associate activity lastly we will call the second activity from first one with the data.

If you are using eclipse
File --> New --> New Android Application

Then come to the layout folder and create an android layout xml file.

Then come to the main package folder in src and create an class file named as Second.

Your new layout file

<?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="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

</LinearLayout>
Your new activity class

package com.example.datapassexample;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class Second extends Activity{

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
TextView textView = (TextView) findViewById(R.id.textView1);
Intent intent = getIntent();
if(intent.getExtras() != null)
{
String text = intent.getStringExtra("name");
textView.setText(text);
}
}

}
Your first activity class
package com.example.datapassexample;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText editText1 = (EditText) findViewById(R.id.editText1);
Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setClassName(getApplicationContext(), Second.class.getName());
intent.putExtra("name", editText1.getText().toString());
startActivity(intent);
}
});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

}

!!!!!!
The value that you pass in activity depends on the passed activity so there will be no value in another activity associated with this intent extra even if you use getIntent() function instead of new Intent() function.

So how can i get the same value in another activities?
There are lots of ways to get data in another activities such as you can write to your sqlite database or you can pass using intents again even you can send to any server you defined then you get the value from that server but the fast way is that i also use the singleton method you can store the value among the usage of program if there are some states that the program will be cancelled you should use db. Singleton is like below
open a new class named as Single
package com.example.datapassexample;

public class Single {
private static Single single;
private String name;
protected Single(){
}
public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public static Single getInstance(){
if(single == null){
single = new Single();
}
return single;
}
}

open your MainActivity
add this line into the button click function before startActivity function
Single single = Single.getInstance();
single.setName(editText1.getText().toString());

open your Second Activiy then insert code below
Single single = Single.getInstance();
String text = single.getName();
textView.setText(text);


Now you can use the value that you store in Single class in each of the activities for active states of the program.

Thursday, February 21, 2013

HOW TO ADD IMAGE INSIDE A DIV AND CONTINUE FOR A QUICK PROCESS

                        HOW TO ADD IMAGE INSIDE A DIV AND CONTINUE FOR A QUICK PROCESS
You can traverse the html tree and you can handle all the leafs individually that gives you possibility to play some part of tree. For example if you want to add a div then continue to work that can cause some problem such as you can not see new image in the specified div. Lets code for a button when we click it lets change the div' s image and continue with the other page. I used html5 on Lg and Samsung when i coded. For example this is the button below;


<a href="javascript:route();" id="signup" style="height: 200px; width: 100px"><div id="container"><IMG SRC="oldimage.gif" id="myid"></div></a>

now script turns;
<script type="text/javascript" >

function route(){
var willBeRemoved = document.getElementById("myid");
var container= document.getElementById("container");
container.removeChild(willBeRemoved);
var newimage = document.createElement("img");
oImg.src = "newPicture.gif";
container.appendChild(newimage);
setInterval(function(){changePage()},100);
}
function changePage(){
window.location.href="signup.html";
}

</script>

The code above will add functionality to change image before loading another page because of the process speed there will be no time to change the image but if you specify a duty to process the function it will find a spare time to change...

It is also problem in jquery mobile that if you want to show an information page in time of process you will use the function below;

$.mobile.showPageLoadingMsg("e", "Your Page Is Loading \n Please Wait", true);

the function above takes 2 argument first one is the theme of the window second one is the message that you want to show. Now if you use this function in the gap between two process that will work in a series that will show error in logcat so you can prevent such a strategy we followed for the image and div example.

Thursday, January 24, 2013

Android Phonegap(CORDOVA) Installation and First Project


Phonegap Installation and Using Phonegap
Do you prefer to develop web based device programs? Do you prefer to use your wide range of customized styles with your device feature? I prefer so i choosed phonegap. Phonegap is the old name of Cordova. Apache develops cordova i think so fast.If you compare the versions and their dates you will see the fast of the team.
In briefly cordova helps us to use device from js code. Js code that we will write has lots of built in features to use device functionalities. It does not matter the os of the device. All the de facto os are supported. I used for android and blackberry that enchant me.  They have also very effective documentations for the new-experienced developers from a to z that they published.
Creating the normal java android is the first aim. You will see this structure below.
However, before starting to code, firstly you should download the libraries from this link with the version you want and also you can check your feature availability from thir release posts.
http://phonegap.com/download/

The importants are src,asset, res(xml) folders and Config.xml, AndroidManifest.xml files. You should first examine the usage structure.

You will write your javascript code into html files that will be in asset folder.
You will give permission to the android that if you use device features from your javascript to the AndroidManifest.xml

You will write the cordova plug in definitions to the config.xml file that is in xml folder of the res folder.

Then you will call your html file from your java code that is extended from DroidGap.

Now lets code we will write a vibrating function fort he android device.

To the AndroidManifest.xml file add this
<uses-permission android:name="android.permission.VIBRATE" />
To the xml folder config.xml add this
<plugins>
<plugin name="Device" value="org.apache.cordova.Device"/>
    <plugin name="Notification" value="org.apache.cordova.Notification"/>
</plugins>
Now lets code js.Js will use the cordova-x.y.z.js file that you should put this file into the file you Show from src.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>First Example</title>
<script type="text/javascript" src="cordova-2.3.0.js"></script>
</head>
<body>
<script type=”text/javascript”>
document.addEventListener("deviceready", onDeviceReady, false);
    function onDeviceReady() {
        navigator.geolocation.getCurrentPosition(onSuccess, onError);
    }
function onDeviceReady(){
navigator.notification.vibrate(8000);
}
</script>
Hi
</body>
</html>


Now lets code the Java
package a.b.c;
import android.app.Activity;
import android.os.Bundle;
public class Hi extends DroidGap {

       @Override
       public void onCreate(Bundle savedInstanceState) {
                           super.onCreate(savedInstanceState);
                           super.loadUrl("file:///android_asset/yourhtml.html");
                            
       }
}
 android_asset means to bring inside your asset folder.
You will encounter some wrongs like DroidGap your should put the cordova.jar of android to your libs folder.
After the wrongs cleared now try if you encounter Cordova class not found try to put your cordova.jar to your path from the properties of your Project or your folders such as res/xml/config.xml can be wrong named.

This framework gives a big chance for mobile developers to use wide range of styles through using the device features. When you run the application the all screen web view will be loaded to the device you run and the cordova structure will handle the device from its javascript definitions. If you examine these definitions deeply you will see the plug-in structure of the cordova that enables you to add new features maybe with this incredible framework...



Monday, January 21, 2013

Android Ring The Phone Programmatically


                          Samsung Galaxy Mini Ringing Alarm Sound Problem

When i was developing a small application that was using the default sounds with setting the volume of tone, used AlarmManager class
 AudioManager audioManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
int maxVolumeForDevice= audioManager .getStreamMaxVolume(AudioManager.STREAM_RING);
 audioManager.setStreamVolume(AudioManager.STREAM_RING, maxVolumeForDevice  AudioManager.FLAG_ALLOW_RINGER_MODES);

Firstly get Audiomanager and get the devices max volume (because all devices have different volume) then setting was the target but one of the android device i got good result but in the another device i could not get the good result if the phone was on silent state the volume was not changing so i used adjust function instead of set. That function was supporting some other attributes too such as raising the volume etc...
audioManager.adjustStreamVolume(AudioManager.STREAM_RING, AudioManager.ADJUST_RAISE, AudioManager.FLAG_ALLOW_RINGER_MODES); 
Then you should use RingtoneManager class for the sound file and then you should get the file from the specified path and then play the soud.

For the example of this small program is : https://play.google.com/store/apps/details?id=com.find.lostphone&feature=search_result#?t=W251bGwsMSwxLDEsImNvbS5maW5kLmxvc3RwaG9uZSJd

Wednesday, January 16, 2013

Struts Java Validation

                                           JAVA STRUTS VALIDATION
We have created an example struts java project and routed previously. Now lets control it if there is error or have the value that we do not want.
We will see
How to control automatically generated form bean?
How to route from control mechanism?

Form bean that is extended from ActionForm has a function named as validate which you can see if you click right while your cursor is in the form class then  open source and Override/Implement methods. Choose validate as in below.
This method will give ActionMapping and request object so you can use mapping.findForward(...) to route or you can use another mechanism that is if you return errors from this function that is in the type of ActionErrors, the struts mechanism will route it to the input tag. for example
<action path="/comingFormPath" name="ActionFormName" validate="true" input="MyErrorFile.jsp"
type="actionclass">

public ActionErrors validate(ActionMapping mapping, HttpServletRequest request){
ActionErrors errors= new ActionErrors();
//if there is error 
ActionMessage message = new ActionMessage("tag.in.properties.file");
actionErors.add("yourTag",message);
return errors;
}
So; if errors filled by add method then the struts structure will route it to the input file that the yourTag is your propertyNames will reflect the properties equalities that are attended with add method.

Monday, January 14, 2013

Struts Message Resource

                                                         STRUTS MESSAGE RESOURCE

Struts framework has a resource file mechanism that is very useful from first : it can be used as projects shared constant svn, secondly these are used for internationalization. File contains the name value pairs.

When you start your server that the project has been deployed on, the resource file will be ready for you to use. For example you can use them for labels as shown in below

<%@taglib uri="http://jakarta.apache.org/struts/tags-bean"% prefix="bean">
<bean:message key="name" />

This is easy as you can see.

The other function if you have properties file with different names such as

message-de.properties --> contains German
message-tr.properties --> contains Turkishmessage-fr.properties --> contains French
message-bg.properties --> contains Belgium
message_zh.properties --> contains Chinese

these files must be under your resource folder and you should introduce to your project from your struts-config.xml file such as below:
<message-resource parameter="yourfilepath">
Then you can see the different languages depends on the default language setting.

Java Character Encoding Part 2

                                         JAVA CHARACTER ENCODING PART 2

CHARACTER ENCODING PART 2
In one of my development phase the encoding type was the huge problem why foreign characters that are UTF-8 showed like undefined characters.
Problem was on Jsp page and  jsp had like the structure below

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF8" %>

As you can see above the document was coded on UTF8 and the content charset on screen will be displayed was also UTF-8
If you want to type special characters into your jsp page that you may want to use special characters for your variable names or etc... You should type your
pageEncoding to the desired type.

1 Problem and Solution

Suppose if you want to use special characters in the jsp coding but the pageEncoding does not permit it so what will you do?

My Solution  == If you use your special characters for displaying in your page i would use unicode of the characters with the appropriate encoding defined for
out or in, actually in is for getting the value from the querystring or from any other external as correctly typed.

As an example i will export a figure and an Hebrew character to display then Turkish Character to the console

As i notice that in most of the character encoding problems does not derive from the jsp encoding lots of time changing only charset of the pages did not give me
the right result.

1 ) Server language parameter in one of my problem
2 ) Some explicitly encodings are hided in your 3rd party jars such as
Locale explicitylyLocale = new Locale("...");
...
3 ) Some problems are occurred by the response character encoding. As i encounter defining 1 response character encoding affects whole the page.
and also request character encoding of course
4 ) Also from the os language.
In this small example
<%@ page contentType="text/html; charset=ISO-8859-9" pageEncoding="ISO-8859-9" %>
This is arranged for the Turkish characters to display
<%
 response.setCharacterEncoding("ISO-8859-8");
 out.println("\u2708");
 out.println("\u05E0");
 System.out.println("\u022A");
%>

but response.setCharacterEncoding defined for the Hebrew characters
first one is the figure second one is Hebrew character third one is Turkish character.
Printing on the console depends on the server parameter for example tomcat uses -Dfile.encoding=ISO-8859-9, ISO-8859-8,cp-1252,windows-1256 etc... for different languages
i used the ISO-8859-8 to change the server language that affects the console printing encoding.

Sunday, January 13, 2013

Java Mysql Connection

                          JAVA MYSQL CONNECTION
If you want to develope a program that uses database as mysql you should connect to the mysql. There are some methods of connecting to the database one of them that i will mention is using connector jar.

In J2EE project structure, there is a folder named as libs under the WEB-INF folder which is under your Webapps or WebContent or any of named folder that puts your all user interface files such as jsps, htmls... The lib folder is special for the J2EE development because it holds all the 3rd party jars. So one way is to put your connector jar to there. Just copy your jar into the libs folder thats easy. The connector jar is for the mysql http://dev.mysql.com/downloads/connector/j/

Then lets come to our java file that can be servlet or jsp or bean etc... Of course Jsp is not a good choice :)) Lets come and open a class that will contain our db operations.

lets code a one function that creates a connection

public static Connection getConnection() throws ClassNotFoundException, SQLException{
Class.forName("com.mysql.jdbc.Driver");
Connection connection = null;

try {
connection = DriverManager
.getConnection("jdbc:mysql://localhost:3306/canuysal","root", "yourpassword");

} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return null;
}
return connection;
}

This will return your connection


connection = DriverManager
.getConnection("jdbc:mysql://localhost:3306/canuysal","root", "yourpassword");
In this function
/localhost:3306/ this is your address and port where the db installed.
"root" this is your user
"yourpassword" this is your password

1 ) Lets insert into table and query the record.


ResultSet insertId = null;
String record= "0";
Connection connection = getConnection();
if (connection != null) {
Statement st = connection.createStatement();
 int val = st.executeUpdate("INSERT TABLES(X,Y,Z) VALUES('x','y','z')");
 Statement st2 = connection.createStatement();
 insertId = st2.executeQuery("SELECT gameId from TABLES WHERE X='x'");
 while (insertId.next()) {
record= insertId.getString("X");
}
} else {
System.out.println("Connection Fails!!!!");
}
connection.close();

2 ) Lets delete now
Statement st2 = connection.createStatement();

int val = st2.executeUpdate("DELETE FROM TABLES WHERE X = 'x'");

that if you put this code the field will be deleted from the table.





Android Device Install Location

                                             ANDROID DEBUGGING DEVICE INSTALL LOCATION
If you set up your environment for the android development and if you have a android device and its usb cable, then you are very lucky because you will be 10 times faster then from debuggin on machine. Firstly you shoudl open your eclipse ide and you should plug your usb to your android device then to your computer usb port. If your android device was not detected by the computer automatically, you can solve this problem from automatic driver update and install that you can open devices and printers section for the windows 7 and click to the undefined android device as right then click device installation settings and then you can continue, i encounter one time that was device can not be defined and can not load the driver automatically so i opened the Windows Update section that the automatic update was disabled. And the driver update was there waiting for my command then i downloaded and the device was ready that was defined by the computer.

Lets go with the debugging by machine. If you run the android program from your ide, ide will automatically find your machine even if your emulater was opened. Now you can load your program to your machine to debug in real device.

Sometimes for some devices that has small storage in its own you may encounter this error

Installation error: INSTALL_FAILED_INSUFFICIENT_STORAGE

This error occurres because ,the storage is not enough. If you open your android programs root file that is AndroidManifest file that is on the root of your project, you can see;

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.istanbuldenizotobusleri"
    android:versionCode="1"
    android:versionName="1.0"
    android:installLocation="preferExternal" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="8" />
The red one in the code solves the problem that we encounter. There are also some options that you can select such as "auto","internalOnly","preferExternal".

!! So If there is not an external storage you will get a error like the above

Installation error: INSTALL_FAILED_MEDIA_UNAVAILABLE

As you can see above you can insert your external storage to solve the problem.

Java File Operations

                                    JAVA FILE OPERATIONS
File operations in Java are simple as you will see. In the next example we will get file from a specified place then we will read the file line by line and then we will write to file. Lets start

1 ) Firstly we should get file.
File file = new File("C:/can/donusturulecek.txt");

2 ) Then we mostly use Buffered Reader to get content of the file

BufferedReader reader= new BufferedReader(new FileReader(file));

3 ) and then we can traverse the file line by line

while (reader.ready()) {
String read = reader.readLine();
System.out.println(read);
}

4 ) After the operation logic finished you should close the connection

reader.close();

!!If the connection is opened, after some operations it may give a error.

5 ) Lets write now to the file



try {
       BufferedWriter out = new BufferedWriter(new FileWriter("C:/can/filefirst.txt"));
           for(int i= 0 ; i< splitfirst.length ; i++){
            out.write("Hi, Hello");
           
           }
         
           out.close();
       } catch (IOException e) {}

in.close();

6 ) If you want to go to a new line at the end of your input to the file you can use
out.newLine();

Below there is whole example that reads file from a specified place and divides the content to the 3 section in the file and saves them different files such as file has content below;

a b c
d e f
g h i
. . .
then this program will save as
filefirst.txt
a
d
g
filesecond.txt
b
e
h
filethird.txt
c
f
i

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;


public class Files {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
int counter=0;
File file = new File("C:/can/converting.txt");
BufferedReader reader= new BufferedReader(new FileReader(file));
String first="",second="",third="";
while (reader.ready()) {
counter++;
 String s = reader.readLine();
 System.out.println(s);
 if(s.compareTo(" ") != 0){
 String[] split = s.split(" ");

 first += split[0] + "/";
 second += split[1]+ "/";
 third += split[2]+ "/";
 }
}
in.close();
try {
String[] splitfirst = first.split("/");
       BufferedWriter out = new BufferedWriter(new FileWriter("C:/can/filefirst.txt"));
           for(int i= 0 ; i< splitfirst.length ; i++){
            out.write(splitfirst[i]);
            out.newLine();
           }
         
           out.close();
       } catch (IOException e) {}

in.close();
try {
String[] splitfirst = second.split("/");
       BufferedWriter out = new BufferedWriter(new FileWriter("C:/can/filesecond.txt"));
           for(int i= 0 ; i< splitfirst.length ; i++){
            out.write(splitfirst[i]);
            out.newLine();
           }
         
           out.close();
       } catch (IOException e) {}

in.close();
try {
String[] splitfirst = third.split("/");
       BufferedWriter out = new BufferedWriter(new FileWriter("C:/can/filethird.txt"));
           for(int i= 0 ; i< splitfirst.length ; i++){
            out.write(splitfirst[i]);
            out.newLine();
           }
         
           out.close();
       } catch (IOException e) {}
in.close();
}
}


Character Encoding

                                         CONVERT CHARACTER ENCODING
Lots of times we encounter character problems such as why Chinese characters are square and Arabic characters are ?. To achive this problem i was using unicode converters and i showed the characters as their unicode codes. So how can we convert characters from Utf to Iso or to Unicode there are small functions below :

1 ) If you want to convert your utf-8 data to unicode this function may help you


private String convertConvertingToUnicode(String str) {
// TODO Auto-generated method stub
unicodeString unicode = new unicodeString();
String converted = unicude.convert(str);
return converted;

}


2 ) If you want to convert unicode to Utf this may help you

String convertConvertingToUnicode =<--//Your string that contains unicode code
String[] strs = convertConvertingToUnicode.split("\\\\");
String result = "";
for(int i = 0;i < strs.length;i++)
{
String send = strs[i];
if(strs[i].length()>0)
if(strs[i].charAt(0) == 'u'){
send = "\\"+strs[i];
}
result += convertToUtf(send);
}

//All the document now is in result as utf with meaningfull
}

private String convertToUtf(String string) {
// TODO Auto-generated method stub
String str = string;
Matcher m = Pattern.compile("(?i)\\\\u([\\da-f]{4})").matcher(str);
String a = str;
if (m.find()) {
   a = String.valueOf((char) Integer.parseInt(m.group(1), 16));
}
if(str.length() > 6)
{
a += str.substring(6);
}
if(a.compareTo("")==0){
a = str;
}
return a;
}

3 ) And also you can change the encoding type

byte[] byts = string.getBytes("UTF-8");
String newstring= new String(byts,"Whatever you want for example  ISO-8859-9");

I needed a converter lots of time in development times so i prepared a program on android that may also help you for the character conversion you can try from your android device...

If you are getting unreadable words; if you try in eclipse ide you should look at the console encoding that is in runconfigurations or if you are developing ee in JSP-JF-SERVLET-STRUTS-SPRING... any web based technology, you should look first to the page encodings, then tomcat startup parameters...
Android Application



Tuesday, January 8, 2013

STRUTS FORWARD EXAMPLE


                                                      STRUTS FORWARD
We created a basic struts project before and now we will route it to the jsp we will define. Importants are these :
1 ) Action class mapping process
2 ) Config file forward tag
3 ) jsp

In the action class we returned null before and now we will return different such as :
return mapping.findForward("forward1");

Now it will route with the parameter forward1

struts config xml


<forward name="forward1" path="/forward1.jsp"></forward>

now the forward1 parameter will be handled by forward name attribute and the path will be executed.

your forward1.jsp under the WebContent of your project or webapp whatever you named that folder will be executed.