Android obtains the picture file in the database through API
- 2021-11-24 03:02:07
- OfStack
Overview
Today, I reviewed how Android can get the pictures in our database and convert them to bitmap for display.
Development environment and technology
Use Visual Studio 2019
Android Studio 3.5
API is developed using ASP. NET WEB API
Database operation only Entity Framework
Use the local database as the data source
If you are a programmer who needs to develop software and API, you can look at 1. If you are not, you can choose to skip $\ color {# 6995C2} {API development} $.
API development
Here, I use API for the convenience of development. But according to international practice, let's first look at the source code of API.
Personally, I prefer json, so we convert all ports to JSON. The code is as follows:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API Configuration and Services
// Web API Route
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
}
}
We need to add a code sentence to our WebApiCinfig class so that we can turn all the port return data into JSON format data.
Then let's look at how to return our picture data:
// GET: api/Pictures
public object GetPictures()
{
var showData = db.Pictures.ToList();
List<Tuple<int,string>> list = new List<Tuple<int, string>>();
foreach (var item in showData)
{
list.Add(new Tuple<int, string>(item.Id,Convert.ToBase64String(item.Img)));
}
return list;
}
Here we use the Base64 approach, first converting our byte array to a string and adding it to a tuple. And return.
In this way, our basic part of API is completed.
How does Android manipulate pictures
First we show access to our network resources.
Want to see 1 code:
/**
* ClassName- @MainActivity-@ Initially change the picture at the bottom of the main page
**/
private void initPictureData() {
new Thread(new Runnable() {
@Override
public void run() {
// Pass http Network access, access to our network data. Will Http Adj. GET Method is encapsulated
String httpData = Global.httpGet("Pictures", "");
// Will JSON Parse and add to the List Medium
List<pictureEntity> list = pictureData_JsonHelper.getJsonData(httpData);
Log.d("main_pictureData", String.valueOf(list.size()));
final List<Bitmap> bitmapsList = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
// In the loop, the String Convert to a picture. Our transformation method is encapsulated here
bitmapsList.add(Global.stringToBitmap(list.get(i).getPicString()));
}
Log.d("BitmapsData", String.valueOf(bitmapsList.size()));
// Below is ViewPager Gets or sets the operation of the.
final List<View> viewsList = new ArrayList<>();
for (int i = 0; i < bitmapsList.size(); i++) {
View view = View.inflate(MainActivity.this, R.layout.viewpage_item, null);
ImageView imageView = view.findViewById(R.id.itemImageView);
imageView.setImageBitmap(bitmapsList.get(i));
viewsList.add(view);
}
runOnUiThread(new Runnable() {
@Override
public void run() {
ViewPager viewPager = findViewById(R.id.viewPager);
viewPager.setAdapter(new viewPager_Adapter(viewsList));
}
});
}
}).start();
}
In this way, all our operations are completed. Then let's take a look at the method we use to encapsulate ourselves here.
The method of Http will not be looked at here. I'm sure everyone will.
public static Bitmap stringToBitmap(String pictureString) {
// Use Base64 Will String Convert to Bitmap Type
byte[] bytes = Base64.decode(pictureString, Base64.NO_WRAP);
// Use BitmapFactory Converts a byte array to a Bitmap
// Here, we need to check the returned data of the database base64 Do the number slightly 1 Next processing. Otherwise, the image may not display normally.
for (int i = 0; i < bytes.length; ++i) {
if (bytes[i] < 0) {
bytes[i] += 256;
}
}
// Generate a picture and return it.
return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
}
In this way, our whole process has been completed.
Additional knowledge: android obtains network data (ultra-simple, direct call)
I will not talk too much nonsense, or directly on the code!
String getNetData(String connectURL){
String result = ""; // Used to get the returned String ;
// Send post Request
HttpPost httpRequest = new HttpPost(connectURL);
//Post To run a transfer variable, you must use the NameValuePair[] Array storage
try {
// Issue HTTP Request
Log.d(" Request a connection ", " Sending a request ");
List params = new ArrayList();
params.add(new BasicNameValuePair("start", "123321"));//post Request (required, data customization)
//params.add(new BasicNameValuePair("end", end+""));// You can add multiple Post Request code, php Get the key value pair in
httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
// Acquire HTTP response
HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
// If the status code is 200 Then the request is successful and the returned data is obtained
Log.d(" Connection value ", String.valueOf(httpResponse.getStatusLine().getStatusCode()));
if (httpResponse.getStatusLine().getStatusCode() == 200) {
// Fetch a string
Log.d(" Request a connection ", " Connection succeeded ");
result = new String(EntityUtils.toString(httpResponse.getEntity(),"utf8"));
}
} catch (Exception e) {
mHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(getContext(), " Network error ",Toast.LENGTH_SHORT).show();
}
});
e.printStackTrace();
}
return result;
}
// The next step is to parse the obtained json Data, json The data analysis needs to be customized according to the requirements