J brother --------- interview Summary of Beijing Android recruitment companies 2, --------- android

Source: Internet
Author: User

J brother --------- interview Summary of Beijing Android recruitment companies 2, --------- android


I followed the previous article to write down the http://blog.csdn.net/u011733020/article/details/45998861, thank you very much in the previous article to me pointed out the problem of the brothers.


Interview company: wudaokou interview time: May 27 AM. interview process: I feel that the company is still very dynamic. after entering the application form, the personnel will talk to me about the reason for leaving the company from home (how can I answer this question when I look for a job, it is best to look for some objective factors, not to mention that the company was not good in the past ...) Then I went to the interview with android technology. The interview lasted about 40 minutes. The practice has summarized six or seven questions. This is a relatively high technical level. I have not encountered any questions during development. This interview is boring... But failure is the father of success. Not discouraged

Interviewer 01: parse json. {
"11: 00": "0 ",
"12: 00": "0 ",
"13:00": "0 ",
"14: 00": "0 ",
"15: 00": "0 ",
"16: 00": "0 ",
"17: 00": "0 ",
"18:00": "0 ",
"19: 00": "0 ",
"20:00": "0 ",
"21:00": "0 ",
"22:00": "0"
}
This problem was not encountered during development at ordinary times, and I was also lazy. I didn't see any parsing methods. I just said at the time that parsing the json source code is similar to parsing xml and traversing every level, saved to the map set. I know there should be a way to get it, but I didn't think of using iterator.
J brother replied: I didn't answer the above method at the time. I have read the json source code and saved it to a HashMap <key, value> collection.
In fact, the parsing is very simple, that is, converting it into a JsonObject and getting the iterator, traversing the set will get the value. The code is simple.
Try {obj = new JSONObject (json); Iterator iterator = obj. keys (); while (iterator. hasNext () {Object next = iterator. next (); // get key obj. get (iterator. next (). toString (); // get value} catch (JSONException e) {// TODO Auto-generated catch blocke. printStackTrace ();}
Don't care about it at ordinary times. Get rid of the chain at key moments !!!
Interviewer 01: How can Listview be implemented if there are multiple types of items.


J's answer: the probability of being asked is still quite high. I have never encountered such a requirement or understood it before, so I did not answer very well. Here I came back to search for the information and found that google developers have made corresponding support for this situation, so listview itself supports multiple types of items. When using listview to adapt data to listview, we usually use the adapter and four methods getCount getItem getItemId getView. Therefore, when we use multiple types of items, we need to describe two methods: getItemViewType getViewTypeCount. The two methods mean
GetViewTypeCount:

Returns the number of types of Views that will be createdgetView. Each type represents a set of views that can be converted ingetView. If the adapter always returns the same type of View for all items, this method shoshould return 1.

This method will only be called when the adapter is set onAdapterView.

Overrides:GetViewTypeCount () in BaseAdapter
Returns:
The number of types of Views that will be created by this adapter
This means to return the number of types of items generated during getview. If all the items in our listview have only one type, we do not need to rewrite this method, this method is called when setAdapter is provided to listview.
It can be found in baseAdapter that the default value is 1.
 public int getViewTypeCount() {        return 1;    }

Another method is getItemViewType.

Get the type of View that will be createdgetViewFor the specified item.

Specified:GetItemViewType (...) inAdapter
Parameters:
PositionThe position of the item within the adapter's data set whose view type we want.
Returns:
An integer representing the type of View. Two views shocould share the same type if one can be converted to the other in getView. Note: Integers must be in the range 0 getViewTypeCount-1. IGNORE_ITEM_VIEW_TYPECan also be returned
This method returns the type of the item to be created by getview.
The return value range is 0 ~~~~ To type-1.


This is the two key methods. If we want to implement multiple types, we need to implement these two methods.

This is the result.
The only difference between code implementation and documentary item is that the current type is added to the above two methods and the getview method. Some code in the Adapter below
@Overridepublic View getView(int position, View convertView, ViewGroup parent) {int type = list.get(position).type;int itemViewType = getItemViewType(position);System.out.println("type===itemViewType"+(itemViewType==type));if(getItemViewType(position)==0){convertView =inflater.inflate(R.layout.item01_layout, parent, false);return convertView;         }else if(getItemViewType(position)==1){convertView =inflater.inflate(R.layout.item02_layout, parent, false);return convertView;}else{convertView =inflater.inflate(R.layout.item03_layout, parent, false);return convertView;}}@Overridepublic int getItemViewType(int position) {System.out.println("getItemViewType-------------------------------"+list.get(position).type);return list.get(position).type;}@Overridepublic int getViewTypeCount() {return maxType;}

The reuse of convertview has not been taken into account here. However, if there are many convertview entries, we cannot simply use them. to reuse them, we need to determine the type separately, and convertview to achieve reuse. If the type is frequently used, write a lot of judgments in the getview method. If type = 0 inflate a layout01, type = 2 inflate a layout02 .... for example, if there are ten getview methods, we need to judge the type for ten times separately and determine the convetview = null. Therefore, if there are more types, the logic of this method is not readable, However, I did not think of any good method. I searched for some information on the Internet. This is a good feeling. Although I want to write many classes in this method, I don't feel like I need to write all the code in a getview. If you have any good ideas, share them together.How to reuse convertview with multiple listview types

Interviewer 01: How can I achieve manual scaling of images.


Q: I was asked to implement it myself because I used the open-source PhotoView in my project. At that time, I did not read the source code. I only knew the similar touchevent and the two-point touch time. It was about image drag and drop. The key to implementation was the touch time monitoring, the mobile phone moves, the finger leaves the listener, records the initial xy, And the xy at the exit, and scales accordingly in onlayout ondraw. for photoview analysis, I found some information. Here is an analysis. If you are interested, you can take a look at it. My personal experience is not bad. Address. Interviewer 01: ImageLoader source code analysis


J brother answer: development, more or less can be exposed to asynchronous loading pictures, we know that universalImageLoader (github address https://github.com/nostra13/Android-Universal-Image-Loader) Loading pictures can effectively prevent the picture caused by oom. Because it is open-source and well-encapsulated, it is used directly in general projects. The usage of imageloader is not described here. The general idea is to use cache, resources are reasonably saved to ensure efficiency. Generally, the first loading is from the network, and then you can determine whether to save the image locally. By the way, you can save the image in the memory. The principle is clearly expressed in this figure.
Generally
ImageLoader. getInstance (). displayImage (picurl, imageview); // input the image url and imageview object.



This ViewAware object contains a weakReference, yes. The image is cached by this weak reference in the memory.

Implements a weak reference, which is the middle of the three types of references. Once the garbage collector decides that an objectobjIs weakly-reachable, the following happens:

  • A setrefOf references is determined.refContains the following elements:
    • All weak references pointingobj.
    • All weak references pointing to objects from whichobjIs either strongly or softly reachable.
  • All references inrefAre atomically cleared.
  • All objects formerly being referencedrefBecome eligible for finalization.
  • At some future point, all references inrefWill be enqueued with their corresponding reference queues, if any.
Weak references are useful for mappings that shocould have their entries removed automatically once they are not referenced any more (from outside). The difference between SoftReferenceAnd WeakReferenceIs the point of time at which the demo-is made to clear and enqueue the reference:
  • ASoftReferenceShocould be cleared and enqueuedAs late as possible, That is, in case the VM is in danger of running out of memory.
  • AWeakReferenceMay be cleared and enqueued as soon as is known to be weakly-referenced.
The preceding is a weakreference annotation.
WeakReference implements a weak reference, which is one of three references (StrongReference, WeakReference, and SoftReference. Once the Garbage Collector determines that an object is weak (the object can be obtained in five ways: stronugly reachable, softly reachable, weakly reachable, phantomly reachable, unreachable), the following situations occur:
Calculate a group of referenced ref. ref includes the following elements:
All weak references pointing to obj
All weak references pointing to objects. objects is a soft or strong object.
All references in ref are automatically deleted.
Become eligible for finalization)
In the future, all references in the ref will be placed in the appropriate reference queue.
Weak references to those mappings, the entities in these mappings will be automatically deleted once they are not referenced. The difference between weak references and soft references is that the time points for clearing and queuing are different:
A weak reference should be cleared and added to the queue as late as possible, because it is dangerous if the memory is insufficient.
A weak referenced object is a weak object that is referenced and is cleared and queued.
When the JVM memory is insufficient, GC preferentially recycles the WeakReference object. For more information about weakreference, see http://wiseideal.iteye.com/blog/1469295.
Public void displayImage (String uri, ImageAware imageAware, DisplayImageOptions options, ImageLoadingListener, ImageLoadingProgressListener progressListener) {checkConfiguration (); if (imageAware = null) {throw new listener (listener );} if (listener = null) {listener = defaultListener;} if (options = null) {options = configuration. defaultDisplayImageOptions;} if (TextUtils. isEmpty (uri) {// <span style = "color: # ff0000;"> determines whether the input address is blank </span> engine. cancelDisplayTaskFor (imageAware); listener. onLoadingStarted (uri, imageAware. getWrappedView (); if (options. shouldShowImageForEmptyUri () {// <span style = "color: # ff6666;"> whether the default image is set </span> imageAware. setImageDrawable (options. getImageForEmptyUri (configuration. resources);} else {imageAware. setImageDrawable (null);} listene R. onLoadingComplete (uri, imageAware. getWrappedView (), null); // <span style = "color: # ff0000;"> callback after loading </span> return;} ImageSize targetSize = ImageSizeUtils. defineTargetSizeForView (imageAware, configuration. getMaxImageSize (); String memoryCacheKey = MemoryCacheUtils. generateKey (uri, targetSize); engine. prepareDisplayTaskFor (imageAware, memoryCacheKey); listener. onLoadingStarted (uri, imageAware. getWrappedV Iew (); Bitmap bmp = configuration. memoryCache. get (memoryCacheKey); if (bmp! = Null &&! Bmp. isRecycled () {L. d (LOG_LOAD_IMAGE_FROM_MEMORY_CACHE, memoryCacheKey); if (options. shouldPostProcess () {ImageLoadingInfo imageLoadingInfo = new ImageLoadingInfo (uri, imageAware, targetSize, memoryCacheKey, options, listener, progressListener, engine. getLockForUri (uri); ProcessAndDisplayImageTask displayTask = new ProcessAndDisplayImageTask (engine, bmp, imageLoadingInfo, defineHandler (options); if (options. isSyncLoading () {displayTask. run ();} else {engine. submit (displayTask) ;}} else {options. getDisplayer (). display (bmp, imageAware, LoadedFrom. MEMORY_CACHE); listener. onLoadingComplete (uri, imageAware. getWrappedView (), bmp) ;}} else {if (options. shouldShowImageOnLoading () {imageAware. setImageDrawable (options. getImageOnLoading (configuration. resources);} else if (options. isResetViewBeforeLoading () {imageAware. setImageDrawable (null);} ImageLoadingInfo imageLoadingInfo = new ImageLoadingInfo (uri, imageAware, targetSize, memoryCacheKey, options, listener, progressListener, engine. getLockForUri (uri); // Save the information to this object LoadAndDisplayImageTask displayTask = new LoadAndDisplayImageTask (engine, imageLoadingInfo, defineHandler (options); // generate the download task if (options. isSyncLoading () {// download displayTask. run ();} else {engine. submit (displayTask );}}}

There are too many codes, but they are different from each other. In the task Method for downloading images, some thread-safe synchronization will be performed, and the other is to determine whether the local memory has been downloaded before. If yes, you can directly use it, did not download and then try to save it in the disk cache
private boolean downloadImage() throws IOException {InputStream is = getDownloader().getStream(uri, options.getExtraForDownloader());if (is == null) {L.e(ERROR_NO_IMAGE_STREAM, memoryCacheKey);return false;} else {try {return configuration.diskCache.save(uri, is, this);} finally {IoUtils.closeSilently(is);}}}

Interviewer 01: Question about oom loading large images


J Ge replied: for large images, loading them directly to Imageview is prone to OOM exceptions. Therefore, we need to compress the images and compress them based on the mobile phone resolution. First, we need to obtain the mobile phone Resolution:
  WindowManager windowManager= (WindowManager)getSystemService(WINDOW_SERVICE);        Display display= windowManager.getDefaultDisplay();        height = display.getHeight();        width = display.getWidth();
Then calculate the width and height of the image and compress the image in the displayed image according to the proportion.
Public void calImageView () {// Log. I ("file", "ImageWidth:" + ImageWidth); // Log. I ("file", "ImageHeight:" + ImageHeight); BitmapFactory. options options = new BitmapFactory. options (); options. inJustDecodeBounds = true; // bitmap = null String path = ""; // The BitmapFactory address of the corresponding image. decodeFile (path, options); int ImageWidth = options. outWidth; int ImageHeight = options. outHeight; System. out. print ("ImageWidth:" + ImageWidth); System. out. print ("ImageHeight:" + ImageHeight); int scaleX = ImageWidth/width; int scaleY = ImageHeight/height; int scale = 1; if (scaleX> scaleY & scaleY> = 1) {scale = scaleX;} if (scaleY> scaleX & scaleX> = 1) {scale = scaleY;} // parse image options. inJustDecodeBounds = false; options. inSampleSize = scale; Bitmap bitmap = BitmapFactory. decodeFile ("/storage/emulated/a.jpg", options); iv. setImageBitmap (bitmap); // ByteArrayOutputStream baos = null; another compression method // baos = new ByteArrayOutputStream (); // bitmap. compress (Bitmap. compressFormat. JPEG, 30, baos );}


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.