Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static final String UPLOAD_URL = "http://servidor.com/pasta/registrar.php";
- public static final String UPLOAD_KEY = "imagemPerfil";
- public static final String UPLOAD_ID = "idUsuario";
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_registro);
- Regnome = (EditText) findViewById(R.id.editTextNome);
- Regsobrenome = (EditText) findViewById(R.id.editTextSobrenome);
- Regtelefone = (EditText) findViewById(R.id.editTextTelefone);
- Regcelular = (EditText) findViewById(R.id.editTextCelular);
- Reglogradouro = (EditText) findViewById(R.id.editTextLogradouro);
- Regnumero = (EditText) findViewById(R.id.editTextNumero);
- Regcomplemento = (EditText) findViewById(R.id.editTextComplemento);
- Regreferencia = (EditText) findViewById(R.id.editTextReferencia);
- Regcidade = (EditText) findViewById(R.id.editTextCidade);
- Regcep = (EditText) findViewById(R.id.editTextCEP);
- Regcpfcnpj = (EditText) findViewById(R.id.editTextCPFCNPJ);
- Regemail = (EditText) findViewById(R.id.editTextEmail);
- Regusuario = (EditText) findViewById(R.id.editTextUsuario);
- Regsenha = (EditText) findViewById(R.id.editTextSenha);
- Reguf = (Spinner) findViewById(R.id.spinnerUF);
- RegufText = Reguf.getSelectedItem().toString();
- result = (ImageView) findViewById(R.id.imgPerfil);
- }
- public void abrirCamera() {
- Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
- if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
- startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
- }
- }
- public void chamarGaleria() {
- Intent intent = new Intent();
- intent.setType("image/*");
- intent.setAction(Intent.ACTION_GET_CONTENT);
- startActivityForResult(Intent.createChooser(intent, "Selecione a imagem"), SELECT_PHOTO);
- }
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
- Bundle extras = data.getExtras();
- Bitmap imageBitmap = (Bitmap) extras.get("data");
- result.setImageBitmap(imageBitmap);
- } else if (requestCode == SELECT_PHOTO && resultCode == RESULT_OK && data != null && data.getData() != null){
- filePath = data.getData();
- try {
- bitmapreme = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
- if (bitmapreme.getWidth() >= bitmapreme.getHeight()){
- bitmapdest = Bitmap.createBitmap(
- bitmapreme,
- bitmapreme.getWidth()/2 - bitmapreme.getHeight()/2,
- 0,
- bitmapreme.getHeight(),
- bitmapreme.getHeight()
- );
- }else{
- bitmapdest = Bitmap.createBitmap(
- bitmapreme,
- 0,
- bitmapreme.getHeight()/2 - bitmapreme.getWidth()/2,
- bitmapreme.getWidth(),
- bitmapreme.getWidth()
- );
- }
- bitmapdest = Bitmap.createScaledBitmap(bitmapdest, 600, 600, false);
- result.setImageBitmap(bitmapdest);
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- public String getStringImage(Bitmap bmp){
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
- byte[] imageBytes = baos.toByteArray();
- String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
- return encodedImage;
- }
- public void salvarReg(View view) {
- if (Regnome.getText().toString().trim().length() == 0 ||
- Regsobrenome.getText().toString().trim().length() == 0 ||
- Regcidade.getText().toString().trim().length() == 0 ||
- Regcpfcnpj.getText().toString().trim().length() == 0 ||
- Regemail.getText().toString().trim().length() == 0 ||
- Regusuario.getText().toString().trim().length() == 0 ||
- Regsenha.getText().toString().trim().length() == 0
- ) {
- mostrarMensagem("Erro", "Nenhum dos campos obrigatórios pode estar em branco. Por favor, preencha corretamente todos os campos.");
- } else {
- String str_nome = Regnome.getText().toString();
- String str_sobrenome = Regsobrenome.getText().toString();
- String str_telefone = Regtelefone.getText().toString();
- String str_celular = Regcelular.getText().toString();
- String str_logradouro = Reglogradouro.getText().toString();
- String str_numero = Regnumero.getText().toString();
- String str_complemento = Regcomplemento.getText().toString();
- String str_referencia = Regreferencia.getText().toString();
- String str_cidade = Regcidade.getText().toString();
- String str_uf = Reguf.getSelectedItem().toString();
- String str_cep = Regcep.getText().toString();
- String str_cpfcnpj = Regcpfcnpj.getText().toString();
- String str_email = Regemail.getText().toString();
- String str_usuario = Regusuario.getText().toString();
- String str_senha = Regsenha.getText().toString();
- String str_dataCad = Regdata.toString();
- String empresas = "000";
- String acesso = "001";
- String type = "registrar";
- BackgroundWorker backgroundWorker = new BackgroundWorker(this);
- backgroundWorker.execute(type, str_nome, str_sobrenome, str_telefone, str_celular, str_logradouro, str_numero, str_complemento, str_referencia, str_cidade, str_uf, str_cep, str_cpfcnpj, str_email, str_usuario, str_senha, str_dataCad, empresas, acesso);
- uploadImage();
- //limpaTexto();
- }
- }
- public void uploadImage() {
- class UploadImage extends AsyncTask<Bitmap, Void, String> {
- ProgressDialog loading;
- RequestHandler rh = new RequestHandler();
- @Override
- protected void onPreExecute() {
- super.onPreExecute();
- loading = ProgressDialog.show(Registro.this, "Carregando imagem", "Aguarde alguns instantes...", true, true);
- }
- @Override
- protected void onPostExecute(String s) {
- super.onPostExecute(s);
- loading.dismiss();
- Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
- }
- @Override
- protected String doInBackground(Bitmap... params) {
- Bitmap bitmap = params[0];
- String uploadImage = getStringImage(bitmap);
- HashMap<String, String> data = new HashMap<>();
- data.put(UPLOAD_KEY, uploadImage);
- data.put(UPLOAD_ID, uploadImage);
- String result = rh.sendPostRequest(UPLOAD_URL, data);
- return result;
- }
- }
- UploadImage ui = new UploadImage();
- ui.execute(bitmapdest);
- }
- public void showMessage(View view) {
- final String items[] = {"Câmera", "Arquivo", "Cancelar"};
- AlertDialog.Builder builder = new AlertDialog.Builder(this);
- builder.setTitle("Selecione a origem da imagem: ");
- builder.setItems(items, new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface d, int choice) {
- // Do something with the selection
- if (choice == 0) {
- abrirCamera();
- } else if (choice == 1) {
- chamarGaleria();
- } else if (choice == 2) {
- return;
- }
- }
- });
- builder.show();
- }
- }
- public class RequestHandler {
- public String sendGetRequest(String uri) {
- try {
- URL url = new URL(uri);
- HttpURLConnection con = (HttpURLConnection) url.openConnection();
- BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
- String result;
- StringBuilder sb = new StringBuilder();
- while((result = bufferedReader.readLine())!=null){
- sb.append(result);
- }
- return sb.toString();
- } catch (Exception e) {
- return null;
- }
- }
- public String sendPostRequest(String requestURL,
- HashMap<String, String> postDataParams) {
- URL url;
- String response = "";
- try {
- url = new URL(requestURL);
- 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(getPostDataString(postDataParams));
- writer.flush();
- writer.close();
- os.close();
- int responseCode = conn.getResponseCode();
- if (responseCode == HttpsURLConnection.HTTP_OK) {
- BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
- response = br.readLine();
- } else {
- response = "Erro ao registrar";
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- return response;
- }
- private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
- StringBuilder result = new StringBuilder();
- boolean first = true;
- for (Map.Entry<String, String> entry : params.entrySet()) {
- if (first)
- first = false;
- else
- result.append("&");
- result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
- result.append("=");
- result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
- }
- return result.toString();
- }
- Context context;
- AlertDialog alertDialog;
- BackgroundWorker(Context ctx) {
- context = ctx;
- }
- @Override
- protected String doInBackground(String... params) {
- String type = params[0];
- String login_url = "http://servidor.com/pasta/login.php";
- String registrar_url = "http://servidor.com/pasta/registrar.php";
- String consultar_url = "http://servidor.com/pasta/consultar.php";
- //String excluir_url = "http://servidor.com/pasta/excluir.php";
- if (type.equals("login")) {
- try {
- String usuario = params[1];
- String senha = params[2];
- URL url = new URL(login_url);
- HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
- httpURLConnection.setRequestMethod("POST");
- httpURLConnection.setDoOutput(true);
- httpURLConnection.setDoInput(true);
- OutputStream outputStream = httpURLConnection.getOutputStream();
- BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
- String dados = URLEncoder.encode("usuario", "UTF-8") + "=" + URLEncoder.encode(usuario, "UTF-8") + "&"
- + URLEncoder.encode("senha", "UTF-8") + "=" + URLEncoder.encode(senha, "UTF-8");
- bufferedWriter.write(dados);
- bufferedWriter.flush();
- bufferedWriter.close();
- outputStream.close();
- InputStream inputStream = httpURLConnection.getInputStream();
- BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
- String result = "";
- String linha = "";
- while ((linha = bufferedReader.readLine()) != null) {
- result += linha;
- }
- bufferedReader.close();
- inputStream.close();
- httpURLConnection.disconnect();
- return result;
- } catch (MalformedURLException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- } else if (type.equals("registrar")) {
- try {
- String nome = params[1];
- String sobrenome = params[2];
- String telefone = params[3];
- String celular = params[4];
- String logradouro = params[5];
- String numero = params[6];
- String complemento = params[7];
- String referencia = params[8];
- String cidade = params[9];
- String uf = params[10];
- String cep = params[11];
- String cpfcpnj = params[12];
- String email = params[13];
- String usuario = params[14];
- String senha = params[15];
- String dataCad = params[16];
- String empresas = params[17];
- String acesso = params[18];
- URL url = new URL(registrar_url);
- HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
- httpURLConnection.setRequestMethod("POST");
- httpURLConnection.setDoOutput(true);
- httpURLConnection.setDoInput(true);
- OutputStream outputStream = httpURLConnection.getOutputStream();
- BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
- String dados = URLEncoder.encode("nome", "UTF-8") + "=" + URLEncoder.encode(nome, "UTF-8") + "&"
- + URLEncoder.encode("sobrenome", "UTF-8") + "=" + URLEncoder.encode(sobrenome, "UTF-8") + "&"
- + URLEncoder.encode("telefone", "UTF-8") + "=" + URLEncoder.encode(telefone, "UTF-8") + "&"
- + URLEncoder.encode("celular", "UTF-8") + "=" + URLEncoder.encode(celular, "UTF-8") + "&"
- + URLEncoder.encode("logradouro", "UTF-8") + "=" + URLEncoder.encode(logradouro, "UTF-8") + "&"
- + URLEncoder.encode("numero", "UTF-8") + "=" + URLEncoder.encode(numero, "UTF-8") + "&"
- + URLEncoder.encode("complemento", "UTF-8") + "=" + URLEncoder.encode(complemento, "UTF-8") + "&"
- + URLEncoder.encode("referencia", "UTF-8") + "=" + URLEncoder.encode(referencia, "UTF-8") + "&"
- + URLEncoder.encode("cidade", "UTF-8") + "=" + URLEncoder.encode(cidade, "UTF-8") + "&"
- + URLEncoder.encode("uf", "UTF-8") + "=" + URLEncoder.encode(uf, "UTF-8") + "&"
- + URLEncoder.encode("cep", "UTF-8") + "=" + URLEncoder.encode(cep, "UTF-8") + "&"
- + URLEncoder.encode("cpfcnpj", "UTF-8") + "=" + URLEncoder.encode(cpfcpnj, "UTF-8") + "&"
- + URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode(email, "UTF-8") + "&"
- + URLEncoder.encode("usuario", "UTF-8") + "=" + URLEncoder.encode(usuario, "UTF-8") + "&"
- + URLEncoder.encode("senha", "UTF-8") + "=" + URLEncoder.encode(senha, "UTF-8") + "&"
- + URLEncoder.encode("dataCad", "UTF-8") + "=" + URLEncoder.encode(dataCad, "UTF-8") + "&"
- + URLEncoder.encode("empresas", "UTF-8") + "=" + URLEncoder.encode(empresas, "UTF-8") + "&"
- + URLEncoder.encode("acesso", "UTF-8") + "=" + URLEncoder.encode(acesso, "UTF-8");
- bufferedWriter.write(dados);
- bufferedWriter.flush();
- bufferedWriter.close();
- outputStream.close();
- InputStream inputStream = httpURLConnection.getInputStream();
- BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
- String result = "";
- String line = "";
- while ((line = bufferedReader.readLine()) != null) {
- result += line;
- }
- bufferedReader.close();
- inputStream.close();
- httpURLConnection.disconnect();
- return result;
- } catch (MalformedURLException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- } else if (type.equals("consultar")) {
- try {
- String nome = params[1];
- URL url = new URL(consultar_url);
- HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
- httpURLConnection.setRequestMethod("POST");
- httpURLConnection.setDoOutput(true);
- httpURLConnection.setDoInput(true);
- OutputStream outputStream = httpURLConnection.getOutputStream();
- BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
- String dados = URLEncoder.encode("nome", "UTF-8") + "=" + URLEncoder.encode(nome, "UTF-8");
- bufferedWriter.write(dados);
- bufferedWriter.flush();
- bufferedWriter.close();
- outputStream.close();
- InputStream inputStream = httpURLConnection.getInputStream();
- BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
- String result = "";
- String line = "";
- while ((line = bufferedReader.readLine()) != null) {
- result += line;
- }
- bufferedReader.close();
- inputStream.close();
- httpURLConnection.disconnect();
- return result;
- } catch (MalformedURLException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- } else if(type.equals("uploadPerfil")) {
- try {
- String imagemPerfil = params[1];
- URL url = new URL(consultar_url);
- HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
- httpURLConnection.setRequestMethod("POST");
- httpURLConnection.setDoOutput(true);
- httpURLConnection.setDoInput(true);
- OutputStream outputStream = httpURLConnection.getOutputStream();
- BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
- String dados = URLEncoder.encode("imagemPerfil", "UTF-8") + "=" + URLEncoder.encode(imagemPerfil, "UTF-8");
- bufferedWriter.write(dados);
- bufferedWriter.flush();
- bufferedWriter.close();
- outputStream.close();
- InputStream inputStream = httpURLConnection.getInputStream();
- BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
- String result = "";
- String line = "";
- while ((line = bufferedReader.readLine()) != null) {
- result += line;
- }
- bufferedReader.close();
- inputStream.close();
- httpURLConnection.disconnect();
- return result;
- } catch (MalformedURLException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- } else {
- return null;
- }
- return null;
- }
- @Override
- protected void onPreExecute() {
- alertDialog = new AlertDialog.Builder(context).create();
- alertDialog.setTitle("Login Status");
- }
- @Override
- protected void onPostExecute(String result) {
- //if(result.toString().equals("usuario")) {
- // context.startActivity(new Intent(context, Inicio.class));
- //}
- String s = result.trim();
- //alertDialog.setMessage(s);
- switch (s) {
- case "user":
- context.startActivity(new Intent(context, Inicio.class));
- break;
- case "adm":
- context.startActivity(new Intent(context, InicioAdm.class));
- break;
- default:
- alertDialog.setMessage(s);
- alertDialog.show();
- }
- }
- @Override
- protected void onProgressUpdate(Void... values) {
- super.onProgressUpdate(values);
- }
- }
- <?php
- require "conexao.php";
- $nome = $_POST["nome"];
- $sobrenome = $_POST["sobrenome"];
- $telefone = $_POST["telefone"];
- $celular = $_POST["celular"];
- $logradouro = $_POST["logradouro"];
- $numero = $_POST["numero"];
- $complemento = $_POST["complemento"];
- $referencia = $_POST["referencia"];
- $cidade = $_POST["cidade"];
- $uf = $_POST["uf"];
- $cep = $_POST["cep"];
- $cpfcnpj = $_POST["cpfcnpj"];
- $email = $_POST["email"];
- $usuario = $_POST["usuario"];
- $senha = $_POST["senha"];
- $dataCad = $_POST["dataCad"];
- $empresas= $_POST["empresas"];
- $acesso = $_POST["acesso"];
- //$idUsuario = $_POST["idUsuario"];
- $imagemPerfil = $_POST["imagemPerfil"];
- $mysql_qry = "INSERT INTO `u562378822_banco`.`usuarios` VALUES (null, '$nome', '$sobrenome', '$telefone', '$celular', '$logradouro', '$numero', '$complemento', '$referencia', '$cidade', '$uf', '$cep', '$cpfcnpj', '$email', '$usuario', '$senha', '$dataCad', '$dataAcesso', '$empresas', '$acesso', null);";
- $verifica_qry = "SELECT usuario FROM usuarios WHERE usuario LIKE '$usuario';";
- $tudo_qry = "SELECT * FROM `u562378822_banco`.`usuarios` WHERE `usuarios`.`usuario` ='$usuario';";
- $tudo_exec = mysqli_query($conexao,$tudo_qry);
- $idUsuario = mysqli_fetch_array($tudo_exec);
- $sqldeimagem = "UPDATE usuarios SET `imagemPerfil` = '$imagemPerfil' WHERE `usuarios`.`idUsuario` ='$idUsuario[0]';";
- $verificador = mysqli_query($conexao,$verifica_qry);
- if(mysqli_num_rows($verificador) > 0){
- echo "Erro. Este nome de usuario já está sendo usado por alguém. Por favor, escolha outro.";
- } elseif($conexao->query($mysql_qry) === TRUE) {
- if($conexao->query($sqldeimagem) === TRUE){
- $linhasAfetadas = mysqli_affected_rows($conexao);
- if ($linhasAfetadas == 0) {
- echo "Nenhuma coisa mudou";
- } elseif ($linhasAfetadas == 1) {
- echo "Imagem registrada com sucesso";
- } elseif ($linhasAfetadas > 0) {
- echo "sucesso mudaram as linhas $linhasAfetadas";
- } else {
- echo "erro";
- }
- }
- //$atualizador = mysqli_query($conexao,$sqldeimagem);
- //$linhasAfetadas = mysqli_affected_rows($conexao);
- } else {
- echo "Erro. Os dados não foram salvos.";
- }
- $conexao->close();
- ?>
- $imagem = 'myimage.png';
- $extensao = pathinfo($imagem, PATHINFO_EXTENSION);
- $dataraw = file_get_contents($imagem);
- echo 'data:image/' . $extensao . ';base64,' . base64_encode($dataraw);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement