在Android

时间:2019-01-22 17:22:13

标签: java php android xml

我正在尝试在本地Web服务器(phpmyadmin)上的MySQL数据库中存储和检索图像,但是,当我尝试在应用程序中显示图像时,什么都没有显示。以下是带有源代码的文件:

SignUpActivity.java -我将存储在可绘制文件夹中的图像从bitmap转换为byteArrayOutputStream并将blob数据保存在我的数据库中(请参见register.php文件)

package com.test.myapp;

import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.CardView;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.arihant.messmaster.MainMenu;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;

public class test {
    package com.test.myapp;

    public class SignUpActivity extends AppCompatActivity {
        private CardView signUp;
        private TextInputLayout inputLayoutEmail;
        private TextInputLayout inputLayoutPhone;
        private EditText firstName;
        private EditText lastName;
        private EditText email;
        private EditText phone;
        private static final String KEY_STATUS = "status";
        private static final String KEY_PHOTO = "photo";
        private static final String KEY_FIRSTNAME = "first_name";
        private static final String KEY_LASTNAME = "last_name";
        private static final String KEY_EMAIL = "email";
        private static final String KEY_PASSWORD = "password";
        private static final String KEY_PHONE = "phone";
        private String registerUrl = "http://192.168.43.21/app/register.php";
        public SessionHandler sessionHandler;

        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_sign_up);
            inputLayoutEmail = findViewById(R.id.sign_up_input_layout_email);
            inputLayoutPhone = findViewById(R.id.sign_up_input_layout_phone);
            firstName = findViewById(R.id.sign_up_first_name);
            lastName = findViewById(R.id.sign_up_last_name);
            email = findViewById(R.id.sign_up_email);
            phone = findViewById(R.id.sign_up_phone);
            signUp = findViewById(R.id.button_signup);
            sessionHandler = new SessionHandler(this);

            signUp.setOnClickListener(new View.OnClickListener() {
                @RequiresApi(api = Build.VERSION_CODES.O)
                @Override
                public void onClick(View v) {
                    JSONObject request = new JSONObject();
                    try {
                        Bitmap bitmap = ((BitmapDrawable) getResources().getDrawable(R.drawable.default_user)).getBitmap();
                        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                        bitmap.compress(Bitmap.CompressFormat.PNG, 0, byteArrayOutputStream);
                        request.put(KEY_PHOTO, Arrays.toString(byteArrayOutputStream.toByteArray()));
                        byteArrayOutputStream.close();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    JsonObjectRequest jsArrayRequest = new JsonObjectRequest(Request.Method.POST, registerUrl, request, new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject response) {
                            try {
                                if (response.getInt(KEY_STATUS) == 0) {
                                    sessionHandler.setLogin(true);
                                    signUpMethod();
                                } else if (response.getInt(KEY_STATUS) == 1) {
                                    inputLayoutEmail.setError("User already exists!");
                                    email.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.error, 0);
                                    email.requestFocus();
                                } else if (response.getInt(KEY_STATUS) == 2) {
                                    inputLayoutPhone.setError("User already exists");
                                    phone.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.error, 0);
                                    phone.requestFocus();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    });

                    Singleton.getInstance(getApplicationContext()).addToRequestQueue(jsArrayRequest);
                }
            });
        }

        @TargetApi(Build.VERSION_CODES.O)
        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        public void signUpMethod() {
            try {
                Bitmap bitmap = ((BitmapDrawable) getResources().getDrawable(R.drawable.default_user)).getBitmap();
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 0, byteArrayOutputStream);
                sessionHandler.loginUser(Arrays.toString(byteArrayOutputStream.toByteArray()), firstName.getText().toString(), lastName.getText().toString(), email.getText().toString(), phone.getText().toString());
                byteArrayOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }

            Intent intent = new Intent(SignUpActivity.this, MainMenu.class);
            EditText phone = findViewById(R.id.sign_up_phone);
            intent.putExtra("phone", phone.getText().toString());
            startActivity(intent);
            finish();
        }

        @Override
        public void onBackPressed() {

        }
    }
}

Register.php -从SignUpActivity.java获取JSON对象并存储在数据库中。这里,尽管数据库中string字段的数据类型为PHOTO,但是我将图像文件存储为longblob数据类型。

<?php
$response = array();

include 'db_connect.php';
include 'functions.php';

$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE);

if (isset($input['photo']) && isset($input['first_name']) && isset($input['last_name']) && isset($input['email']) && isset($input['password']) && isset($input['phone'])) {
    $photo = $input['photo'];
    $first_name = $input['first_name'];
    $last_name = $input['last_name'];
    $email = $input['email'];
    $password = $input['password'];
    $phone = $input['phone'];

    if (!userExistsEmail($email) && !userExistsPhone($phone)) {
        $salt = getSalt();
        $password = password_hash(concatPasswordWithSalt($password, $salt), PASSWORD_DEFAULT);
        $insertQuery = "INSERT INTO user_data(PHOTO, FIRST_NAME, LAST_NAME, EMAIL, PASSWORD, SALT, PHONE) VALUES(?, ?, ?, ?, ?, ?, ?)";

        if ($stmt = $con->prepare($insertQuery)) {
            $stmt->bind_param("sssssss", $photo, $first_name, $last_name, $email, $password, $salt, $phone);
            $stmt->execute();
            $response["status"] = 0;
            $stmt->close();
        }
    } else if (userExistsEmail($email)) {
        $response["status"] = 1;
    } else if (userExistsPhone($phone)) {
        $response["status"] = 2;
    }
} else {
    $response["status"] = 2;
}

echo json_encode($response);
?>

成功登录后,

login.php

<?php
$response = array();

include 'db_connect.php';
include 'functions.php';

$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE);

if (isset($input['email']) && isset($input['password'])) {
    $email = $input['email'];
    $password = $input['password'];
    $query = "SELECT PHOTO, FIRST_NAME, LAST_NAME, EMAIL, PASSWORD, SALT, PHONE FROM user_data WHERE EMAIL = ?";

    if ($stmt = $con->prepare($query)) {
        $stmt->bind_param("s", $email);
        $stmt->execute();
        $stmt->bind_result($photo, $first_name, $last_name, $email, $password_hash, $salt, $phone);

        if ($stmt->fetch()) {
            if(password_verify(concatPasswordWithSalt($password, $salt), $password_hash)) {
                $response["status"] = 0;
                $response["photo"] = $photo;
                $response["first_name"] = $first_name;
                $response["last_name"] = $last_name;
                $response["email"] = $email;
                $response["phone"] = $phone;
            } else {
                $response["status"] = 1;
            }
        } else {
            $response["status"] = 1;
        }

        $stmt->close();
    }
} else {
    $response["status"] = 2;
    $response["message"] = "Missing mandatory parameters";
}

echo json_encode($response);
?>

MainMenuActivity.java -显示photofirst_namelast_nameemailphone。此处,图像文件未显示。 UserinfoSessionHandler是两个帮助类。

package com.test.myapp;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.arihant.messmaster.utility.SessionHandler;
import com.arihant.messmaster.utility.UserInfo;

public class MainMenu extends AppCompatActivity {
    private SessionHandler sessionHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_menu);
        ImageView photo = findViewById(R.id.profile_picture);
        TextView firstName = findViewById(R.id.menu_first_name);
        TextView lastName = findViewById(R.id.menu_last_name);
        TextView email = findViewById(R.id.menu_email);
        TextView phone = findViewById(R.id.menu_phone);
        CardView logout = findViewById(R.id.button_logout);
        sessionHandler = new SessionHandler(getApplicationContext());
        UserInfo userInfo = sessionHandler.getUserDetails();
        photo.setImageBitmap(BitmapFactory.decodeByteArray(userInfo.getPhoto().getBytes(), 0, userInfo.getPhoto().getBytes().length));
        firstName.setText(userInfo.getFirstName());
        lastName.setText(userInfo.getLastName());
        email.setText(userInfo.getEmail());
        phone.setText(userInfo.getPhone());

        logout.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onClick(View v) {
                deleteSharedPreferences("isLoggedIn");
                sessionHandler.setLogin(false);
                Intent intent = new Intent(MainMenu.this, LoginActivity.class);
                startActivity(intent);
                finish();
            }
        });
    }

    @Override
    public void onBackPressed() {
    }
}

activity_main_menu.xml

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

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

        <ImageView
            android:id="@+id/profile_picture"
            android:layout_width="150dp"
            android:layout_height="150dp"
            android:layout_gravity="center" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginTop="20dp"
            android:gravity="center"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/menu_first_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="18sp"
                android:textColor="@android:color/white"
                android:fontFamily="@font/montserrat_regular" />

            <TextView
                android:id="@+id/menu_last_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="18sp"
                android:textColor="@android:color/white"
                android:fontFamily="@font/montserrat_regular" />

        </LinearLayout>

        <TextView
            android:id="@+id/menu_email"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="18sp"
            android:textColor="@android:color/white"
            android:fontFamily="@font/montserrat_regular" />

        <TextView
            android:id="@+id/menu_phone"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="18sp"
            android:textColor="@android:color/white"
            android:fontFamily="@font/montserrat_regular" />

        <android.support.v7.widget.CardView
            android:id="@+id/button_logout"
            android:layout_width="200dp"
            android:layout_height="50dp"
            android:layout_gravity="center"
            android:layout_marginTop="30dp"
            app:cardBackgroundColor="@android:color/holo_blue_dark"
            app:cardCornerRadius="25dp"
            app:cardElevation="10dp">

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true"
                    android:fontFamily="@font/montserrat_regular"
                    android:text="@string/logout"
                    android:textColor="@android:color/white"
                    android:textSize="20sp" />

            </RelativeLayout>

        </android.support.v7.widget.CardView>

    </LinearLayout>

</RelativeLayout>

我还检查了是否从数据库中检索了整个blob。

我在SO上查看了其他类似的问题,但没有找到任何帮助,其中一些是基于SQLite的。此外,尝试在Google上进行搜索,并浏览了有关存储和从本地网络服务器检索的YouTube视频。我也尝试使用JDBC驱动程序,但这对我没有帮助,因为我被困在安装mysql-connector.jar上。

0 个答案:

没有答案