Download a large number of images from the server on Android

Edit 2: Even after bounty, no one can give a complete solution. So I decided it myself. I posted the solution below.

I searched about it on Google and also found various good results. But since I am not an expert in server and backend terms, I would like to ask a question on a separate question. I have a website hosting that helps me launch an institution website.

  • My Android application should have an option such as "Photo Gallery", which displays images from my site (where I upload images to a folder). I think this can be done by managing some JSON files.

  • Let there be a folder \ public_html \ MyApp \ Images, which consists of folders such as "Event1", "Event2", etc. I upload images to these different folders, and my Android application should upload them (perhaps by separately giving users the choice to choose the folder).

Is it possible? If any advanced database system is needed, please give me some links for this. Is there a way to create JSON automatically containing image links?

Edit: Recently, I bought website hosting for backend stuff, and I did not do any server-side scripting or anything else. That is why a detailed answer is required. I don’t know how to manage these images, just upload images and place links in JSON or use some MySQL, SQL or any other terms that I have never used.

+5
source share
11 answers

I found a solution myself. This is fairly easy to understand and implement and requires only JSON knowledge. First, see this image from the directory of my website:

"event1", "event2" are the names of the albums. We can create so many necessary.

" getfolders is very important. Content:

{ "test":[ { "sub":"event1", "content":"https://i1.wp.com/www.downloadinformer.com/wp-content/uploads/2017/03/AMPFB.jpg?w=1366", "param":"1.php" }, { "sub":"event2", "content":"myimageurl", "param":"myphpfilenamewithextension" } ] } 

Here we record the names of the albums, as you can see in the "sub" field. The "content" field contains a link to the album thumbnail, and "param" contains the name of the corresponding PHP file. Do not worry, you do not need to learn PHP. This is a finished script.

1.php

 <?php $indir = array_filter(scandir('event1'), function($item) { return $item[0] !== '.'; }); echo json_encode($indir); ?> 

What does this PHP file do? It lists all the file names present in the specified folder. As you can see, we specified " event1 " as the name of the folder in this PHP file. Thus, it will return all image names in JSON format. Do not forget to specify this PHP file in the "param" field of the "getfolders" file.

Good. So it was a kind of algorithm. If you have any confusion, reread it again. Now I will show the code.

I did two actions (did not prefer fragments). One to show albums, and the second to show the images present in it.

Operation 1 - > Scabs getfolders and retrieves the albums that we specified earlier.

Album name: sub field of the above JSON, Thumbnail album: content specified above JSON, (Hidden from the user) Image name list: param field

So we can show it in Recyclerview with this information. Now we specify the OnClickListener for our elements.

When you click β†’ Start the second action with Intent and transfer the album name, which is essentially the name of the folder on our server. Thus, we gain access to the folder containing the images. Also pass the value of the param field. This gives us the URL "www.mywebsite.com/..../alreadyspecifieddirectory/1.php"

Activity-> 2 Implement GridLayoutManager to show photos to the user. Retrieve previously passed values ​​using getIntent() . First we need to execute this PHP file and parse the contents of the JSON. Here is the code:

  private void loadJSON(){ StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_DATA, new Response.Listener<String>() { @Override public void onResponse(String response) { try { JSONObject jsonObject = new JSONObject(response); for (int i=2; i<jsonObject.length()+2;i++){ String value =jsonObject.getString(String.valueOf(i)); if (value.length()!=0) { ListItem item = new ListItem(value, mParam1+"/"+value, "nothing"); listItems.add(item); } } adapter = new PhotoLibraryAdapter(Photos.this,listItems,photosList,true); photosList.setAdapter(adapter); progressBar.setVisibility(View.GONE); } catch (Exception e) {progressBar.setVisibility(View.GONE);} } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { progressBar.setVisibility(View.GONE); } }); RequestQueue requestQueue = Volley.newRequestQueue(this); requestQueue.add(stringRequest); } 

Please note that we started the cycle from 2 because the PHP file returns the values ​​from index 2, because the value 0 and value 1 are waste values ​​and are called ".". and correspondingly.

Therefore, we get the names of the images that we can pass from the URL: "www.mywebsite.com/.../albumnameretrievedearlier/imagenamegivenbyPHPfile"

and transfer it to the adapter so that we can upload images using the Picasso library.

What is it! If you have any questions, feel free to ask in the comments.

EDIT 1: Here's what it looks like:

0
source

In appearance, you need two new database tables. One for storing your albums and one for storing individual images.

 CREATE TABLE `album` ( `album_id` INT(11) PRIMARY KEY NOT NULL AUTO_INCREMENT, `album_name` VARCHAR(255) NOT NULL, `album_date` DATE NOT NULL); 

album save all album metadata so that it stores Event1 with its details, Event2, etc.

 CREATE TABLE `images` ( `image_id` INT(11) PRIMARY KEY NOT NULL AUTO_INCREMENT, `album_id` INT(11) NOT NULL, `image_date` DATE NOT NULL, `image_path` VARCHAR(255) NOT NULL, FOREIGN KEY (album_id) REFERENCES album(album_id)); 

images save all images with their paths and the albums to which they belong, using album_id as a foreign key

Your requests for all images will be

 SELECT * FROM `images`; 

Images from a specific album will be requested as

 SELECT * FROM `images` WHERE `album_id` = *YOUR_ID*; 

SQL query result can be JSON encoded using

 json_encode($query_result); //PHP code 

EDIT : Sample gallery application on Android Hive

It seems that you save the images as a BLOB directly in the database, therefore this gives you a 64kb limit. It is better if you save the image paths. If this is not possible, base64 will encode the images and save them in a VARCHAR column.

+4
source

You can get the path from all the images from the server to JSON and display the images by going through the path using the Picasso library as -

 Picasso.with(context).load("imagepath").placeholder(R.drawable.placeholder) 

.error (R.drawable.placeholder_error) .into (ImageView);

+2
source

Sorry for my English. You can add the folder name to the database when creating the folder and load the entire folder name in the application, and also save the image name in the database with the folder name table key as a foreign key, and when the user selects the folder name, use this folder name primery key and get all the images with this key and upload it to the application.

+1
source

Sorry for the bad english ...

Are these images saved as a BLOB type in your database or do you keep some kind of link to it?

You can send some kind of HTTP request with the name of the folder, and then create json with image data. I use Volley lib for HTTP requests in my application, it works very easily and well

+1
source

Yes, you really can do it, it is possible, as well as practical, since you have a server. The first thing to do is to make the API using this api, you can create URLs that android can extract from JSON data from objects, it also means that you need to convert the image path to JSON. This great tutorial explains everything about the process and more. Since you download a large number, I suggest you use Picasso to cache images, as well as view recyclers

https://www.simplifiedcoding.net/android-programming-tutorial-to-get-all-images-from-server/

Happy coding!

+1
source

The blob type may be different. On the one hand, it can mean sql blob type . And the most important is the MIME type as here

If you are encoding your API / Backend in Java, it might look like it would pass the image to the client who requested the blob:

 public javax.ws.rs.core.Response exportBlob( String blobName ) throws Exception { Blob imageBlob = resultSet.getBlob(yourBlobColumnIndex); //query the blob from the Database String type = "image/png"; // Set your needed MIME Type StreamingOutput data = createStreamingOutput( imageBlob ); // stream it as a binary return Response.ok( data, type ).build(); } /** * Creates an Outputstream of the Data from the given Blob. * * @param blob the blob that needs to be converted. * @return Outputstream of the Blob Data. * @throws WebApplicationException when the conversion failed. */ private static StreamingOutput createStreamingOutput( final java.sql.Blob blob ) { return output -> { try ( InputStream stream = blob.getBinaryStream() ) { byte[] buff = new byte[4096]; int count; while ( ( count = stream.read( buff ) ) != -1 ) { if ( count > 0 ) { output.write( buff, 0, count ); } } } catch ( SQLException e ) { throw new WebApplicationException( e.getMessage(), e ); } }; } 

Converting it to Base64 is also an option. You have to adapt to what you can use in android in order to convert this binary information back to image again.

An example for Android might be the following:

 //byteArray is what you recieved from the API in this example Bitmap bm = BitmapFactory.decodeByteArray(byteArray, 0 ,byteArray.length); 

EDIT:

Since you stated that you have little knowledge in this type of scenario, I can add some resources.

  • How to save the actual image in a MySQL database here (this is not so different for databases other than syntax)
  • A bit confusing example of processing blob on php here
  • An example of blob processing in Java is here

Often talk about using BLOB to save images. You could make life really very simple by simply adding a base64 representation of the image to the database. This way you will not need to process the dataType BLOB. However, I generally do not like this solution personally and prefer to use BLOB. (I already added an article about blob, so I will not do this anymore)

There are also some links to get into Backend development, but this is the part where your own efforts fall into place. It is a lot to learn, but do not be afraid. Once you finish your base, it will become easier.

Java frameworks

Interesting PHP platforms

PHP Backend Tutorial

Online course

Good luck on the way!

+1
source

You are trying to encode all the images in base64 and then paste into the database and then create api that extract all the images from your database and then synchronize your Android application with this api and save the images as sqlite in the local database. 1. The main profit is that now you can upload your gallery imges offline also

+1
source

This solution does not need a database.

You need two API endpoints in PHP

Image upload / api / upload

 <?php $target_dir = "uploads/"; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); // Check if image file is a actual image or fake image if(isset($_POST["submit"])) { $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if($check !== false) { echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } } // Check if file already exists if (file_exists($target_file)) { echo "Sorry, file already exists."; $uploadOk = 0; } // Check file size if ($_FILES["fileToUpload"]["size"] > 500000) { echo "Sorry, your file is too large."; $uploadOk = 0; } // Allow certain file formats if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded."; } else { echo "Sorry, there was an error uploading your file."; } } ?> 
  1. Image List

First list all the directories in the download directory:

 $array = glob("uploads/*", GLOB_ONLYDIR); echo json_encode($array); 
  1. If you want to create a specific folder, you can do this by sending the folder name and adding the request URL and a list of all files.

    $ array = glob ("uploads /".$_ REQUEST ['dir']." / * "); echo json_encode ($ array);

EDIT

 // provides the current working directory echo getcwd() ."\r\n"; // then navigate to path // glob(getcwd() . DIRECTORY_OF_IMAGES)); // GLOB_BRACE tells to find all extensions in the brace $array = glob(getcwd() . "/web/bundles/img/*.{jpg,gif,png}", GLOB_BRACE); 

Read this article http://php.net/manual/en/function.glob.php

+1
source

See, If you have a hosting account for hosting, you will get the opportunity to create your own database without even writing a single line of mysql code. For the server side, you need to learn Php. In addition, it is never recommended to store images in a database. Store them in your repository on your hosting site and their links (URL) in the database. This will speed up the selection of images.

For the android side, just use the Picasso library, which saves you time and space for downloading images from the server.

You are all ready to go. :) Comment for requests.

+1
source

I advise you to consider these two options for maintaining and storing files:

0
source

Source: https://habr.com/ru/post/1269140/


All Articles