android - 根据连接表返回的值发送电子邮件

标签 android mysql email

我已经解决了这个问题,但遇到了另一个问题,选择语句现在正在工作,但电子邮件 Intent 没有运行(好吧,我没有收到任何电子邮件)

我的创建语句现在是;

myDB.execSQL("CREATE TABLE IF NOT EXISTS dressdetails " +
                "(dress_id integer primary key AUTOINCREMENT, profile_id INTEGER, image1 BLOB, designer VARCHAR, style VARCHAR, size VARCHAR, viel VARCHAR, " +
                "drycleaning VARCHAR, FOREIGN KEY(profile_id) REFERENCES profile(id));");

我有一个可点击的按钮,允许用户进入他们的设备图库并检索照片

Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
            photoPickerIntent.setType("image/*");
            startActivityForResult(photoPickerIntent, SELECT_PHOTO);
        }
    });
}

// Method to receive bundle with image Uri and convert to bitmap so it can be inputted into the database
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

    try{
        switch(requestCode) {
            case SELECT_PHOTO:
                if (resultCode == RESULT_OK) {
                    Uri selectedImage = imageReturnedIntent.getData();
                    InputStream imageStream = getContentResolver().openInputStream(selectedImage);
                    yourSelectedImage = BitmapFactory.decodeStream(imageStream);
                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    yourSelectedImage.compress(Bitmap.CompressFormat.JPEG, 80, stream);
                    stream.toByteArray();
                }
        }
        // Catch input/output errors
    }catch(IOException ex){
        ex.printStackTrace();
    }
}

然后我尝试插入图像

myDB.execSQL("INSERT INTO dressdetails(profile_id, designer, style, size, viel, drycleaning) VALUES ('" + idReceived + "', '" +
            yourSelectedImage + "', '" + Designer + "', '" + Style + "', '" + WhatSize + "', '" + WantViel + "', '" + DryCleaningCost + "');");

下一部分是我认为出错的地方;

/// Method to convert the image from int to byte[] so can be stored in database ///


public byte[] convertToByteArray(int image){

    Resources resources = getResources();
    Drawable drawable = resources.getDrawable(image);
    Bitmap bitmap =  ((BitmapDrawable)drawable).getBitmap();
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 0, stream);
    //byte[] bitmapData = stream.toByteArray();
    return stream.toByteArray();
    //return bitmapData;

}


/// Sample dresses inputted for your purposes, now when you search there will be some dresses to output /// + yourSelectedImage + "', '"
public void inputExamples() {


    int image10 = R.drawable.wdone;
    int image2 = R.drawable.wdtwo;
    int image3 = R.drawable.wdthree;
    int image4 = R.drawable.wdfour;
    int image5 = R.drawable.wdfive;
    int image6 = R.drawable.wdsix;
    int image7 = R.drawable.wdseven;
    int image8 = R.drawable.wdeight;
    int image9 = R.drawable.wdnine;

    byte[] eg1 = convertToByteArray(image10);
    byte[] eg2 = convertToByteArray(image2);
    byte[] eg3 = convertToByteArray(image3);
    byte[] eg4 = convertToByteArray(image4);
    byte[] eg5 = convertToByteArray(image5);
    byte[] eg6 = convertToByteArray(image6);
    byte[] eg7 = convertToByteArray(image7);
    byte[] eg8 = convertToByteArray(image8);
    byte[] eg9 = convertToByteArray(image9);

我直接看到了我看过的准备好的陈述,但说实话,我只是对此感到陌生,而且它有点超出了我的理解范围。

然后,我在此连接表上进行选择查询,以检索回裙子以及我想要在电子邮件中转发的其他信息。

Cursor c = myDB.rawQuery("SELECT profile_id, image1, designer, drycleaning FROM dressdetails INNER JOIN profile ON (" +
            "profile.id = dressdetails.profile_id) WHERE dressdetails.size LIKE '%" + size + "%' OR dressdetails.style LIKE '%" + style + "%' OR dressdetails.viel LIKE '%"
            + viel + "%';", null);*/
if(c.moveToFirst()){
        do {
            // store it as a string in a variable
            dressesProfileId = c.getString(c.getColumnIndex("profile_id"));

            /// *** HERE is where I store the image into a variable *** ///
            //queryImageRetrieved = c.getString(c.getColumnIndex("image1"));
            dryCleaningDetails = c.getString(c.getColumnIndex("drycleaning"));
        } while (c.moveToNext());
    }

    c.close();

我将字符串转换为字节[]

 /// *** Here I try to convert the string back into a byte array *** ///
    byte[] bytes;
    try{
        bytes = queryImageRetrieved.getBytes("UTF-8"); BitmapFactory.decodeByteArray(bytes, 0, queryImageRetrieved.length());
        // Catch any I/O exceptions
        System.out.println("You have reached here and bytes has a value " + bytes);
    }catch (Exception e){
        e.printStackTrace();
    }

然后另一个光标检索匹配用户的联系信息

 /// method 2 for returning contact details of matching dress from profile table and storing in variables ///
    String rentorName = "";
    String rentorEmail = "";
    String rentalPrice = "";
    String query = "SELECT username, useremail, rentalprice FROM profile INNER JOIN dressdetails ON (" +
            "profile.id = dressdetails.profile_id) WHERE id = ?";
    Cursor c1 = myDB.rawQuery(query, new String[] { dressesProfileId });
    //Cursor c1 = myDB.rawQuery("SELECT username, useremail FROM profile INNER JOIN dressdetails ON (" +
            //"profile.id = dressdetails.profile_id) WHERE profile.id = ?", new String[] {dressesProfileId});
    if(c1.moveToFirst()) {
        // Store the values needed in variables so we can send it to the user in an email with the image
        do {
            rentorName = c1.getString(c1.getColumnIndex("username"));
            rentorEmail = c1.getString(c1.getColumnIndex("useremail"));
            rentalPrice = c1.getString(c1.getColumnIndex("rentalprice"));
            sellerContactDetails = "The name of the seller is " + rentorName + ", their email address is " + rentorEmail +
                    ", the rental price is " + rentalPrice + " and the dry cleaning cost is " + dryCleaningDetails + ";";

            // Check that it has worked - Debug tool
            Toast.makeText(this, sellerContactDetails, Toast.LENGTH_SHORT).show();

            // Continue until no more dresses match the set criteria
        } while (c1.moveToNext());
    }

    // Close the cursor and the database
    c1.close();
    myDB.close();

最后,我有电子邮件 Intent 将检索到的信息和图像发送给用户。

// Send results to users email
    Log.i("Send email", "");

    String[] TO = { rentorEmail };
    Intent emailIntent = new Intent(Intent.ACTION_SEND);
    emailIntent.setData(Uri.parse("mailto:"));
    emailIntent.setType("plain/text");


    emailIntent.putExtra(Intent.EXTRA_EMAIL, TO);
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, "P2P Weddings");
    emailIntent.putExtra(Intent.EXTRA_TEXT, sellerContactDetails);

    try {
        startActivity(Intent.createChooser(emailIntent, "Send mail..."));
        finish();
        Log.i("Finished sending email ", "");
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(SearchCriteria.this,
                "There is no email client installed.", Toast.LENGTH_SHORT).show();
    }

我知道这很长,抱歉,我很快就要完成我的第一个应用程序了,但已经被困在这一点上一周了!任何帮助将不胜感激。谢谢大家!

这就是 logcat 所说的

 Caused by: android.database.sqlite.SQLiteException: unrecognized token: "[B@350f45fe, 'Versace', 'Off the shoulder', '6', 'Yes', '€25');" (code 1): , while compiling: INSERT INTO dressdetails(profile_id, image1, designer, style, size, viel, drycleaning) VALUES (1, [B@350f45fe, 'Versace', 'Off the shoulder', '6', 'Yes', '€25');

最佳答案

yourSelectedImage 是一个位图,在这里您将 yourSelectedImage.toString() 添加到表中:

myDB.execSQL("INSERT INTO dressdetails(profile_id, designer, style, size, viel, drycleaning) VALUES ('" + idReceived + "', '" +
            yourSelectedImage + "', '" + Designer + "', '" + Style + "', '" + WhatSize + "', '" + WantViel + "', '" + DryCleaningCost + "');");

我建议不要将图像保存到数据库中,但如果这样做,您应该序列化位图并确保正确转义它。

更新:

根据您在问题中包含的错误消息,上述 SQL 语句等于此字符串:

"INSERT INTO dressdetails(profile_id, image1, designer, style, size,
viel, drycleaning) VALUES (1, [B@350f45fe, 'Versace', 'Off the shoulder',
'6', 'Yes', '€25');"

您看到“[B@350f45fe”吗?

这里显然有问题,因为 VALUES 中的第二个参数应该用单引号引起来。我不知道它们是如何消失的,可能是一些溢出,甚至是sql注入(inject)(或者即使它不是故意注入(inject),如果yourSelectedImage.toString()有单引号,它也会呈现无效的SQL)。但无论如何,即使它有效,看起来您也会保存 Bitmap.toString,它类似于“Bitmap[@350f45fe]”,但不是实际的位图数据。

关于android - 根据连接表返回的值发送电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34887032/

相关文章:

RecyclerView.Adapter 内的 Android Kotlin ImageView 未按预期更新

Android:具有分页 3 流的 ViewModel 正在泄漏

java - 单击 ListView 项后,图像不会显示在另一个 Activity 中

mysql - mysql 的 GROUP BY 或 DISTINCT 遇到困难

java - 这段代码中的 java 关键字 "this"是多余的吗?

mysql - 找不到“./mysql/user.MYD”(错误代码 : 2 - No such file or directory)

php - 修复尝试从数据库检索数据时 php 中的显示格式

html - iPhone Mail 在 html 电子邮件中调整图像/div 的大小

email - 胡言乱语的垃圾邮件 - 这是什么意思?

email - S22 imap 从 office365 获取邮件