Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Native Development

Reply
Developer
jmoukel
Posts: 111
Registered: ‎07-05-2012
My Device: none
My Carrier: MOvistar
Accepted Solution

BB10: Downloaded Images Don't Show Up

Hi guys,

 

I have been downloading images from my app for a couple of months now. And everything has worked just fine, until yesterday. For some reason, the images my app downloads are not showing anymore.

 

This is what my app does when downloading an image:

  1. Downloads the image.
  2. Saves it in the device (in .../Sandboxes/MyAppFolder/data).
  3. Loads it from the device and show it up.

It's not a server problem, because I can download those images from my pc.

 

I moved the downloaded images from the device to my pc to see how they look like, and I cannot even see them. They don't even have the size in disk they should have, so I guess they're incomplete.

 

I even went back to the old code that dowloads and saves the images and that used to work, and the problem persists.

 

Any ideas about how to solve this?

 

Thanks a lot.

Please use plain text.
Developer
simon_hain
Posts: 16,004
Registered: ‎07-29-2008
My Device: Z10 LE
My Carrier: O2 Germany

Re: BB10: Downloaded Images Don't Show Up

difficult to say without knowing your code, my crystal ball is all cloudy :smileysad:
----------------------------------------------------------
feel free to press the like button on the right side to thank the user that helped you.
please mark posts as solved if you found a solution.
@SimonHain on twitter
Please use plain text.
Developer
jmoukel
Posts: 111
Registered: ‎07-05-2012
My Device: none
My Carrier: MOvistar

Re: BB10: Downloaded Images Don't Show Up

Thanks for trying simon_hain. Here's the code (located in my NetworkManager.cpp). Note: in the function called requestFinished(...), in the big IF, the flow goes directly to the "Downloaded Images" part. 

 

// Class constructor:
//   Creates a QNetworkAccessManager object instance and connects a custom slot
//   to its finished signal.
NetworkManager::NetworkManager(QObject *obj) : QObject()
{
	// Creating a network access manager
	mNetworkAccessManager = new QNetworkAccessManager(obj);

	// Connect a custom slot to its finished signal
	bool result = connect(mNetworkAccessManager,
						  SIGNAL(finished(QNetworkReply*)),
						  this, SLOT(requestFinished(QNetworkReply*)));

	// In case there's an error connecting the network manager with the finished signal,
	//  we print it.
	Q_ASSERT(result);
	Q_UNUSED(result);
}

// Initiates a request to the given url in the "url" input parameter and indicates
//	 which is the object that originated the request.
void NetworkManager::initiateImageRequest(QString url, int imageVersion, QObject* asker, int askerPositionInList, int askerManager, int id = -1)
{
	QString imgName = getImageNameFromURL(url);

	// Checking the image was saved already on the device or not
	if(thisImageIsSavedAlready(imgName, askerManager, imageVersion))
	{
		QDateTime* createdDate = getImageCreatedDate(imgName, askerManager, imageVersion);
		QDateTime  currentDate = QDateTime::currentDateTime();
	}
	else
	{
		// Create and send the network request
		QNetworkRequest request = QNetworkRequest();
		request.setUrl(QUrl(url));
		request.setOriginatingObject(asker);

		QNetworkReply* reply = mNetworkAccessManager->get(request);
		reply->setProperty("askerPositionInList", askerPositionInList);
		reply->setProperty("id", id);
	}
}

// Handles any request finished signal coming from any request.
void NetworkManager::requestFinished(QNetworkReply* reply)
{
    // Check the network reply for errors
    if (reply->error() == QNetworkReply::NoError)
    {
    	// Getting the request that was posted for this reply.
    	QNetworkRequest req = reply->request();

    	// Decision Making base on request
    	if(!GlobalData::DESTAQUES_DA_SEMANA_URL->compare((QString) (req.url()).toString()))
    	{
    		saveXml("destaquesDaSemana.xml", reply, GlobalData::DESTAQUE_MANAGER, 0);
    	}
    	else if(!GlobalData::FILMES_IN_THEATERS_URL->compare((QString) (req.url()).toString()))
    	{
    		saveXml("filmesInTheaters.xml", reply, GlobalData::FILMES_MANAGER, 0);
    	}
    	else if(!GlobalData::UPCOMING_FILMES_URL->compare((QString) (req.url()).toString()))
		{
			saveXml("upcomingFilmes.xml", reply, GlobalData::FILMES_MANAGER, 1);
		}
    	else if(req.url().toString().contains(GlobalData::DETAILED_FILMES_URL))
		{
    		QString* movieCode = getMovieCode(req.url().toString());
    		movieCode->append(".xml");

			saveXml(*movieCode, reply, GlobalData::DETAILED_FILMES_MANAGER, 0);
		}
    	else if(req.url().toString().contains(GlobalData::CINEMAS_URL))
		{
			saveXml("cinemas.xml", reply, GlobalData::CINEMAS_MANAGER, 0);
		}
    	// Downloaded Images
    	else if(req.url().toString().endsWith("jpg"))
    	{
        	reply->setProperty("type", -1);

    		// Figuring out where the request came from
    		if(dynamic_cast<Destaque*> (req.originatingObject()))
    			// Destaque Image Request
    			reply->setProperty("type", DESTAQUE_IMAGE_REQUEST);
    		else if(dynamic_cast<Filme*> (req.originatingObject()))
				// Filme Image Request
				reply->setProperty("type", FILMES_IMAGE_REQUEST);

    		// Saving received image in device
    		saveImage(reply);
    	}

    	// Indicating that donwloading was successful
    	fprintf(stderr,
				"Successful Download: %s\n",
				(req.url()).toString().toLocal8Bit().data());
    }
    else
    {
    	QNetworkRequest req = reply->request();
        qDebug() << "\n Problem with the network";
        qDebug() << "\n" << reply->errorString();
        fprintf(stderr,
        		"PROBLEM with the network while downloading this: %s\n",
        		((QString) req.url().toString()).toLocal8Bit().data());

		// Emitting connectionProblem signal when the error is not because of
        //   a Unknown Protocol or a Content tha Was Not Found
		if(reply->error() != QNetworkReply::ProtocolUnknownError &&
		   reply->error() != QNetworkReply::ContentNotFoundError)
			emitConnectionProblemsSignal();
    }
}

// This saves the image contained in the input "reply". It saves it in a different
//	 folder depending on the type of the request made to get the image.
bool NetworkManager::saveImage(QNetworkReply* reply)
{
	QString filePathWithName = "data/img/";
	QString imageName;
	bool canSaveImage;
	bool canSaveInImgFolder;
	bool successfullySaved = false;

	// Creating the image folder (if no created yet)
	canSaveInImgFolder = createFolder("data/img/");
	canSaveImage = canSaveInImgFolder;

	// Getting the (future) image name
	imageName = getImageNameFromURL(reply->url().toString());

	// Deciding where to save the image
	if(reply->property("type") == DESTAQUE_IMAGE_REQUEST)
	{
		// Destaques Images
		bool canSaveInDestaquesFolder = createFolder("data/img/destaques");
		canSaveImage = canSaveInDestaquesFolder;
		filePathWithName += "destaques/" + imageName;
	}
	else if(reply->property("type") == FILMES_IMAGE_REQUEST)
	{
		// Destaques Images
		bool canSaveInDestaquesFolder = createFolder("data/img/filmes");
		canSaveImage = canSaveInDestaquesFolder;
		filePathWithName += "filmes/" + reply->property("id").toString() + ".jpg";
	}

	// Saving the image on the device
	if(canSaveImage)
		successfullySaved = openAndSaveFile(filePathWithName, reply);

	// If the image was succesfully saved, we pass its local address to the originating object.
	if(successfullySaved)
	{
		QNetworkRequest req = reply->request();
		QObject* origObj = req.originatingObject();

		if(dynamic_cast<DataManager*> (origObj))
		{
			((DataManager*)origObj)->setLocalImage(filePathWithName, reply->property("askerPositionInList").toInt());
		}
	}
	else
	{
		fprintf(stderr, "PROBLEM Failed to save Image: %s\n", filePathWithName.toLocal8Bit().data());
	}

	return successfullySaved;
}

// This opens/creates a file which path+name is the value of the string "filePathWithName".
//   Then it fills this file with the response coming from the "reply" input parameter. Finally
//	 it closes the file.
bool NetworkManager::openAndSaveFile(QString filePathWithName, QNetworkReply* reply)
{
	bool r = true;
	QFile *mFile = new QFile(filePathWithName);
	QNetworkRequest req = reply->request();

	// Open the file and print an error if the file cannot be opened
	if (!mFile->open(QIODevice::ReadWrite))
	{
		r = false;
		qDebug() << "\n Failed to open file";
		fprintf(stderr,
				"PROBLEM Failed to open file: %s\n",
				filePathWithName.toLocal8Bit().data());
		return r;
	}

	// Write to the file using the reply data and close the file
	mFile->write(reply->readAll());
	mFile->flush();
	mFile->close();

	return r;
}

 

Please use plain text.
Developer
Zmey
Posts: 1,511
Registered: ‎12-18-2012
My Device: PlayBook, Z10, DAC

Re: BB10: Downloaded Images Don't Show Up

If it was working before I can only assume that the client application was blocked on server (for example by User-Agent or by IP).

If the files aren't zero size try examining their contents. Do they have "PNG" at the start etc? If they're smaller than expected maybe they contain HTML data with error description.

Andrey Fidrya, @zmeyc on twitter
Please use plain text.
Developer
jmoukel
Posts: 111
Registered: ‎07-05-2012
My Device: none
My Carrier: MOvistar

Re: BB10: Downloaded Images Don't Show Up

Thanks for your reply Zmey! Your wise suggestions (again) helped me to solve the problem.

 

I opened the images with a text editor. In there it says: "The document has moved to this address: ...". So, the problem was that they moved the images to another location.

 

It works now. 

 

Thanks a lot Zmey.

 

Please use plain text.
Developer
turdidae
Posts: 15
Registered: ‎06-02-2012
My Device: BlackBerry 10 Dev Alpha
My Carrier: Play Poland

Re: BB10: Downloaded Images Don't Show Up

Hi

 

This is my code to save images, check if it will work for you(this is part of requestFinished slot):

 

	QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());

	QFile file(getImgPath(reply->url().path()));

	file.open(QIODevice::WriteOnly);

	QDataStream out(&file);
	QByteArray null;
	null = reply->readAll();
	out.writeRawData(null,null.size());


	file.close();

 

 

Krzysiek

Please use plain text.
Developer
jmoukel
Posts: 111
Registered: ‎07-05-2012
My Device: none
My Carrier: MOvistar

Re: BB10: Downloaded Images Don't Show Up

Hi turdidae,

I already solved the problem. It was a server problem.

Thanks for your help.
Please use plain text.
Contributor
raysonyeung
Posts: 21
Registered: ‎02-07-2013
My Device: Z10
My Carrier: Company

Re: BB10: Downloaded Images Don't Show Up

Are you required to handle that much context verification?

 

Actually you can simply request the image file url and get the reply.

1. For the request, why do you need set the attributes of the reply after send out the request?

2. Are you using https as the request protocol?

 

For the reply, you just need to check

1. reply->error() == NoError

2. reply->attribute( QNetworkRequest::HttpStatusCodeAttribute ) == 200

3. use Q_ASSET() to make sure the reply is valid

 

Then you can directly save the image into the data folder.

Btw, please make sure you can create the "data/img" folder as I saw you want to save the image in it.

Also, please make sure you have the permission to access the internet and save the file in the application folder.

 

The last one I think is, you should be direclty use the sandbox directory. As your app is installed as a release version. It no longer appear in the sandbox directory. I suggest you use QDir::currentPath() + "/data/img"

Please use plain text.
Developer
jmoukel
Posts: 111
Registered: ‎07-05-2012
My Device: none
My Carrier: MOvistar

Re: BB10: Downloaded Images Don't Show Up

Hi raysonyeung,

I already solved the problem. It was a server problem.

Thanks for your help.
Please use plain text.
Developer
simon_hain
Posts: 16,004
Registered: ‎07-29-2008
My Device: Z10 LE
My Carrier: O2 Germany

Re: BB10: Downloaded Images Don't Show Up

you can handle a redirect by checking an attribute on the reply:
reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
----------------------------------------------------------
feel free to press the like button on the right side to thank the user that helped you.
please mark posts as solved if you found a solution.
@SimonHain on twitter
Please use plain text.