Base64编码数组中的单行

时间:2015-05-04 14:25:18

标签: php android base64 gson

我正在构建一个Android应用程序,应该可以拍照,然后将其存储在数据库中。我把那部分搞定了。但是,当我尝试将其再次加载到我的应用程序中时,那就是当它变得棘手时。

我将图像存储为我的数据库中的longblob,我可以从我的logcat中的json读数中看到,longblob作为字符串返回。一个很长的字符串,我无法处理。当我尝试添加到我的gson创建的包装类时,它只是给了我一个nullpointer。

现在,我已经看过几个地方,建议我在我的php文件中对它进行base64_encode。我找到了一种方法,但只能在php文件中添加另一个数组,我希望避免在我的java代码中处理不同的数组。

到目前为止我的php看起来像这样:

<?php
function resultToArray($result) {
    $rows = array();
    while($row = $result->fetch_assoc()) {
        $rows[] = $row;

       foreach($rows as $key=>$value){ /* Creating this extra array is what I'm looking to avoid. */
           $newArrData[$key] =  $spots[$key];
           $newArrData[$key]['Image'] = base64_encode($spots[$key]['Image']);
       }
     }
     return $rows;
}
$mysqli = new mysqli("host", "username", "password", "db_to_use");
$email = $mysqli->real_escape_string($_GET['email']);
$mysqli->set_charset('utf8');
$query = ("SELECT * FROM Cards WHERE Email_FK='{$email}'");
$result = $mysqli->query($query);
$rows = resultToArray($result);
echo json_encode($rows);

$result->free();
?>

我返回9个不同的值,包含图片。有没有办法避免创建newArrData数组,所以我只需要处理代码中的那个?

我在java代码中的包装类:

import java.io.Serializable;

/**
 * Created by KasperG on 22/04/2015.
 */
public class Card implements Serializable {
    private String Email_FK;
    private String BarcodeNumbers;
    private String MemberNumber;
    private String StoreID;
    private String CardID;
    private String HasBarcode;
    private String StoreName;
    private String CustomCard;
    //private Base64 Image;


    public Card() {

    }

    public Card(String barcodeNumbers, String memberNumber, String storeID, String hasBarcode, String cardID, String storeName, String CustomCard) {
        this.StoreID = storeID;
        if (barcodeNumbers.isEmpty()) {
            this.BarcodeNumbers = null;
        } else {
            this.BarcodeNumbers = barcodeNumbers;
        }
        if (memberNumber.isEmpty()) {
            this.MemberNumber = null;
        } else {
            this.MemberNumber = memberNumber;
        }
        this.HasBarcode = hasBarcode;
        this.CardID = cardID;
        this.StoreName = storeName;
        this.CustomCard = CustomCard;
    }
    /*
    public Card(String memberNumber, String storeID) {
        this.memberNumber = memberNumber;
        this.storeID = storeID;
    }
    */

    public String getBarcodeNumbers() {
        return BarcodeNumbers;
    }

    public String getMemberNumber() {
        return MemberNumber;
    }

    public String getHasBarcode() {
        return HasBarcode;
    }

    public String getCardID() {
        return CardID;
    }

    public String getStoreName() {
        return StoreName;
    }

    public int getStoreID() {
        return Integer.parseInt(StoreID);
    }

    public String getCustomStore() { return CustomCard; }

    //public Base64 getImageString() { return Image; }


    @Override
    public String toString() {
        return "MemberNumber: " + MemberNumber + "\n" +
                "BarcodeNumbers: " + BarcodeNumbers + "\n" +
                "Store ID: " + StoreID + "\n" +
                "Has Barcode " + HasBarcode + "\n" +
                "Card ID: " + CardID + "\n" +
                "Store Name: " + StoreName + "\n" +
                "Custom Card? " + CustomCard + "\n" +
                "Image String: " /*+ Image*/;
    }
}

&#34;图像&#34;变量是故意的,因为如果我不这样做,它根本不起作用!

我在哪里使用gson从包装器创建类;

public ArrayList<Card> getCards(MyCardsScreenActivity activity) {
    myCards = activity;

    String email = SaveSharedPreferences.getUserName(activity);
    ArrayList<Card> cards = new ArrayList<>();
    try {
        String link = "http://test.wallyy.com/new_get_card_info.php?email=" + email;
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet();
        request.setURI(new URI(link));
        HttpResponse response = client.execute(request);
        String data = EntityUtils.toString(response.getEntity());
        Log.d("Pass3?", data.toString());

        Gson gson = new Gson();
        Card[] cards1 = gson.fromJson(data.toString(), Card[].class);
        for(Card card : cards1) {
            cards.add(card);
            Log.d("Card toString;\n", card.toString());
        }
    }
    catch(Exception ex) {}

    if (!cards.isEmpty()) {
        myCards.setHasCards(true);
    }
    else {
        myCards.setHasCards(false);
    }
    return cards;
}

有人能指出我在正确的方向吗?

编辑: 按照@CJ Wurtz&#39;建议,我把我的php文件更改为了这个;

while($row = $result->fetch_assoc()) {
        $row['Image'] = base64_encode($row['Image']);
        $rows[] = $row;
    }

然而,这仍然不适用于Android方面。更新了我的包装类;

public class Card implements Serializable {
    private String Email_FK;
    private String BarcodeNumbers;
    private String MemberNumber;
    private String StoreID;
    private String CardID;
    private String HasBarcode;
    private String StoreName;
    private String CustomCard;
    private Base64 Image;


    public Card() {

    }

但是当我添加Image变量时,gson不会创建包装类的任何实例。

Reedit:刚才意识到我粘贴了错误的http方法。更新后的public ArrayList<Card> getCards(MyCardsScreenActivity) {...}是我要调用的一个,用于创建包装类的实例并将它们添加到arraylist中。

2 个答案:

答案 0 :(得分:0)

为什么不用base64_encoded版本覆盖“Image”元素?

即:

while($row = $result->fetch_assoc()) {
    $row['Image'] = base64_encode($row['Image']);
    $rows[] = $row;
}

我不确定那个$spots数组来自哪里,所以也许这个解决方案对你不起作用,但基本上只是说你从数据库中获取的每一行,更新该数组为在将它添加到最终结果数组之前的行,您将返回。

答案 1 :(得分:0)

我的包装器类设置错误。我不确定如何处理来自服务器的响应,但是通过在我的包装器类中进行一些更改,我得到了它的工作。

我的包装类现在看起来像这样;

    import java.io.Serializable;

    /**
     * Created by KasperG on 22/04/2015.
     */
    public class Card implements Serializable {
        private String Email_FK;
        private String BarcodeNumbers;
        private String MemberNumber;
        private String StoreID;
        private String CardID;
        private String HasBarcode;
        private String StoreName;
        private String CustomCard;
        private String Image;


        public Card() {

        }

        public Card(String barcodeNumbers, String memberNumber, String storeID, String hasBarcode, String cardID, String storeName, String CustomCard, String Image) {
            this.StoreID = storeID;
            if (barcodeNumbers.isEmpty()) {
                this.BarcodeNumbers = null;
            } else {
                this.BarcodeNumbers = barcodeNumbers;
            }
            if (memberNumber.isEmpty()) {
                this.MemberNumber = null;
            } else {
                this.MemberNumber = memberNumber;
            }
            this.HasBarcode = hasBarcode;
            this.CardID = cardID;
            this.StoreName = storeName;
            this.CustomCard = CustomCard;
            this.Image = Image;
        }

        public String getBarcodeNumbers() {
            return BarcodeNumbers;
        }

        public String getMemberNumber() {
            return MemberNumber;
        }

        public String getHasBarcode() {
            return HasBarcode;
        }

        public String getCardID() {
            return CardID;
        }

        public String getStoreName() {
            return StoreName;
        }

        public int getStoreID() {
            return Integer.parseInt(StoreID);
        }

        public String getCustomStore() { return CustomCard; }

       public String getImageString() { return Image; }


        @Override
        public String toString() {
            return "MemberNumber: " + MemberNumber + "\n" +
                    "BarcodeNumbers: " + BarcodeNumbers + "\n" +
                    "Store ID: " + StoreID + "\n" +
                    "Has Barcode " + HasBarcode + "\n" +
                    "Card ID: " + CardID + "\n" +
                    "Store Name: " + StoreName + "\n" +
                    "Custom Card? " + CustomCard + "\n" +
                    "Image String: " + Image;
        }
    }

将Image变量的类型更改为String,使其成为;

public ArrayList<Card> getCards(MyCardsScreenActivity activity) {
        myCards = activity;

        String email = SaveSharedPreferences.getUserName(activity);
        ArrayList<Card> cards = new ArrayList<>();
        try {
            String link = "http://address.com/new_get_card_info.php?email=" + email;
            HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet();
            request.setURI(new URI(link));
            HttpResponse response = client.execute(request);
            String data = EntityUtils.toString(response.getEntity());
            Log.d("Pass3?", data.toString());

            Gson gson = new Gson();
            Card[] cards1 = gson.fromJson(data.toString(), Card[].class);
            for(Card card : cards1) {
                cards.add(card);
                Log.d("Card toString;\n", card.toString());
            }
        }
        catch(Exception ex) {}

        if (!cards.isEmpty()) {
            myCards.setHasCards(true);
        }
        else {
            myCards.setHasCards(false);
        }
        return cards;
    }

的工作。然后我只需处理该字符串;

byte[] bytes = Base64.decode(card.getImageString(), Base64.DEFAULT);
bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

再次,抱歉这个制度不好的问题。我将尽力使我的问题更加重要。