android中通过jsoup解析html

Posted 五月 6th, 2012 by arm8 and filed in 安卓开发

在andoroid怎样解析html文件,webview是一个非常好的选择,如果只想解析出其中的部分数据,而且没有服务器端代码的情况下使用jsoup解析是一个非常好的选择因为其有强大的选择器。例如解析如下


该网站的通过查看页面原代码如下:

…….
<table width=”100%” border=”0″ cellpadding=”5″ cellspacing=”0″>
                      <td>
                        <h2>Online Staff Directory</h2>
                      </td>
                    </tr>
                    <tr>
                      <td colspan=”2″><img src=”http://www.tp.edu.sg/spacer.gif” width=”1″ height=”5″></td>
                    </tr>
                    <tr>
                      <td>
<form action=”findstf.asp?div=All&from=” method=”post”>
  Staff Search: <input type=”text” size=”21″ maxlength=”30″ name=”name”> <input
  type=”submit” value=”Submit”>
</form>
<hr NOSHADE size=”1″ width=”99%”><p>

    <P><a href=”mdeptlist.asp?dept=BUS&from=”><< Another Division</a></P>

<p align=”center”><font color=”#990000″>BUS Admin/General Office                                              </font></p>
<table border=”0″ cellpadding =”0″ width=”99%” cellspacing=”0″>
<tr>
          <th align=”left” width=”10%”>Dept/Sch</p></th>
          <th align=”left” width=”5%”>&nbsp;</p></th>
          <th align=”left” width=”42%”>Name/Designation</p></th>
          <th align=”left” width=”8%”>Telephone</p></th>
</tr>
<tr bgcolor=#ECECEC>
    <td width=”10%”  valign=”top” align=”left”>&nbsp;</td>
    <td width=”5%”  valign=”top” align=”left”>&nbsp;</td>
    <td width=”42%” valign=”top” align=”left”>
    
<a href=”mailto:senghuat@tp.edu.sg”>Heng Seng Huat, Edward                            </a>

    </td>
    <TD width=”8%” valign=”top” align=”left”>67805056</td>
    </TR>    
    <tr bgcolor=#ECECEC>
    <td width=”10%”  valign=”top” style=”padding-left:8px;” align=”left”>BUS/A     </td>
    <td width=”5%”  valign=”top” align=”left”>&nbsp;</td>
    <td width=”42%” valign=”top” align=”left”>
Section Head</td>
    <TD width=”8%” valign=”top” align=”left”>&nbsp;</td>
    </TR>    
<tr bgcolor=#ECECEC>
    <td width=”10%”  valign=”top” align=”left”>&nbsp;</td>
    <td width=”5%”  valign=”top” align=”left”>&nbsp;</td>
    <td width=”42%” valign=”top” align=”left”>&nbsp;</td>
    <TD width=”8%” valign=”top” align=”left”>&nbsp;</td>
    </TR>    

…….

在android中只想获取其中的名字和电话,那么解析方法如下:
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements

……

    Document doc = Jsoup.connect(“http://www-app.tp.edu.sg/scripts/staffdir/Emplist.asp?step=1&div=BUS/AF&from=”).get();
            Elements links = doc.select(“a[href]“);
            Elements tds = doc.select(“td[width=8%]“);

……

因为名字是有超链接,故可以通过jsoup的选择器a[hred]获取所有的超链接内容,而后进行筛选即可获取名字;电话也是如此因为在源代码中得知电话的td标签width=8%这样的属性标识电话,可以通过选择器进行获取。

Jsoup提供了强大的选择器,如

但是这样做的话给客户端太大的压力,最好的方式还是在服务器端将数据渲染成xml或者json来做,这样客户端解析起来比较快捷,效率高

JAVA htmlparser 使用实例

Posted 五月 5th, 2012 by arm8 and filed in 安卓开发
初学java,
开始开发一个 Android的小应用,因为用到html解析技术,java中的几种xml解析技术尝试了一下之后发现用来解析html会有大大小小的错误,进而考虑采用专业的htmlparser来解析。因为初次接触android开发,在通过下面的例子成功测试了htmlparser的基本用法
—————————
BufferedReader bis = new BufferedReader(new InputStreamReader(new 
 
FileInputStream( f), “GBK”) );
                String szContent=”";
                String szTemp;
               
                while ( (szTemp = bis.readLine()) != null) {
                    szContent+=szTemp+”\n”;
                }
                bis.close();
        //String szContent = openFile(f);
                Log.e(“szxxxxxx”, szContent);
        Parser parser = new Parser( szContent );
 
 try {
Parser parser = new Parser( szContent );
        Log.e(“ttttttt”,”sdfsd”);
        // 提取html中的第一个table标签
        NodeFilter filter = new TagNameFilter(“table”);
        org.htmlparser.util.NodeList nodes = 
 
parser.extractAllNodesThatMatch(filter);
        org.htmlparser.tags.TableTag textnode = 
 
(org.htmlparser.tags.TableTag) ((org.htmlparser.util.NodeList) 
 
nodes)
        .elementAt(0);
        Log.e(“getText”, textnode.getText());
        }catch (Exception e) {
        Log.e(“eeeeee”, e.toString());
        }
——————————
之后,我把它部署到了android程序中,可是死活编译不了,错误从出。
后来查阅资料得知htmlparser不宜用在android开发中,不得已放弃而选择了jsoup。。。

Java入门:String和StringBuffer之概览

Posted 五月 5th, 2012 by arm8 and filed in 安卓开发

 

String和StringBuffer之概览
  非可变对象一旦创建之后就不能再被改变,可变对象则可以在创建之后被改变。String对象是非可变对象,StringBuffer对象则是可变对象。为获得更佳的性能你需要根据实际情况小心谨慎地选择到底使用这两者中的某一个。下面的话题会作详细的阐述。(注意:这个章节假设读者已经具备Java的String和StringBuffer的相关基础知识。)
 
创建字符串的较佳途径
你可以按照以下方式创建字符串对象:
1. String s1 = ”hello”; 
    String s2 = ”hello”; 
2. String s3 = new String(“hello”);
    String s4 = new String(“hello”);
 
上面哪种方式会带来更好的性能呢?下面的代码片断用来测量二者之间的区别。

StringTest1.java
package com.performance.string;
/** This class shows the time taken for creation of
 *  String literals and String objects.
 */
public class StringTest1 {
public static void main(String[] args){
    // create String literals
    long startTime = System.currentTimeMillis();
    for(int i=0;i<50000;i++){
    String s1 = ”hello”;
    String s2 = ”hello”;
    }
    long endTime = System.currentTimeMillis();
    System.out.println(“Time taken for creation of String literals : ”
                  + (endTime - startTime) + ” milli seconds” );
    // create String objects using ’new’ keyword       
    long startTime1 = System.currentTimeMillis();
    for(int i=0;i<50000;i++){
    String s3 = new String(“hello”);
    String s4 = new String(“hello”);
    }
    long endTime1 = System.currentTimeMillis();
    System.out.println(“Time taken for creation of String objects : ”
                  + (endTime1 - startTime1)+” milli seconds”);
    }
}
这段代码的输出:
Time taken for creation of String literals : 0 milli seconds
Time taken for creation of String objects : 170 milli seconds
 
JVM是怎样处理字符串的呢?
  Java虚拟机会维护一个内部的滞留字符串对象的列表(唯一字符串的池)来避免在堆内存中产生重复的String对象。当JVM从class文件里加载字符串字面量并执行的时候,它会先检查一下当前的字符串是否已经存在于滞留字符串列表,如果已经存在,那就不会再创建一个新的String对象而是将引用指向已经存在的String对象,JVM会在内部为字符串字面量作这种检查,但并不会为通过new关键字创建的String对象作这种检查。当然你可以明确地使用String.intern()方法强制JVM为通过 new关键字创建的String对象作这样的检查。这样可以强制JVM检查内部列表而使用已有的String对象。
  所以结论是,JVM会内在地为字符串字面量维护一些唯一的String对象,程序员不需要为字符串字面量而发愁,但是可能会被一些通过 new关键字创建的String对象而困扰,不过他们可以使用intern()方法来避免在堆内存上创建重复的String对象来改善Java的运行性能。下一小节会向大家展示更多的信息。
 
下图展示了未使用intern()方法来创建字符串的情况。
 
string_creating_without_intern() method
  你可以自己使用==操作符和String.equals()方法来编码测试上面提到的区别。==操作符会返回true如果一些引用指向一个相同的对象但不会判断String对象的内容是否相同;String.equals()方法会返回true如果被操作的String对象的内容相同。对于上面的代码会有s1==s2,因为s1和s2两个引用指向同一个对象,对于上面的代码,s3.equals(s4)会返回true因为两个对象的内容都一样为”hello”。你可以从上图看出这种机制。在这里有三个独立的包含了相同的内容(”hello”)的对象,实际上我们不需要这么三个独立的对象―― 因为要运行它们的话既浪费时间又浪费内存。
 
  那么怎样才能确保String对象不会重复呢?下一个话题会涵盖对于内建String机制的兴趣。
 
滞留字符串的优化作用
  同一个字符串对象被重复地创建是不必要的,String.intern ()方法可以避免这种情况。下图说明了String.intern()方法是如何工作的,String.intern()方法检查字符串对象的存在性,如果需要的字符串对象已经存在,那么它会将引用指向已经存在的字符串对象而不是重新创建一个。下图描绘了使用了intern()方法的字符串字面量和字符串对象的创建情况。
 
string_creating_with_intern() method
下面的例程帮助大家了解String.intern()方法的重要性。
StringTest2.java
 
package com.performance.string;
// This class shows the use of intern() method to improve performance
public class StringTest2 {
public static void main(String[] args){
    // create String references like s1,s2,s3…so on..
    String variables[] = new String[50000];
    for( int i=0;i        variables[i] = ”s”+i;
    }
    // create String literals
    long startTime0 = System.currentTimeMillis();
    for(int i=0;i        variables[i] = ”hello”;
    }
    long endTime0 = System.currentTimeMillis();
    System.out.println(“Time taken for creation of String literals : ”
                         + (endTime0 - startTime0) + ” milli seconds” );
    // create String objects using ’new’ keyword       
    long startTime1 = System.currentTimeMillis();
    for(int i=0;i        variables[i] = new String(“hello”);
    }
    long endTime1 = System.currentTimeMillis();
    System.out.println(“Time taken for creation of String objects with ’new’ key word : ”
                        + (endTime1 - startTime1)+” milli seconds”);
    // intern String objects with intern() method   
    long startTime2 = System.currentTimeMillis();
    for(int i=0;i        variables[i] = new String(“hello”);
        variables[i] = variables[i].intern();
    }
    long endTime2 = System.currentTimeMillis();
    System.out.println(“Time taken for creation of String objects with intern(): ”
                        + (endTime2 - startTime2)+” milli seconds”);
    }
}
这是上面那段代码的输出结果:
Time taken for creation of String literals : 0 milli seconds
Time taken for creation of String objects with ’new’ key word : 160 milli seconds
Time taken for creation of String objects with intern(): 60 milli seconds
 
连接字符串时候的优化技巧
  你可以使用+操作符或者String.concat()或者StringBuffer.append()等办法来连接多个字符串,那一种办法具有最佳的性能呢?
  如何作出选择取决于两种情景,第一种情景是需要连接的字符串是在编译期决定的还是在运行期决定的,第二种情景是你使用的是 StringBuffer还是String。通常程序员会认为StringBuffer.append()方法会优于+操作符或 String.concat()方法,但是在一些特定的情况下这个假想是不成立的。
 
1) 第一种情景:编译期决定相对于运行期决定
请看下面的StringTest3.java代码和输出结果。

package com.performance.string;
/** This class shows the time taken by string concatenation at compile time and run time.*/
public class StringTest3 {
  public static void main(String[] args){
    //Test the String Concatination
    long startTime = System.currentTimeMillis();
    for(int i=0;i<5000;i++){
    String result = ”This is”+ ”testing the”+ ”difference”+ ”between”+
            ”String”+ ”and”+ ”StringBuffer”;
    }
    long endTime = System.currentTimeMillis();
    System.out.println(“Time taken for string concatenation using + operator : ”
         + (endTime - startTime)+ ” milli seconds”);
    //Test the StringBuffer Concatination
    long startTime1 = System.currentTimeMillis();
    for(int i=0;i<5000;i++){
    StringBuffer result = new StringBuffer();
         result.append(“This is”);
        result.append(“testing the”);
        result.append(“difference”);
        result.append(“between”);
       result.append(“String”);
       result.append(“and”);
       result.append(“StringBuffer”);
     }
    long endTime1 = System.currentTimeMillis();
    System.out.println(“Time taken for String concatenation using StringBuffer : ”
           + (endTime1 - startTime1)+ ” milli seconds”);
  }
}
这是上面的代码的输出结果:
Time taken for String concatenation using + operator : 0 milli seconds
Time taken for String concatenation using StringBuffer : 50 milli seconds
很有趣地,+操作符居然比StringBuffer.append()方法要快,为什么呢?
 
  这里编译器的优化起了关键作用,编译器像下面举例的那样简单地在编译期连接多个字符串。它使用编译期决定取代运行期决定,在你使用new关键字来创建String对象的时候也是如此。
 
编译前:
String result = ”This is”+”testing the”+”difference”+”between”+”String”+”and”+”StringBuffer”;
编译后:
String result = ”This is testing the difference between String and StringBuffer”;

这里String对象在编译期就决定了而StringBuffer对象是在运行期决定的。运行期决定需要额外的开销当字符串的值无法预先知道的时候,编译期决定作用于字符串的值可以预先知道的时候,下面是一个例子。
 
编译前:
public String getString(String str1,String str2) {
    return str1+str2;
}
编译后:
return new StringBuffer().append(str1).append(str2).toString();
运行期决定需要更多的时间来运行。
 
2) 第二种情景:使用StringBuffer取代String
看看下面的代码你会发现与情景一相反的结果――连接多个字符串的时候StringBuffer要比String快。
StringTest4.java
 
package com.performance.string;
/** This class shows the time taken by string concatenation
using + operator and StringBuffer  */
public class StringTest4 {
 public static void main(String[] args){
    //Test the String Concatenation using + operator
    long startTime = System.currentTimeMillis();
    String result = ”hello”;
    for(int i=0;i<1500;i++){
        result += ”hello”;
    }
    long endTime = System.currentTimeMillis();
    System.out.println(“Time taken for string concatenation using + operator : ”
                  + (endTime - startTime)+ ” milli seconds”);
    //Test the String Concatenation using StringBuffer
    long startTime1 = System.currentTimeMillis();
    StringBuffer result1 = new StringBuffer(“hello”);
    for(int i=0;i<1500;i++){
        result1.append(“hello”);
    }
    long endTime1 = System.currentTimeMillis();
    System.out.println(“Time taken for string concatenation using StringBuffer :  ”
                  + (endTime1 - startTime1)+ ” milli seconds”);
    }
}
这是上面的代码的输出结果:
Time taken for string concatenation using + operator : 280 milli seconds
Time taken for String concatenation using StringBuffer : 0 milli seconds
看得出StringBuffer.append()方法要比+操作符要快得多,为什么呢?

  原因是两者都是在运行期决定字符串对象,但是+操作符使用不同于StringBuffer.append()的规则通过String和StringBuffer来完成字符串连接操作。(译注:什么样的规则呢?)
 
借助StringBuffer的初始化过程的优化技巧
  你可以通过StringBuffer的构造函数来设定它的初始化容量,这样可以明显地提升性能。这里提到的构造函数是StringBuffer(int length),length参数表示当前的StringBuffer能保持的字符数量。你也可以使用ensureCapacity(int minimumcapacity)方法在StringBuffer对象创建之后设置它的容量。首先我们看看StringBuffer的缺省行为,然后再找出一条更好的提升性能的途径。
 
StringBuffer的缺省行为:
  StringBuffer在内部维护一个字符数组,当你使用缺省的构造函数来创建StringBuffer对象的时候,因为没有设置初始化字符长度,StringBuffer的容量被初始化为16个字符,也就是说缺省容量就是16个字符。当StringBuffer达到最大容量的时候,它会将自身容量增加到当前的2倍再加2,也就是(2*旧值+2)。
  如果你使用缺省值,初始化之后接着往里面追加字符,在你追加到第16个字符的时候它会将容量增加到34(2*16+2),当追加到34个字符的时候就会将容量增加到70(2*34+2)。无论何事只要StringBuffer到达它的最大容量它就不得不创建一个新的字符数组然后重新将旧字符和新字符都拷贝一遍――这也太昂贵了点。所以总是给StringBuffer设置一个合理的初始化容量值是错不了的,这样会带来立竿见影的性能增益。
  我利用两个StringBuffer重新测试了上面的StringTest4.java代码,一个未使用初始化容量值而另一个使用了。这次我追加了50000个’hello’对象没有使用+操作符。区别是我使用StringBuffer(250000)的构造函数来初始化第二个 StringBuffer了。
 
输出结果如下:
Time taken for String concatenation using StringBuffer with out setting size: 280 milli seconds
Time taken for String concatenation using StringBuffer with setting size: 0 milli seconds
StringBuffer初始化过程的调整的作用由此可见一斑。所以,使用一个合适的容量值来初始化StringBuffer永远都是一个最佳的建议。
 
关键点
1. 无论何时只要可能的话使用字符串字面量来常见字符串而不是使用new关键字来创建字符串。
2. 无论何时当你要使用new关键字来创建很多内容重复的字符串的话,请使用String.intern()方法。
3. +操作符会为字符串连接提供最佳的性能――当字符串是在编译期决定的时候。
4. 如果字符串在运行期决定,使用一个合适的初期容量值初始化的StringBuffer会为字符串连接提供最佳的性能。

StringBuffer

Posted 五月 5th, 2012 by arm8 and filed in 安卓开发

StringBuffer定义了下面三个构造函数:

      StringBuffer()                // 默认构造函数,预留了16个字符的空间,该空间不需再分配

      StringBuffer(int size)   //设置指定缓冲区大小

StringBuffer(String str) //设置StringBuffer对象初始化的内容并预留16个字符空间,且不需再分配空间

* intlength()

      调用length()方法可以得到StringBuffer对象的长度,调用capacity()可以得到总的分配容量。两个方法都是返回一个int类型的值。

      * void ensureCapacity(int capacity)

如果想在构造StringBuffer对象后为某些字符预分配空间,可以使用ensureCapacity()方法,设置缓冲区的大小,这在事先已知要在StringBuffer上追加大量小字符串的情况下是有用的。ensureCapcity()方法具有如下的一般形式: void  ensureCapacity(int capacity)

* voidsetLength(int len)

使用setLength()方法可以设置StringBuffer对象的长度,它的一般形式如下:

void  setLength(intlen)   如果len大于StringBuffer对象当前的length()值的话,那么会在StringBuffer对象后面加上空字符;如果比length()小的话,则len后面的字符串会丢失。

      * char charAt(int where)

        void setCharAt(int where, char ch)

  使用charAt()方法可以得到StringBuffer对象中指定位置上的字符,setCharAt()      可以设置指定位置上的字符。它们的一般形式如下:

      char charAt(int where)

      void setCharAt(int where,char ch)      

对于这两种法法,where值必须是非负的,同时不能超过或等于StringBuffer对象的长度。

*getChars(int suorceStart,int sourceEnd,char target[] , inttargetStart)

*append()

 Append()方法将任一其他类型数据的字符串形式连接到调用StringBuffer对象的后面,对所有内置的类型和Object,它都有重载形式。下面是几种形式:

StringBufferappend(String str)

StringBufferappend(int num)

StringBufferappend(Object obj)

 

*insert()

 Insert()方法将一个字符串插入另一个字符串中。下面是它的几种形式:

 StringBuffer insert(int index,Stringstr)

 StringBuffer insert(int index,charch)

 StringBuffer insert(int index,Objectobj)

 

      *reverse()            // StringBuffer reverse()

       StringBuffer strbf=newStringBuffer(“ABCDEFG”);

       strbf.reverse(); 

       System.out.println(strbf); //输出GFEDCBA

      

   * StringBuffer delete(intstartIndex,int endIndex)

       StringBuffer deleteCharAt(int loc)

      删除指定位置的字符串和指定位置的字符。例如删除第一个字符后的所有字符:

       strbf.delete(1,strbf.length());

 

      *replace()   

       它完成在StringBuffer内部用一个字符串代替另一个指定起始位置和结束位置的字符串的功能,注意的是,被代替的字符不包括结束位置上的字符,它的一般形式是,:

       StringBuffer replace(int startIndex, intendIndex,String str)

 

     * substring() 返回StringBuffer的一部分值

        String substring(int startIndex)

        String substring(int startIndex, intendIndex)

android中的activity和startActivity 详细分析

Posted 五月 5th, 2012 by arm8 and filed in 安卓开发

. 概述:Activity作为公共类,继承自ContextThemeWrapper.

Activity专注于用户所要做的事情。几乎所有的Activity都是和用户进行交互的。因此,Activity通过使用setContentView(view)来展示界面元素。尽管Activities通常是全屏显示窗口的,但是你可以指定下面两种方法的一种来进行显示:

浮动窗体:android:theme=”?android:attr/windowIsFloating”

嵌入到其他的Activity中。

2.startActivity(Intent)和startActivityForResult(Intent,int)的区别使用:

startActivity(Intent) 方法可以用来启动一个新的 activity ,这个 activity 将被放置在 activity 栈的栈顶。这个方法只有一个参数 Intent ,这个参数描述了将被执行的 activity 。
      有时候你希望在一个 activity 结束时得到它返回的结果。举个例子,你可能启动一个 activity 来让用户从通讯簿中选择一个人;当它结束的时候将会返回这个所选择的人。为了得到这个返回的信息,你可以使用 startSubActivity(Intent, int) 这个方法来启动新的 activity ,第二个整形参数将会作为这次调用的识别标记。这个 activity 返回的结果你可以通过 onActivityResult(int, int, String, Bundle) 方法来获得,此方法的第一个参数就是之前调用所使用的识别标记。
      当 activity 退出的时候,它可以调用 setResult(int) 来将数据返回给他的父进程。这个方法必须提供一个结果码,这个结果码可以使标准结果 RESULT_CANCELED, RESULT_OK ,也可以是其他任何从 RESULT_FIRST_USER 开始的自定义值。此外,它还可以返回一段字符串(经常是一段数据的 URL 地址),一个包含它所有希望值的 Bundle 。这些信息都会在父 activity 的回调函数 Activity.onActivityResult() 中出现,并连同最初提供的识别标记一起(此处有些拗口,意思其实就是子activity 返回的内容、返回码、识别标记都将作为参数,按照不同的返回情况来调用父activity 的Activity.onActivityResult() 方法,以实现出现各种返回时父activity 做出响应的处理)。

Android SimpleAdapter

Posted 五月 5th, 2012 by arm8 and filed in 安卓开发

Android SimpleAdapter

 这个类是一个大家一看就明白的适用于数据绑定或者说数据渲染的一个类,只是这个类有些复杂,复杂之处在于其参数的设定,以及加载的形式上,官方文档上说是一个简单的Adapter,不过在我们基础入门而言已经算是复杂的了,他的继承结构层次是:

ava.lang.Object 

 ↳android.widget.BaseAdapter  

 ↳android.widget.SimpleAdapter

它的构造函数是:

public SimpleAdapter (Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to)

官方说明了其各个参数含义,我这里根据自己的理解解释下:

第一个context,很明显大家根据英文可以知道是上下文的意思,它官方的意思是:SimpleAdapter所要运行关联到的视图,这个是什么呢?就是你这个SimpleAdapter所在的Activity(一般而言),所以这个参数一般是this

第二个是一个泛型只要是一个List就行,这一般会想到是ArrayList,而他内部存储的则是Map或者继承自Map的对象,比如HashMap,这些语法都是Java的基本语法,不再详述了!这里呢是作为数据源,而且每一个ArraList中的一行就代表着呈现出来的一行,Map的键就是这一行的列名,值也是有列名的。

第三个资源文件,就是说要加载这个两列所需要的视图资源文件,你可以左边一个TextView右边一个TextView,目的在于呈现左右两列的值!

第四个参数是一个数组,主要是将Map对象中的名称映射到列名,一一对应

第五个是将第四个参数的值一一对象的显示(一一对应)在接下来的int形的id数组中,这个id数组就是LayOut的xml文件中命名id形成的唯一的int型标识符

 

这样也就达到了数据的列表呈现!

 

列表(ListView)、表格(GridView),这在手机应用上面肯定是少不了的,怎样实现比较复杂一点的界面呢,先看一下我的效果图。

image image

这样布局的情况是最基本的,也是最常用的,网上关于这样的布局有多种版本的实现方法,但是有很多需要自己实现Adapter,那样子是比较复杂而且没有必要的,因为我们有简约而不简单的SimpleAdapter。

1. ListView

SimpleAdapter的核心代码:

		for (int i = 0; i < 10; i++) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("PIC", R.drawable.pic);
			map.put("TITLE", "Test Title");
			map.put("CONTENT", "Test Content");
			contents.add(map);
		}
		SimpleAdapter adapter = new SimpleAdapter(this,
				(List<Map<String, Object>>) contents, R.layout.listitem,
				new String[] { "PIC", "TITLE", "CONTENT" }, new int[] {
						R.id.listitem_pic, R.id.listitem_title,
						R.id.listitem_content });

		listView.setAdapter(adapter);

 

listitem的Layout:

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="fill_parent" android:layout_height="?android:attr/listPreferredItemHeight">
	<ImageView android:id="@+id/listitem_pic"
		android:layout_width="wrap_content" android:layout_height="fill_parent"
		android:layout_alignParentTop="true" android:layout_alignParentBottom="true"
		android:src="@drawable/pic" android:adjustViewBounds="true"
		android:padding="2dip" />
	<TextView android:id="@+id/listitem_title"
		android:layout_width="wrap_content" android:layout_height="wrap_content"
		android:layout_toRightOf="@+id/listitem_pic"
		android:layout_alignParentRight="true" android:layout_alignParentTop="true"
		android:layout_above="@+id/listitem_content"
		android:layout_alignWithParentIfMissing="true" android:gravity="center_vertical"
		android:text="@+id/listitem_title" android:textSize="22px" />
	<TextView android:id="@+id/listitem_content"
		android:layout_width="fill_parent" android:layout_height="wrap_content"
		android:layout_toRightOf="@+id/listitem_pic"
		android:layout_alignParentBottom="true"
		android:layout_alignParentRight="true" android:singleLine="true"
		android:ellipsize="marquee" android:text="@+id/item_content"
		android:textSize="14px" />
</RelativeLayout>

 

 

2. GridView

SimpleAdapter的核心代码:

		for (int i = 0; i < 10; i++) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("PIC", R.drawable.pic);
			map.put("TITLE", "Test Title");
			contents.add(map);
		}
		SimpleAdapter adapter = new SimpleAdapter(this,
				(List<Map<String, Object>>) contents, R.layout.griditem,
				new String[] { "PIC", "TITLE" }, new int[] { R.id.griditem_pic,
						R.id.griditem_title, });

		gridView.setAdapter(adapter);

griditem的Layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_height="fill_parent" android:layout_width="fill_parent"
	android:orientation="vertical">
	<ImageView android:id="@+id/griditem_pic"
		android:layout_width="wrap_content" android:layout_height="wrap_content"
		android:layout_gravity="center_horizontal">
	</ImageView>
	<TextView android:id="@+id/griditem_title"
		android:layout_width="wrap_content" android:layout_height="wrap_content"
		android:layout_gravity="center_horizontal" android:text="test">
	</TextView>
</LinearLayout>

ANDROID Log图文详解(Log.v,Log.d,Log.i,Log.w,Log.e)

Posted 五月 4th, 2012 by arm8 and filed in 安卓开发

 android.util.Log常用的方法有以下5个:Log.v() Log.d() Log.i() Log.w() 以及 Log.e() 。根据首字母对应VERBOSE,DEBUG,INFO, WARN,ERROR。

  1、Log.v 的调试颜色为黑色的,任何消息都会输出,这里的v代表verbose啰嗦的意思,平时使用就是Log.v(“”,”");

  2、Log.d的输出颜色是蓝色的,仅输出debug调试的意思,但他会输出上层的信息,过滤起来可以通过DDMS的Logcat标签来选择;

  3、Log.i的输出为绿色,一般提示性的消息information,它不会输出Log.v和Log.d的信息,但会显示i、w和e的信息;

  4、Log.w的意思为橙色,可以看作为warning警告,一般需要我们注意优化Android代码,同时选择它后还会输出Log.e的信息;

  5、Log.e为红色,可以想到error错误,这里仅显示红色的错误信息,这些错误就需要我们认真的分析,查看栈的信息了;

  下面是我做的一个简单的LogDemo(Step By Step):

  Step 1:准备工作(打开LogCat视窗).

  启动Eclipse,在Window->Show View会出来一个对话框,当我们点击Ok按钮时,会在控制台窗口出现LogCat视窗.如下图:
  1.jpg

  2.jpg
  Step 2:新建一个Android工程,命名为LogDemo.

  Step 3:设计UI界面,我们在这里就加了一个Button按钮(点击按钮出现Log日志信息).
  Main.xml代码如下:
  <?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/bt”
       android:layout_width=”wrap_content”
       android:layout_height=”wrap_content”
      android:text=”Presse Me Look Log”
    />
    </LinearLayout>

  Step 4:设计主类LogDemo.java,代码如下:
  package com.android.test;
  import android.app.Activity;
  import android.os.Bundle;
  import android.util.Log;
  import android.view.View;
  import android.widget.Button;
  public class LogDemo extends Activity

  {
       private static final String ACTIVITY_TAG=”LogDemo”;
       private Button bt;
                public void onCreate(Bundle savedInstanceState)

      {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.main);
              //通过findViewById找到Button资源
              bt = (Button)findViewById(R.id.bt);
              //增加事件响应
              bt.setOnClickListener(new Button.OnClickListener()

         {
              @Override
             public void onClick(View v)

           {
                Log.v(LogDemo.ACTIVITY_TAG, “This is Verbose.”);
                Log.d(LogDemo.ACTIVITY_TAG, “This is Debug.”);
                Log.i(LogDemo.ACTIVITY_TAG, “This is Information”);
                Log.w(LogDemo.ACTIVITY_TAG, “This is Warnning.”);
                Log.e(LogDemo.ACTIVITY_TAG, “This is Error.”);
             }
              });
        }
     }

  Step 5:运行LogDemo工程,效果如下:
  3.jpg

  当我们点击按钮时,会触发事件,在Logcat视窗下有如下效果:
  4.jpg

linux用mknod怎么创建设备,创建了设备怎么用

Posted 五月 4th, 2012 by arm8 and filed in linux
mknod命令用于创建一个设备文件,即特殊文件
首先要明白什么是设备文件,简单的我们说 操作系统与外部设备(入磁盘驱动器,打印机,modern,终端 等等)都是通过设备文件来进行通信的,在Unix/Linux系统与外部设备通讯之前,这个设备必须首先要有一个设备文件,设备文件均放在/dev目录下
一般情况下在安装系统的时候系统自动创建了很多已检测到的设备的设备文件,但有时候我们也需要自己手动创建,命令行生成设备文件的方式有 insf,mksf,mknod等等
根据mknod命令的使用参数来看【mknod Name { b | c } Major Minor 】,使用mknod之前,至少要明白以下几点:
设备文件类型:分为块设备和字符设备。ls -l /dev 结果显示第一个字段有b*** 和 c****,这里即标识了块设备和字符设备。
    字符设备文件----字符设备文件传送数据给设备的时候,一次传送一个字符,终端,打印机,绘图仪,modern等设备都经过字符设备文件传送数据
    块设备---系统通过块设备文件存取一个设备的时候,先从内存中的buffer中读或写数据,而不是直接传送数据到物理磁盘,这种方式能有效的提高磁盘和CD-ROMS的I/O性能。磁盘和CD-ROMS即可以使用字符设备文件也可使用块设备文件。
主号和次号:
    主号:当在任意目录使用ls -l 时,结果的第5个字段就是主号,设备主号代表了这个设备使用的是哪个设备驱动程序
    次号:次号是一个24位的十六进制数字,定义了设个设备在系统中的物理的位置

就拿我们常用的创建卷组来看;
先来看看mknod 命令,如果该设备文件你想放在一个特定的文件夹下当然就先创建文件夹
mknod 设备文件名[/dev/xyz]  b/c  主号  次号
{  mkdir /dev/vg01
   mknod /dev/vg01/group  c  64  0X010000
}
创建之后,就可以使用你想要创建的设备对于德创建命令了,如我现在的卷组的创建命令:
vgcreate /dev/vg01  /dev/dsk/c*t*d*
一直进行下去
之后的步骤根据不同的设备而不尽相同

/proc/devices 和/dev关系

Posted 五月 4th, 2012 by arm8 and filed in linux

 

 
/proc/devices/下的设备是驱动程序生成的,它可产生一个major供mknod作为参数。 
/dev/下的设备是通过mknod加上去的,用户通过此设备名来访问驱动。
The following script, scull_load, is part of the scull distribution. The user of a driver that is distributed in the form of a module can invoke such a script from the system’s rc.local file or call it manually whenever the module is needed.

#!/bin/sh
module=”scull”
device=”scull”
mode=”664″

# invoke insmod with all arguments we got
# and use a pathname, as newer modutils don’t look in . by default
/sbin/insmod ./$module.ko $* || exit 1

# remove stale nodes
rm -f /dev/${device}[0-3]

major=$(awk “\\$2= =\”$module\” {print \\$1}” /proc/devices)

mknod /dev/${device}0 c $major 0
mknod /dev/${device}1 c $major 1
mknod /dev/${device}2 c $major 2
mknod /dev/${device}3 c $major 3

# give appropriate group/permissions, and change the group.
# Not all distributions have staff, some have “wheel” instead.
group=”staff”
grep -q ‘^staff:’ /etc/group || group=”wheel”

chgrp $group /dev/${device}[0-3]
chmod $mode /dev/${device}[0-3]

 

请问:linux环境下,/dev/目录下的内容与/proc/下文件devices中的内容有什么区别?我在目标板上做实验时发现,当我向板子上加载驱动模块时,devices文件中有变化,而/dev下根本没有变化,/dev/下不也应该是设备接点吗,为什么为模块建立设备接点时,/dev/下却没有变化呢? 
请各位帮帮忙,谢谢!!!

/proc/devices/中的设备是通过insmod加载到内核的,它可产生一个major供mknod作为参数。 
/dev/*.* 是通过mknod加上去的,格式:mknod device1 c/b major minor 如:mknod dr1 c 254 0,用户通过此设备名来访问你的驱动。

 

 

请问:linux环境下,/dev/目录下的内容与/proc/下文件devices中的内容有什么区别?我在目 标板上做实验时发现,当我向板子上加载驱动模块时,devices文件中有变化,而/dev下根本没有变化,/dev/下不也应该是设备接点吗,为什么为 模块建立设备接点时,/dev/下却没有变化呢? 
请各位帮帮忙,谢谢!!!

 

/proc/devices/中的设备是通过insmod加载到内核的,它可产生一个major供mknod作为 参数。 
/dev/*.* 是通过mknod加上去的,格式:mknod device1 c/b major minor 如:mknod dr1 c 254 0,用户通过此设备名来访问你的驱动。

 

 

设备 文件 ,设备编号  #ll  -a /dev  在每一行都可以看到设备文件、设备编号(主、次) 
对于每种硬件设备,系统内核有相应的设备驱动程序负责对它的处理。而在Unix 中,使用设备文件的方式来表示硬件设备,每种设备驱动程序都被抽象 为设备文件的形式,这样就给应用程序一个一致的文件界面,方便应用程序和操作系统之间的通信。 

习惯上,所有的设备文件 都放置在/dev 目录下。 

/proc/devices/中的设备是通过insmod加载到内核的,它可产生一个major供mknod作为 参数 。 
/dev/*.* 是通过mknod加上去的,格式:mknod device1 c/b major minor 如:mknod dr1 c 254 0,用户通过此设备名来访问你的驱动。

mknod – make block or character special files
mknod [OPTION]… NAME TYPE [MAJOR MINOR]
    option 有用的就是 -m 了
    name   自定义
    type   有 b 和 c 还有 p
    主设备号
    次设备号

主 设备号是由/usr/src/linux/include/linux/major.h定义的,如下定义了一个DOC设备: 
#define IGEL_FLASH_MAJOR 62 

假如有一个命令mknod doc b 62 0 : 
其中的doc为定义的名 字,b指块设备,0指的是整个DOC。如果把0换为1,则1指的是DOC的第一个分区。2是第2个,依次类推

 
#################################################################################
 
 
/proc/devices/中的设备是通过insmod加载到内核的,它可产生一个major供mknod作为参数。
/dev/*.* 是通过mknod加上去的,格式:mknod device1 c/b major minor 如:mknod dr1 c 254 0,用户通过此设备名来访问你的驱动。

谷歌遭封杀:终端、应用不许使用谷歌标识

Posted 五月 4th, 2012 by arm8 and filed in 移动资讯

5月3日晚,深圳市国证通管理咨询有限公司的官方网站发布了一则“工信部关于Google使用通知”的通告:

“尊敬的客户: 接到CTA进网实验室通知,当前国家工信部已经对”Google”使用有新通知,2012年5月3日执行移动终端产品出厂不允许有Google字样及相关应用,违者不进行任何行政审批。现在工信部对所有移动终端产品,包括手机,PAD等设备出厂都不允许带有Google标识、应用,包括Google搜索、Google书签和Google浏览器等与有关的字样。为避免后期出现异常,请全部屏蔽后再送检!”

工信部欲封杀Google的消息早有传闻,如果这则工信部关于Google使用通知属实,将会引发国内移动互联网的大地震,甚至有波动全球移动互联网。因为中国的手机网民数量在全球手机网民的占比是很重要的份数。

工信部电信研究院在2012年初发布了移动终端白皮书:截止到2011年第四季度,按出货量计算,Android以51%的的份额居首,苹果iOS以24%的占比位居第二。从国产手机整体来看,Android、iOS和Symbian操作系统占据了上半年移动智能终端新增市场的90%,国内企业只占2%,白皮书中这样写道。

艾媒咨询(iiMedia Research)最新统计结果显示,截止到2011年11月底,中国手机应用开发者安卓约75万人。

艾媒咨询(iiMedia Research)最新发布的《2012Q1中国手机浏览器市场季度监测报告》显示,2012Q1中国手机浏览器用户手机操作系统平台分布方面,Android系统平台占比达32.8% ,成为用户手机中占比最高的系统平台。

目前Google移动应用产品有:Google eBooks、Street View on Google 、Google Tunes、gReader、谷歌拼音输入法、Google Maps、Google翻译、谷歌星空地图等。Google Play在今年一月份的应用数量超过40万款。

目前带有Google标识的手机是三星的Galaxy Nexus。