《android的SQLite与文件下载》

下面是我程序的图片

《android的SQLite与文件下载》

《android的SQLite与文件下载》

下面是我的程序代码:

主函数:

package com.example.allpor;

import com.example.database.DataBase;

import android.os.Bundle;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
/**
 * 这是主要的Activity
 * 主要负责的就是模拟登录过程
 * @author 吕檀溪
 *
 */
public class MainActivity extends Activity {
    private DataBase base;
    private Button butOk;
    private Button butCl;
    private EditText nameText;
    private EditText pwdText;
    private SQLiteDatabase db;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        butOk=(Button) findViewById(R.id.ok);
        butCl=(Button) findViewById(R.id.clear);
        nameText=(EditText) findViewById(R.id.name);
        pwdText=(EditText) findViewById(R.id.pwd);
        
        base=new DataBase(this, "mine", null, 1);
        db=base.getReadableDatabase();
        base.onCreate(db);
        ContentValues values=new ContentValues();
        values.put("name", "lvtanxi");
        values.put("pwd", "jaychou");
        db.insert("demo_user", null, values);
        
        ButtonClick click=new ButtonClick();
        butOk.setOnClickListener(click);
        butCl.setOnClickListener(click);
    }

/**
 * 创建Button的点击事件监听器
 * @author 吕檀溪
 *
 */
    class ButtonClick implements OnClickListener{

        @Override
        public void onClick(View view) {
            Button but=(Button) view;
            if(R.id.ok==but.getId()){
                String name=nameText.getText().toString();
                String pwd=pwdText.getText().toString();
                String[] array={name,pwd};
                Cursor cursor=db.rawQuery("select * from demo_user where name=? and pwd=?", array);
                if(cursor.moveToNext()){
                    Toast.makeText(MainActivity.this, R.string.success, Toast.LENGTH_SHORT).show();
                    Intent intent=new Intent();
                    intent.putExtra("array", array);
                    intent.setClass(MainActivity.this, ShowDown.class);
                    startActivity(intent);
                }else{
                    Toast.makeText(MainActivity.this, R.string.down, Toast.LENGTH_SHORT).show();
                }
            }else{
                nameText.setText("");
                pwdText.setText("");
            }
            
        }
        
    }
    
}

第二个Activity:

package com.example.allpor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.example.database.DownLoad;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.RadioGroup.OnCheckedChangeListener;
/**
 * 进行下载的页面
 * @author 吕檀溪
 *
 */
public class ShowDown extends Activity{
    private Button but;
    private CheckBox box1;
    private CheckBox box2;
    private CheckBox box3;
    private RadioGroup group;
    private TextView text;
    private List<String> list;
    private Map<String, String> map;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.show);
        box1=(CheckBox) findViewById(R.id.box1);
        box2=(CheckBox) findViewById(R.id.box2);
        box3=(CheckBox) findViewById(R.id.box3);
        but=(Button) findViewById(R.id.load);
        group=(RadioGroup) findViewById(R.id.grop);
        text=(TextView) findViewById(R.id.user);
        
        Intent intent=getIntent();
        String[] array=intent.getStringArrayExtra("array");
        text.setText("欢迎:"+array[0]+"; 您的密码是:"+array[1]);
        list=new ArrayList<String>();
        map=new HashMap<String, String>();
        Resources resources=getResources();
        map.put(resources.getString(R.string.box1), "http://61.164.160.62:8080/1/1/3163/wo99.com_1200916179836395.mp3?tflag=1392807562");
        map.put(resources.getString(R.string.box2), "http://storage11.ocdn.kugou.com/M00/04/8A/e4Olo04Avl7VWT-KACkYABpLCnI118.mp3 ");
        map.put(resources.getString(R.string.box3), "http://flv.whcedu.cn/files/2012-12/10/10184450552.mp3 ");
        CheckBoxChange boxChange=new CheckBoxChange();
        box1.setOnCheckedChangeListener(boxChange);
        box2.setOnCheckedChangeListener(boxChange);
        box3.setOnCheckedChangeListener(boxChange);
        
        group.setOnCheckedChangeListener(new RadioGroupChange());
        
        but.setOnClickListener(new ButtonClick());
        
    }
    
    /**
     * Button的点击事件
     * @author 吕檀溪
     *
     */
    class ButtonClick implements OnClickListener{

        @Override
        public void onClick(View view) {
              for (String str : list) {
                 DownLoad load=new DownLoad();
                 load.toRun(map.get(str), "myMp3", str+".mp3");
            }
        }
        
    }
    /**
     * RadioButton的Change事件
     * @author 吕檀溪
     *
     */
    class RadioGroupChange implements OnCheckedChangeListener{

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            RadioButton radio=(RadioButton) group.findViewById(checkedId);
            System.out.println(radio.getText().toString());
        }
        
    }
    /**
     * CheckBox的Change事件
     * @author 吕檀溪
     *
     */
    class CheckBoxChange implements android.widget.CompoundButton.OnCheckedChangeListener{

        @Override
        public void onCheckedChanged(CompoundButton buttonView,
                boolean isChecked) {
            CheckBox box=(CheckBox) buttonView;
            String msg=box.getText().toString();
            if(isChecked){
                list.add(msg);
            }else{
                list.remove(msg);
            }
        }
        
    }
}

创建数据库的类:

package com.example.database;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * 创建android的SQLite数据库
 * @author 吕檀溪
 *
 */
public class DataBase extends SQLiteOpenHelper{

    public DataBase(Context context, String name, CursorFactory factory,
            int version) {
        super(context, name, factory, version);
        
    }

    //执行创建数据库的语句
    @Override
    public void onCreate(SQLiteDatabase db) {
            System.out.println("---->onCreate");
            db.execSQL("drop table if exists demo_user");
            db.execSQL("create table demo_user(id integer primary key autoincrement,name text,pwd text)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        
    }

}

下载的线程类:

package com.example.database;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.os.Environment;
/**
 * 下载歌曲的线程类
 * @author 吕檀溪
 *
 */
public class DownLoad implements Runnable{

    private URL url;
    private String path;
    private String urlStr;
    private String dirName;
    private String fileName;
    
    //在实例化线程类的同时得到外部存储器的路径
    public DownLoad() {
        path=Environment.getExternalStorageDirectory()+File.separator;
    }
    /**
     * 启动线程
     * @param url 下载文件的地址
     * @param dirName 文件夹的名字
     * @param fileName 下载文件的名字
     */
    public void toRun(String url,String dirName,String fileName){
        this.urlStr=url;
        this.dirName=dirName;
        this.fileName=fileName;
        new Thread(this).start();
    }
    @Override
    public void run() {
        int num=downFile();
        System.out.println("-------->"+num);
        
    }
    
    /**
     * 下载文件;返回整数。0:成功;1:文件存在;-1:下载出错
     * @return
     */
    private int downFile(){
        InputStream in=null;
        try {
            if(comparFile(dirName+File.separator+fileName)){
                return 1;
            }else{
                in=getInputStream(urlStr);
                writeFile(in);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }finally{
            if(null != in){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return 0;
    }
    
    /**
     * 写出下载的文件到SD卡
     * @param in
     * @return
     * @throws Exception
     */
    private File writeFile(InputStream in)throws Exception{
        File file=null;
        OutputStream out=null;
        try {
            createDir(dirName); 
            file=createFile(fileName);
            out=new FileOutputStream(file);
            byte[] array=new byte[4*1024];
            int len=0;
            while (-1 !=(len=in.read(array))) {
                out.write(array, 0, len);
                
            }
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(null !=out){
                out.close();
            }
        }
        return file;
    }
    
    //创建下载的文件
    private File createFile(String fileName)throws Exception {
        File file=new File(path+dirName+File.separator+fileName);
        file.createNewFile();
        return file;
    }
    //创建文件夹
    private File createDir(String dirName) {
        File dir=new File(path+dirName);
        if(!dir.exists() && !dir.isDirectory()){
            dir.mkdir();
        }
        return dir;
    }
    //判断文件是否存在
    private boolean comparFile(String filePath){
        File file=new File(path+filePath);
        return file.exists();
    }
    //通过下载地址得到输入流
    private InputStream getInputStream(String urlStr)throws Exception {
        url=new URL(urlStr);
        HttpURLConnection connection=(HttpURLConnection) url.openConnection();
        return connection.getInputStream();
    }

}

布局文件之主页面:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >
    <TextView 
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/text1"
        />
    <EditText 
        android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@android:drawable/editbox_background"
        android:layout_below="@id/text1"
        />
    <TextView 
        android:id="@+id/text2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/text2"
        android:layout_below="@id/name"
        />
    <EditText 
        android:id="@+id/pwd"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:password="true"
        android:background="@android:drawable/editbox_background"
        android:layout_below="@id/text2"
        />
   <Button 
       android:id="@+id/clear"
       android:layout_height="wrap_content"
       android:layout_width="wrap_content"
       android:text="@string/clear"
       android:layout_below="@id/pwd"
       android:layout_alignRight="@id/pwd"
       />
    <Button 
        android:id="@+id/ok"
        android:layout_height="wrap_content"
           android:layout_width="wrap_content"
           android:text="@string/ok"
           android:layout_below="@id/pwd"
           android:layout_toLeftOf="@id/clear"
        />
</RelativeLayout>

显示的第二页面:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >
    <TextView 
        android:id="@+id/user"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
    <LinearLayout
        android:id="@+id/lay1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/user"
        android:orientation="horizontal"
        >
        <CheckBox 
               android:id="@+id/box1"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:text="@string/box1"
            />
        <CheckBox 
               android:id="@+id/box2"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:text="@string/box2"
            />
        <CheckBox 
               android:id="@+id/box3"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:text="@string/box3"
            />
    </LinearLayout>
    <LinearLayout
        android:id="@+id/lay2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_below="@id/lay1"
        >
        <RadioGroup 
            android:id="@+id/grop"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            >
            <RadioButton
                android:id="@+id/radio1"
                android:layout_width="wrap_content"
                   android:layout_height="wrap_content"
                   android:text="@string/raido1"
                />
            <RadioButton
                android:id="@+id/radio2"
                android:layout_width="wrap_content"
                   android:layout_height="wrap_content"
                   android:text="@string/raido2"
                   android:layout_marginLeft="120px"
                   android:layout_marginTop="-36px"
                />
        </RadioGroup>
    </LinearLayout>
    <Button 
        android:id="@+id/load"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/load"
        android:layout_below="@id/lay2"
        android:layout_centerHorizontal="true"
        />
</RelativeLayout>

最后是常量:

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

    <string name="app_name">allpor</string>
    <string name="action_settings">Settings</string>
    <string name="text1">请输入姓名:</string>
    <string name="text2">请输入密码:</string>
    <string name="ok">登录</string>
    <string name="clear">重置</string>
    <string name="success">登录成功</string>
    <string name="down">登录失败</string>
    <string name="box1">青花瓷</string>
    <string name="box2">牛仔很忙</string>
    <string name="box3">甜甜的</string>
    <string name="raido1">普通</string>
    <string name="raido2">高质量</string>
    <string name="load">下载全部</string>
</resources>

你可能感兴趣的:(android,sqlite,下载,checkbox)