Monday 19 December 2011

Why Android Layout file opened as XML?


When I'm trying to open Android Layout File(Double Click on it), it opened as XML file, so, why?

The reason is android SDK sometime make the developer crazy with some bugs like this" Opening layout file as XML and design instead of Graphical Layout"










 The solution is:
Right Click on the Layout file -> Open with -> Android Layout Editor















Mohammad Abu Hmead

Open android xml layout

When I'm trying to open Android Layout File(Double Click on it), it opened as XML file, so, why?
The reason is android SDK sometime make the developer crazy with some bugs like this" Opening layout file as XML and design instead of Graphical Layout"

The solution is:
Right Click on the Layout file -> Open with -> Android Layout Editor

Sunday 18 December 2011

Error within Debug UI: java.lang.reflect.InvocationTargetException

I this is a popup dialog contains this error "Error within Debug UI:  java.lang.reflect.InvocationTargetException",
I googled it, but I didn't found the solution.



I tried to delete the Project from the Projects Work space, and I reimported it, it worked fine.
so, the easiest solution is
"Delete the Project from the work space, Reimport it again to the work space"
The result: it will work 100%

Mohammad Abu Hmead

Saturday 22 October 2011

Create GlassFish Domain

How to add GlassFish server to Netbeans and create new domain?


Follow the following Figures



GlsssFish Version 

GlassFish Location



GlassFish Domain, the check box "use default Ports" checked unchecke it

To get the server port



You can call any servelt on this server via the server computer IP and GlassFish Server Port which is 28354
Ex: http://43.17.33.9:28354/ServletProject/ServletName

Best Wishes,

Mohammad Abu Hmead

Get or Change MS SQL server TCP/IP

How to get or change MS SQL TCP/IP?
  1. Open Sql Server Configuration Manager.
  2. Open SQL server network configuration.
  3. Press on Protocols for MSSQLSERVER.
  4. Right click on TCP/IP -> Enable. Look at the figures  bellow.


Double Click on TCP/IP will show the figure bellow 

Go to IP All Section and look at the TCP Port Field if is it empty write 1433 which is the default port for the SQL server.

Best Wishes, 

Mohammad Abu Hmead

Create MS SQL new Login

How to create new user on MS SQL?


  1. Open MS Sql Management Studio.
  2. Log in via Windows Authentication.
  3. Open Security Folder.
  4. Open Logins  Folder.
  5. Right Click -> New Login...
  6. Write the user name.
  7. Select the Sql Authentication 
  8. Type a password 
  9. Pick the DB which this user should manage.
Look @ the figure bellow 

      10. Press on User Mapping, Pick the DB which you want this user to manage and select the memberships     rules. look at the Figure bellow.



         11. The Status Tab should be as the following Figure.





    12. Press OK.
    13. Right click on Server name -> Properties 
    14. Press on Security tap and Pick SQL server and windows authentication mode under Server Authentication section. Look @ the figure bellow




Best Wishes,


Mohammad Abu Hmead.

Create MS SQL account

How to create new user on MS SQL?

  1. Open MS Sql Management Studio.
  2. Log in via Windows Authentication.
  3. Open Security Folder.
  4. Open Logins  Folder.
  5. Right Click -> New Login...
  6. Write the user name.
  7. Select the Sql Authentication 
  8. Type a password 
  9. Pick the DB which this user should manage.
  10. Press OK.
Look @ the figure bellow 







Tuesday 20 September 2011

Connection Types in J2ME


HTTP:
Connector.open(“http://www.mysite.com”);
Sockets:
Connector.open(“socket://localhost:80”);
Datagrams:
Connector.open(“datagram://www.mysite.com:2861”);
Serial Port:
Connector.open(“comm:0;baudrate=2241”);
File:
Connector.open(“file:/textFile.txt”);

Sunday 28 August 2011

Search in NTEXT column in SQL


To search in a column in SQL whose DataType is NTEXT or NVARCHAR use the reserved word LIKE
See the Example Below 
use DBName
select
from dbo.TableName
where NTextFieldName LIKE 'Your Search Word or Sentence'



Insert Into Sql Table from Formatted Text File


use DBName
BULK INSERT  dbo.Table_1 FROM 'c:\textFileName.txt' 
WITH (      


      FIELDTERMINATOR = '\t', --Tab
      ROWTERMINATOR = 'q'      --Char 'q'
);

SQL server Cast and Print


DECLARE @VariableName varchar(30)
SET @VariableName = 'Ring'
BEGIN
   SELECT CAST(@VariableName as NVARCHAR(1))
 PRINT @VariableName;
END
GO
--------------------
out put:
R

SQL Loop through records and replace


use DB_Name
DECLARE @var_1 as nvarchar(300)
DECLARE @var_2 as int --DECLARE @VariableName as Variable DataType
                                              --You can DECLARE many variable seperated by comma
                                              --to add another variable to the previous declaration use this example
                                              --,
                                              --@Variable2 as char

                             
DECLARE cursor_ CURSOR FOR   --declare the cursor
SELECT    primary_key_column_name , column2         --write a correct select statmen
FROM dbo.TableName

OPEN cursor_      --Open the cursor
FETCH NEXT FROM cursor_ INTO @var_1, @var_2  -- filling the variables using the cursor
WHILE (@@FETCH_STATUS = 0)        --Looping through the cursor
  BEGIN                             --Write you code here to do what you want


if(@var_2='null' or @var_2='NULL' OR @var_2='Null')

   UPDATE dbo.Channels SET var_2=column_name_to_be_replaced_with
   WHERE primary_key_column_name=@var_1

   FETCH NEXT FROM cursor_ INTO @chanID_, @chanName_Ar_ --To move the cursor to the next row
  END
  CLOSE cursor_                       --You have to close the cursor
  DEALLOCATE cursor_                  --You have to free the memory

Thursday 25 August 2011

Read Arabic text file into Sql server 2008 table

*  Save your text file as "unuicode"
*  use ntext, nvarchar, nchar as Columns Datatypes

* The DB collation should be Arabic_100_CI_AS

use this query:


use DBname
BULK INSERT  dbo.TableName FROM 'c:\TextFileName.txt' 
WITH (    

      FIELDTERMINATOR = '\t',
      ROWTERMINATOR = 'q'    
);


\t: is the delimiter between columns
q: is the delimiter between rows

Sunday 7 August 2011

How to start GlassFish 3.0 at boot in windows?

You may want to start your GlassFish 3.0 Server automatically at windows boot (Start). to do that
Follow these instructions:

1) Go to the installation location and open the bin folder, this is the default bath
C:\glassfish3\bin

2) Double click on "asadmin.bat" file
3) Type "start-domain myDomain" and press enter
4) To create the windows service which starts the server automatically at windows boot
type the command " create-service" and the server domain which you want to create a service for it;
 " create-service myDomain" and press Enter.
5) You need to install the service on Windows
    I) open cmd and type "sc create domain1 start= auto binPath= C:\mapviewer11g_qs\glassfish3\glassfish\domains\domain1\bin\domain1Service.exe"


or II) use the following procedure
    a) go to .net framework C:\Windows\Microsoft.NET
    b) search about installutil.exe
    c) if their is no .net framework installed, you need to install .net 4 or later to
        find installutil.exe
    d) Copy the path of installutil.exe  and past it at the end of the "Path" system
        variable
    e) Open cmd as administrator and cd into the bin directory of the domain which you
        created a service for it and type installutil sericeName.exe and hit enter
     f) Restart your PC.
     g) Configure your Service from system services


See the following snapshot

















Congratulations, your server runs automatically

Note: to view all creating commands type "create" and press enter, and so on for any word
Mohammad Abu Hmead

How to start GlassFish 3.0 at boot time in windows?

You may want to start your GlassFish 3.0 Server automatically at windows boot (Start). to do that
Follow these instructions:

1) Go to the installation location and open the bin folder, this is the default bath
C:\glassfish3\bin

2) Double click on "asadmin.bat" file
3) Type "start-domain myDomain" and press enter
4) To create the windows service which starts the server automatically at windows boot
type the command "create-service" and the server domain which you want to create a service for it;
 "create-services myDomain" and press Enter.
4) Restart your PC.

See the following snapshot

















Congratulations, your server runs automatically

Note: to view all creating commands type "create" and press enter, and so on for any word
Mohammad Abu Hmead

Thursday 21 July 2011

Creat Servlet and Connect it to MS SQL server


1) Install Netbeans 6.9 or later
2) Download GlassFish from this site
install GlassFish, it will run easy
3) Run NetBeans IDE and view Services window 


Right Click on servers the click on "add server.."

Type instead of x the version of the GlassFish you want to add
the press Next and type the link of the GlassFish installation folder 
press Next and Select the domain and press Finish
** Now your GlassFish Created 

4) Now you have to start the server by right click on GlassFish 3.1 and click start 
if the server didn't  start the solution is bellow

5) Creating GlassFish Domain
open your  glass fish directory and open bin folder 
double click on "asadmin" it will run and type "domain" then an error list will shown like the figure bellow 

never mind, just I want to show you how you can get correct commands 
now type "create-domain domain2" and wait for response 

back to netbeans and repeat step 3 but choose domain2 and run the server

---------------------------------------------
Now we want to configure MSSQL server
1) install SQL server 2005 or later
2) Create your DB with windows authentications 
3) Create new user with Sql authentications with password and select the DB to be shown to this user 
4) Go to DB and right Click and choose properties and press on Permissions and select the user and check all CheckBoxes under Grant Header like the figure bellow 

5) Now you want to know the port number on which the SQL server listen to
by doing like the two figures bellow

from the previous figure you can get the port.


-------------------------------------------
Now Creating Servlet 

1) Run Netbeans and press on "File" tab and press on "New Project" 
2) Select Java Web from Categories and Web Application from Projects
3) Type your project name and directory and the libraries directory 
4) Choose GlassFish and JEE 
5) Do like the figure bellow (let all of them empty)

Click finish, now you have a web project

*** Creating Servlet
on project name right click and select  new Servlet
Do like the bellow two figures 



Press finish and edit the 

Add the sql db driver into libraries 
downloadable from this site http://www.mediafire.com/?3ycmaelhoot

Look at the example bellow

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import javax.servlet.annotation.WebServlet;

/**
 *
 * @author Mohammad
 */
//this to call the servlet from an ip address
//http://ipaddress:port/defaultSite/ServletCallableName

@WebServlet(name = "ServletCallableName", urlPatterns = {"/ServletCallableName"})

public class NewServlet extends HttpServlet {

    private Connection conn;
    private PrintWriter printWriter;
    private StringBuffer stringBuffer;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String ua = request.getHeader("User-Agent");      

        stringBuffer = new StringBuffer();
       
            CallableStatement callableStatment = null;

            try {
                Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;"//1433 sql port look at    
//figures bellow
                        + "databaseName=WhoWantsToBeMillionaireQs;user=mohammad;password=moh");

                callableStatment = conn.prepareCall("{call get_rando_rows(?)}");//call get_rando_rows: procedure name created on Sql serve DB, takes one parameter, the procedure runs 3 select statments and returns 3 results as three tables 
                callableStatment.setString("Count", "5");//the procedure parameter 

                boolean isExecuted = callableStatment.execute();//to execute the query 

                int rsCount = 0;
                try {

                    do {
                        if (isExecuted) {
                            ResultSet rs = callableStatment.getResultSet();
                            rsCount++;

                            ResultSetMetaData rsmd = rs.getMetaData();
                            int numOfColumns = rsmd.getColumnCount();
                            while (rs.next()) {
                                for (int i = 1; i <= numOfColumns; i++) {
                                    stringBuffer.append(rs.getString(i));
                                    stringBuffer.append("|#|");
                                }
                            }
                            rs.close();
                            System.out.println();
                            isExecuted = callableStatment.getMoreResults();
                        }
                    } while (isExecuted);
                    callableStatment.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            } catch (SQLException ex) {
                stringBuffer.append("  SQL Exception.  ");
                stringBuffer.append(ex.getMessage());
            } catch (ClassNotFoundException cex) {
                stringBuffer.append("  Class Not Found Exception  ");
                stringBuffer.append(cex.getMessage());
            } catch (Exception ex) {
                stringBuffer.append("Unknown Exception  ");
                stringBuffer.append(ex.getMessage());

            }
       
        response.setContentType("text/plain");
        printWriter = response.getWriter();
        printWriter.print(stringBuffer.toString());
        printWriter.close();

    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}


Mohammad Abu Hmead 
Palestine 
21.07.2011
01:43 AM

Sunday 17 July 2011

Connection between Java and SQL Server

Hint: Use sqljdbc4.jar


package server;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import javax.servlet.annotation.WebServlet;
/**
 *
 * @author Mohammad
 */
@WebServlet(name = "viewFromSQL", urlPatterns = {"/viewFromSQL"})
public class EmailConnectedtoSQLServer2008 extends HttpServlet {
Connection theConnection;
 private ServletConfig config;
 public void init(ServletConfig config)
  throws ServletException{
  this.config=config;
 }
    public void service (HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
         
   HttpSession session = req.getSession(true);
   res.setContentType("text/html");
   PrintWriter out = res.getWriter();

        out.println("<HTML><HEAD><TITLE>Emai List.</TITLE>");
   out.println("</HEAD>");
   out.println("<BODY bgColor=blanchedalmond text=#008000 topMargin=0>");
        out.println("<P align=center><FONT face=Helvetica><FONT color=fuchsia style=\"BACKGROUND-COLOR: white\"><BIG><BIG>List of E-mail addresses.</BIG></BIG></FONT></P>");
   out.println("<P align=center>");
        out.println("<TABLE align=center border=1 cellPadding=1 cellSpacing=1 width=\"75%\">");
 
        out.println("<TR>");
        out.println("<TD>Name</TD>");
        out.println("<TD>E-mail</TD>");
        out.println("<TD>Website</TD></TR>");
 try{
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");//Loading Sun's JDBC ODBC Driver
            theConnection = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;" +
         "databaseName=email;user=moh;password=123"); //Connect to emaildb Data source
            out.println("<br> DATABASE NAME IS:" 
                    + theConnection.getMetaData().getDatabaseProductName()+"</br>");
            Statement theStatement=theConnection.createStatement();
            ResultSet theResult=theStatement.executeQuery("SELECT * FROM emaillists"); //Select all records from emaillists table.
 
              while(theResult.next()) //Fetch all the records and print in table
  {
                   
     out.println();
       out.println("<TR>");
       out.println("<TD>" + theResult.getString(1) + "</TD>");
       out.println("<TD>" + theResult.getString(2) + "</TD>");
   String s=theResult.getString(3);
       out.println("<TD><a href=" + s + ">" + s + "</a></TD>");
       out.println("</TR>");

  }
            theResult.close();//Close the result set
            theStatement.close();//Close statement
            theConnection.close(); //Close database Connection
      }catch(Exception e){
  out.println(e.getMessage());//Print trapped error.
 }
 
       out.println("</TABLE></P>");
       out.println("<P>&nbsp;</P></FONT></BODY></HTML>");

 }
 public void destroy(){

 }
}

JAVA to MS Access Connection (JDBC-ODBC bridge)



Tuesday 21 June 2011

Java Abstraction

Abstract class is a class that is declared abstract
*  it may or may not include abstract methods.
*  Abstract classes cannot be instantiated, but they can be subclassed.
*  If a class includes abstract methods, the class itself must be declared abstract.
When an abstract class is subclassed, the subclass must have implementations for all of the 
   abstract  methods.
* When an abstract class inherited from an abstract class there is no need to 
  implement its super abstract methods


Abstract method is a method that is declared without an implementation:(without braces, and followed by a semicolon)
abstract void setUserName(String name);

Friday 17 June 2011

Java Overloading

Overloading is the same method name with different parameters.
the Constructors can be overloaded
**Methods with Same name in The Class or its Subclasses with different Signature.
Signature (Parameters DataTypes or Number)ex
Class A{
public A(){....}
public A(int x){....}
public A(char x){....}
public void getSomeThing(){.....}
public void getSomeThing(char x){.....}
public void getSomeThing(String x,int y){.....}
public void getSomeThing(double x){.....}
}
Class B extends A{
public void getSomeThing(String x,char y){.....}
}
** You can pass float or double to method who's parameter datatype is double but contrary is prohibited


The overloaded methods can be static , final and or abstract.


Hint: Java uses method Parameters Types and count to specify which method.
Java doesn't differentiate between methods depending on there return DataType 


Hint: Use Overloading when you need multiple methods with different parameters, but methods do the same thing.
Don't use Overloading when methods do different tasks


For more info: http://www.java-samples.com/showtutorial.php?tutorialid=284


Thursday 16 June 2011

Null returned when using findViewById


Hello,
sometime you have nullpointerexception when using findViewById like the code snippet bellow
                TextView tv=(TextView)findViewById(R.id.textViewVV);
if(tv!=null)
tv.setText("Not Null");
this is done because you call different of the set layout
the solution is to call views from the layout you use on the current Activity
like this

setContentView(R.layout.test);
TextView tv=(TextView)findViewById(R.id.textViewVV);
if(tv!=null)
tv.setText("Good");
textViewVV is in test layout, so, this code works fine.


Tuesday 7 June 2011

Read file into byte array in j2me

import java.io.InputStreamimport java.io.OutputStreamimport javax.microedition.io.Connectorimport javax.microedition.io.file.FileConnection/**
 * This class to read file from memory and create a file on phone memory
 * @author Mohammad Abu Hmead
 * 08.03.11
 */
public class CreateAndReadFileOnAndFromMemory {

    public static final 
String FILE_LOCATIO_IN_PHOTOS=System.getProperty("fileconn.dir.photos");
    public static final 
String FILE_LOCATIO_IN_VIDEOS=System.getProperty("fileconn.dir.videos");
    public static final 
String FILE_LOCATIO_IN_TONES=System.getProperty("fileconn.dir.tones");
    public static final 
String FILE_LOCATIO_ON_MEMORY_CARD=System.getProperty("fileconn.dir.memorycard");
    
    private 
String fileLocationURL="Not specified yet";

    public 
CreateAndReadFileOnAndFromMemory(String fileLocation,String fileNameWithItsExtension)
    {
        
fileLocationURL=fileLocation+fileNameWithItsExtension;
    }
    public 
String getFileLocationURL(){
        return 
fileLocationURL;
    }
    public 
void setFileLocationURL(String fileLocationURL) {
        
this.fileLocationURL fileLocationURL;
    }

    public 
void writeIntoFile(String textToBeWrittenthrows Exception
    
{
            
FileConnection fileConnection;

            
fileConnection = (FileConnectionConnector.open(fileLocationURLConnector.READ_WRITE);

            if(!
fileConnection.exists())
                
fileConnection.create();

            
OutputStream outputStream=fileConnection.openOutputStream();
            
outputStream.write(textToBeWritten.getBytes("UTF-8"));
            
            
outputStream.flush();
            
outputStream.close();
            
fileConnection.close();
    }

    public 
boolean  createFileOnMem(byte[]  fileBsthrows Exception
    
{
        
boolean isCreated=false;
        try {
            
FileConnection fileConnection;
            
fileConnection = (FileConnectionConnector.open(fileLocationURLConnector.READ_WRITE);
            if(!
fileConnection.exists())
                
fileConnection.create();

            
OutputStream outputStream=fileConnection.openOutputStream();
            
outputStream.write(fileBs);
            
outputStream.flush();
            
outputStream.close();
            
fileConnection.close();
            
isCreated=true;
        } catch (
Exception e) {
        }
            

        return 
isCreated;
            
    }

    public 
byte[] readFileByts() throws Exception
    
{
        
byte[] filebBs=null;

        
FileConnection fileConnection = (FileConnection)
                
Connector.open(fileLocationURLConnector.READ_WRITE);
        if(
fileConnection.exists())
        {
            
filebBs=new byte[(int)fileConnection.fileSize()];
            
InputStream is=fileConnection.openInputStream();
            
is.read(filebBs0filebBs.length);
            
is.close();
            
is=null;
            
fileConnection.close();
        }
        return 
filebBs;
    }

    public 
boolean deleteTheFile()
    {
        
boolean isDeleted=false;
        
FileConnection fileConnection;
        try {
            
fileConnection = (FileConnectionConnector.open(fileLocationURLConnector.READ_WRITE);
            if(
fileConnection.exists())
            {
                
fileConnection.delete();
                
isDeleted=true;
            }
        } catch (
Exception ex) {

        }
        return 
isDeleted;
    }
}