Thursday, July 28, 2016

How to use Google Map API in Android.

How to use Google Map API in Android.
1- you need to create Google API Key
https://developers.google.com/maps/documentation/android-api/
Image1
Click on get Key and follow the process till you get the below screen showing Google API Key
Image2
2- Now create a certificate so that we can authenticate our request using belwo commands
keytool -list -v -alias androiddebugkey -keystore C:\xyz\.android\debug.keystore -storepass android -keypass android
3- Go to
https://code.google.com/apis/console/
if you had already created a project in that case it will direct it to you on below pages
https://console.developers.google.com/iam-admin/projects
Select service accounts from left tab and select your project and generate key id of both the projects.
Image3



Image4
Image5
Image7
4- Create an andorid project and select google Map Activity (we are using Android Studio)
5- Add your Google API key to the srting.xml file
6- Make sure to add latest gms:play-services i nandroid studio as shown below.
Go to File -> Project Structure
Select 'Project Settings'
Select 'Dependencies' Tab
Click '+' and select '1.Library Dependencies'
Search for : com.google.android.gms:play-services
Select the latest version and click 'OK'
7- Run the application
- If you get below error
application won't run unless you update google play service
make sure to follow belwo steps
SDK Manager => Extras => Google Play Services.
Image6

Note: Make sure you change your API_KEY inside both google_maps_api.xml and strings.xml
- If you get this error java.util.concurrent.ExecutionException: com.android.dex.DexIndexOverflowException
add below line in build.gradle inside defaultConfig{}
multiDexEnabled true
Image8

Tuesday, July 19, 2016

How to call REST API using SOAPUI and Basic Authentication

1- Create New SOAP Rest project
Image_1

2- Provide REST Project URL
Image_2

3- Set up Basic Auth

Image_3

4- Click on new basic
Image_4
Select Basic Auth
Image_5


5- Enter User Id and Passwd and select Authenticate pre-emptively radio button
Image_6
Add your resource 
Image_7

Run your request and you will be able to get response in xml, JSON, HTML and RAW.

Monday, July 18, 2016

Calling JIRA REST Web service (Basic Authentication) in android and getting response in JSON.


1- MainActivity

package restapi.siddhu.test.com.restapi;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;

import android.os.AsyncTask;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.core.util.Base64;


public class MainActivity extends AppCompatActivity {

    String text = "siddhu";
    Button b;
    private static String BASE_URL = "https://yourjiraaddress.com";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        b = (Button)findViewById(R.id.my_button);
        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                b.setClickable(false);
                //Create instance for AsyncCallWSGetProjectInfo
                AsyncCallWSGetRetrospect objAsyncCallWSGetRetrospect = new AsyncCallWSGetRetrospect();
                //Call execute
                objAsyncCallWSGetRetrospect.execute();
                // Inflate the layout for this fragment
            }
        });
    }


    private class AsyncCallWSGetRetrospect extends AsyncTask {

        @Override
        protected Void doInBackground(String... params) {
            String auth = new String(Base64.encode("userid:password"));
            try {
            String projects = invokeGetMethod(auth, BASE_URL+"/rest/api/2/project");
            System.out.println(projects);

            JSONArray projectArray = new JSONArray(projects);
            for (int i = 0; i < projectArray.length(); i++) {
                JSONObject proj = projectArray.getJSONObject(i);
                System.out.println("Key:"+proj.getString("key")+", Name:"+proj.getString("name"));
                text = text + "Key:"+proj.getString("key")+", Name:"+proj.getString("name");
            }
            } catch (Exception e) {
                System.out.println("Username or Password wrong!");
                e.printStackTrace();
            }
            return null;
        }
        @Override
        protected void onPostExecute(Void result) {
            if (text!=null) {
                EditText et = (EditText)findViewById(R.id.my_edit);
                et.setText(text);
            }
            Button b = (Button)findViewById(R.id.my_button);
            b.setClickable(true);
        }

        @Override
        protected void onPreExecute() {
            //Toast.makeText(getContext(), "Fetching Retrospect information of Sprint ...", Toast.LENGTH_SHORT).show();
            //loading.show();
        }

        @Override
        protected void onProgressUpdate(Void... values) {

        }
    }

    private static String invokeGetMethod(String auth, String url) throws Exception, ClientHandlerException {
        Client client = Client.create();
        WebResource webResource = client.resource(url);
        ClientResponse response = webResource.header("Authorization", "Basic " + auth).type("application/json")
                .accept("application/json").get(ClientResponse.class);
        int statusCode = response.getStatus();
        if (statusCode == 401) {
            throw new Exception("Invalid Username or Password");
        }
        return response.getEntity(String.class);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.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();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}


2- content_main.xml

    TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Http GET Demo"
    Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="GET"
        android:id="@+id/my_button"
        android:layout_below="@+id/my_edit"
        android:layout_alignLeft="@+id/my_edit"
        android:layout_alignStart="@+id/my_edit"
        android:layout_marginTop="62dp" 
    EditText
        android:layout_margin="20dip"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:minLines="15"
        android:maxLines="15"
        android:textSize="12sp"
        android:editable="false"
        android:id="@+id/my_edit"


3- AndrodManifest.xml


   uses-permission android:name="android.permission.INTERNET"



Note: Please add following jar in android studio/project
jersey-client-1.8.jar
jersey-core-1.8.jar
json-20090211.jar
rest-client-1.0.jar



Sunday, July 03, 2016

How to add progress bar in android

1- In activity class use below code

ProgressDialog loading = null;
Inside onCreate method:-
loading = new ProgressDialog(ProjectPageActivity.this);
        loading.setMessage("Please wait...");
        loading.setCancelable(false);
        loading.setIndeterminate(true);
        loading.setProgressStyle(ProgressDialog.STYLE_SPINNER);

2- Use below code to show the progress graph

            loading.show();

3- Use below code to hide it
loading.dismiss();

Add back functionality with button on android and icon

Use following code to add back button functionality in android
Image2
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setNavigationIcon(R.drawable.arwbck);
toolbar.setOverflowIcon(getResources().getDrawable(R.drawable.menuicn));
toolbar.setTitleTextColor(Color.RED);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);

@Override
public boolean onSupportNavigateUp(){
finish();
return true;
}


How to use expandableview and list view

1- XML modification
Add following tag in your xml. This will assist us in showing list.
android:id="@+id/listProject"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#b5b5b5"
android:dividerHeight="1dp"
android:listSelector="@drawable/list_selector">


ListView1

2- Now add Items in list.Create a new *.xml and add below code in it. This xmls define what you want to show in above image
We are showing only Project name in the list

android:id="@+id/tvProjectName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom ="9dip"
android:text="@string/tvProjectName"
android:textColor="#040404"
android:textSize="20dip"
android:textStyle="bold"
android:typeface="sans"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />

3- In project activity java code use below line
// List items
ListView list;
ProjectBinderData adapter = null;
List> projectDataCollection;
HashMap mapSingleProjectDataCollection;
try {
projectDataCollection = new ArrayList>();
for(int i=0;i{
mapSingleProjectDataCollection = new HashMap();
mapSingleProjectDataCollection.put(KEY_PROJECT_ID, projectInfoList[i].getProperty("projectId").toString()); try {
projectDataCollection = new ArrayList>();
for(int i=0;i{
mapSingleProjectDataCollection = new HashMap();
mapSingleProjectDataCollection.put(KEY_PROJECT_ID, projectInfoList[i].getProperty("projectId").toString());
mapSingleProjectDataCollection.put(KEY_PROJECT_NAME, projectInfoList[i].getProperty("projectName").toString());
projectDataCollection.add(mapSingleProjectDataCollection);
}
//Add to the Arraylist
ProjectBinderData bindingData = new ProjectBinderData(ProjectPageActivity.this,projectDataCollection);

list = (ListView) findViewById(R.id.listProject);
Log.i("BEFORE", "<<------------- before="" setadapter--------------="">>");
list.setAdapter(bindingData);
Log.i("AFTER", "<<------------- after="" setadapter--------------="">>");
// Click event for single list row and send the data to sprint page.
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView parent, View view,
int position, long id) {
Intent i = new Intent();
i.setClass(ProjectPageActivity.this, SprintPageActivity.class);
// parameters
i.putExtra("projectId", projectDataCollection.get(position).get(KEY_PROJECT_ID));
i.putExtra("projectViewId", projectViewId);
// start the sample activity
startActivity(i);
}
});
}
catch (Exception ex) {
//Toast.makeText(getApplicationContext(), "System Error Please try after some time !!!!!",Toast.LENGTH_SHORT).show();
ex.printStackTrace();
}
mapSingleProjectDataCollection.put(KEY_PROJECT_NAME, projectInfoList[i].getProperty("projectName").toString());
mapSingleProjectDataCollection.put(KEY_CURRENT_SPRINT, "Current Sprint "+projectInfoList[i].getProperty("completedSprint").toString()+"/"+projectInfoList[i].getProperty("totalSprint").toString());
mapSingleProjectDataCollection.put(KEY_TOTAL_SPRINT, projectInfoList[i].getProperty("totalSprint").toString());
mapSingleProjectDataCollection.put(KEY_COMPLETED_SPRINT, projectInfoList[i].getProperty("completedSprint").toString());
mapSingleProjectDataCollection.put(KEY_PROJECT_START_DATE, projectInfoList[i].getProperty("projectStartDate").toString());
mapSingleProjectDataCollection.put(KEY_PROJECT_END_DATE, projectInfoList[i].getProperty("projectEndDate").toString());
mapSingleProjectDataCollection.put(KEY_RAG_STATUS, projectInfoList[i].getProperty("ragStatus").toString());
mapSingleProjectDataCollection.put(KEY_PROJECT_STATUS, projectInfoList[i].getProperty("projectStatus").toString());
projectDataCollection.add(mapSingleProjectDataCollection);
}
//Add to the Arraylist
ProjectBinderData bindingData = new ProjectBinderData(ProjectPageActivity.this,projectDataCollection);

list = (ListView) findViewById(R.id.listProject);
Log.i("BEFORE", "<<------------- before="" setadapter--------------="">>");
list.setAdapter(bindingData);
Log.i("AFTER", "<<------------- after="" setadapter--------------="">>");
// Click event for single list row and send the data to sprint page.
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView parent, View view,
int position, long id) {
Intent i = new Intent();
i.setClass(ProjectPageActivity.this, SprintPageActivity.class);
// parameters
i.putExtra("projectId", projectDataCollection.get(position).get(KEY_PROJECT_ID));
i.putExtra("projectViewId", projectViewId);
// start the sample activity
startActivity(i);
}
});
}
catch (Exception ex) {
//Toast.makeText(getApplicationContext(), "System Error Please try after some time !!!!!",Toast.LENGTH_SHORT).show();
ex.printStackTrace();
}
4- Create a new class ProjectBinderData
public class ProjectBinderData extends BaseAdapter {

static final String KEY_PROJECT_ID = "KEY_PROJECT_ID";
static final String KEY_PROJECT_NAME= "KEY_PROJECT_NAME";

LayoutInflater inflater;
List> projectDataCollection;
ViewHolder holder;
public ProjectBinderData() {
// TODO Auto-generated constructor stub
}
public ProjectBinderData(Activity act, List> map) {
this.projectDataCollection = map;
inflater = (LayoutInflater) act
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

public int getCount() {
// TODO Auto-generated method stub
// return idlist.size();
return projectDataCollection.size();
}
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null){
vi = inflater.inflate(R.layout.list_project, null);
holder = new ViewHolder();
holder.tvProjectName = (TextView)vi.findViewById(R.id.tvProjectName); // Project name
vi.setTag(holder);
}
else{
holder = (ViewHolder)vi.getTag();
}
// Setting all values in listview
holder.tvProjectName.setText(projectDataCollection.get(position).get(KEY_PROJECT_NAME));
return vi;
}
/*
*
* */
static class ViewHolder{
TextView tvProjectName;
}
}

How to use Decoview chart i.e. Google Fit in android

Decoview

1- XML class to tag Deco View element
xmlns:custom="http://schemas.android.com/apk/res-auto"
custom:dv_lineWidth="5dp"
android:id="@+id/dynamicArcView"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_toRightOf="@+id/tvProjectEndDate"
android:layout_above="@+id/projectStatus"
android:layout_alignParentTop="true">
android:id="@+id/percentage"
android:layout_width="60dp"
android:layout_height="40dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="30sp"
android:layout_above="@+id/tvProjectEndDate"
android:layout_toRightOf="@+id/textView5"
android:layout_toEndOf="@+id/textView5"
android:layout_marginLeft="30dp"
android:layout_marginBottom="10dp" />

2- Make following change in corresponding Activity JAVA class.
//Adding the coe to show the graph start

//SeriesItem seriesItem = new SeriesItem.Builder(Color.parseColor("#00B0CA"))
SeriesItem seriesItem = new SeriesItem.Builder(Color.parseColor("#e60000"))
.setRange(0, 100, 0)
.build();
//first 0 indicate start, second 100 indicate we have to cover 100% area of the round graph and thrid 0 indidate current starting point.
final DecoView decoView = (com.hookedonplay.decoviewlib.DecoView)vi.findViewById(R.id.dynamicArcView);
final int backIndex = decoView.addSeries(seriesItem);
/*decoView.addEvent(new DecoEvent.Builder(50)
.setIndex(backIndex)
.build());cmd
*/
int series1Index = decoView.addSeries(seriesItem);
final TextView textPercentage = (TextView)vi.findViewById(R.id.percentage);
final float totalSprint = Float.parseFloat(projectDataCollection.get(position).get(KEY_TOTAL_SPRINT));
final float completedSprint = Float.parseFloat(projectDataCollection.get(position).get(KEY_COMPLETED_SPRINT));
float percentBuild = (completedSprint/totalSprint);
//Above code is to calculate perfect % Value that need to be show inside graph
decoView.addEvent(new DecoEvent.Builder(percentBuild * 100f)
.setIndex(backIndex)
.build());
seriesItem.addArcSeriesItemListener(new SeriesItem.SeriesItemListener() {
@Override
public void onSeriesItemAnimationProgress(float percentComplete, float currentPosition) {
float percentFilled = (completedSprint/totalSprint);
textPercentage.setText(String.format("%.0f%%", percentFilled * 100f));
textPercentage.setTextColor(Color.parseColor("#e60000"));
}
@Override
public void onSeriesItemDisplayProgress(float percentComplete) {
}
});
//Adding the code to show the graph End]

3- Add following dependecies in build.gradle

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:design:23.1.1'
compile 'com.github.bmarrdev:android-DecoView-charting:v0.9.3'
}