Tuesday 17 May 2016

Save the value by using shared preferences.

What is shared preferences?
  • You can save and retrieve key, value pair data from Shared preferences.
  • SharedPreferences values will persist across user sessions. Data in shared preferences will be persistent even though user closes the application. 
  • You can get values from Shared preferences using getSharedPreferences() method. 
  • You also need an editor to edit and save the changes in shared preferences. 
  • Use SharedPreferences to store data: booleans, floats, ints, longs, and strings.    

Create the Credentials class for save&get the value in sharepreferences.
 
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;

/**
 * Created by Laptop on 12-05-2016.
 */
public class Credentials {
    private static final String APP_KEY = "app_name";
    private static final String USER_ID = "user_id";
    private static final String USER_EMAIL = "email";

    public static void SaveUserID(int id, Context context) {
        SharedPreferences preferences = context.getSharedPreferences(APP_KEY, Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putInt(USER_ID, id);
        editor.apply();
    }

    public static int getUserID(Context context) {
        SharedPreferences preferences = context.getSharedPreferences(APP_KEY, Activity.MODE_PRIVATE);
        return preferences.getInt(USER_ID, 0);
    }


    public static void SaveUserEmail(String email, Context context) {
        SharedPreferences preferences = context.getSharedPreferences(APP_KEY, Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString(USER_EMAIL, email);
        editor.apply();
    }

    public static String getUserEmail(Context context) {
        SharedPreferences preferences = context.getSharedPreferences(APP_KEY, Activity.MODE_PRIVATE);
        return preferences.getString(USER_EMAIL, "");
    }
}

Create the Main file in project.


import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.digi.soft.Utils.Credentials;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Laptop on 12-05-2016.
 */
public class MainActivity extends AppCompatActivity {

    public static final String LOGIN_URL = "http://employee.digisoftsolution.net/api/User/Login";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activtiy_login);
    }

    private void LoginUser() {

        StringRequest stringRequest = new StringRequest(Request.Method.POST, LOGIN_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            int id = jsonObject.optInt("ID");
                            String email = jsonObject.optString("EmployeeEmail");

                            if (id > 0) {
                                //*******Save value through share prefernce*******//
                                Credentials.SaveUserID(id,MainActivity.this);
                                Credentials.SaveUserEmail(email, MainActivity.this);
                                openProfile();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("", "");
                return map;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }
    private void openProfile() {
        Intent intent = new Intent(this, InOutActivity.class);
        startActivity(intent);
    }
    //*******************END*****************//

}


May this code help you. Thanks!!!!!!


                                                                                                                                              

Friday 13 May 2016

Retrieve Data From Server in Android studio using Volley.
What is Android Volley?
Android Volley is an HTTP library that makes networking for Android apps easier and most importantly, faster.

    Open android studio and create a new project.
     File => New => New Project => Configure your new project => Select the form factor yours app   will run on => Add an Activity to Mobile => Customize the Activity => Finish.

    First we need to add Volley Library to our project.  
    compile 'com.mcxiaoke.volley:library-aar:1.0.0'
    Create main xml file in project.   
    Open => app => res => layout - activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.laptop.getting.MainActivity">
    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:clickable="true" />
</RelativeLayout>

    Create row_item file in project.

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

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="12dp"  >

        <RelativeLayout
            android:id="@+id/linear"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <!-- Description-->
            <TextView
                android:id="@+id/description"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="18dp"
                android:layout_alignParentLeft="true"
                android:layout_toLeftOf="@+id/amount"
                android:layout_centerInParent="true"
                android:text="Description"
                android:textStyle="bold"
                android:textColor="#2D2D2D"
                />
            <!-- Amount -->
            <TextView
                android:id="@+id/amount"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Amount"
                android:textColor="#FF0000"
                android:layout_alignParentTop="true"
                android:textSize="18dp"
                android:layout_marginTop="2dp"
                android:textStyle="bold"
                android:gravity="right"
                android:layout_alignTop="@+id/description"
                android:layout_toStartOf="@+id/type" />
            <TextView
                android:id="@+id/type"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="(E)"

                android:layout_alignParentTop="true"
                android:layout_alignParentRight="true"
                android:textSize="8dp"
                android:layout_marginTop="2dp"
                android:textStyle="bold"
                android:gravity="right"
                android:layout_alignTop="@+id/description" />

        </RelativeLayout>
        <RelativeLayout
            android:id="@+id/linear1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/linear"
            android:layout_marginTop="6dp"
            android:orientation="horizontal">
            <!-- Description-->
            <TextView
                android:id="@+id/tag"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:text="Tag"
                android:textColor="#2D2D2D"
                android:layout_toLeftOf="@+id/created"
                android:textSize="16dp"
                android:layout_centerVertical="true" />

            <!-- Amount -->
            <TextView
                android:id="@+id/created"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:text="28-04-2016"
                android:textStyle="bold"
                android:layout_alignParentTop="true"
                android:textColor="#2D2D2D"
                android:textSize="14dp" />
        </RelativeLayout>

        <RelativeLayout
            android:id="@+id/linear2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/linear1"
            android:layout_marginTop="6dp"
            android:orientation="horizontal">
            <!-- Description-->
            <TextView
                android:id="@+id/note"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:text="note"
                android:layout_toLeftOf="@+id/linearLayout"
                android:layout_centerInParent="true"
                android:textColor="#2D2D2D"
                android:textSize="16dp" />


            <LinearLayout
                android:id="@+id/linearLayout"
                android:orientation="horizontal"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_alignParentTop="true"
                android:layout_alignTop="@+id/note">
            </LinearLayout>
        </RelativeLayout>
    </RelativeLayout>
</RelativeLayout>

    Create the Main file in project.
   Open app => main  => src = MainActivity.java

  package com.example.laptop.getting;

import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity  {


    private Toolbar toolbar;
    ListView lvExpend;
    ExpenditureAdapter ExpenAdapter;
    private ProgressDialog progressDialog;
    public static final String JSON_URL ="http://devapi.budgettwo.com/API/Expenditure/ViewExpenditure?id=1";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lvExpend = (ListView) findViewById(R.id.list);
        setTitle("Expenditure");

        sendRequest();
    }

    private void sendRequest() {
        showDialog(true);
        StringRequest stringRequest = new StringRequest(JSON_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        showDialog(false);
                        showJSON(response);
                        Toast.makeText(MainActivity.this, response, Toast.LENGTH_LONG).show();

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        showDialog(false);
         Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
                    }
                });

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }

    private void showJSON(String json) {
        ParseJSON pjson = new ParseJSON(json);
        ArrayList<Expenditure> expenditures = pjson .parseJSON();
        ExpenAdapter = new ExpenditureAdapter(this, expenditures);
        ExpenAdapter.notifyDataSetChanged();
        lvExpend.setAdapter(ExpenAdapter);
        //******Pass to************//
        lvExpend.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Expenditure expenditure = ExpenAdapter.getSelectedItem(position);
            }
        });
    }

    private void showDialog(boolean check) {
        if (check) {
            progressDialog = ProgressDialog.show(MainActivity.this, "", "Loading...");
        } else {
            if (progressDialog != null && progressDialog.isShowing()) {
                progressDialog.dismiss();
            }
        }
    }
}

     Create the ParseJSON file in project. 

 package com.example.laptop.getting;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;

/**
 * Created by Laptop on 19-04-2016.
 */
public class ParseJSON {

    public static final String JSON_ARRAY = "expenditureModel";
    public static final String KEY_ID = "ID";
    public static final String KEY_DESC = "Description";
    public static final String KEY_AMOUNT = "Amount";
    public static final String KEY_TAG = "TagName";
    public static final String KEY_NOTE = "Notes";
    public static final String KEY_CREATED = "CreatedDate";//CreatedOn
    public static final String KEY_TYPE = "Type";
    private JSONArray users = null;
    private String json;

    public ParseJSON(String json) {
        this.json = json;
    }

    private ArrayList<Expenditure> expenditures = new ArrayList<>();

    protected ArrayList<Expenditure> parseJSON() {
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(json);
            users = jsonObject.getJSONArray(JSON_ARRAY);
            for (int i = 0; i < users.length(); i++) {
                Expenditure expenditure = new Expenditure();
                JSONObject jo = users.getJSONObject(i);
                expenditure.id = jo.optInt(KEY_ID);
                expenditure.desc = optString(jo, KEY_DESC);
                expenditure.amount = optString(jo, KEY_AMOUNT);
                expenditure.tag = optString(jo, KEY_TAG);
                expenditure.note = optString(jo, KEY_NOTE);
                expenditure.created = optString(jo, KEY_CREATED);
                expenditure.type=optString(jo,KEY_TYPE);
                expenditures.add(expenditure);
            }
        }
        catch (JSONException e) {
            e.printStackTrace();
        }
        return expenditures;
    }
    /**
     * Return the value mapped by the given key, or {@code null} if not present or null.
     */
    public static String optString(JSONObject json, String key) {
        // http://code.google.com/p/android/issues/detail?id=13830
        if (json.isNull(key))
            return "";
        else
            return json.optString(key, null);
    }
}


     Create the Custom Item file in project.   

  package com.example.laptop.getting;

/**
 * Created by Laptop on 24-04-2016.
 */
public class Expenditure {

    public int id;
    public String desc;
    public String amount;
    public String tag;
    public String note;
    public String created;
    public String type;
}


     Create the Adapter file in project. 

 package com.example.laptop.getting;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.ArrayList;

/**
 * Created by Laptop on 13-05-2016.
 */
public class ExpenditureAdapter extends BaseAdapter {

    private ArrayList<Expenditure> expenditures = new ArrayList<>();
    private Activity context;
    String mDesc, mAmount, mTag, mCalender, mNote, mID;

    public ExpenditureAdapter(Activity context, ArrayList<Expenditure> ids) {
        this.context = context;
        this.expenditures = ids;
    }
    public Expenditure getSelectedItem(int pos) {
        return expenditures.get(pos);
    }
    @Override
    public int getCount() {
        return expenditures.size();
    }
    @Override
    public Object getItem(int position) {
        return null;
    }
    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = context.getLayoutInflater();
        View listViewItem = inflater.inflate(R.layout.list_row, null, true);

        final TextView descTextView = (TextView) listViewItem.findViewById(R.id.description);
        TextView amountTextView = (TextView) listViewItem.findViewById(R.id.amount);
        TextView tagTextView = (TextView) listViewItem.findViewById(R.id.tag);
        TextView noteTextView = (TextView) listViewItem.findViewById(R.id.note);
        TextView createdTextView = (TextView) listViewItem.findViewById(R.id.created);
        TextView typeTextView=(TextView)listViewItem.findViewById(R.id.type);

        descTextView.setText(expenditures.get(position).desc);
        amountTextView.setText(expenditures.get(position).amount);
        tagTextView.setText(expenditures.get(position).tag);
        noteTextView.setText(expenditures.get(position).note);
        createdTextView.setText(expenditures.get(position).created);
        typeTextView.setText("("+expenditures.get(position).type+")");

        return listViewItem;
    }
}


    Add Internet permission in your manifest
 <uses-permission android:name="android.permission.INTERNET"/>


May this code help you. Thanks!!!!!!

Thursday 12 May 2016

JSON parsing using Volley

Android JSON parsing using Volley
What is Android Volley? 


Android Volley is an HTTP library that makes networking for Android apps easier and most importantly, faster.


Creating New Project.

    Open android studio and create a new project.
     File => New => New Project => Configure your new project => Select the form factor yours app will run on => Add an Activity to Mobile => Customize the Activity => Finish.

    First we need to add Volley Library to our project.   
    compile 'com.mcxiaoke.volley:library-aar:1.0.0'

     Create Xml file in project.     
    Open => app => res => layout - activity_main.xml.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="24dp"
        android:layout_marginRight="24dp"
        android:gravity="center"
        android:orientation="vertical">

        <LinearLayout
            android:id="@+id/linearLayput"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/imageView"
            android:orientation="vertical">

            <EditText
                android:id="@+id/email"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:drawableRight="@drawable/user"
                android:focusableInTouchMode="true"
                android:hint="EmailAddress"
                android:inputType="textEmailAddress"
                android:paddingLeft="8dp"
                android:singleLine="true" />

            <EditText
                android:id="@+id/pwd"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="8dp"
                android:layout_marginTop="8dp"
                android:drawableRight="@drawable/password"
                android:hint="Password"
                android:inputType="textPassword"
                android:paddingLeft="8dp"
                android:singleLine="true" />
        </LinearLayout>

        <Button
            android:id="@+id/login"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/linearLayput"
            android:layout_marginTop="16dp"
            android:background="@color/primary"
            android:text="Sign In Now"
            android:textColor="@android:color/white" />
    </RelativeLayout>
</LinearLayout>


 Create the Java file in project.
 Open app => main => src = LoginActivity.java

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.digi.soft.Utils.Credentials;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Laptop on 12-05-2016.
 */

public class LoginActivity extends AppCompatActivity {
    EditText emailEditText, pwdEditText;
    Button loginButton;
    ProgressDialog dialog;
    public static final String LOGIN_URL = "Please enter the login API";
    public static final String KEY_EMAIL = "Enter email parameter";
    public static final String KEY_PWD = "Enter password parameter";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activtiy_login);
        Init();
        Listner();
    }

    private void Listner() {
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (emailEditText.length() == 0) {
                    Snackbar.make(v, "Enter user email.", Snackbar.LENGTH_LONG).setAction("Action", null).show();
                } else if (pwdEditText.length() == 0) {
                    Snackbar.make(v, "Enter user password.", Snackbar.LENGTH_LONG).setAction("Action", null).show();
                } else {
                    LoginUser();
                }
            }
        });
    }

    private void LoginUser() {

        final String email = emailEditText.getText().toString().trim();
        final String pwd = pwdEditText.getText().toString().trim();

        StringRequest stringRequest = new StringRequest(Request.Method.POST, LOGIN_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        showDialog(false);
                        Toast.makeText(LoginActivty.this, response, Toast.LENGTH_LONG).show();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(LoginActivty.this, error.toString(), Toast.LENGTH_LONG).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put(KEY_EMAIL, email);
                map.put(KEY_PWD, pwd);
                return map;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }

    private void showDialog(boolean check) {
        if (check) {
            dialog = ProgressDialog.show(LoginActivity.this, "", "Loading.....");
            dialog.show();
        } else {
            dialog.dismiss();
        }
    }

    private void openProfile() {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
    }

    private void Init() {
        emailEditText = (EditText) findViewById(R.id.email);
        pwdEditText = (EditText) findViewById(R.id.pwd);
        loginButton = (Button) findViewById(R.id.login);
    }

   
 Add Internet permission in your manifest
 <uses-permission android:name="android.permission.INTERNET"/>


May this code help you. Thanks!!!!!!