android开发知识小汇2

Android开发之ListView 适配器(Adapter)优化
1
2
3
4
5
6
7
8
Adapter的作用就是ListView界面与数据之间的桥梁,当列表里的每一项显示到页面时,都会调用Adapter的getView方法返回一个View。想过没有? 在我们的列表有1000000项时会是什么样的?是不是会占用极大的系统资源?

下面是三种优化级别
level1是最基础的使用
level2是稍微优化
level3是优化过后的代码

原文地址:http://blog.csdn.net/zuolongsnail/article/details/7197979
未命名.jpg 外部引用原始文档
1
2
3
4
5
6
7
public View getView(int position, View convertView, ViewGroup parent) {
	View item = mInflater.inflate(R.layout.list_item_icon_text, null);
	((TextView) item.findViewById(R.id.text)).setText(DATA[position]);
	((ImageView) item.findViewById(R.id.icon))
			.setImageBitmap((position & 1) == 1 ? mIcon1 : mIcon2);
	return item;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public View getView(int position, View convertView, ViewGroup parent) {
	if (convertView == null) {
		convertView = mInflater.inflate(R.layout.item, null);
	}
	((TextView) convertView.findViewById(R.id.text))
			.setText(DATA[position]);
	((ImageView) convertView.findViewById(R.id.icon))
			.setImageBitmap((position & 1) == 1 ? mIcon1 : mIcon2);
	return convertView;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
public View getView(int position, View convertView, ViewGroup parent) {
	ViewHolder holder;
	if (convertView == null) {
		convertView = mInflater.inflate(R.layout.list_item_icon_text, null);
		holder = new ViewHolder();
		holder.text = (TextView) convertView.findViewById(R.id.text);
		holder.icon = (ImageView) convertView.findViewById(R.id.icon);
		convertView.setTag(holder);
	} else {
		holder = (ViewHolder) convertView.getTag();
	}
	holder.text.setText(DATA[position]);
	holder.icon.setImageBitmap((position & 1) == 1 ? mIcon1 : mIcon2);
	return convertView;
}

static class ViewHolder {
	TextView text;
	ImageView icon;
}




Android HttpClient上传文件(亲测,成功)
1
 Android HttpClient上传文件  的一个封装方法。里面有一小段代码是处理获取JSON格式数据 

System.out.println("executing request " + httppost.getRequestLine()); 返回协议和返回码 
正确的话是 http 1.1 200 
System.out.println(EntityUtils.toString(resEntity,"utf-8")); 
获取处理后的页面内容

android并不自带MultipartEntity吧? 
对的。把httpmime-4.1.1.jar 这个放进lib中就可以使用 MultipartEntity了 
下载地址:http://pan.baidu.com/share/link?shareid=90009&uk=4012369003

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
public String post(String pathToOurFile,String urlServer) throws ClientProtocolException, IOException, JSONException {
   HttpClient httpclient = new DefaultHttpClient();
   //设置通信协议版本
   httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
   
   //File path= Environment.getExternalStorageDirectory(); //取得SD卡的路径

//String pathToOurFile = path.getPath()+File.separator+"ak.txt"; //uploadfile
//String urlServer = "http://192.168.1.88/test/upload.php"; 

   HttpPost httppost = new HttpPost(urlServer);
   File file = new File(pathToOurFile);

   MultipartEntity mpEntity = new MultipartEntity(); //文件传输
   ContentBody cbFile = new FileBody(file);
   mpEntity.addPart("userfile", cbFile); // <input type="file" name="userfile" />  对应的


   httppost.setEntity(mpEntity);
   System.out.println("executing request " + httppost.getRequestLine());
   
   HttpResponse response = httpclient.execute(httppost);
   HttpEntity resEntity = response.getEntity();

   System.out.println(response.getStatusLine());//通信Ok
   String json="";
   String path="";
   if (resEntity != null) {
     //System.out.println(EntityUtils.toString(resEntity,"utf-8"));
     json=EntityUtils.toString(resEntity,"utf-8");
     JSONObject p=null;
     try{
   	  p=new JSONObject(json);
   	  path=(String) p.get("path");
     }catch(Exception e){
   	  e.printStackTrace();
     }
   }
   if (resEntity != null) {
     resEntity.consumeContent();
   }

   httpclient.getConnectionManager().shutdown();
   return path;
 }
android自定义弹出层
DialogShow.java 外部引用原始文档
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package com.asfman;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class DialogShow extends Activity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button btn = (Button) findViewById(R.id.button1);
        btn.setOnClickListener(new Button.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                new Tip(DialogShow.this).show();
            }

        });
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.asfman;

import android.app.Dialog;
import android.content.Context;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;

public class Tip {

    private ImageView image;
    private Dialog mDialog;

    public Tip(Context context) {
        mDialog = new Dialog(context, R.style.dialog);
        Window window = mDialog.getWindow();
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = -30;
        wl.y = 20;
        window.setAttributes(wl);
        window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
        //window.setGravity(Gravity.CENTER);
        window.setLayout(ViewGroup.LayoutParams.FILL_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        mDialog.setContentView(R.layout.tip);
        mDialog.setFeatureDrawableAlpha(Window.FEATURE_OPTIONS_PANEL, 0);
        image = (ImageView) mDialog.findViewById(R.id.image);
        image.setOnClickListener(new ImageView.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                mDialog.dismiss();
            }
        });
    }

    public void show() {
        mDialog.show();
    }

}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="dialog" parent="@android:style/Theme.Dialog">
<!--         <item name="android:windowFrame">@null</item> -->
<!--         <item name="android:windowIsFloating">true</item> -->
<!--         <item name="android:windowIsTranslucent">false</item> -->
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowBackground">@null</item>
<!--         <item name="android:backgroundDimEnabled">false</item> -->
    </style>
</resources>
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="300dp" android:layout_height="190dp"
    android:orientation="vertical" android:background="@drawable/blueinfowindow">
    <LinearLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:orientation="horizontal"
        android:id="@+id/upContent" android:layout_marginTop="30dp"
        android:layout_marginLeft="30dp">
        <TextView android:id="@+id/description" android:layout_width="220dp"
            android:layout_height="wrap_content"
            android:text="1.this is the test text!\n
            1.this is the test text!\n1.this is the test text!\n1.this is the test text!\n" android:textColor="#000000" />
        <ImageView android:id="@+id/image" android:background="@drawable/icon" android:layout_width="wrap_content" android:layout_height="wrap_content"/>    
    </LinearLayout>
</LinearLayout>

获得手机浏览器的历史记录
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
private String history() {
    String string = null;
    ContentResolver contentResolver = getContentResolver();
 
    Cursor cursor = contentResolver.query(
            Uri.parse("content://browser/bookmarks"),
            new String[] { "url" }, null, null, null);
 
    while (cursor != null && cursor.moveToNext()) {
        string = cursor.getString(cursor.getColumnIndex("url"));
        Log.d("debug", string == null ? "null" : string);
    }
    return string;
}



Android 打开网页搜索关键词
SearchManager.java 外部引用原始文档
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
String searchStr = "eoe";
/* 取得网页搜寻的intent */
Intent search = new Intent(Intent.ACTION_WEB_SEARCH);
search.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
search.putExtra(SearchManager.QUERY, searchStr);
 
final Bundle appData = getIntent().getBundleExtra(
        SearchManager.APP_DATA);
if (appData != null) {
    search.putExtra(SearchManager.APP_DATA, appData);
}
startActivity(search);


使用SAX解析XML文件
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
SAX(Simple API for XML),是指一种接口,或者一个软件包。

DOM:文档驱动。DOM在解析文件之前把整个文档装入内存,处理大型文件时其性能很差,是由于DOM的树结构所造成的,此结构占用的内存较多。

SAX:事件驱动型的XML解析方式。顺序读取XML文件,不需要一次全部装载整个文件。当遇到像文件开头,文档结束,或者标签开头与标签结束时,会触发一个事件,用户通过在其回调事件中写入处理代码来处理XML文件,适合对XML的顺序访问,且是只读的。

由于移动设备的内存资源有限,SAX的顺序读取方式更适合移动开发。

SAX解析XML步骤
①创建XML解析处理器。
②创建SAX解析器。
③将XML解析处理器分配给解析器。
④对文档进行解析,将每个事件发送给处理器。

原文地址:http://blog.csdn.net/zuolongsnail/article/details/6453468
MainActivity.java 外部引用原始文档
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
 * MainActivity
 * 
 * @author zuolongsnail
 * 
 */
public class MainActivity extends Activity {
	private Button parseBtn;
	private ListView listView;
	private ArrayAdapter<Person> adapter;
	private ArrayList<Person> persons;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		parseBtn = (Button) findViewById(R.id.parse);
		listView = (ListView) findViewById(R.id.list);
		parseBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				persons = MainActivity.this.readXml();
				adapter = new ArrayAdapter<Person>(MainActivity.this,
						android.R.layout.simple_expandable_list_item_1, persons);
				listView.setAdapter(adapter);
			}
		});
	}

	private ArrayList<Person> readXml() {
		InputStream file = this.getClass().getClassLoader()
				.getResourceAsStream("persons.xml");
		// ①创建XML解析处理器
		SAXXmlContentHandler contentHandler = new SAXXmlContentHandler();
		try {
			// 创建一个SAXParserFactory
			SAXParserFactory factory = SAXParserFactory.newInstance();
			// ②创建SAX解析器
			SAXParser parser = factory.newSAXParser();
			// ③将XML解析处理器分配给解析器
			// ④对文档进行解析,将每个事件发送给处理器。
			parser.parse(file, contentHandler);
			file.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
		return contentHandler.getBooks();
	}
}
SAXXmlContentHandler.java 外部引用原始文档
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/**
 * 解析XML处理器
 * @author zuolongsnail
 *
 */
public class SAXXmlContentHandler extends DefaultHandler {

	private ArrayList<Person> persons;
	private Person person;
	private String tagName;

	public ArrayList<Person> getBooks() {
		return persons;
	}

	@Override
	public void startDocument() throws SAXException {
		this.persons = new ArrayList<Person>();
		Log.e("SAXXmlContentHandler", "开始解析XML文件");
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		Log.e("SAXXmlContentHandler", "读取标签");
		this.tagName = localName;
		if(this.tagName.equals("person")){
			person = new Person();
			person.setId(Integer.parseInt(attributes.getValue(0)));
		}
	}
	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		Log.e("SAXXmlContentHandler", "根据tagName获取标签的内容");
		if (this.tagName != null) {
			String data = new String(ch, start, length);
			if (this.tagName.equals("name")) {
				this.person.setName(data);
			} else if (this.tagName.equals("age")) {
				this.person.setAge(Integer.parseInt(data));
			}
		}
	}
	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		if(localName.equals("person")){
			this.persons.add(person);
		}
		this.tagName = null;
	}
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<?xml version="1.0" encoding="UTF-8"?>
<persons>
	<person id="1">
		<name>张三</name>
		<age>24</age>
	</person>
	<person id="2">
		<name>李四</name>
		<age>25</age>
	</person>
	<person id="3">
		<name>王五</name>
		<age>26</age>
	</person>
</persons>
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
 * Person实体类
 * @author zuolongsnail
 *
 */
public class Person {
	private int id;
	private String name;
	private int age;
	public Person() {

	}
	public Person(int id, String name, int age) {
		this.id = id;
		this.name = name;
		this.age = age;
	}
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "姓名:" + this.name + ",年龄:" + this.age;
	}
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical" android:layout_width="fill_parent"
	android:layout_height="fill_parent">
	<TextView android:layout_width="fill_parent"
		android:layout_height="wrap_content" android:text="@string/hello" />
	<Button android:id="@+id/parse" android:layout_width="wrap_content"
		android:layout_height="wrap_content" android:text="SAX解析XML" />
	<ListView android:id="@+id/list" android:layout_width="fill_parent"
		android:layout_height="fill_parent">
	</ListView>
</LinearLayout>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值