shujuku

actionbar


public class MainActivity extends Activity {

    private TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //获得ActionBar
        ActionBar bar = getActionBar();
        //为AcationBar设置标题
        bar.setTitle("阿苏的话");
        //设置标题的显示
        bar.setDisplayShowTitleEnabled(true);
        //设置ActionBar的log
        bar.setIcon(R.drawable.ic_launcher);
        
        tv = (TextView) findViewById(R.id.tv);
        //设置bar
        initTab(bar );
            
    }


    private void initTab(ActionBar bar) {
        //设置ActionBr 的类型模式
        bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        
        //tab的监听
         TabListener listener=new TabListener() {
            
            public void onTabUnselected(Tab tab, FragmentTransaction ft) {
                // TODO Auto-generated method stub
                
            }
            
            public void onTabSelected(Tab tab, FragmentTransaction ft) {
                // TODO Auto-generated method stub
                //将当前tab的名字显示到主页上
                tv.setText(tab.getText());
            }
            
            public void onTabReselected(Tab tab, FragmentTransaction ft) {
                // TODO Auto-generated method stub
                
            }
        };
        //为ActionBar添加Tab 并添加监听
        bar.addTab(bar.newTab().setText("开始").setTabListener(listener));
        bar.addTab(bar.newTab().setText("赞成呢").setTabListener(listener));
        bar.addTab(bar.newTab().setText("结束").setTabListener(listener));
        
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
    //添加menu菜单的选择监听
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        //获得该条的id
        int itemId = item.getItemId();
        //
        if(itemId==R.id.action){
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}
------------------------------------------------------------------------------
1. SharedPreference
   (1)app内的使用 
   (2)app之间的使用.
   (3)mode的种类:4种: private,append,write,read

2. Properties
   (1)java中如何使用?
    src目录下: Test.class.getClassLoader().getResourceAsStream("")
    当前包下:Test.class.getResourceAsStream("");
   (2)android中如何使用?
    assets目录中:InputStream is = getAssets().open("");
    raw目录中: InputStream is = getResources().openRawResource(id);
    SD卡:FileInputStream fis = new FileInputStream(Environment.getExternalStorageDirectory() + "/aa.properties");

    Properties p  = new Properties();
    p.load(fis);

3. SQLite数据库
   (1) SQLiteDatabase.openDatabase(path, factory, flags)
       openOrCreateDatabase(name, mode, factory)
   (2) 继承SQLiteOpenHelper类
       构造方法
       onCreate什么时候执行?
       onUpgrade什么时候执行?

       执行SQL方法:使用原生sql语句,使用api(如:insert,delete,update)

   (3) Xutils操作数据库(第三方工具)
       提供了方便的api(如:save,delete,update)

4. ContentProvider内容提供者
  系统自带的:读取通讯录
  自定义的:需要继承ContentProvider,实现抽象方法(比如:insert,query)
       URI: content://包名/表名/
             权限的配置:   
          写在application标签内
       <provider
            android:name="类的全名"
            android:permission="包类.provider.all"
            android:readPermission="包类.provider.read"
            android:writePermission="包类.provider.write" />

      声明权限:写在application标签外


5. 扫描SD卡
   Environment类:
  SD卡状态: mounted,checking,unmout等
  /mnt/sdcard/文件

6. 文件操作
   openInputStream();//取内存中的文件data/data/包路径/files目录
  FileFilter过滤器,可以获取指定格式的文件

7. ActionBar导航条
   设置显示和隐藏:show()和hide()
   显示模式:list和table

8. XML
  (1)认识xml
    (2)CDATA <![CDATA[特殊字符]]>
    (3)解析:
      dom解析:加载整个文件内容到内存中。
      sax解析: DefaultHandler中的重要方法:startElement,endElement,startDocument,characters,endDocument等。
        pull解析:与sax相似。获取eventType,根据它来获取值。
  (4)写xml
        Xml.newSerializer();
    Dom方式
    字符串拼接

9. Json
  (1)json语法
    (2)解析:
      JSONObject/JSONArray 灵活
    Gson解析 定义类与json一致。注解的使用(如:@SerializeName="json对应的名")
        FastJson 阿里
    
通讯录

  1     public static List<Mycontact> readContacts(Context context){
        List<Mycontact> list=new ArrayList<Mycontact>();
        ContentResolver resolver = context.getContentResolver();
        Cursor cursor = resolver.query(Phone.CONTENT_URI, null, null, null, null);
        while(cursor.moveToNext()){
            String tel = cursor.getString(cursor.getColumnIndex(Phone.NUMBER));
            String name = cursor.getString(cursor.getColumnIndex(Phone.DISPLAY_NAME));
            list.add(new Mycontact(0, name, tel));
        }
        return list;
    }
  2 XML文件适配<uses-permission android:name="android.permission.READ_CONTACTS"/>

读取SDshipei
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    

Json解析


    1.    public static List<Commody> getList(Context context){
        List<Commody> list=new ArrayList<Commody>();
        Gson gson=new Gson();
        try {
            list=gson.fromJson(new InputStreamReader(context.getAssets().open("commodity.json"), "gbk"), new TypeToken<List<Commody>>(){}.getType());
        } catch (Exception e) {
            
            e.printStackTrace();
        }    
        return list;
    }
     2  public static String readfile(Context context) throws Exception{
        BufferedReader bd=new BufferedReader(new InputStreamReader(context.getAssets().open("housedata.json"),"GBK"));
        String line=null;
        StringBuilder sb=new StringBuilder();
        while((line=bd.readLine()) != null){
            sb.append(line).append("\n");
        }
        Log.e("1", sb.toString());
        return sb.toString();
    }
    
    
    public static List<dat> getfile(Context context) throws Exception{
        Gson gson=new Gson();      
        Data data = gson.fromJson(Datautil.readfile(context),Data.class);
        List<dat> houses = data.data.houses;    
        Log.e("2",houses.toString());
        return houses;
    }
}

动画

               Animation animation2 = AnimationUtils.loadAnimation(this, R.anim.t1);
           img.startAnimation(animation2);

无限轮播

      初始化时的设置
    int index=Integer.MAX_VALUE/2-Integer.MAX_VALUE/2%ids.length;
    vp.setCurrentItem(index);
      最大化
          Integer.MAX_VALUE;
       页面滑动和小圆点适配
      rg.check(arg0%ids.length%3);

导航

             sp = getSharedPreferences("config",MODE_PRIVATE);
            if(sp.getBoolean("isFirst",false)){
            startActivity(new Intent(MainActivity.this,SecondActivity.class));
            finish();
        }else{
            Editor editor = sp.edit();
            editor.putBoolean("isFirst",true).commit();
             }

Json解析中不同类的分类


       public void initdata() throws Exception{
        getfile = Comutil.getfile(MainActivity.this);        
        for (Goods g : getfile) {
            if("listmr".equals(g.type)){
                listmr=g.item;
            }
            if("listxl".equals(g.type)){
                listxl=g.item;
            }
            if("listxy".equals(g.type)){
                listxy=g.item;
            }
            if("listjg".equals(g.type)){
                listjg=g.item;
            }
        }
    }

获得音乐文件

     private List<f1> getall(){
        List<f1>  list=new ArrayList<f1>();
        
        //得到contentResolv
        ContentResolver resolver = getContentResolver();
        Cursor cursor = resolver.query(Media.EXTERNAL_CONTENT_URI, null, null, null, null);
        if(cursor!=null&&cursor.getCount()>0){

            for (cursor.moveToFirst(); !cursor.isAfterLast();cursor.moveToNext()) {
                String string = cursor.getString(cursor.getColumnIndex(Media.DATA));
                String name = cursor.getString(cursor.getColumnIndex(Media.DISPLAY_NAME));
                                long long1 = cursor.getLong(cursor.getColumnIndex(Media.SIZE));
                    String size = Formatter.formatFileSize(SecondActivity.this, long1);
                list.add(new f1(name,string));
            }
        }
        return list;
    }



音乐播放

       
                String path = music.getPath();
                if(player==null){
                player = new MediaPlayer();
                try {
                    player.setDataSource(path);
                    player.prepare();
                    player.setOnPreparedListener(new OnPreparedListener() {
                        @Override
                        public void onPrepared(MediaPlayer mp) {
                            player.start();
                        }
                    });
                
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            
            }else{
                player.start();
            }
        
        
            
            @Override
            public void onClick(View v) {
                if(player!=null&&player.isPlaying()){
                    player.pause();
                }
        
        
    }


Dom解析

   1           public List<book> parse(InputStream is) throws Exception {
        DocumentBuilder b = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document parse = b.parse(is);
        
        Element element = parse.getDocumentElement();
        NodeList nodeList = element.getElementsByTagName("book");
        List<book> list=new ArrayList<book>();
        for(int i=0;i<nodeList.getLength();i++){
            
            book k=new book();
            Node node = nodeList.item(i);
            NodeList childNodes = node.getChildNodes();
            for(int j=0;j<childNodes.getLength();j++){                
                Node item = childNodes.item(j);
                String name = item.getNodeName();
                if("name".equalsIgnoreCase(name)){
                    k.name=item.getFirstChild().getNodeValue();
                }else     if("author".equalsIgnoreCase(name)){
                    k.author=item.getFirstChild().getNodeValue();
                }else    if("price".equalsIgnoreCase(name)){
                    k.price=item.getFirstChild().getNodeValue();
                }
            }
            list.add(k);
        }
        
        return list;
    }

       2
    public List<book> parse(InputStream is) throws Exception {
        list = new ArrayList<book>();
        DocumentBuilder b= DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document p = b.parse(is);
        Element element = p.getDocumentElement();
        NodeList books = element.getElementsByTagName("book");
        for(int i=0;i<books.getLength();i++){
            book bk=new book();
            Node item = books.item(i);
            NodeList childNodes = item.getChildNodes();
            for(int j=0;j<childNodes.getLength();j++){
                Node item2 = childNodes.item(j);
                String nodeName = item2.getNodeName();
                
                if("name".equalsIgnoreCase(nodeName)){
                    bk.name = item2.getFirstChild().getNodeValue();
                }else if("price".equalsIgnoreCase(nodeName)){
                    bk.price = item2.getFirstChild().getNodeValue();
                }else if("author".equalsIgnoreCase(nodeName)){
                    bk.author = item2.getFirstChild().getNodeValue();
                }
            }
            list.add(bk);
        }
        return list;
    }



Saxj解析
        @Override
    public List<book> parse(InputStream is) throws Exception {
           SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
           XMLReader xmlReader = parser.getXMLReader();
           Saxhandler handler=new Saxhandler();
           xmlReader.setContentHandler(handler);
           xmlReader.parse(new InputSource(is));
           return handler.getlist();
    
    }

    static class Saxhandler extends DefaultHandler{

        
        private List<book> list;
                private book b;
        private String value;
        

        @Override
        public void startDocument() throws SAXException {
            list = new ArrayList<book>();
            b=null;
        }

        @Override
        public void startElement(String uri, String localName, String qName,
                Attributes attributes) throws SAXException {
            if("book".equalsIgnoreCase(qName)){
                b=new book();
            }
        }

        @Override
        public void endElement(String uri, String localName, String qName)
                throws SAXException {
            if("name".equalsIgnoreCase(qName)){
                b.name=value;
            }else if("price".equalsIgnoreCase(qName)){
                b.price=value;
            }else if("author".equalsIgnoreCase(qName)){
                b.author=value;
            }else if("book".equalsIgnoreCase(qName)){
                list.add(b);
            }
        }

        @Override
        public void characters(char[] ch, int start, int length)
                throws SAXException {
            value = new String(ch,start,length);
        }

    public List<book> getlist(){
        return list;
    }
        
    }
}



  Pull解析

public List<book> parse(InputStream is) throws Exception {
        XmlPullParser p = Xml.newPullParser();
        p.setInput(is,"utf-8");
        book b=null;
        int type = p.getEventType();
        while(type!=XmlResourceParser.END_DOCUMENT){
            String name = p.getName();            
            switch (type) {
            case XmlResourceParser.START_DOCUMENT:
                list = new ArrayList<book>();
            break;
            case XmlResourceParser.START_TAG:
            
                if("book".equalsIgnoreCase(name)){
                   b=new book();    
                }else if("name".equalsIgnoreCase(name)){
                    b.name=p.nextText();
                }else if("price".equalsIgnoreCase(name)){
                    b.price=p.nextText();
                }
                else if("author".equalsIgnoreCase(name)){
                    b.author=p.nextText();
                }
            break;
            case XmlResourceParser.END_TAG:
            
                if("book".equalsIgnoreCase(name)){
                    list.add(b);
                }
            break;
            }
            type=p.next();
        }
        return list;
    }

        2

     public static List<book> parse(Context cxt,int XMlid) throws Exception{
        
        XmlResourceParser p = cxt.getResources().getXml(XMlid);
        book b=null;
        int type = p.getEventType();
        
        while(type!=XmlResourceParser.END_DOCUMENT){
            String name = p.getName();
            switch (type) {
            case XmlResourceParser.START_DOCUMENT:
            list=new ArrayList<book>();
                break;
            case XmlResourceParser.START_TAG:
                if("book".equalsIgnoreCase(name)){
                        b=new book();        
                }else if("name".equalsIgnoreCase(name)){
                    b.name=p.nextText();
                }else if("author".equalsIgnoreCase(name)){
                    b.author=p.nextText();
                }else if("price".equalsIgnoreCase(name)){
                    b.price=p.nextText();
                }
                break;
            case XmlResourceParser.END_TAG:
                if("book".equalsIgnoreCase(name)){
                    list.add(b);
                    b=null;
                }
                
                break;
                
            }
            type=p.next();
        }
        
    
        return list;
    }

--------------------------------------

项目下的json文件解析



public class ComUtil {

    public static List<Goods> getfile(Context context) throws Exception{
         List<Goods> list=new ArrayList<Goods>();
        
        Gson gson = new Gson();
        list=gson.fromJson(new InputStreamReader(context.getAssets().open("commodity.json"),"gbk"), new TypeToken<List<Goods>>(){}.getType());
            return list;
    
    }
}

--------------------------------
数据库循环添加



    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table phone(id integer primary key autoincrement ,name varhcar(20, price varchar(20),brand varhcar(20))");
        try {
            List<Phone> list = Datautil.getfile(context);
            ContentValues values=new ContentValues();
            for(Phone p:list){
                values.put("name",p.name);
                values.put("price",p.price);
                values.put("brand",p.brand);
                db.insert("phone", null, values);
                
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
----------------------------------------

文件抽取



    private void scanfile(File file ) {
    
          File[] listFiles = file.listFiles(new FileFilter() {
            
            @Override
            public boolean accept(File pathname) {
                if(pathname.isDirectory()){
                    return true;
                }
                String name = pathname.getName();
                boolean b=name.endsWith(".mp3");
                return b;
            }
            
        });
        for (File file2 : listFiles) {
            if(file2.isFile()){
                list.add(file2);
            }else{
                scanfile(file2);
            }
        }
        Log.e("2",list.toString());
    }
------------------------------------------------
写json 文件

package com.example.daywritejson;


import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import vo.Books;
import vo.f1;

import com.google.gson.Gson;

import android.os.Bundle;
import android.app.Activity;

import android.widget.TextView;

public class MainActivity extends Activity {

    private TextView tv;
    private JSONObject jsonObject;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = (TextView) findViewById(R.id.tv);    
        try {
            jsonObject=getJsomString();
            tv.setText(jsonObject.toString());
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();            
        }
        try {
            Gson gson=new Gson();
            InputStreamReader read=new InputStreamReader(getAssets().open("f2.text"));
            Books f1 = gson.fromJson(read,Books.class);
            tv.setText(f1.getto());
        } catch (IOException e) {
            e.printStackTrace();
        }    
    }

    private Books getBooks(String json) throws Exception{
        Books books=new Books();
        List<f1> list = new ArrayList<f1>();
        JSONObject object = new JSONObject(json);
        JSONArray jsonArray = object.getJSONArray("books");
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jo = jsonArray.getJSONObject(i);
            String name = jo.getString("name");
            String author = jo.getString("author");
            String price = jo.getString("price");
            f1 f = new f1(name,author,price);
            list.add(f);
        }
        books.setBooks(list);
        return books;
    }
    private JSONObject getJsomString() throws Exception {
        
    jsonObject = new JSONObject();
    jsonObject.put("name", "nujawus");
    jsonObject.put("author", "洛萨");
    jsonObject.put("price", 59);
    return jsonObject;
        
    }
}
-------------------------------------------------------------------



文件浏览



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lv = (ListView) findViewById(R. id.lv);
        
        file = Environment.getExternalStorageDirectory();
        list = getfile();
        lv.setAdapter(new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_expandable_list_item_1,list));
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View v, int position,
                    long arg3) {
                file = files[position];
                list= getfile();
                if(list != null){
                    lv.setAdapter(new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_expandable_list_item_1,list));
                }
                
            }
        });
    }

    private List<String> getfile(){
        files = file.listFiles();
        list = new ArrayList<String>();
        for (File file1 : files) {
            list.add(file1.getName()+"\n"+file1.getAbsolutePath());
        }
        return list;
    }
    @Override
    public void onBackPressed() {
        file = file.getParentFile();
        list = getfile();
        lv.setAdapter(new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_expandable_list_item_1,list));

    }
}
-----------------------------------------------------------------
数据库增删改查(dao层)


public class UserDao {
    Context context;
    private Sqlutil sq;
     public UserDao(Context context) {
        super();
        this.context = context;
        sq = new Sqlutil(context);
    }

    //查找
     public  List<User> findall(){
         List<User> list=new ArrayList<User>();
         SQLiteDatabase db = sq.getWritableDatabase();
         Cursor cursor = db.query("user", null, null, null, null, null, null);
         if(cursor!=null&&cursor.getCount()>0){
             while(cursor.moveToNext()){
                User u=new User ();
                u.user_name = cursor.getString(cursor.getColumnIndex("user_name"));
                u.user_password = cursor.getString(cursor.getColumnIndex("user_password"));
                u.user_id = cursor.getInt(cursor.getColumnIndex("user_id"));
                list.add(u);
             }
         }
         Log.e("0",list.toString());
         return list;
     }
    //添加
    
     public void inserts(String user_name,String user_password){
         SQLiteDatabase db = sq.getWritableDatabase();
         ContentValues values=new ContentValues();
         values.put("user_name", user_name);
         values.put("user_password", user_password);        
         db.insert("user", null, values);
         db.close();
         Log.e("1","已经添加");
     }    
     //删除
    
     public void del(int id){
         SQLiteDatabase db = sq.getWritableDatabase();
         String whereClause="user_id="+id;
        db.delete("user", whereClause, null);
        db.close();
         Log.e("2","已经删除");
     }
     //修改
    
     public void updt(String user_name,String user_password,int user_id){
         SQLiteDatabase db = sq.getWritableDatabase();        
         ContentValues values=new ContentValues();
         values.put("user_name", user_name);
         values.put("user_password", user_password);    
         db.update("user", values,"user_id="+user_id, null);
         db.close();
         Log.e("3","已经修改");
     }
}
-------------------------------------------------------------------------------
变色



    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.t1:
            setcolcr(0);
            vp.setCurrentItem(0);
            break;
        case R.id.t2:
            setcolcr(1);
            vp.setCurrentItem(1);
             break;
       case R.id.t3:
           setcolcr(2);
           vp.setCurrentItem(2);
        break;
        }
        
    }
    public void setcolcr(int a ){
        switch (a) {
        case 0:
            t1.setBackgroundColor(Color.MAGENTA);
            t2.setBackgroundColor(Color.CYAN);
            t3.setBackgroundColor(Color.CYAN);
            break;
        case 1:
            t1.setBackgroundColor(Color.CYAN);
            t2.setBackgroundColor(Color.MAGENTA);
            t3.setBackgroundColor(Color.CYAN);
             break;
       case 2:
           t1.setBackgroundColor(Color.CYAN);
            t2.setBackgroundColor(Color.CYAN);
            t3.setBackgroundColor(Color.MAGENTA);
        break;
        }
    }
----------------------------------------------------------------------------------

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值