Android 小知識

###一、創建Dialog時 Dialog dialog = new Dialog(getApplicationContext()); 傳入getApplicationContext()上下文在運行期間爲什麼報錯?

Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application

在這裏我們需要先明白3個Context概念:
1、Activity.getApplicationContext():

Return the context of the single, global Application object of the current process.  This generally should only be used if you need a Context whose lifecycle is separate from the current context, that is tied to the lifetime of the process rather than the current component.

2、Activity.this/View.getContext():

Returns the context the view is running in, through which it can access the current theme, resources, etc.

3、Activity.getBaseContext():

return the base context as set by the constructor or setBaseContext

Activity.this與getApplicationContext()的生命週期不同, 前者的生命週期依賴於所在的Activity,後者的生命週期依賴於整個應用。所以new Dialog(getApplicationContext())時會發生錯誤,Dialog依賴的是一個View, 而View對應一個Activity,若傳入getApplicationContext(),其生命週期是整個應用,當退出當前Activity的時候,就會報Unable to add window – token null is not for an application的錯誤,應該傳入當前Activity的Context。

###二、二分排序
最近面試時碰到了一個二分排序,由於完全不知道二分排序的思想就GG了;面試結束後就趕緊學習了下二分排序。

####1、算法思想:二分法插入排序是在插入第i個元素時,對前面的0~i-1元素進行折半,先跟他們中間的那個元素比,如果小,則對前半再進行折半,否則對後半進行折半,直到left>right,然後再把第i個元素前1位與目標位置之間的所有元素後移,再把第i個元素放在目標位置上。

####2、分析:
二分排序的時間複雜度是O(n*log2n),空間複雜度O(1),是穩定排序。

####3、實現

####以數組的方式實現:

int[] data = { 34, 32, 12, 61, 23, 36, 40, -15, 21, 11 };
		int i, j;
		int low, high, mid;
		int temp;
		for (i = 1; i < data.length; i++) {
			temp = data[i];
			low = 0;
			high = i - 1;
			while (low <= high) {
				mid = (low + high) / 2;
				if (data[mid] > temp)
					high = mid - 1;
				else
					low = mid + 1;

			}
			for (j = i - 1; j > high; j--)
				data[j + 1] = data[j];
			data[high + 1] = temp;
		}
		for (i = 0; i < 10; i++) {
			System.out.printf("%d\t", data[i]);
		}

####以集合的方式實現:

public class BinarySortDemo {

	public static void main(String[] args) {
		List<Integer> datas = new ArrayList<Integer>();
		for(int i=0; i<10; i++){
			datas.add(new Random().nextInt(100));
		}
		for(Integer data : datas){
			System.out.print(" "+data);
		}
		System.out.println();
		sort(datas);
	}

	public static void sort(List<Integer> datas){
		int i;
		int low, high, mid;
		Integer temp;
		for (i = 1; i < datas.size(); i++) {
			temp = datas.get(i);
			low = 0;
			high = i - 1;
			while (low <= high) {
				mid = (low + high) / 2;
				if (datas.get(mid) > temp)
					high = mid - 1;
				else
					low = mid + 1;

			}
			datas.remove(temp);
			datas.add(high + 1, temp);
		}
		for(Integer data : datas){
			System.out.print(" "+data);
		}
	}
}
發佈了38 篇原創文章 · 獲贊 45 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章