Thursday 30 August 2018

Retrofit Use



public interface Api {
    //the base URL for our API   
 //make sure you are not using localhost 
   //find the ip usinc ipconfig command   
 String BASE_URL = "http://192.168.43.124/ImageUploadApi/";

    //this is our multipart request    
//we have two parameters on is name and other one is description 
   @Multipart    @POST("Api.php?apicall=upload")
    Call<MyResponse> uploadImage(@Part("image\"; filename=\"myfile.jpg\" ") 
RequestBody file, @Part("desc") RequestBody desc);

}



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



public class ApiClient {

    private static Retrofit retrofit = null;

    private static Gson gson = new GsonBuilder().setLenient().create();

    public static Retrofit getClient() {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(AppConstant.BASEURL.URL.trim())
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .build();
        }
        return retrofit;
    }

}

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

public interface MyApiEndpointInterface {

@POST(AppConstant.ENDPOINT.CHAT_STATUS)
Call<JsonObject> chatUser(@Body JsonObject jsonObject);

}


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

public class AppConstant {
  public interface BASEURL {

        //        String URL = "http://truckslogistics.com/Projects-Work/LoggedIn/Mobile_APP/";//   
      //   String URL = "http://fxpips.co.uk/loggedin/Mobile_APP/";    
    String URL = "http://www.loggedinapp.com/Mobile_APP/";
    }
public interface ENDPOINT {
String CHAT_STATUS = "chat/chatUser.php";
}
}


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

------------------Library-------------
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
implementation 'com.squareup.retrofit2:retrofit:2.3.0'

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

public class MyResponse  implements Serializable {
    String status = "";
    String message = "";
    String File_Url = "";

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getFile_Url() {
        return File_Url;
    }

    public void setFile_Url(String file_Url) {
        File_Url = file_Url;
    }

}

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

---------------------------------------------------------------------------------------
                 --------------Activity---------

private void apicallingSetChatStatus() {
    JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("method", "chat_user");
    jsonObject.addProperty("user_id", "1");
    jsonObject.addProperty("admin_id", "1");
    /*{"method":"chat_user","user_id":"1"}*/   
 /*{"method":"chat_user","user_id":"1","admin_id":""}*/  
  retrofitSetChatStatus(jsonObject);
}


private void retrofitSetChatStatus(JsonObject jsonObject) {
    MyApiEndpointInterface apiService =
            ApiClient.getClient().create(MyApiEndpointInterface.class);
    Call<JsonObject> call = apiService.chatUser(jsonObject);
    call.enqueue(new Callback<JsonObject>() {
        @Override     
   public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
            if (response.body() != null) {
                try {
                    Log.d("SetChatResponse ....", String.valueOf(response.body()));

                    JSONObject jsonObject1 = new JSONObject(response.body().toString());
                    String message = jsonObject1.getString("message");
                    String status = jsonObject1.getString("status");
                    if (status.equals("200")) {
                        stautschat = "1";
                    } else {
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Function.Snackbar(ChatActivity.this, findViewById(android.R.id.content), "Something went wrong.");
            }
        }

        @Override      
  public void onFailure(Call<JsonObject> call, Throwable t) {
        }
    });
}

Wednesday 8 August 2018

Network check Run Time


-------------------------------MainActivity---------------------------------

/*
 * You need to implement NetworkStateReceiverListener.
 * This interface is described inside the NewtworkStateReceiver class
 */
public class MyActivity implements NetworkStateReceiverListener {
    /* ... */
    private NetworkStateReceiver networkStateReceiver;

}



----------------And---------------------------

public void onCreate(Bundle savedInstanceState) {
    /* ... */
    networkStateReceiver = new NetworkStateReceiver();
    networkStateReceiver.addListener(this);
    this.registerReceiver(networkStateReceiver, new IntentFilter(android.net.ConnectivityManager.CONNECTIVITY_ACTION));
}

public void onDestroy() {
    super.onDestroy();
    networkStateReceiver.removeListener(this);
    this.unregisterReceiver(networkStateReceiver);

}



-----------------And----------------------

@Override
public void networkAvailable() {
    Log.d("tommydevall", "I'm in, baby!");
    /* TODO: Your connection-oriented stuff here */
}

@Override
public void networkUnavailable() {
    Log.d("tommydevall", "I'm dancing with myself");
    /* TODO: Your disconnection-oriented stuff here */       

}



---------------NetworkStateReceiver.java------------------------------


public class NetworkStateReceiver extends BroadcastReceiver {

    protected Set<NetworkStateReceiverListener> listeners;
    protected Boolean connected;

    public NetworkStateReceiver() {
        listeners = new HashSet<NetworkStateReceiverListener>();
        connected = null;
    }

    public void onReceive(Context context, Intent intent) {
        if(intent == null || intent.getExtras() == null)
            return;

        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = manager.getActiveNetworkInfo();

        if(ni != null && ni.getState() == NetworkInfo.State.CONNECTED) {
            connected = true;
        } else if(intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,Boolean.FALSE)) {
            connected = false;
        }

        notifyStateToAll();
    }

    private void notifyStateToAll() {
        for(NetworkStateReceiverListener listener : listeners)
            notifyState(listener);
    }

    private void notifyState(NetworkStateReceiverListener listener) {
        if(connected == null || listener == null)
            return;

        if(connected == true)
            listener.networkAvailable();
        else
            listener.networkUnavailable();
    }

    public void addListener(NetworkStateReceiverListener l) {
        listeners.add(l);
        notifyState(l);
    }

    public void removeListener(NetworkStateReceiverListener l) {
        listeners.remove(l);
    }

    public interface NetworkStateReceiverListener {
        public void networkAvailable();
        public void networkUnavailable();
    }
}

Wednesday 1 August 2018

Camera,Gallery Image

-----------------------------------Androidmanifest--------------------------

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />



-------------------Activity------------------
package com.loggedin.mmf.myapplicationcameraimagetake;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import static android.Manifest.permission.CAMERA;

public class MainActivity extends AppCompatActivity {
    private Button buttonImage;
    public static int SELECT_FROM_GALLERY = 2;
    public static int CAMERA_PIC_REQUEST = 0;
    private static final int REQUEST = 1337;
    public static final int PERMISSION_REQUEST_CODE = 1111;
    Uri mImageCaptureUri;
    Bitmap productImageBitmap;
    ImageView profilePic;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        buttonImage = (Button) findViewById(R.id.buttonImage);
        profilePic = (ImageView) findViewById(R.id.profilePic);
        buttonImage.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                selectImage();

            }
        });
    }

    private void selectImage() {
        final CharSequence[] options = {"From Camera", "From Gallery", "Cancel"};
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Please choose an Image");
        builder.setItems(options, new DialogInterface.OnClickListener() {
            @Override            public void onClick(DialogInterface dialog, int item) {
                if (options[item].equals("From Camera")) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        if (checkCameraPermission())
                            cameraIntent();
                        else                            requestPermission();
                    } else                        cameraIntent();
                } else if (options[item].equals("From Gallery")) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        if (checkGalleryPermission())
                            galleryIntent();
                        else                            requestGalleryPermission();
                    } else                        galleryIntent();
                } else if (options[item].equals("Cancel")) {
                    dialog.dismiss();
                }
            }
        });
        builder.create().show();
    }

    private void galleryIntent() {
        Intent intent = new Intent().setType("image/*").setAction(Intent.ACTION_PICK);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_FROM_GALLERY);
    }

    private void cameraIntent() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
        startActivityForResult(intent, CAMERA_PIC_REQUEST);
    }

    private void requestPermission() {
        ActivityCompat.requestPermissions(MainActivity.this, new String[]{CAMERA}, PERMISSION_REQUEST_CODE);
    }

    private void requestGalleryPermission() {
        ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST);
    }

    private boolean checkCameraPermission() {
        int result1 = ContextCompat.checkSelfPermission(MainActivity.this, CAMERA);
        return result1 == PackageManager.PERMISSION_GRANTED;
    }

    private boolean checkGalleryPermission() {
        int result2 = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE);
        return result2 == PackageManager.PERMISSION_GRANTED;
    }

    @Override    protected void onActivityResult(int requestCode, int resultCode, Intent data) {


        if (requestCode == CAMERA_PIC_REQUEST && resultCode == Activity.RESULT_OK && null != data) {
            Uri cameraURI = data.getData();
            productImageBitmap = (Bitmap) data.getExtras().get("data");
            profilePic.setImageBitmap(productImageBitmap);
            profilePic.setVisibility(View.VISIBLE);

        } else if (requestCode == SELECT_FROM_GALLERY && resultCode == Activity.RESULT_OK && null != data) {
            Uri galleryURI = data.getData();
            profilePic.setImageURI(galleryURI);
        }
    }

}





----------------activity.xml-----------------
<?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"    tools:context=".MainActivity">

    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="vertical">

        <TextView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="Hello World!"            app:layout_constraintBottom_toBottomOf="parent"            app:layout_constraintLeft_toLeftOf="parent"            app:layout_constraintRight_toRightOf="parent"            app:layout_constraintTop_toTopOf="parent" />
<ImageView    android:layout_width="match_parent"    android:layout_height="300dp"    android:id="@+id/profilePic"/>
        <Button            android:id="@+id/buttonImage"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:text="Picture"/>
    </LinearLayout>
</RelativeLayout>

AutoComplete Address (Updated)

-------------------------------------Activity---------------------------------- package placeautocomplete.iteritory.com; import androi...