Skip to main content

Image uploading




  • Image Upload — Resources about uploading images using various programming languages and frameworks like jQuery, Ajax and more.
  • Image Upload in Mobile — Resources about uploading images in mobile operating systems like Android and iOS using various frameworks and programming languages.
  • Image Upload in Web Apps — Resources about uploading images in web applications using languages and frameworks like PHP, Angular.js, JQuery and more.
Code for the main activity:

package com.deeparora.po;

import android.Manifest;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.util.EncodingUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Pattern;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

import github.nisrulz.screenshott.ScreenShott;


public class POMainActivity extends AppCompatActivity implements View.OnClickListener,AdapterView.OnItemSelectedListener {

    ///@InjectView(R.id.spinnerlogin)
    Spinner splogin;
   // @InjectView(R.id.editTextEmail)
    EditText eTxtEmail;
    //@InjectView(R.id.editTextPassword)
    EditText passs;
    boolean check = false;
String name;
    Spinner spCity;
    String encrypted;
    List<User> data;
    List<String> data1;
    int PERMISSION_ALL = 1;
    String[] PERMISSIONS = {

            Manifest.permission.INTERNET


    };



    Button button;



    EditText eTxtMobile;
    ArrayAdapter<String> adapter;

    public static final int CONNECTION_TIMEOUT = 100000;
    public static final int READ_TIMEOUT = 150000;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pomain);
        ActionBar actionBar = getSupportActionBar();
      //  ButterKnife.inject(this);
        //eTxtEmail.setVisibility(View.INVISIBLE);
        //Bitmap bitmap_view = ScreenShott.getInstance().takeScreenShotOfView(view);
        splogin=(Spinner)findViewById(R.id.spinnerlogin);
        eTxtEmail=(EditText) findViewById(R.id.editTextEmail);
        passs=(EditText) findViewById(R.id.editTextPassword);
        eTxtMobile=(EditText) findViewById(R.id.editTextMobile);
       button=(Button) findViewById(R.id.button);
        eTxtMobile.setVisibility(View.INVISIBLE);
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item);
        adapter.add("--Login by email or mobile--"); //0
        adapter.add("Email");
        adapter.add("Mobile");

        splogin.setAdapter(adapter);

        splogin.setOnItemSelectedListener(this);

        if (!hasPermissions(this, PERMISSIONS)) {
            ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
            if (!hasPermissions(this, PERMISSIONS)) {
                //   Toast.makeText(getApplicationContext(),"Permissions denied .You can change them in Settings>Apps",Toast.LENGTH_LONG).show();
            }
        }

        button.setOnClickListener(this);
// onClick of button perform this simplest code.


    }

    private boolean isValidMobile(String phone) {


        if (!Pattern.matches("[a-zA-Z]+", phone)) {
            if (phone.length() < 9 || phone.length() > 11) {
                // if(phone.length() != 10) {
                check = false;
                Toast.makeText(getApplicationContext(), "invalid mobile no", Toast.LENGTH_SHORT).show();

            } else {

                check = true;

            }
        } else {
            check = false;
            Toast.makeText(getApplicationContext(), "invalid mobile no", Toast.LENGTH_SHORT).show();
        }
        return check;
    }

    private void isValidpass(String pass) {



    }

    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager
                = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }
    @Override
    public void onClick(View view) {
        if (isNetworkAvailable()==true) {
            String mode;
            String email = eTxtEmail.getText().toString().trim();
            String phone = eTxtMobile.getText().toString().trim();
            String pass = passs.getText().toString().trim();


            if (email.length() > 0) {
                String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";
                if (email.matches(emailPattern)) {


                    if (pass.length() < 3 || pass.isEmpty()) {
                        // if(phone.length() != 10) {

                        Toast.makeText(getApplicationContext(), "Password must be atleast 8 characters long", Toast.LENGTH_SHORT).show();

                    } else {

                        mode = "E";
                        String passss;

                        byte[] plaintextByte = EncodingUtils.getAsciiBytes(pass);

                        byte[] hash = md5("wEu23v454qWe1");

                        try {
                            Cipher cipher = Cipher.getInstance("DESEDE/ECB/PKCS5Padding");
                            SecretKeySpec myKey = new SecretKeySpec(hash, "DESede");

                            cipher.init(Cipher.ENCRYPT_MODE, myKey);

                            try {
                                byte[] encryptedPlainText = cipher.doFinal(plaintextByte);

                                encrypted = Base64.encodeToString(encryptedPlainText, 0);
                                Log.i("ENCRYPT", "Pwd encrypted: " + encrypted);

                                passss = encrypted.trim();
                              //  Toast.makeText(getApplicationContext(), passss, Toast.LENGTH_SHORT).show();

                                new AsyncLogin().execute(mode, phone, passss, email);
                            } catch (IllegalBlockSizeException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            } catch (BadPaddingException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }

                        } catch (NoSuchAlgorithmException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (NoSuchPaddingException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (InvalidKeyException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                        //  Toast.makeText(getApplicationContext(),MD5_Hash_String , Toast.LENGTH_SHORT).show();

                    }

                } else {
                    Toast.makeText(getApplicationContext(), "Invalid email address", Toast.LENGTH_SHORT).show();
                }
            } else if (phone.length() > 0) {

                if (!Pattern.matches("[a-zA-Z]+", phone)) {
                    if (phone.length() < 9 || phone.length() > 11) {
                        // if(phone.length() != 10) {
                        check = false;
                        Toast.makeText(getApplicationContext(), "invalid mobile no", Toast.LENGTH_SHORT).show();

                    } else {


                        if (pass.length() < 3 || pass.isEmpty()) {
                            // if(phone.length() != 10) {

                            check = true;
                            Toast.makeText(getApplicationContext(), "Password must be atleast 3 characters long", Toast.LENGTH_SHORT).show();

                        } else {
                            mode = "M";
                            String passss;

                            byte[] plaintextByte = EncodingUtils.getAsciiBytes(pass);

                            byte[] hash = md5("wEu23v454qWe1");

                            try {
                                Cipher cipher = Cipher.getInstance("DESEDE/ECB/PKCS5Padding");
                                SecretKeySpec myKey = new SecretKeySpec(hash, "DESede");

                                cipher.init(Cipher.ENCRYPT_MODE, myKey);

                                try {
                                    byte[] encryptedPlainText = cipher.doFinal(plaintextByte);

                                    encrypted = Base64.encodeToString(encryptedPlainText, 0);
                                    Log.i("ENCRYPT", "Pwd encrypted: " + encrypted);

                                    passss = encrypted.trim();
                                 //   Toast.makeText(getApplicationContext(), passss, Toast.LENGTH_SHORT).show();

                                    new AsyncLogin().execute(mode, phone, passss, email);
                                } catch (IllegalBlockSizeException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                } catch (BadPaddingException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                            } catch (NoSuchAlgorithmException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            } catch (NoSuchPaddingException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            } catch (InvalidKeyException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }



                        }


                    }
                } else {
                    check = false;
                    Toast.makeText(getApplicationContext(), "invalid mobile no", Toast.LENGTH_SHORT).show();
                }


            } else if (email.isEmpty() || phone.isEmpty()) {
                Toast.makeText(getApplicationContext(), "Please enter email or mobile no", Toast.LENGTH_SHORT).show();
            }


        }
        else {
            AlertDialog.Builder builder1 = new AlertDialog.Builder(POMainActivity.this);
            builder1.setMessage("Please switch on your Internet connection");
            builder1.setCancelable(true);

            builder1.setPositiveButton(
                    "Ok",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                        }
                    });


            AlertDialog alert11 = builder1.create();
            alert11.show();

        }

    }



    public static final byte[] md5(String s) {
        try {

            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(s.getBytes("UTF-8"));

            String md5 = EncodingUtils.getString(messageDigest, "UTF-8");

            Log.i("Function MD5", md5);
            Log.i("Function MD5 Length","Length: "+ md5.length());

            return messageDigest;

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }


    public static String encryptString(String sString) throws IllegalBlockSizeException {
        String sKey = "wEu23v454qWe1"; //used in Encrypti
        byte[] aPwdhash,aBuff;
        String encrypted;

        // String md5 = EncodingUtils.getString(abuff, "ASCII");
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            aBuff = sString.getBytes("ASCII");
            //here error
            aPwdhash = md.digest(sKey.getBytes("ASCII"));
            Cipher cipher = Cipher.getInstance("ECB");
            SecretKeySpec myKey = new SecretKeySpec(aPwdhash, "DESede");

            cipher.init(Cipher.ENCRYPT_MODE, myKey);

            //  Log.i("Function MD5", md5);
            // Log.i("Function MD5 Length", "Length: " + md5.length());
            byte[] encryptedPlainText = cipher.doFinal(aBuff);

            encrypted = Base64.encodeToString(encryptedPlainText, 0);
            Log.i("ENCRYPT", "Pwd encrypted: " + encrypted);
            return encrypted;
        } catch (BadPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }


   /*     String sEncrypted;
        Byte[] aPwdhash, aBuff;
        TripleDESCryptoServiceProvider oDes = new TripleDESCryptoServiceProvider();
        MD5CryptoServiceProvider oHashmd5 = new MD5CryptoServiceProvider();
        aBuff = ASCIIEncoding.ASCII.GetBytes(sString);
        aPwdhash = oHashmd5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(sKey));
        oHashmd5 = null;
        oDes.Key = aPwdhash;
        oDes.Mode = CipherMode.ECB;
        sEncrypted = Convert.ToBase64String(oDes.CreateEncryptor().TransformFinalBlock(aBuff, 0, aBuff.Length));*/
        return null;
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {


        // Explict Way
        // groupId , itemId, order, title
        /*menu.add(1,101,0,"All Songs");
        menu.add(1,102,0,"Artists");
        menu.add(2,201,0,"Recently Played");
        menu.add(2,202,0,"Favourites");*/

        // Implict Way | IOC (Inversion Of Control)

        getMenuInflater().inflate(R.menu.menu2,menu);

        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        //int gid = item.getGroupId();
        int id = item.getItemId(); // fetch the id on which user has done selection

        /*switch (id){
            case 101:
                Toast.makeText(this,"You Selected All Songs",Toast.LENGTH_LONG).show();
                break;
            case 102:
                Intent intent = new Intent(ActivityOne.this,ActivityTwo.class);
                startActivity(intent);
                break;
            case 201:
                break;
            case 202:
                break;
        }*/

        switch (id){

            case R.id.contact:
                Intent intent1 = new Intent(POMainActivity.this, CONTACT.class);
                startActivity(intent1);
                break;
            case R.id.aboutus:
                Intent intent2 = new Intent(POMainActivity.this, Aboutus.class);
                startActivity(intent2);
                break;

        }

        return super.onOptionsItemSelected(item);
    }

    private class AsyncLogin extends AsyncTask<String, String, String> {
        ProgressDialog pdLoading = new ProgressDialog(POMainActivity.this);
        HttpURLConnection conn;
        URL url = null;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            //this method will be running on UI thread
            pdLoading.setMessage("\tLoading...");
            pdLoading.setCancelable(false);
            pdLoading.show();

        }

        @Override
        protected String doInBackground(String... params) {
            String response = params[0];
            String response1 = params[1];
            String response2 = params[2];
            Log.i("tag","oQDnoBk8vC8=");
            Log.i("tab",response2+"");
            String response3 = params[3];


            StringBuilder sbk = new StringBuilder();
            try {
                String urla = "http://202.164.39.172:2345/test/training/POREPORT/signin.php";
                String data = "";
                URL x = new URL(urla);
                HttpURLConnection connection = (HttpURLConnection) x.openConnection();
                connection.setRequestMethod("POST");
                connection.setDoOutput(true);
                connection.setDoInput(true);
                OutputStream OS = null;

                OS = connection.getOutputStream();

                BufferedWriter bufferedWriter = null;

                bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
                data = URLEncoder.encode("mode", "UTF-8") + "=" + URLEncoder.encode(response, "UTF-8") + "&" + URLEncoder.encode("mobile", "UTF-8") + "=" + URLEncoder.encode(response1, "UTF-8") + "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(response2, "UTF-8") + "&" + URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode(response3, "UTF-8");

                bufferedWriter.write(data);
                bufferedWriter.flush();
                bufferedWriter.close();
                OS.close();
                //fetching response
                InputStreamReader inp = new InputStreamReader(connection.getInputStream());

                Scanner scnrp = new Scanner(inp);
                while (scnrp.hasNext()) {
                    sbk.append(scnrp.nextLine());

                }
                // return sbk.toString();
            } catch (Exception e) {

                Log.d("tag", e + "");
            }
            //   return sbk.toString();

            return sbk.toString();
        }
        // Pass data to onPostExecute method


        @Override
        protected void onPostExecute(String result) {

            //this method will be running on UI thread
           // Toast.makeText(getApplicationContext(), result+"hello" + "", Toast.LENGTH_LONG).show();
            pdLoading.dismiss();

            data1 = new ArrayList<>();
            /// pdLoading.dismiss();
            try {
                //JSONObject jobj = new+ JSONObject( URLDecoder.decode( result, "UTF-8" ));
                JSONArray jArray = new JSONArray(result);

                Log.e("jj7", result);
                for (int i = 0; i < jArray.length(); i++) {
                    JSONObject json_data = jArray.getJSONObject(i);
                    // User user = new User();
                    //  user.setDistrict(json_data.getString("districts"));
                    // user.setTasheel(json_data.getString("Tehsil"));
                    // user.setTasheel2(json_data.getString("Tehsil2"));
                    String country = json_data.getString("Id");
                    Log.e("jj8", country);
                    data1.add(country);
                    name=country;
                    Log.e("jj89", country);
                    //data.add(user);
                }


                if (data1.isEmpty()) {
                    Log.e("jj889", data1 + "");
                    Toast.makeText(getApplicationContext(), "Invalid email id or password", Toast.LENGTH_LONG).show();
                } else {

                    SharedPreferences sp = getSharedPreferences("loginpref", MODE_PRIVATE);
                    SharedPreferences.Editor editor=sp.edit();
                    editor.putString("id",name);
                    editor.commit();
                    String jp=sp.getString("id",null);
                                    //    Toast.makeText(getApplicationContext(), jp, Toast.LENGTH_LONG).show();
                    Intent intent = new Intent(POMainActivity.this, CluList.class);
                    intent.putExtra("keyName",name);
                    startActivity(intent);

                    Log.e("jj8119", data1 + "");
                }
                //adapter.setDropDownViewResource(R.layout.spinner_textview);
                // sp2.setAdapter(adapter);
            }

            catch (JSONException e) {
                Toast.makeText(POMainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
            }

        }


    }


    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
        String name = adapter.getItem(i);
        //user.city = city;
        if (name == "Email") {
            eTxtMobile.getText().clear();
            eTxtMobile.setVisibility(View.INVISIBLE);
            eTxtEmail.setVisibility(View.VISIBLE);

        } else if (name == "Mobile") {
            eTxtEmail.getText().clear();
            eTxtEmail.setVisibility(View.INVISIBLE);
            eTxtMobile.setVisibility(View.VISIBLE);
        }

    }

    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {

    }


    public boolean hasPermissions(Context context, String... permissions) {
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
            for (String permission : permissions) {
                if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                    // Toast.makeText(getApplicationContext(),"Permissions denied .You can change them in Settings>Apps",Toast.LENGTH_LONG).show();
                    return false;
                }
            }
        }
        return true;
    }


    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        int count = 0;
        if (requestCode == PERMISSION_ALL) {
            for (int i = 0; i < permissions.length; i++) {
                String permission = permissions[i];
                int grantResult = grantResults[i];

                if (permission.equals(Manifest.permission.INTERNET)) {
                    if (grantResult == PackageManager.PERMISSION_GRANTED) {
                        //  onPPSButtonPress();
                    } else {
                        count++;
                        //  Toast.makeText(getApplicationContext(),"Permissions denied .You can change them in Settings>Apps",Toast.LENGTH_LONG).show();
                        //requestPermissions(new String[]{Manifest.permission.SEND_SMS}, PERMISSIONS_CODE);
                    }
                }



            }
        }
    }
}
                        Toast.makeText(getApplicationContext(), "Password must be atleast 8 characters long", Toast.LENGTH_SHORT).show();

                    } else {

                        mode = "E";
                        String passss;

                        byte[] plaintextByte = EncodingUtils.getAsciiBytes(pass);

                        byte[] hash = md5("wEu23v454qWe1");

                        try {
                            Cipher cipher = Cipher.getInstance("DESEDE/ECB/PKCS5Padding");
                            SecretKeySpec myKey = new SecretKeySpec(hash, "DESede");

                            cipher.init(Cipher.ENCRYPT_MODE, myKey);

                            try {
                                byte[] encryptedPlainText = cipher.doFinal(plaintextByte);

                                encrypted = Base64.encodeToString(encryptedPlainText, 0);
                                Log.i("ENCRYPT", "Pwd encrypted: " + encrypted);

                                passss = encrypted.trim();
                              //  Toast.makeText(getApplicationContext(), passss, Toast.LENGTH_SHORT).show();

                                new AsyncLogin().execute(mode, phone, passss, email);
                            } catch (IllegalBlockSizeException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            } catch (BadPaddingException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }

                        } catch (NoSuchAlgorithmException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (NoSuchPaddingException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (InvalidKeyException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                        //  Toast.makeText(getApplicationContext(),MD5_Hash_String , Toast.LENGTH_SHORT).show();

                    }

                } else {
                    Toast.makeText(getApplicationContext(), "Invalid email address", Toast.LENGTH_SHORT).show();
                }
            } else if (phone.length() > 0) {

                if (!Pattern.matches("[a-zA-Z]+", phone)) {
                    if (phone.length() < 9 || phone.length() > 11) {
                        // if(phone.length() != 10) {
                        check = false;
                        Toast.makeText(getApplicationContext(), "invalid mobile no", Toast.LENGTH_SHORT).show();

                    } else {


                        if (pass.length() < 3 || pass.isEmpty()) {
                            // if(phone.length() != 10) {

                            check = true;
                            Toast.makeText(getApplicationContext(), "Password must be atleast 3 characters long", Toast.LENGTH_SHORT).show();

                        } else {
                            mode = "M";
                            String passss;

                            byte[] plaintextByte = EncodingUtils.getAsciiBytes(pass);

                            byte[] hash = md5("wEu23v454qWe1");

                            try {
                                Cipher cipher = Cipher.getInstance("DESEDE/ECB/PKCS5Padding");
                                SecretKeySpec myKey = new SecretKeySpec(hash, "DESede");

                                cipher.init(Cipher.ENCRYPT_MODE, myKey);

                                try {
                                    byte[] encryptedPlainText = cipher.doFinal(plaintextByte);

                                    encrypted = Base64.encodeToString(encryptedPlainText, 0);
                                    Log.i("ENCRYPT", "Pwd encrypted: " + encrypted);

                                    passss = encrypted.trim();
                                 //   Toast.makeText(getApplicationContext(), passss, Toast.LENGTH_SHORT).show();

                                    new AsyncLogin().execute(mode, phone, passss, email);
                                } catch (IllegalBlockSizeException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                } catch (BadPaddingException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                            } catch (NoSuchAlgorithmException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            } catch (NoSuchPaddingException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            } catch (InvalidKeyException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }



                        }


                    }
                } else {
                    check = false;
                    Toast.makeText(getApplicationContext(), "invalid mobile no", Toast.LENGTH_SHORT).show();
                }


            } else if (email.isEmpty() || phone.isEmpty()) {
                Toast.makeText(getApplicationContext(), "Please enter email or mobile no", Toast.LENGTH_SHORT).show();
            }


        }
        else {
            AlertDialog.Builder builder1 = new AlertDialog.Builder(POMainActivity.this);
            builder1.setMessage("Please switch on your Internet connection");
            builder1.setCancelable(true);

            builder1.setPositiveButton(
                    "Ok",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                        }
                    });


            AlertDialog alert11 = builder1.create();
            alert11.show();

        }

    }



    public static final byte[] md5(String s) {
        try {

            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(s.getBytes("UTF-8"));

            String md5 = EncodingUtils.getString(messageDigest, "UTF-8");

            Log.i("Function MD5", md5);
            Log.i("Function MD5 Length","Length: "+ md5.length());

            return messageDigest;

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }


    public static String encryptString(String sString) throws IllegalBlockSizeException {
        String sKey = "wEu23v454qWe1"; //used in Encrypti
        byte[] aPwdhash,aBuff;
        String encrypted;

        // String md5 = EncodingUtils.getString(abuff, "ASCII");
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            aBuff = sString.getBytes("ASCII");
            //here error
            aPwdhash = md.digest(sKey.getBytes("ASCII"));
            Cipher cipher = Cipher.getInstance("ECB");
            SecretKeySpec myKey = new SecretKeySpec(aPwdhash, "DESede");

            cipher.init(Cipher.ENCRYPT_MODE, myKey);

            //  Log.i("Function MD5", md5);
            // Log.i("Function MD5 Length", "Length: " + md5.length());
            byte[] encryptedPlainText = cipher.doFinal(aBuff);

            encrypted = Base64.encodeToString(encryptedPlainText, 0);
            Log.i("ENCRYPT", "Pwd encrypted: " + encrypted);
            return encrypted;
        } catch (BadPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }


   /*     String sEncrypted;
        Byte[] aPwdhash, aBuff;
        TripleDESCryptoServiceProvider oDes = new TripleDESCryptoServiceProvider();
        MD5CryptoServiceProvider oHashmd5 = new MD5CryptoServiceProvider();
        aBuff = ASCIIEncoding.ASCII.GetBytes(sString);
        aPwdhash = oHashmd5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(sKey));
        oHashmd5 = null;
        oDes.Key = aPwdhash;
        oDes.Mode = CipherMode.ECB;
        sEncrypted = Convert.ToBase64String(oDes.CreateEncryptor().TransformFinalBlock(aBuff, 0, aBuff.Length));*/
        return null;
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {


        // Explict Way
        // groupId , itemId, order, title
        /*menu.add(1,101,0,"All Songs");
        menu.add(1,102,0,"Artists");
        menu.add(2,201,0,"Recently Played");
        menu.add(2,202,0,"Favourites");*/

        // Implict Way | IOC (Inversion Of Control)

        getMenuInflater().inflate(R.menu.menu2,menu);

        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        //int gid = item.getGroupId();
        int id = item.getItemId(); // fetch the id on which user has done selection

        /*switch (id){
            case 101:
                Toast.makeText(this,"You Selected All Songs",Toast.LENGTH_LONG).show();
                break;
            case 102:
                Intent intent = new Intent(ActivityOne.this,ActivityTwo.class);
                startActivity(intent);
                break;
            case 201:
                break;
            case 202:
                break;
        }*/

        switch (id){

            case R.id.contact:
                Intent intent1 = new Intent(POMainActivity.this, CONTACT.class);
                startActivity(intent1);
                break;
            case R.id.aboutus:
                Intent intent2 = new Intent(POMainActivity.this, Aboutus.class);
                startActivity(intent2);
                break;

        }

        return super.onOptionsItemSelected(item);
    }

    private class AsyncLogin extends AsyncTask<String, String, String> {
        ProgressDialog pdLoading = new ProgressDialog(POMainActivity.this);
        HttpURLConnection conn;
        URL url = null;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            //this method will be running on UI thread
            pdLoading.setMessage("\tLoading...");
            pdLoading.setCancelable(false);
            pdLoading.show();

        }

        @Override
        protected String doInBackground(String... params) {
            String response = params[0];
            String response1 = params[1];
            String response2 = params[2];
            Log.i("tag","oQDnoBk8vC8=");
            Log.i("tab",response2+"");
            String response3 = params[3];


            StringBuilder sbk = new StringBuilder();
            try {
                String urla = "http://202.164.39.172:2345/test/training/POREPORT/signin.php";
                String data = "";
                URL x = new URL(urla);
                HttpURLConnection connection = (HttpURLConnection) x.openConnection();
                connection.setRequestMethod("POST");
                connection.setDoOutput(true);
                connection.setDoInput(true);
                OutputStream OS = null;

                OS = connection.getOutputStream();

                BufferedWriter bufferedWriter = null;

                bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
                data = URLEncoder.encode("mode", "UTF-8") + "=" + URLEncoder.encode(response, "UTF-8") + "&" + URLEncoder.encode("mobile", "UTF-8") + "=" + URLEncoder.encode(response1, "UTF-8") + "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(response2, "UTF-8") + "&" + URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode(response3, "UTF-8");

                bufferedWriter.write(data);
                bufferedWriter.flush();
                bufferedWriter.close();
                OS.close();
                //fetching response
                InputStreamReader inp = new InputStreamReader(connection.getInputStream());

                Scanner scnrp = new Scanner(inp);
                while (scnrp.hasNext()) {
                    sbk.append(scnrp.nextLine());

                }
                // return sbk.toString();
            } catch (Exception e) {

                Log.d("tag", e + "");
            }
            //   return sbk.toString();

            return sbk.toString();
        }
        // Pass data to onPostExecute method


        @Override
        protected void onPostExecute(String result) {

            //this method will be running on UI thread
           // Toast.makeText(getApplicationContext(), result+"hello" + "", Toast.LENGTH_LONG).show();
            pdLoading.dismiss();

            data1 = new ArrayList<>();
            /// pdLoading.dismiss();
            try {
                //JSONObject jobj = new+ JSONObject( URLDecoder.decode( result, "UTF-8" ));
                JSONArray jArray = new JSONArray(result);

                Log.e("jj7", result);
                for (int i = 0; i < jArray.length(); i++) {
                    JSONObject json_data = jArray.getJSONObject(i);
                    // User user = new User();
                    //  user.setDistrict(json_data.getString("districts"));
                    // user.setTasheel(json_data.getString("Tehsil"));
                    // user.setTasheel2(json_data.getString("Tehsil2"));
                    String country = json_data.getString("Id");
                    Log.e("jj8", country);
                    data1.add(country);
                    name=country;
                    Log.e("jj89", country);
                    //data.add(user);
                }


                if (data1.isEmpty()) {
                    Log.e("jj889", data1 + "");
                    Toast.makeText(getApplicationContext(), "Invalid email id or password", Toast.LENGTH_LONG).show();
                } else {

                    SharedPreferences sp = getSharedPreferences("loginpref", MODE_PRIVATE);
                    SharedPreferences.Editor editor=sp.edit();
                    editor.putString("id",name);
                    editor.commit();
                    String jp=sp.getString("id",null);
                                    //    Toast.makeText(getApplicationContext(), jp, Toast.LENGTH_LONG).show();
                    Intent intent = new Intent(POMainActivity.this, CluList.class);
                    intent.putExtra("keyName",name);
                    startActivity(intent);

                    Log.e("jj8119", data1 + "");
                }
                //adapter.setDropDownViewResource(R.layout.spinner_textview);
                // sp2.setAdapter(adapter);
            }

            catch (JSONException e) {
                Toast.makeText(POMainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
            }

        }


    }


    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
        String name = adapter.getItem(i);
        //user.city = city;
        if (name == "Email") {
            eTxtMobile.getText().clear();
            eTxtMobile.setVisibility(View.INVISIBLE);
            eTxtEmail.setVisibility(View.VISIBLE);

        } else if (name == "Mobile") {
            eTxtEmail.getText().clear();
            eTxtEmail.setVisibility(View.INVISIBLE);
            eTxtMobile.setVisibility(View.VISIBLE);
        }

    }

    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {

    }


    public boolean hasPermissions(Context context, String... permissions) {
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
            for (String permission : permissions) {
                if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                    // Toast.makeText(getApplicationContext(),"Permissions denied .You can change them in Settings>Apps",Toast.LENGTH_LONG).show();
                    return false;
                }
            }
        }
        return true;
    }


    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        int count = 0;
        if (requestCode == PERMISSION_ALL) {
            for (int i = 0; i < permissions.length; i++) {
                String permission = permissions[i];
                int grantResult = grantResults[i];

                if (permission.equals(Manifest.permission.INTERNET)) {
                    if (grantResult == PackageManager.PERMISSION_GRANTED) {
                        //  onPPSButtonPress();
                    } else {
                        count++;
                        //  Toast.makeText(getApplicationContext(),"Permissions denied .You can change them in Settings>Apps",Toast.LENGTH_LONG).show();
                        //requestPermissions(new String[]{Manifest.permission.SEND_SMS}, PERMISSIONS_CODE);
                    }
                }



            }
        }
    }
}

Comments

Popular posts from this blog

Variables

Variables The main way to store information in the middle of a PHP program is by using a variable. Here are the most important things to know about variables in PHP. All variables in PHP are denoted with a leading dollar sign ($). The value of a variable is the value of its most recent assignment. Variables are assigned with the = operator, with the variable on the left-hand side and the expression to be evaluated on the right. Variables can, but do not need, to be declared before assignment. Variables in PHP do not have intrinsic types - a variable does not know in advance whether it will be used to store a number or a string of characters. Variables used before they are assigned have default values. PHP does a good job of automatically converting types from one to another when necessary. PHP variables are Perl-like. PHP has a total of eight data types which we use to construct our variables − Integers  − are whole numbers, without a decima...

SQL Server - INTERSECT Operator

Description The SQL Server (Transact-SQL) INTERSECT operator is used to return the records that are in common between two SELECT statements or data sets. If a record exists in one query and not in the other, it will be omitted from the INTERSECT results. It is the intersection of the two SELECT statements. Intersect Query Explanation:  The INTERSECT query will return the records in the blue shaded area. These are the records that exist in both Dataset1 and Dataset2. Each SELECT statement within the SQL Server INTERSECT must have the same number of columns in the result sets with similar data types. Syntax The syntax for the NTERSECT operator in SQL Server (Transact-SQL) is: SELECT expression1, expression2, ... expression_n FROM tables [WHERE conditions] INTERSECT SELECT expression1, expression2, ... expression_n FROM tables [WHERE conditions]; Parameters or Arguments expressions The columns or calculations that you wish to compare between the two SELECT ...

About Application

The product is supposed to be an open source application, developed under the PRSC(Punjab Remote Sensing Centre)organization, for the usage of PUDA(Punjab Urban Planning and Development Authority ). It is An android based system implementing client-server model. The Po portal System provides simple mechanism for the Planning officer to share  truly verified report. The following are the main features that are included in the application are: Common platform support: Offers operating support for most of the known and commercial operating systems i.e. android operating system. Number of users being supported by the system: Though the number is precisely not mentioned but the system is able to support a large number of online users at a time. Search: search for the pending list of the cases assigned is generally by logging in to the application. Id system: provides each officer with a unique Id which is sent at the time of report submission. Verification  section: Verif...