Create Custom Gesture on Emulator in Android

In my previous post : Create Your Own Gesture Overlay in Android where you can use your gesture overlay in your program. In my previous post you'll use my predefined overlay but if you want to make your own custom gesture overlay then what you need to do ?
Don't take tension i am here then why are you fear...
Here i am telling you how to make your own custom gesture in emulator in android.

  • First of all you need to open your android emulator.
  • After that you'll open the Gestures Builder  option  in emulator screen.






  • Open them and click on Add gesture button.


Create Custom Gesture on Emulator in Android,how to Create Custom Gesture on Emulator in Android,Custom Gesture on Emulator in Android,Gesture on Emulator in Android,Emulator in Android,


  • Then you'll see the next screen called create a gesture and enter the name and draw your pattern.

Note : Here name is a message which will be give you as output when draw that particular pattern.


  • At last click on Add Gesture button.
  • In order to get gesture file, open the FileExplorer tab in the DDMS perspective. (If you don’t have the FileExplorer tab available, add it from: Window -> Show View -> File Explorer). Navigate to /sdcard directory and copy the gesture file to your computer, for example on your desktop.



  • To copy the gesture file from the emulator, select it and click the “Pull a file from the device” button, marked with red in the screenshot below:




  • Paste gestures file in res/raw/gestures file.

Create Your Own Gesture Overlay in Android

Today i am telling you a special effect for your android apps which gives you power to establish your apps in market. This effect name is Gesture.
Here you'll draw a pattern and it give you some predicted your defined value just as given below image:

                     how to Create Your Own  Gesture Overlay in Android,Create Your Own  Gesture Overlay in Android,Your Own  Gesture Overlay in Android,Own  Gesture Overlay in Android,Gesture Overlay in Android,Overlay in Android, how to Create Your Own  Gesture Overlay in Android,Create Your Own  Gesture Overlay in Android,Your Own  Gesture Overlay in Android,Own  Gesture Overlay in Android,Gesture Overlay in Android,Overlay in Android,                                                       how to Create Your Own  Gesture Overlay in Android,Create Your Own  Gesture Overlay in Android,Your Own  Gesture Overlay in Android,Own  Gesture Overlay in Android,Gesture Overlay in Android,Overlay in Android, how to Create Your Own  Gesture Overlay in Android,Create Your Own  Gesture Overlay in Android,Your Own  Gesture Overlay in Android,Own  Gesture Overlay in Android,Gesture Overlay in Android,Overlay in Android,
Above images are clear to understand what you want to do. Here i am using two event when i draw 'p' for 'previous' and 'n' for 'next' event.
If you want to create custom gesture : check this post
Now we go ahead with coding.
GesturesActivity.java
package com.blogspot.geekonjava.gestures.demo;

import java.util.ArrayList;

import com.example.android.gestures.demo.R;

import android.app.Activity;
import android.gesture.Gesture;
import android.gesture.GestureLibraries;
import android.gesture.GestureLibrary;
import android.gesture.GestureOverlayView;
import android.gesture.Prediction;
import android.gesture.GestureOverlayView.OnGesturePerformedListener;
import android.os.Bundle;
import android.widget.Toast;

public class GesturesActivity extends Activity implements OnGesturePerformedListener {
    private GestureLibrary mLibrary;

 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mLibrary = GestureLibraries.fromRawResource(this, R.raw.geekonjava);
        if (!mLibrary.load()) {
         finish();
        }

        GestureOverlayView gestures = (GestureOverlayView) findViewById(R.id.gestures);
        gestures.addOnGesturePerformedListener(this);
    }
 
 public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {
  ArrayList<Prediction> predictions = mLibrary.recognize(gesture);

  // We want at least one prediction
  if (predictions.size() > 0) {
   Prediction prediction = predictions.get(0);
   // We want at least some confidence in the result
   if (prediction.score > 1.0) {
    // Show the spell
    Toast.makeText(this, prediction.name, Toast.LENGTH_SHORT).show();
   }
  }
 }
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

    <TextView
                  android:id="@+id/textView1"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:text="GeekOnJava Gesture Effect"
                  android:textAppearance="?android:attr/textAppearanceLarge" />

        
          <android.gesture.GestureOverlayView
        android:id="@+id/gestures"
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="1.0"
        android:background="#0017ff"
         >

            
        
         </android.gesture.GestureOverlayView>

        
   

</LinearLayout>

Download zipped Example >>

How to make Notification in Android

Hello friends you'll see the notification in android like when you get new mail then a small icon comes on your android device. Some times we have requirement to show alert user from background services or from broadcast receiver then best way to notify user by Notification Alert.Before going ahead tell a answer of question as a comment which  is given below:
Q. Is notification in android coolest trick to make your apps attractive ?
If yes then i am telling you how to do you for your apps. We'll make Notification Alerts with the use of NotificationManager.

Below image is directory structure of given program

How to make Notification in Android,make Notification in Android,Notification in Android,Notification Alert,NotificationManager,android notification example,Create Notification Alert
NotificationAlert.java
This java file is main class in which notification would be generate through button.
How to make Notification in Android,make Notification in Android,Notification in Android,Notification Alert,NotificationManager,android notification example,Create Notification Alert

package com.androidexample.notification;


import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;

public class NotificationAlert extends Activity {

 private static final int NOTIFY_ME_ID=1337;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.notification_alert);
  
  final Button notify = (Button) findViewById(R.id.notify);
  
  notify.setOnClickListener(new OnClickListener() {
   public void onClick(View v) {
  
     /*********** Create notification ***********/
     
     final NotificationManager mgr=
      (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
     
     Notification note=new Notification(R.drawable.stat_notify_chat,
                 "GeekOnJava Status message!",
                 System.currentTimeMillis());
     
     // This pending intent will open after notification click
     PendingIntent i = PendingIntent.getActivity(getBaseContext(), 0, 
                                new Intent(getBaseContext(), NotifyMessage.class),
               0);
     
     note.setLatestEventInfo(getBaseContext(), "GeekOnJava Notification Title",
           "This is the GeekOnJava android example notification message", i);
     
     //After uncomment this line you will see number of notification arrived
     //note.number=2;
     mgr.notify(NOTIFY_ME_ID, note);
   } 
  });
  
 }
}

How to make Notification in Android,make Notification in Android,Notification in Android,Notification Alert,NotificationManager,android notification example,Create Notification Alert
NotifyMessage.java
This class is use to show the notification message.

How to make Notification in Android,make Notification in Android,Notification in Android,Notification Alert,NotificationManager,android notification example,Create Notification Alert

package com.androidexample.notification;

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

public class NotifyMessage extends Activity {
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  
  TextView txt=new TextView(this);
  
  txt.setText("This is GeekOnJava activity after click on notification message");
  setContentView(txt);
 }
}

notification_alert.xml
<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"
    tools:context=".NotificationAlert" >

    <Button android:text="Click for Notify GeekOnJava Message" 
    android:clickable="true" 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" 
    android:id="@+id/notify" 
    android:layout_marginLeft="80dip" 
    android:layout_marginRight="80dip"
    ></Button>

</RelativeLayout>
///////////

How to Make Java IDE in Swing

Every java geekers use IDE like MyEcllipse,Netbeans etc. for java programming and if i would say you can make your own java IDE then what your reaction.
How to Make Java IDE in Swing,Make Java IDE in Swing,Java IDE in Swing,IDE in Swing,How to Create an Editor for Java Applications,Create an Editor for Java Applications,an Editor for Java Applications,Editor for Java Applications,Java Applications,

Yaa its amazing as hear but not hard as you think. Before going ahead give me simple answer :
Q : Which IDE you're use for Java programming ? Please answer in comment section .
Now what we need to do first of all download the JSyntaxPane.jar The main goal is to make it easy to have nice looking Java Swing Editors with support for Syntax Highlighting.
Now your application has access to all of the following editor kits:
How to Make Java IDE in Swing,Make Java IDE in Swing,Java IDE in Swing,IDE in Swing,How to Create an Editor for Java Applications,Create an Editor for Java Applications,an Editor for Java Applications,Editor for Java Applications,Java Applications,

Now we use it by two simple step:
  1. Create a JFrame
  2. Add a JEditorPane
jsyntaxpane.DefaultSyntaxKit.initKit();
jEditorPane.setContentType("text/java");
You don't need to declare "jsyntaxpane" and then initialize it. Simply use it, exactly as above, i.e., use its "initKit" call and then you're done. That one line of code is literally all that's needed, after which you can set the MIME type of your choice.
 For "text/java", you'll get all of this when you run your JFrame:
How to Make Java IDE in Swing,Make Java IDE in Swing,Java IDE in Swing,IDE in Swing,How to Create an Editor for Java Applications,Create an Editor for Java Applications,an Editor for Java Applications,Editor for Java Applications,Java Applications,


Above image tells you which editor kits are available. Now you need to check jsyntaxpane.kitsfortypes.properties where you'll get the mappings between MIME types and editor kits:
text/c=jsyntaxpane.syntaxkits.CSyntaxKit
text/cpp=jsyntaxpane.syntaxkits.CppSyntaxKit
text/java=jsyntaxpane.syntaxkits.JavaSyntaxKit
text/groovy=jsyntaxpane.syntaxkits.GroovySyntaxKit
text/javascript=jsyntaxpane.syntaxkits.JavaScriptSyntaxKit
text/xml=jsyntaxpane.syntaxkits.XmlSyntaxKit
text/sql=jsyntaxpane.syntaxkits.SqlSyntaxKit
text/properties=jsyntaxpane.syntaxkits.PropertiesSyntaxKit
text/python=jsyntaxpane.syntaxkits.PythonSyntaxKit
text/tal=jsyntaxpane.syntaxkits.TALSyntaxKit
text/jflex=jsyntaxpane.syntaxkits.JFlexSyntaxKit
text/ruby=jsyntaxpane.syntaxkits.RubySyntaxKit
In this editor have some pre-defined functionality like Ctrl-F(Find),Ctrl-H(Replace) etc. Another very cool predefined feature is code completion by Press Ctrl-Space and your abbreviations will expand to full code snippets. These are defined in 'jsyntaxpane.javasyntaxkit.completion.properties'
pu=public |
pr=private |
st=static |
cl=class |
St=String |
fri=for(int i=0; i<10; i++) {\n|
sout=System.out.println(|)
serr=System.err.println(|)
psvm=public static void main(String[] args) {\n|
Note: The pipe symbol indicates where the cursor will find itself when the abbreviation has been expanded.
Similarly, there is such a file for Groovy as well, in 'jsyntaxpane.groovysyntaxkit.completion.properties', in the META-INF/services folder.

And what determines the colors and styles of the code for the editor kits? Yet another properties file, this one called 'jsyntaxpane.syntaxstyles.properties'. Here's the default content:
OPERATOR = 0x000000, 0
KEYWORD = 0x3333ee, 0
KEYWORD2 = 0x3333ee, 3
TYPE = 0x000000, 1
TYPE2 = 0x000000, 3
STRING = 0xcc6600, 0
STRING2 = 0xcc6600, 1
NUMBER = 0x999933, 1
REGEX = 0xcc6600, 0
IDENTIFIER = 0x000000, 0
COMMENT = 0x339933, 2
COMMENT2 = 0x339933, 3
DEFAULT = 0x000000, 0
WARNING = 0xCC0000, 0
ERROR = 0xCC0000, 3
What does it all mean? 
The keys are the token types, used throughout the editor kits. The values are hexes for the colors, followed by

  •  1=>"bold"
  •  2=>"italic"
  •  3=> "bold & italic"
At last and in short, this is a very powerful JAR that you can simply drop into your application.

Create Custom Toast in Android

Today i give you attractive look to your android project by using custom toast.Toast alert is a notification message that display for certain amount of time, and automatically fades out after set time.

  • Use it to show alert message to user.
  • Use it for debugging your application.
  • Use toast alert message to show alert from background service,broadcast receiver,getting data from server...etc.

In this example we're creating a custom toast alert.

How to Create Custom Toast in Android,Create Custom Toast in Android,Custom Toast in Android,Toast in Android,

android.widget.Toast class used to create toast alert message.
Normal Toast which we use in our android program :
//Show alert for short period of time
Toast.makeText(getApplicationContext(), "This is Toast example.", Toast.LENGTH_SHORT).show();
  
//Show alert for long period of time
Toast.makeText(getApplicationContext(), "This is Toast example.", Toast.LENGTH_LONG).show();
Now we'll do something different and remove old fashion Toast.
How to Create Custom Toast in Android,Create Custom Toast in Android,Custom Toast in Android,Toast in Android,

We're using:

  1. toast.xml file for toast layout.
  2. toast_border.xml file for toast style.
toast_border.xml
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <stroke android:width="4dp" android:color="#FFFFFFFF" />
    <padding android:left="7dp" android:top="7dp"
            android:right="7dp" android:bottom="7dp" />
    <corners android:radius="4dp" />
</shape>
toast.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/toast_border">
     
    <ImageView android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/image0" />
     
    <TextView
        android:paddingLeft="10dp"
        android:textColor="#ffffff"
        android:textStyle="bold"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="The image has been uploaded to server."
        android:layout_gravity="center_vertical" />
 
</LinearLayout>
main_activity.xml
<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"
    tools:context=".CustomToast"
    android:background="#890000">
 
    <TextView
        android:paddingTop="20px"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
     
    <Button
        android:id="@+id/Clickhere"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click here to see custom alert"
        />
 
</RelativeLayout>
CustomToast.java
 import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
 
public class CustomToast extends Activity {
 
    private Button Clickhere;
     
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_custom_toast);
         
        Clickhere = (Button) findViewById(R.id.Clickhere);
         
        // Button click listner
        Clickhere.setOnClickListener(new OnClickListener() {
 
            @Override
            public void onClick(View v) {
 
                showCustomAlert();  
 
            }
        });
    }
 
     
    public void showCustomAlert()
    {
         
        Context context = getApplicationContext();
        // Create layout inflator object to inflate toast.xml file
        LayoutInflater inflater = getLayoutInflater();
          
        // Call toast.xml file for toast layout 
        View toastRoot = inflater.inflate(R.layout.toast, null);
          
        Toast toast = new Toast(context);
         
        // Set layout to toast 
        toast.setView(toastRoot);
        toast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL,
                0, 0);
        toast.setDuration(Toast.LENGTH_LONG);
        toast.show();
         
    }
 
}

Thats done and comment for more posts !!!! 

Upload Image on Server in Android Using JSON

Hello friends i am telling you how to upload image on server in android using json. Its my project part in which i need to upload client image on folder in server. So i use json to do it and distribute that code with you.
How to Upload Image on Server in Android Using JSON,Upload Image on Server in Android Using JSON,Image on Server in Android Using JSON,Server in Android Using JSON,Android Using JSON,

Project file directory is given below :
How to Upload Image on Server in Android Using JSON,Upload Image on Server in Android Using JSON,Image on Server in Android Using JSON,Server in Android Using JSON,Android Using JSON,
  • First of all you need to make your layout file "activity_main.xml"

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

     <ImageView
         android:id="@+id/imageView_pic"
         android:layout_width="100dp"
         android:layout_height="100dp"
         android:layout_gravity="center"
         android:src="@drawable/ic_launcher" />

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

     <Button
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:text="Click To Upload File"
         android:id="@+id/uploadButton"
     />
       
     <TextView
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:text=""
         android:id="@+id/messageText"
         android:textColor="#000000"
         android:textStyle="bold"
     />

  </LinearLayout>

  • After making layout you need to make class file "MainActivity.java"

package com.sunil.upload;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
 
public class MainActivity extends Activity implements OnClickListener{
    
    private TextView messageText;
    private Button uploadButton, btnselectpic;
    private ImageView imageview;
    private int serverResponseCode = 0;
    private ProgressDialog dialog = null;
       
    private String upLoadServerUri = null;
    private String imagepath=null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
     
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         
        uploadButton = (Button)findViewById(R.id.uploadButton);
        btnselectpic = (Button)findViewById(R.id.button_selectpic);
        messageText  = (TextView)findViewById(R.id.messageText);
        imageview = (ImageView)findViewById(R.id.imageView_pic);
        
        btnselectpic.setOnClickListener(this);
        uploadButton.setOnClickListener(this);
        upLoadServerUri = "http://10.0.2.2/uploads/UploadToServer.php";
        ImageView img= new ImageView(this);
        
    }
     
    
    @Override
 public void onClick(View arg0) {
  if(arg0==btnselectpic)
  {
   Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Complete action using"), 1);
  }
  else if (arg0==uploadButton) {
   
    dialog = ProgressDialog.show(MainActivity.this, "", "Uploading file...", true);
    messageText.setText("uploading started.....");
    new Thread(new Runnable() {
                 public void run() {
                                     
                      uploadFile(imagepath);
                                              
                 }
               }).start();     
  }
  
 } 
    
    @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
     
     if (requestCode == 1 && resultCode == RESULT_OK) {
            //Bitmap photo = (Bitmap) data.getData().getPath(); 
          
            Uri selectedImageUri = data.getData();
            imagepath = getPath(selectedImageUri);
            Bitmap bitmap=BitmapFactory.decodeFile(imagepath);
            imageview.setImageBitmap(bitmap);
            messageText.setText("Uploading file path:" +imagepath);
      
     }
    }
      public String getPath(Uri uri) {
             String[] projection = { MediaStore.Images.Media.DATA };
             Cursor cursor = managedQuery(uri, projection, null, null, null);
             int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
             cursor.moveToFirst();
             return cursor.getString(column_index);
         }
     
    public int uploadFile(String sourceFileUri) {
          
       
       String fileName = sourceFileUri;
 
          HttpURLConnection conn = null;
          DataOutputStream dos = null;  
          String lineEnd = "\r\n";
          String twoHyphens = "--";
          String boundary = "*****";
          int bytesRead, bytesAvailable, bufferSize;
          byte[] buffer;
          int maxBufferSize = 1 * 1024 * 1024; 
          File sourceFile = new File(sourceFileUri); 
          
          if (!sourceFile.isFile()) {
           
            dialog.dismiss(); 
            
            Log.e("uploadFile", "Source File not exist :"+imagepath);
            
            runOnUiThread(new Runnable() {
                public void run() {
                 messageText.setText("Source File not exist :"+ imagepath);
                }
            }); 
            
            return 0;
           
          }
          else
          {
            try { 
             
               // open a URL connection to the Servlet
                FileInputStream fileInputStream = new FileInputStream(sourceFile);
                URL url = new URL(upLoadServerUri);
                
                // Open a HTTP  connection to  the URL
                conn = (HttpURLConnection) url.openConnection(); 
                conn.setDoInput(true); // Allow Inputs
                conn.setDoOutput(true); // Allow Outputs
                conn.setUseCaches(false); // Don't use a Cached Copy
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                conn.setRequestProperty("uploaded_file", fileName); 
                
                dos = new DataOutputStream(conn.getOutputStream());
      
                dos.writeBytes(twoHyphens + boundary + lineEnd); 
                dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                                    + fileName + "\"" + lineEnd);
                
                dos.writeBytes(lineEnd);
      
                // create a buffer of  maximum size
                bytesAvailable = fileInputStream.available(); 
      
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];
      
                // read file and write it into form...
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);  
                  
                while (bytesRead > 0) {
                 
                  dos.write(buffer, 0, bufferSize);
                  bytesAvailable = fileInputStream.available();
                  bufferSize = Math.min(bytesAvailable, maxBufferSize);
                  bytesRead = fileInputStream.read(buffer, 0, bufferSize);   
                  
                 }
      
                // send multipart form data necesssary after file data...
                dos.writeBytes(lineEnd);
                dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
      
                // Responses from the server (code and message)
                serverResponseCode = conn.getResponseCode();
                String serverResponseMessage = conn.getResponseMessage();
                 
                Log.i("uploadFile", "HTTP Response is : " 
                  + serverResponseMessage + ": " + serverResponseCode);
                
                if(serverResponseCode == 200){
                 
                    runOnUiThread(new Runnable() {
                         public void run() {
                          String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                                  +" F:/wamp/wamp/www/uploads";
                          messageText.setText(msg);
                             Toast.makeText(MainActivity.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
                         }
                     });                
                }    
                
                //close the streams //
                fileInputStream.close();
                dos.flush();
                dos.close();
                 
           } catch (MalformedURLException ex) {
            
               dialog.dismiss();  
               ex.printStackTrace();
               
               runOnUiThread(new Runnable() {
                   public void run() {
                    messageText.setText("MalformedURLException Exception : check script url.");
                       Toast.makeText(MainActivity.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
                   }
               });
               
               Log.e("Upload file to server", "error: " + ex.getMessage(), ex);  
           } catch (Exception e) {
            
               dialog.dismiss();  
               e.printStackTrace();
               
               runOnUiThread(new Runnable() {
                   public void run() {
                    messageText.setText("Got Exception : see logcat ");
                       Toast.makeText(MainActivity.this, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
                   }
               });
               Log.e("Upload file to server Exception", "Exception : "  + e.getMessage(), e);  
           }
           dialog.dismiss();       
           return serverResponseCode; 
           
           } // End else block 
         }

 
}
  • After that you need to coding you server side "UploadToServer.php"
<?php
  
    $file_path = "uploads/";
     
    $file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
    if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
        echo "success";
    } else{
        echo "fail";
    }
 ?>
Download this example from here: Upload Image on Server in Android Using JSON

Why should we create an Abstract class

When we study Abstract class in OOPs.
Few questions always come in front of you.
1. What is abstract class ?
2. Where should we use abstract class ?
3. What is difference between Abstract class and Interface

Here i am explaining solutions for first and second question.

Why should we create an Abstract class


Q. What is Abstract Class?
Answer: 

1. An abstract class is one that cannot be instantiated. All other functionality of the class still exists, and its fields, methods, and constructors are all accessed in the same manner.

2. There is chance too few methods are common to some class (business logic). And remaining methods are different. In that kind of scenarios you can implement all the common methods in one class, and declare the remaining as abstract. Then you should declare the class as abstract.

3. Abstract classes let you add base behavior so programmers don't have to code everything, while still forcing them to follow your design.

4. Use the abstract keyword to declare a class abstract. The keyword appears in the class declaration somewhere before the class keyword.

For example:
Games.java

abstract class Games{
          private String nameofteam;
          private int noofplayer;
public Games(String nameofteam,  int noofplayer)
   {
      System.out.println("Constructing a Game");
      this.nameofteam= nameofteam;
      this.noofplayer= noofplayer;
   }
public String getTeamName()
   {
      return nameofteam;
   }
public int getNoOfPlayer()
   {
      return noofplayer;
   }
//////// Abstract Method /////////////////////
 public abstract int computeRanking();
 public abstract int calculateScore();
}

Check above code carefully. You can see a keyword "abstract" in the first line. This is indicate that you are declaring this class as an abstract class.
Now move to the body of this class. I have created some instance variables, methods like normal class and two methods containing abstract keyword.

Both abstract methods have no body.

Explanation:

Suppose I am creating an apps for Games Management System and writing a script to manage individual game records.
In most of the games, you can make  few variables and methods common such as
Variables like nameofteam, noofplayer and methods like getTeamName, getNoOfPlayer . Because these values are necessary in all games. You can define these things here and use common business logic.

But in case of abstract methods like computeRanking or calculateScore You can not create common business logics for all games. The procedure to calculate ranking or score is different for different games.

Now next question is how to use this abstract class?

Suppose i am writing a script for a game like Football.

Football.java

class Football extends Games
{
         public Football(String name,  int number)
               {
                      super(name,  number);
                   
                }
        public int computeRanking()
              {
                      /*
                       Write here codes to compute ranking for football.
                      */

              }
      public int calculateScore()
              {
                      /*
                       Write here codes to calculate score for football.
                      */

              }

}

Similarly you can create scripts for other games such as Cricket, Rugby, Hockey etc.

Create another class: GermanGame.java

public class GermanGame
{
   public static void main(String [] args)
   {
      Football  f = new Football ("Germany",  11);
     
      System.out.println("Call computeRanking ");
      f.computeRanking ();
      System.out.println("\n Call calculateScoreusing ");
     f.calculateScore();
    }
}

Here I am managing details about a football team. So, I create an instance Football. If you want to manage other games, You just create a class of that game and extend with Games class.

I think this enough to understand the usage of Abstract Class.

In next post, I will explain the difference between Abstract class and Interface.

If You have any query. Plz comment here. I will give response as soon as possible.

How to Post to Twitter using Twitter API Wrapper – Twitter4J

Twitter4J is one of the most popular APIs for handling Twitter in Java. If we don’t want to handle the Twitter REST API calls directly .
How to Post to Twitter using Twitter API Wrapper – Twitter4J,Post to Twitter using Twitter API Wrapper – Twitter4J,Twitter using Twitter API Wrapper – Twitter4J,Twitter API Wrapper – Twitter4J,API Wrapper – Twitter4J,Twitter4J,

We want go simple then Twitter4J is the way.
Read this : How to use Twitter Consumer Key and Consumer Secret
All we need to do is add only one jar file from Twitter4J twitter4j-core-3.0.5.jar to the dependency and use the respective classes to make the calls.
package com.geekonjava.java;
 
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
 
public class JavaTweet {
 
  static String consumerKeyStr = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX";
  static String consumerSecretStr = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX";
  static String accessTokenStr = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX";
  static String accessTokenSecretStr = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX";
 
  public static void main(String[] args) {
 
    try {
      Twitter twitter = new TwitterFactory().getInstance();
 
      twitter.setOAuthConsumer(consumerKeyStr, consumerSecretStr);
      AccessToken accessToken = new AccessToken(accessTokenStr,
          accessTokenSecretStr);
 
      twitter.setOAuthAccessToken(accessToken);
 
      twitter.updateStatus("Post using Twitter4J Again");
 
      System.out.println("Successfully updated the status in Twitter.");
    } catch (TwitterException te) {
      te.printStackTrace();
    }
  }
 
}
Thank you for coming and comment for appreciation !!!

How to Post to Twitter Using Twitter REST API

Now we are all set to post to Twitter using Java. In this section, let us see how we can use the REST APIs directly in our Java application. Let us use the status update post Twitter API.

How to Post to Twitter Using Twitter REST API,Post to Twitter Using Twitter REST API,Twitter Using Twitter REST API,Twitter REST API,

All we need to do is,
Read this : How to use Twitter Consumer Key and Consumer Secret
To make these REST call lets use oauth-signpost and Apache Commons HTTP. Following are the dependent jars to be used,
  1. commons-codec-1.6.jar
  2. commons-io-2.4.jar
  3. commons-logging-1.1.3.jar
  4. httpclient-4.3.1.jar
  5. httpcore-4.3.jar
  6. signpost-core-1.2.1.2.jar
  7. signpost-commonshttp4-1.2.1.2.jar
package com.geekonjava.java;
 
import oauth.signpost.OAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
 
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
 
public class JavaRestTweet {
  static String consumerKeyStr = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX";
  static String consumerSecretStr = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX";
  static String accessTokenStr = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX";
  static String accessTokenSecretStr = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX";
 
 
  public static void main(String[] args) throws Exception {
    OAuthConsumer oAuthConsumer = new CommonsHttpOAuthConsumer(consumerKeyStr,
        consumerSecretStr);
    oAuthConsumer.setTokenWithSecret(accessTokenStr, accessTokenSecretStr);
 
    HttpPost httpPost = new HttpPost(
        "http://api.twitter.com/1.1/statuses/update.json?status=Hello%20Twitter%20World.");
 
    oAuthConsumer.sign(httpPost);
 
    HttpClient httpClient = new DefaultHttpClient();
    HttpResponse httpResponse = httpClient.execute(httpPost);
 
    int statusCode = httpResponse.getStatusLine().getStatusCode();
    System.out.println(statusCode + ':'
        + httpResponse.getStatusLine().getReasonPhrase());
    System.out.println(IOUtils.toString(httpResponse.getEntity().getContent()));
 
  }
}
Comment please to appreciate for more post !!!

How to Post to Twitter using Java

Today i am telling you how to post your content to Twitter using Java. They provides a rich REST API to create Twitter enabled applications.
Before going forward to coding we need to generate Twitter API keys which enables us to access the APIs.
We need to get "Consumer Key" and "Consumer Secret" from Twitter. Using these two, we should generate, "Access Token" and "Access Token Secret".
How to Twitter Consumer Key and Consumer Secret
  • Go to the URL https://dev.twitter.com/apps and create a new application. 
  • Give access level in ‘Settings’ as ‘Read, Write and Access direct messages’. 
  • You will get both consumer key and secret.
How to Post to Twitter using Java,Post to Twitter using Java,Twitter using Java,



Twitter Access Token
  • We can generate access tokens using the consumer keys. It can be done using the API or through the interface as well.
  • I am going with generating using the Twitter website itself as shown below. Ensure that the access level comes the same as in consumer keys or regenerate it.