Monday, 29 December 2014

Upload file to xampp server android acts as a client

How to Start the XAMPP Server

  1. Start Terminal. Issue this command to go where XAMPP is installed
    cd /Applications/XAMPP/xamppfiles
  2. Issue the following command.  You have to use SUDO because this command needs root level privilege. Note that ./ is important. It indicates xampp is in the current folder
    SUDO ./xampp start
  3. Before running this create a folder uploads in htdocs which is inside xampp  
  4. SampleClient&Server 

GCM Client and Server Example

Following zip contains both GCM Client and GCM Server sample implementation

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

How to run GCM Server

--------------------
1)Add Apache Tomcat Runtime environment installation in eclipse
    1.1)Go to help --->Install new software
     1.2)Select or add "http://download.eclipse.org/releases/galileo"
    1.3)Check the following: “JST Server Adapters” (there are two)

Now the adapters are installed, but not configured. Configuration is like this:

2) Go to: Eclipse -> Preferences 
3) Select: Server -> Runtime Environment
4) Click: “Add…”
5) Select: Apache -> Apache Tomcat v6.0 (or choose the version you need)
Add J2EE tools to the Eclipse
------------------------------------
Go to Help->Install New Software.
In the dropdown, select 'Juno - http://download.eclipse.org/releases/juno '
Expand 'Web, XML, Java EE, and OSGI Enterprise Development'
Check the box for 'Eclipse Java EE Developer Tools'
After the above two steps are done
1)Create new dynamic project in eclipse and copy paste above files present in the GCMServer
2)Start the Tomcat server by selecting windows--->ShowView--->servers
3)Server tab will be opened below then add new wizard and set up the tomcat
4)Right click on the server and set its location to the downloaded tomcat directory
5)Double click on the server overview page will be opened where click on openlaunchconfiguration and go to class path and add tomcatjuli.jar to user Entries which is present in bin of the downloaded tomcat
6)Specify server location as "Use Tomcat Installation"
7)Save and start the server
8)Go to browswer and type the following address "http://localhost:8080/GCMService/index.jsp"
9)Click on submit



 Following keys should be entered in the GCM Server

------------------------------------------------
1)Device token which is obtained when we run GCM Client on the Phone

private static final String DROID_BIONIC = "APA91bE0HSlPYPbF7Rd9tmrCWKS4yqiFx5WX6sFjxKeP3eKR2iXuae9Fbm_UzEt4HC3PWGaicGsJjkUAepAIImimv3HOPGX8zI1EYDwuivXu1rTiUY1t-9KIULoMzf75OIqM-zOXbEF0-hf8P14XqqbyzNOoS_EtaTO96VVzDM5id0bCXt2qZmo";
2)Key for Server Applications which can be taken from google console page

private static final String SENDER_ID = "AIzaSyAJYd7DLJr3Voazx_cEBEPtkjhet_znx_9";


Following keys should be entered in GCM Client
------------------------------------------------------
1)Project ID
senderID = "858139312320"



Client and Server Example

Tuesday, 16 September 2014

Build android project using ANT Script

1)Set path for Java , Android tools , Android platform tools
2)Install Apache set path for it.You can also set from command prompt like
set ANT_HOME=C:\ANT\Ant\apache-ant-1.9.4-bin\apache-ant-1.9.4

Once Path is set ping for ANT command and check whether you get response.

Following steps to build project using ANT[Debug APK]

1)Following command in command prompt


Once this command is success  check your project files like build.xml , local.properties ..etc are generated

2)Next step is building an APK.
Following command to build debug version of APK
ant debug
Above command should be entered in the command prompt once you navigate to your project path

3)After this we get  message in command prompt as build successful , if build gets failed due to any reason just try ant clean and again give ant debug

4)Once build is successful you will get an APK in the bin folder of the project


Following steps to build project using ANT[Release Signed APK]


1)Following command in command prompt

Once this command is success  check your project files like build.xml , local.properties ..etc are generated

2)Add the following lines to your local.properties file

key.store=D:\\Android\\keyStore\\myfile
key.alias=myfile

3)Next step is building an APK.



Following command to build release version of Signed APK
ant release
Above command should be entered in the command prompt once you navigate to your project path

4)You will be prompted to enter password for key store .
Enter the required password and press enter.

5)After this we get  message in command prompt as build successful , if build gets failed due to any reason just try ant clean and again give ant release

6)Once build is successful you will get an Signed APK in the bin folder of the project

Toggle Button



import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import android.widget.ToggleButton;

public class MyAndroidAppActivity extends Activity {

    private ToggleButton toggleButton1, toggleButton2;
    private Button btnDisplay;

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

        addListenerOnButton();

    }

    public void addListenerOnButton() {

        toggleButton1 = (ToggleButton) findViewById(R.id.toggleButton1);
        toggleButton2 = (ToggleButton) findViewById(R.id.toggleButton2);
        btnDisplay = (Button) findViewById(R.id.btnDisplay);

       
       
        btnDisplay.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                StringBuffer result = new StringBuffer();
                result.append("toggleButton1 : ").append(
                        toggleButton1.getText());
                result.append("\ntoggleButton2 : ").append(
                        toggleButton2.getText());

                Toast.makeText(MyAndroidAppActivity.this, result.toString(),
                        Toast.LENGTH_SHORT).show();

            }

        });
       
        toggleButton1.setOnClickListener(new OnClickListener() {
           
            @Override
            public void onClick(View arg0) {
            if(toggleButton1.isChecked())
            {
                Toast.makeText(getApplicationContext(), "Checked", Toast.LENGTH_LONG).show();
               
            }
            else
            {
                Toast.makeText(getApplicationContext(), "un Checked", Toast.LENGTH_LONG).show();
               
            }
               
            }
        });
       

    }
}

Main.xml


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

    <ToggleButton
        android:id="@+id/toggleButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textOn="@drawable/power_on"
        android:textOff="@drawable/ic_launcher"
        android:text="ToggleButton" />

    <ToggleButton
        android:id="@+id/toggleButton2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textOn="@string/toggle_turn_on"
        android:textOff="@string/toggle_turn_off"
        android:checked="true" />

    <Button
        android:id="@+id/btnDisplay"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/btn_display" />

</LinearLayout>

Sunday, 7 September 2014

Hash Map with multiple values

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * HashMap - Single Key and Multiple Values using List
 *
 *
 *
 */
public class SingleKeyMultipleValueUsingList {
    public static void main(String[] args) {
        // create map to store
        Map<String, List<String>> map = new HashMap<String, List<String>>();
        // create list one and store values
        List<String> valSetOne = new ArrayList<String>();
        valSetOne.add("Apple");
        valSetOne.add("Aeroplane");
        // create list two and store values
        List<String> valSetTwo = new ArrayList<String>();
        valSetTwo.add("Bat");
        valSetTwo.add("Banana");
        // create list three and store values
        List<String> valSetThree = new ArrayList<String>();
        valSetThree.add("Cat");
        valSetThree.add("Car");
        // put values into map
        map.put("A", valSetOne);
        map.put("B", valSetTwo);
        map.put("C", valSetThree);
        // iterate and display values
        System.out.println("Fetching Keys and corresponding [Multiple] Values n");
        for (Map.Entry<String, List<String>> entry : map.entrySet()) {
            String key = entry.getKey();
            List<String> values = entry.getValue();
            System.out.println("Key = " + key);
            System.out.println("Values = " + values + "n");
        }
    }
}

Thursday, 4 September 2014

Check BlueTooth status during App Start and Monitor status using broad cast receiver

Manifest Permissions

<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
 <uses-permission android:name="android.permission.BLUETOOTH" />

Main activity

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.Toast;


public class MainActivity extends ActionBarActivity {
   
        private BluetoothAdapter mBluetoothAdapter = null;
     private static final int REQUEST_ENABLE_BT = 3;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
       
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

       //register BroadcastReceiver here
         registerReceiver(new BTStateChangedBroadcastReceiver(),
                    new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
              if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }
       
                   
       
       
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

   
   
     @Override
        public void onStart() {
            super.onStart();
        

            // If BT is not on, request that it be enabled.
            // setupChat() will then be called during onActivityResult
            if (!mBluetoothAdapter.isEnabled()) {
                Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
            // Otherwise, setup the chat session
            }
        }
     public void onActivityResult(int requestCode, int resultCode, Intent data) {
           
            switch (requestCode) {
         
            case REQUEST_ENABLE_BT:
                // When the request to enable Bluetooth returns
                if (resultCode == Activity.RESULT_OK) {
                       Toast.makeText(this, R.string.bt_enabled, Toast.LENGTH_SHORT).show();
                
                } else {
                    // User did not enable Bluetooth or an error occurred
                    Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
                    finish();
                }
            }
        }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container,
                    false);
            return rootView;
        }
    }

}



BroadCast Receiver :

This is needed in order to monitor status


import android.bluetooth.BluetoothAdapter;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class BTStateChangedBroadcastReceiver extends BroadcastReceiver {
   
     @Override
     public void onReceive(Context context, Intent intent) {
      int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
        -1);
      
      switch(state){
      case BluetoothAdapter.STATE_CONNECTED:
       Toast.makeText(context,
        "BTStateChangedBroadcastReceiver: STATE_CONNECTED",
        Toast.LENGTH_SHORT).show();
       break;
      case BluetoothAdapter.STATE_CONNECTING:
       Toast.makeText(context,
        "BTStateChangedBroadcastReceiver: STATE_CONNECTING",
        Toast.LENGTH_SHORT).show();
       break;
      case BluetoothAdapter.STATE_DISCONNECTED:
       Toast.makeText(context,
        "BTStateChangedBroadcastReceiver: STATE_DISCONNECTED",
        Toast.LENGTH_SHORT).show();
       break;
      case BluetoothAdapter.STATE_DISCONNECTING:
       Toast.makeText(context,
        "BTStateChangedBroadcastReceiver: STATE_DISCONNECTING",
        Toast.LENGTH_SHORT).show();
       break;
      case BluetoothAdapter.STATE_OFF:
       Toast.makeText(context,
        context.getResources().getString(R.string.bluetooth_alert),
        Toast.LENGTH_SHORT).show();
       break;
      case BluetoothAdapter.STATE_ON:
       Toast.makeText(context,
        "BTStateChangedBroadcastReceiver: STATE_ON",
        Toast.LENGTH_SHORT).show();
       break;
      case BluetoothAdapter.STATE_TURNING_OFF:
       Toast.makeText(context,
        "BTStateChangedBroadcastReceiver: STATE_TURNING_OFF",
        Toast.LENGTH_SHORT).show();
       break;
      case BluetoothAdapter.STATE_TURNING_ON:
       Toast.makeText(context,
        "BTStateChangedBroadcastReceiver: STATE_TURNING_ON",
        Toast.LENGTH_SHORT).show();
       break;
      }
     }
   
    }

Monday, 25 August 2014

Android Gallery Page Indicator

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
 
 
public class ImageAdapter extends BaseAdapter {
    private Context mContext;
 
    //array of integers for images IDs
    private Integer[] mImageIds = {
            R.drawable.avatar_423,
            R.drawable.da,
            R.drawable.penguins
 
    };
 
    //constructor
    public ImageAdapter (Context c){
        mContext = c;
    }
 
    @Override
    public int getCount() {
        return mImageIds.length;
    }
 
    @Override
    public Object getItem(int i) {
        return i;
    }
 
    @Override
    public long getItemId(int i) {
        return i;
    }
 
    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        ImageView imageView = new ImageView(mContext);
 
        imageView.setImageResource(mImageIds[i]);
        imageView.setLayoutParams(new Gallery.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
        return imageView;
    }
}
 
 
 
 

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:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Hello World, MyActivity"/>
 
    <!-- This is the Gallery -->
    <Gallery xmlns:android="http://schemas.android.com/apk/res/android"
             android:id="@+id/gallery"
             android:layout_width="fill_parent"
             android:layout_height="wrap_content"/>
 
    <!-- This LinearLayout if for the dots -->
    <LinearLayout android:id="@+id/image_count"
                  android:layout_width="fill_parent"
                  android:layout_height="wrap_content"
                  android:orientation="horizontal"
                  android:gravity="center"
                  android:background="#00000000">
    </LinearLayout>
 
</LinearLayout>
 
 
 

MainActivity

 

 

import android.app.Activity;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
 
public class MyActivity extends Activity
{
    static TextView mDotsText[];
    private int mDotsCount;
    private LinearLayout mDotsLayout;
 
 
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
 
        //here we create the gallery and set our adapter created before
        Gallery gallery = (Gallery)findViewById(R.id.gallery);
        gallery.setAdapter(new ImageAdapter(this));
 
 
        mDotsLayout = (LinearLayout)findViewById(R.id.image_count);
        //here we count the number of images we have to know how many dots we need
        mDotsCount = gallery.getAdapter().getCount();
 
        //here we create the dots
        //as you can see the dots are nothing but "."  of large size
        mDotsText = new TextView[mDotsCount];
 
        //here we set the dots
        for (int i = 0; i < mDotsCount; i++) {
            mDotsText[i] = new TextView(this);
            mDotsText[i].setText(".");
            mDotsText[i].setTextSize(45);
            mDotsText[i].setTypeface(null, Typeface.BOLD);
            mDotsText[i].setTextColor(android.graphics.Color.GRAY);
            mDotsLayout.addView(mDotsText[i]);
        }
 
 
        //when we scroll the images we have to set the dot that corresponds to the image to White and the others
        //will be Gray
        gallery.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView adapterView, View view, int pos, long l) {
 
                for (int i = 0; i < mDotsCount; i++) {
                    MyActivity.mDotsText[i]
                            .setTextColor(Color.GRAY);
                }
 
                MyActivity.mDotsText[pos]
                        .setTextColor(Color.WHITE);
            }
 
            @Override
            public void onNothingSelected(AdapterView adapterView) {
 
            }
        });
    }
}
 
 
Done:)

 

 

Thursday, 24 July 2014

How to browse SQLLite Data in android

While Android puts a powerful built-in database at your disposal, it doesn't come with the best set of debugging tools. In fact, unless you have a rooted device, you can't even get the SQLite tables off your device without jumping through some hoops.  Fortunately, the Android emulator doesn't have this restriction.


Within Eclipse, you need to switch to DDMS mode by going to Window | Open Perspective | DDMS. If you've never used DDMS, you'll likely need to go to Window | Open Perspective | Other and then browse for DDMS within the list

Once the DDMS view is active, choose the File Explorer tab. You'll find your database in the /data/data/your.app.namespace/databases directory. There are two virtually indistinguishable icons in the upper right-hand corner of the tab that represent a pull and a push of a file, respectively. Use the pull icon (the one on the left) to save a copy of the SQLite database to your development machine and change extension of the copied file to .sqlite


 Now you have a copy of your database on your workstation, but you still need some kind of SQLite viewer to take a peek. I use SQLite Manager, because it is free and runs well

Open the SQLite Manager in the fire fox and select connect database option as shown below




Once you select browse for the file which you have saved in your workstation .

Done:)
You can browse and check your data

Pass a HashMap from Angular Client to Spring boot API

This example is for the case where fileData is very huge and in json format   let map = new Map<string, string>()      map.set(this.ge...