Friday 8 April 2016

Back press on Toolbar Apcompact Activity Android

getSupportActionBar().setDisplayHomeAsUpEnabled(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();

        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
JSON Get and POST method using urlconnection


Get Method :

 class GetData extends AsyncTask<String, Void, String> implements DialogInterface.OnCancelListener {

        ProgressHUD mProgressHUD;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mProgressHUD = ProgressHUD.show(PetGallery.this,"Getting Data", false,false, this);
        }

        @Override
        protected String doInBackground(String... params) {
            String msg = null; int status =0;

            StringBuilder sb = new StringBuilder();
            try {
                URL get_url = new URL(Constant.GET_URL);
                HttpURLConnection conn = (HttpURLConnection) get_url.openConnection();
                conn.setRequestMethod("GET");
                conn.setDoInput(true);

                status = conn.getResponseCode();
                msg = conn.getResponseMessage();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(conn.getInputStream()));

                String line = null;
                // Read Server Response
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                    break;
                }
                reader.close();
                return sb.toString();

            } catch (Exception e) {
                Log.e("Http Response: ", msg);
            }

            return msg;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if(s!=null) {
                String status;
                try {
                    JSONObject jsonObject = new JSONObject(s);
                    status = jsonObject.getString(Constant.STATUS);
                    if (status.equals("success")) {
                        JSONArray jsonArray = jsonObject.getJSONArray(Constant.GET_ARRAY);
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject object = jsonArray.getJSONObject(i);
                            String id = object.getString(Constant.PETID);
                            String url = object.getString(Constant.PHOTO_STRING);
                            String details = object.getString(Constant.DESC);
                            String place = object.getString(Constant.PLACE);
                            String date = object.getString(Constant.DATE);
                            String name = object.getString(Constant.NAME);
                            String contact = object.getString(Constant.CONTACT);

                            HashMap<String, String> map = new HashMap<String, String>();
                            map.put(Constant.PETID, id);
                            map.put(Constant.PHOTO_STRING, url);
                            map.put(Constant.DESC, details);
                            map.put(Constant.PLACE, place);
                            map.put(Constant.DATE, date);
                            map.put(Constant.NAME, name);
                            map.put(Constant.CONTACT, contact);

                            //LoadImage.execute(map);
                            list.add(map);
                        }
                        lv.setAdapter(new CustomAdapter(PetGallery.this, list));
                        mProgressHUD.dismiss();
                    } else {
                        mProgressHUD.dismiss();
                        Toast.makeText(getApplicationContext(), "Data not found", Toast.LENGTH_SHORT).show();
                    }

                } catch (Exception e) {
                    Log.e("Json Error", e.getMessage());
                }
            }

        }

        @Override
        public void onCancel(DialogInterface dialog) {
            this.cancel(true);
            mProgressHUD.dismiss();
        }
    }


Post Method:

 class GetTask extends AsyncTask<String, Void, String> implements DialogInterface.OnCancelListener{

        ProgressHUD mProgressHUD;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mProgressHUD = ProgressHUD.show(Pet.this,"Loading", false,false, this);
        }

        @Override
        protected String doInBackground(String... params) {

            URL url;
            String response = "";
            try {

                SharedPreferences preferences = getSharedPreferences("Pet", 0);
                String id = preferences.getString("id", null);
                String data = URLEncoder.encode("pet_id", "UTF-8") + "=" + URLEncoder.encode(id, "UTF-8");

                url = new URL("http://www.imstrong.info/ws/get_pet.php");
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(15000);
                conn.setConnectTimeout(15000);
                conn.setRequestMethod("POST");
                conn.setDoInput(true);
                conn.setDoOutput(true);


                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(os, "UTF-8"));
                writer.write(data);

                writer.flush();
                writer.close();
                os.close();

                conn.connect();
                int responseCode=conn.getResponseCode();

                if (responseCode == HttpsURLConnection.HTTP_OK) {
                    String line;
                    BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    while ((line=br.readLine()) != null) {
                        response+=line;
                    }
                }
                else {
                    response=String.valueOf(responseCode);

                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            return response;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            //Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
            mProgressHUD.dismiss();
            if(s!=null) {
                try {
                    JSONObject object = new JSONObject(s);
                    simageurl = object.getString(Constant.PHOTO_STRING);
                    sdetails = object.getString(Constant.DESC);
                    splace = object.getString(Constant.PLACE);
                    sdate = object.getString(Constant.DATE);
                    sname = object.getString(Constant.NAME);
                    scontact = object.getString(Constant.CONTACT);

                    details.setText(sdetails);
                    place.setText(splace);
                    date.setText("(" + sdate + ")");
                    name.setText(sname);
                    contact.setText(scontact);

                    if(simageurl!=null){
                        Bitmap bitmap = getBitmapFromURL(simageurl);
                        photo.setImageBitmap(bitmap);
                    }else{
                        photo.setImageResource(R.drawable.logo);
                    }


                }catch(Exception e){
                    Log.e("Json Responce : ", e.getMessage());
                }
            }
        }

        @Override
        public void onCancel(DialogInterface dialog) {
            this.cancel(true);
            mProgressHUD.dismiss();
        }
    }
Login Example :

Class file :

package com.topappsdevelopers.funapps;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.webkit.WebView;
import android.widget.TextView;

import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.Profile;
import com.facebook.ProfileTracker;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;

/**
 * Created by Excel on 3/7/2016.
 */
public class DemoActivity extends AppCompatActivity {

    WebView web;

    private CallbackManager callbackManager;
    private TextView textView;

    private AccessTokenTracker accessTokenTracker;
    private ProfileTracker profileTracker;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FacebookSdk.sdkInitialize(getApplicationContext());
        setContentView(R.layout.activity_demo);


        callbackManager = CallbackManager.Factory.create();

        accessTokenTracker = new AccessTokenTracker() {
            @Override
            protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) {

            }
        };

        profileTracker = new ProfileTracker() {
            @Override
            protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {
                displayMessage(newProfile);
            }
        };

        accessTokenTracker.startTracking();
        profileTracker.startTracking();

        LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
        textView = (TextView) findViewById(R.id.textView);

        loginButton.setReadPermissions("user_friends");
        loginButton.registerCallback(callbackManager, callback);


    }


    private FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            AccessToken accessToken = loginResult.getAccessToken();
            Profile profile = Profile.getCurrentProfile();
            displayMessage(profile);
        }

        @Override
        public void onCancel() {

        }

        @Override
        public void onError(FacebookException e) {

        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);

    }

    private void displayMessage(Profile profile) {
        if (profile != null) {
            textView.setText(profile.getName() + " " + profile.getId());
            String name = profile.getName();
            String id = profile.getId();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        accessTokenTracker.stopTracking();
        profileTracker.stopTracking();
    }

    @Override
    public void onResume() {
        super.onResume();
        Profile profile = Profile.getCurrentProfile();
        displayMessage(profile);
    }
}

XMl File :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    <TextView
        android:id="@+id/textView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:text="New Text" />

    <com.facebook.login.widget.LoginButton
        android:id="@+id/login_button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

</LinearLayout>


Manifest File  :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.topappsdevelopers.funapps">

    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

    <permission
        android:name="info.androidhive.parsenotifications.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

    <uses-permission android:name="com.topappsdevelopers.funapps.permission.C2D_MESSAGE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/icon"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".SplashScreenActivity"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".MainActivity"
            android:screenOrientation="portrait">

        </activity>
        <activity
            android:name=".CategoryActivity"
            android:screenOrientation="portrait">

        </activity>

        <activity
            android:name="com.facebook.FacebookActivity"
            android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.Translucent.NoTitleBar" />

        <provider android:authorities="com.facebook.app.FacebookContentProvider1701830333389656"
            android:name="com.facebook.FacebookContentProvider"
            android:exported="true"/>

        <meta-data
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/app_id" />
        <meta-data
            android:name="com.facebook.sdk.ApplicationName"
            android:value="@string/app_name" />

        <activity
            android:name="com.startapp.android.publish.list3d.List3DActivity"
            android:theme="@android:style/Theme" />
        <activity
            android:name="com.startapp.android.publish.OverlayActivity"
            android:configChanges="orientation|keyboardHidden|screenSize"
            android:theme="@android:style/Theme.Translucent" />
        <activity
            android:name="com.startapp.android.publish.FullScreenActivity"
            android:configChanges="orientation|keyboardHidden|screenSize"
            android:theme="@android:style/Theme" />

        <service android:name="com.parse.PushService" />

        <receiver
            android:name=".notification.CustomPushReceiver"
            android:exported="false">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.intent.action.USER_PRESENT" />
                <action android:name="com.parse.push.intent.RECEIVE" />
                <action android:name="com.parse.push.intent.DELETE" />
                <action android:name="com.parse.push.intent.OPEN" />
            </intent-filter>
        </receiver>
        <receiver
            android:name="com.parse.GcmBroadcastReceiver"
            android:permission="com.google.android.c2dm.permission.SEND">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <action android:name="com.google.android.c2dm.intent.REGISTRATION" />

                <!-- IMPORTANT: Change "info.androidhive.parsenotifications" to match your app's package name. -->
                <category android:name="com.topappsdevelopers.funapps" />
            </intent-filter>
        </receiver>
    </application>

</manifest>