Blackberry 10 contact pic to byte array - c++

I am working on migration application. I have to transfer blackberry 10 contacts to android.
I am getting problem in transferring contact pic. I am getting the uri of the pic, create file and try to read the bytes.
ContactPhoto contactPhoto = contact.primaryPhoto();
QString photo = contactPhoto.originalPhoto();
//photo = file:///accounts/1000/pimdata/_startup_data/contacts/2/img-tnqpx0.jpg
if (!photo.isEmpty()){
QFile file(photo);
if (file.open(QIODevice::ReadOnly)) {
qDebug() <<"file.readAll() IF" <<file.readAll() <<endl;
}else{
qDebug() <<"file.readAll() ELSE" <<endl;
}
vcardString += "PHOTO;JPEG;ENCODING=BASE64:" + (file.readAll() + "\n");
}
But else part of the below snip of code is executing
if (file.open(QIODevice::ReadOnly)) {
qDebug() <<"file.readAll() IF" <<file.readAll() <<endl;
}else{
qDebug() <<"file.readAll() ELSE" <<endl;
}
How I read bytes from below uri
file:///accounts/1000/pimdata/_startup_data/contacts/2/img-tnqpx0.jpg

As I suspected, removing file:// from the url works.
Here's the code I used to test :
bb::pim::contacts::ContactPhoto contactPhoto = contact.primaryPhoto();
QString photo = contactPhoto.originalPhoto();
if (!photo.isEmpty()){
QFile file(photo.remove("file://"));
if (file.open(QIODevice::ReadOnly)) {
qDebug() <<"file.readAll() IF" <<file.readAll() <<endl;
}else{
qDebug() <<"file.readAll() ELSE" <<endl;
}
}
Please note that you need to leave one / in front of the url, so your picture url shared in OP would look like :
/accounts/1000/pimdata/_startup_data/contacts/2/img-tnqpx0.jpg
Also, if your goal is to create a VCard vcf file, you don't need to manually create the VCard file content, don't even need to read the bytes of the photo file, the contactToVCard function will do that for you.
QByteArray vcard = contactService.contactToVCard(contact.id(), bb::pim::contacts::VCardPhotoEncoding::BASE64, -1);
qDebug() << "vcard:" << vcard;

Related

How to parse QJsonArray?

In my QT application, there is a need to store the value of structures of the same type in a JSON dictionary.
I know about the [JSON Save Game Example article][1], I tried to figure it out for a long time, I didn’t come to anything, I also surfed the forums with the same result.
The main problem is this:
I have a JSON document:
{
"devices": [
{
"name": "some name",
"price": 2000,
"year": 2022
}
]
}
I use the following code to read the information:
//open my JSON
QFile file("path/to/myfile.json");
file.open(QIODevice::ReadOnly);
QByteArray jsonData = file.readAll();
//finding array
QJsonDocument document = QJsonDocument::fromJson(jsonData);
QJsonObject object = document.object();
QJsonArray temp_array = object["devices"].toArray();
//reading
qDebug() << temp_array[0].toObject().value("name").toString(); //returned ""
qDebug() << temp_array.size(); //returned 0
qDebug() << temp_array.empty(); //returned true
qDebug() << object.keys(); //returned QList("devices")
As I previously pointed out in a comment, trying to read the values of the "name" key returned me an empty string, the size and empty functions indicate that I'm looking at an empty array. However, the keys function indicates that my json object still contains the "devices" key.
What could be the problem?
[1]: https://doc.qt.io/qt-5/qtcore-serialization-savegame-example.html
Your code seems to be doing correct things in correct order but something goes wrong. Either your file is not found or it doesn't get opened, or it is found but parsing fails.
You would find out if you did some checks instead of just assuming things work.
Below you will find example of robust programming. The example code checks
if file exists
if file opening fails
if file parsing to JSON fails
if file is actually JSON object (and not e.g. JSON array)
if size of the JSON array named "devices" is bigger than zero
if object in JSON array contains "name" property
if "name" property type is string
(I didn't try to compile the code, but I'm sure you get the idea and figure out what went wrong. If you made this kind of code to a function you would either return or throw exception when things go wrong...)
QFile file("path/to/myfile.json");
if (!file.exists()) {
qWarning() << "File doesn't exist";
}
if (!file.open(QIODevice::ReadOnly)) {
qWarning() << "Couldn't open file";
}
QByteArray jsonData = file.readAll();
QJsonParseError parseError;
QJsonDocument document(QJsonDocument::fromJson(jsonData, &parseError));
if (parseError.error != QJsonParseError::NoError) {
qWarning() << "Invalid json file. Parsing failed:" << parseError.error << parseError.errorString();
}
if (!document.isObject()) {
qWarning() << "File is not JSON object!";
}
const QJsonObject &object = document.object();
QJsonArray temp_array = object["devices"].toArray();
if (temp_array.size() < 1) {
qWarning() << "JSON array object count:" << temp_array.size();
}
QJsonObject jsonObj = temp_array[0].toObject();
if (jsonObj.contains("name")) {
if (jsonObj["name"].isString()) {
qDebug() << jsonObj["name"].toString();
} else {
qWarning() << "name" << "is not string!";
}
} else {
qWarning() << "Object in JSON array did not have" << "name";
}

How do you delete a sub-string in a string(qstring) in Qt

Is there a function in Qt similar to delete() and copy() in Delphi.
I am reading data from a device connected to my computer via USB and storing it as a QString. Every line that is read is not the same (or is cut short, even while using readyRead). I created a buffer sting to add these "half sting" (eg. string = "This" instead of "This is a string#") to and now I want to copy the string up until the '#' and then delete the string so if new "half stings" get added I can do the same with them. The code below is what I tried
void MainWindow::readSerial()
{
QByteArray serialData = port->readAll();
serialBuffer += serialData;
QByteArray serialString = serialBuffer.
qDebug() << serialString;
ui -> textEdit ->append(serialString);
//serialBuffer.replace(serialString,"");
}
The above code only returns an empty string.
void MainWindow::readSerial()
{
QByteArray serialData = port->readAll();
serialBuffer += serialData;
QString serialString = serialBuffer.mid(serialBuffer.indexOf("$"),serialBuffer.indexOf("\r\n"));
qDebug()<< "index of \r\n" << serialBuffer.indexOf("\r\n");
qDebug() << "SerialString" <<serialString;
ui -> textEdit ->append(serialString);
qDebug() << "SerialBuffer: " << serialBuffer;
serialBuffer.replace(serialString + "\r\n","");
}
the above code works. Thanks all.
regards

Qt: empty content of opened QFile for a .txt file from the project resources

I tried this in my project in mainwindow.cpp:
QString dir = ":/nodesDir/nodesDir/";
QFile baseFile(dir + "allNodeNames.txt");
qDebug() << baseFile.exists(); // true
qDebug() << baseFile.readAll(); // ""
but it is wrong, the content of the file is
plusOperator
Why does it say, that there would be nothing written in the file? Or What did I miss in my code?`
Thanks for answers!
In order to read the file you need to open it for it we use open () and we indicate the way we want it to open. We must also bear in mind that the files stored in the resources are read only, so they can not be modified.
QString dir = ":/nodesDir/nodesDir/";
QFile baseFile(dir + "allNodeNames.txt");
qDebug() << baseFile.exists(); // true
qDebug()<< baseFile.open(QFile::ReadOnly);
qDebug() << baseFile.readAll(); // ""
Output:
true
true
"plusOperator"

reading a file into Qt

I wrote a Program in Qt 5.2.1 that writes some data into a file and now I want to read it and display it. ( in a text edit or any other widget)
Here is my code ( the part I thought is relevant ) -
But i don't get the desires result ... could you look into it and tell me what i an doing wrong
void MainWindow::on_Search_clicked()
{
QString name ;
name = ui->Search_name->text();
QFile readfile("data.txt");
if(!readfile.open(QIODevice::ReadOnly))
{
qDebug() << "error opening file: " << readfile.error();
return;
}
QTextStream instream(&readfile);
QString line = instream.readLine();
// ui->text is a QPlainTextEdit*
ui->text->insertPlainText(line);
readfile.close();
return;
}
You should use
void QPlainTextEdit::appendPlainText ( const QString & text ) [slot]
method, link.

on uploading file to google-drive by using c++/qt filename of newfile is always untitled

I found a similar question: Google Drive API insert new file with Untitled name
but code is not attached there.
My code:
void googled::newuploadSettings(QNetworkReply *reply){
QByteArray data = reply->readAll();
qDebug() << data;
QString x = getValue(data,"access_token");
qDebug() << x;
x = "Bearer " + x;
qDebug() << x;
QNetworkRequest request;
//QString contentType = "text/plain";
QUrl url("https://www.googleapis.com/upload/drive/v2/files?uploadType=media");
//url.addQueryItem("originalFilename","sp");
request.setUrl(url);
request.setRawHeader("Content-Length","200000000");
request.setRawHeader("Content-Type","image/jpeg");
request.setRawHeader("title","sp");
//request.setRawHeader("X-Upload-Content-Length","20000000");
//request.setRawHeader("X-Upload-Content-Type","image/jpeg");
request.setRawHeader("Authorization",x.toLatin1());
//request.setRawHeader("Host","https://www.googleapis.com");
qDebug() << getValue(data,"access_token").toUtf8();
//request.setRawHeader()
QFile file("/home/saurabh/Pictures/005.jpg");
//file.setFileName("kashmir");
file.open(QIODevice::ReadOnly);
QByteArray arr = file.readAll();
file.close();
qDebug() << "file";
QString str = "a";
str.append(arr);
qDebug() << str;
m_netM = new QNetworkAccessManager;
QObject::connect(m_netM, SIGNAL(finished(QNetworkReply *)),
this, SLOT(uploadfinishedSlot(QNetworkReply *)));
m_netM->post(request,arr);
}
I know I have to set title field for giving name to file but am not able to figure out how I would do it in qt
title option should go to request body according to Files.insert() documentation
For instance, if header has
Content-Type: application/json
request body would be
{
"title": "sp"
}
To set title of the file to be "sp". Please look for qt documentation to find how to set request body.