实验1 Android音乐播放器
实验目的
1. 掌握Activity工作机制。
3. 掌握ListView、MediaPlayer等用法。
实验任务
设计一个音乐播放器,用List列表显示手机中所有音乐,支持播放、暂停、继续、上一首、下一首等功能。
程序源代码:
1、主布局:(在项目中新建一个Module:music)
android:id="@+id/musicListView" android:layout_width="match_parent" android:layout_height="match_parent"/> 2、ListView布局: music_item.xml xml version="1.0" encoding="utf-8"?> 3、Music类 public class Music { int ID;//歌曲ID 4、MusicAdapter类 public class MusicAdapter extends ArrayAdapter 5、MainActivity代码 //得到一个空的ContentResolver (MediaStore.Audio.Media._ID)); (MediaStore.Audio.Media.TITLE)); (MediaStore.Audio.Media.ARTIST)); (MediaStore.Audio.Media.DATA)); (MediaStore.Audio.Media.DURATION)); //创建音乐对象,并添加到list中 运行结果截图: APP功能说明: 该音乐播放器支持用List列表显示手机中所有音乐,支持播放、暂停、继续、上一首、下一首、重播、进度条、循环模式等功能。 实验小结: 1、adapter:数据和视图之间的桥梁,数据在adapter中做处理,然后显示到视图上面 2、必须添加SD卡访问权限 才可以访问SD卡; 3、想要启动xxactivity时在该AndroidManifest.xml中 4、要注意细节,比如界面的美观,不能单纯地完成实验而不顾美观,这一点我做的不够好,在以后的学习过程中慢慢改进。 实验2 Android广播+服务编程 实验目的 1. 掌握Broadcast Receiver编程基本方法。 2. 掌握本地Service编程基本用法。 实验任务 利用Android广播和服务组件,设计一个电话监听录音APP,完成如下主要功能: (1)用广播机制监听电话(只要求监听去电电话),启动服务完成录音功能,当结束通话时使用手工方式结束录音。 (2)录音使用MediaRecorder类编程(自查相关资料),录音文件用当前系统时间命名。 实验代码 1、在AndroidManifest.xm中添加权限 2、BootReceiver.java 3、MainActivity.java public class MainActivity extends Activity { 4、RecorderService.Java public class RecorderService extends Service { 运行结果截图如下: 本程序功能:拨打电话时会监听去电,通过广播的方式告诉用户去电号码,通过service录音,录音文件会存在recorder文件夹中,然后将文件夹中的文件读取到页面中显示,点击刷新按钮可以刷新获取的文件。 实验小结: 1、本次试验涉及多种权限设置,因为权限问题调试了好几天才弄好,如果以后我自己开发产品一定不可以让产品这么坑。 2、界面有待美化,但是各种考试将近,还是先这样吧,等考试结束再尝试加入来电监听的功能。 3、Android studio的报错全部都是英文,所以用log调试是一个很棒的方法,以前喜欢注释掉代码调试程序,但是比较麻烦,现在找到了更好的方法。 4、录音的文件有时候需要差不多一分钟才开始播放。 实验3 Android数据存储与访问 实验目的 1. 掌握SQLite数据库编程基本方法。 2. 掌握SimpleCursorAdapter基本用法。 3. 掌握上下文菜单基本用法。 实验任务 完成下图示例功能。 程序代码: 1、DBHelper.java public class DBHelper extends SQLiteOpenHelper { insertActivity public class InsertActivity extends Activity { 2、Person.java public class Person { 3、showActivity public class ShowActivity extends Activity { 4、UpdateActivity public class UpdateActivity extends Activity { 运行结果截图: 程序说明: 该APP完成了插入删除修改查询功能,年龄的输入值可以是数字,id号自动产生且不可改变。 实验小结: 1、利用数据库增删改查是非常方便的,在以后的学习中必然还会用到相关的知识,因此这一章节的内容一定要掌握牢固,记住一些重要的SQL语句。 2、设计APP的时候考虑输入的合理性,在输入年龄的时候应该限定输入的字符只可以是数字,id值是不可以被改变的。 3、如何将数据库和界面联系起来也是这个APP制作成功的关键,上课的时候这个程序的代码我基本都是复制粘贴的,只是感觉到SQLite很强大,下课后仔细敲了一遍才领会到代码的工作原理,不过还没有达到灵活运用的地步,但是我觉得这一节的知识用处很大,在我自己设计APP的时候很可能会用到。 实验4 Android网络爬虫程序 实验目的 1. 掌握HttpURLConnection编程基本方法。 2. 掌握Jsoup HTML解析器基本用法。 实验任务 参考 http://blog.csdn.net/never_cxb/article/details/50524571 制作一个简单的Android新闻客户端。 程序代码: 1、在MainActivity中添加权限 2、Test public class test extends Activity { 3、NewsAdapter.java public class NewsAdapter extends BaseAdapter { News.java public class News { } HttpUtils .java public class HttpUtils { HttpClientActivity 运行结果截屏: 程序功能说明:打开应用程序会获取“http://mobile.csdn.net/”的新闻页面。 实验小结: 1、网络爬虫是大数据重要的组成部分,在这次实验过程中我学习到了一些网络爬虫的相关知识,感觉到了它的强大,也对它产生了浓厚的兴趣,如果以后没有遇到更感兴趣的东西我会选择向大数据的方向发展。 2、利用jsoup解析HTML代码十分方便,但在学习的过程中我发现JSON好像也很腻害的样子,所以打算加强这方面的学习。 3、爬虫过程中最难获取的是图片,但经过各种百度查资料还是被我弄出来了哈哈哈,就是耗时有点长,不过也正是因为这样所以会印象深刻。 4、一学期的android学习已经结束,虽然学习过程中上万次想要放弃,因为那些权限真的是太烦了,还有适配器的使用,我一直到整理实验报告的时候才勉强弄清楚他是怎么将获取的内容和页面显示的内容联系到一起,但是每完成一个实验都会感觉很有成就感。
android:layout_width="match_parent"
android:layout_height="match_parent">
android:layout_height="0dp"
android:id="@+id/music_id"
android:visibility="invisible"/>
android:layout_height="40dp"
android:singleLine="true"
android:text="music_title"
android:textSize="20sp"/>
android:layout_width="60dp"
android:layout_height="40dp"
android:id="@+id/music_artist"
android:textSize="20sp"/>
android:layout_height="0dp"
android:id="@+id/music_url"
android:visibility="invisible"/>
android:layout_height="40dp"
android:gravity="right"
android:singleLine="true"
android:text="music_duration"
android:textSize="20sp"/>
String Title;// 歌曲名称
String Artist;// 艺术家
String Url; //歌曲路径
int Duration; //歌曲时长
public Music(int ID, String title, String artist, String url, int duration) {
this.ID = ID;
Title = title;
Artist= artist;
Url = url;
Duration = duration;
}
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
public String getTitle() {
return Title;
}
public void setTitle(String title) {
Title = title;
}
public String getArtist() {
return Artist;
}
public void setArtist(String artist) {
Artist = artist;
}
public String getUrl() {
return Url;
}
public void setUrl(String url) {
Url = url;
}
public int getDuration() {
return Duration;
}
public void setDuration(int duration) {
Duration = duration;
}
}
private int resourceId;
public MusicAdapter(Context context, int resource, List
super(context, resource, objects);
resourceId = resource;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Music m = getItem(position); // 获取当前项的Music实例
View view = LayoutInflater.from(getContext()).inflate(resourceId, null);
TextView music_id = (TextView) view.findViewById(R.id.music_id);
TextView music_title = (TextView) view.findViewById(R.id.music_title);
TextView music_artist = (TextView) view.findViewById(R.id.music_artist);
TextView music_url = (TextView) view.findViewById(R.id.music_url);
TextView music_duration = (TextView) view.findViewById(R.id.music_duration);
music_id.setText("" + m.getID()); //""不能省
music_title.setText(m.getTitle());
music_artist.setText(m.getArtist());
music_url.setText(m.getUrl());
SimpleDateFormat sdf = new SimpleDateFormat("mm:ss"); //时间格式
String time = sdf.format(m.getDuration()); //m.getDuration()得到的是秒数
music_duration.setText(time);
return view;
}
}
public class MainActivity extends Activity {
private MediaPlayer mPlayer=new MediaPlayer();
private SeekBar sb;
private int current=0;
private static int nowState=0;
TextView nowtime;
TextView totaltime;
int location_pre=-1;
int location_now=-1;
int sum_music;
ArrayList
public ArrayList
ArrayList
Cursor cursor = getContentResolver().query(
//使用content provider查询媒体数据库
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
null,null,null,MediaStore.Audio.Media.TITLE); //按标题排序,默认升序
if ( cursor.moveToFirst() ){//第一条记录
while ( !cursor.isAfterLast() ) {
//遍历每一列 //获取歌曲ID、歌曲的名称 、艺术家、歌曲路径 、歌曲时长
int id=cursor.getInt(cursor.getColumnIndexOrThrow
Stringtilte=cursor.getString(cursor.getColumnIndexOrThrow
Stringartist=cursor.getString(cursor.getColumnIndexOrThrow
String url = cursor.getString(cursor.getColumnIndexOrThrow
int duration = cursor.getInt(cursor.getColumnIndexOrThrow
Music m=new Music(id,tilte,artist,url,duration);
list.add(m);
cursor.moveToNext();
} //end while
cursor.close();
} //end if
return list;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPlayer.setLooping(true);
if (ActivityCompat.checkSelfPermission( MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED ) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[] { Manifest.permission.READ_EXTERNAL_STORAGE }, 123);
return;
}
//判断是否是AndroidN以及更高的版本 N=24
if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.N ) {
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
}
musicArrayList = ScannerMusic(); //获取音乐对象列表
sum_music=musicArrayList.size();
MusicAdapter adapter = new MusicAdapter(// 配置Adpater
MainActivity.this,
R.layout.music_item,
musicArrayList);
nowtime=(TextView) findViewById(R.id.tv_progress);
totaltime=(TextView)findViewById(R.id.tv_total);
final Button bt=(Button)findViewById(R.id.exit);
final ImageButton bt1=(ImageButton) findViewById(R.id.cycle);
ImageButton bt2=(ImageButton) findViewById(R.id.last);
final ImageButton bt3=(ImageButton) findViewById(R.id.pause);
ImageButton bt4=(ImageButton) findViewById(R.id.next);
ImageButton bt5=(ImageButton) findViewById(R.id.restart);
ListView li = (ListView) findViewById(R.id.musicListView);
li.setAdapter(adapter);
li.setChoiceMode(ListView.CHOICE_MODE_SINGLE); //单选
li.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView> parent, View view, int position, long id) {
Music m=musicArrayList.get(position);
sb.setMax(mPlayer.getDuration());
sb.setProgress(0);
current=0;
if (location_pre==-1) {
location_pre=position;
location_now=position;
}
else {
location_pre=position;
location_now=position;
}
try {
mPlayer.reset(); //播放器重置
mPlayer.setDataSource(m.getUrl());
mPlayer.prepare(); //准备播放
mPlayer.start();
sb.setMax(mPlayer.getDuration());
sb.setProgress(0);
bt3.setImageResource(R.drawable.play);
handler.post(update);
} catch(Exception e) {
e.printStackTrace();
}
} //end onItemClick
}); //end setOnItemClick
View.OnClickListener onclicklistener = new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.cycle:
nowState=(nowState+1)%3;
switch (nowState){
case 0:
bt1.setImageResource(R.drawable.onemusic);
Toast.makeText(getApplicationContext(),"单曲循环",Toast.LENGTH_SHORT).show();
break;
case 1:
bt1.setImageResource(R.drawable.order);
Toast.makeText(getApplicationContext(),"顺序播放",Toast.LENGTH_SHORT).show();
break;
case 2:
bt1.setImageResource(R.drawable.rand);
Toast.makeText(getApplicationContext(),"随机播放",Toast.LENGTH_SHORT).show();
break;
}
break;
case R.id.last:
current=0;
if(mPlayer!=null) {
Music m=musicArrayList.get((--location_now+sum_music)%sum_music);
try {
mPlayer.reset();
mPlayer.setDataSource(m.getUrl());
mPlayer.prepare();
sb.setProgress(0);
sb.setMax(mPlayer.getDuration());
bt3.setImageResource(R.drawable.play);
mPlayer.start();
} catch (IOException e) {
e.printStackTrace();
}
}
break;
case R.id.pause:
current=mPlayer.getCurrentPosition();
if (mPlayer.isPlaying()&&mPlayer!=null) {
mPlayer.pause();
bt3.setImageResource(R.drawable.pause);
}
else if(mPlayer!=null&&!mPlayer.isPlaying()) {
mPlayer.start();
bt3.setImageResource(R.drawable.play);
}
break;
case R.id.next:
nextSong();
break;
case R.id.restart:
current=0;
if (mPlayer!=null) {
if(mPlayer.isPlaying()==false){
bt3.setImageResource(R.drawable.play);
}
mPlayer.stop();
try {
mPlayer.prepare();
} catch (IOException ex) {
ex.printStackTrace();
}
mPlayer.seekTo(0);
sb.setMax(mPlayer.getDuration());
sb.setProgress(0);
mPlayer.start();
}
break;
case R.id.exit:
new AlertDialog.Builder(MainActivity.this).setTitle("提示")
.setMessage("确认要退出吗?")
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
finish();
}
})
.setNegativeButton("取消", null).show();
break;
}
}//end onClick
};
bt.setOnClickListener(onclicklistener);
bt1.setOnClickListener(onclicklistener);
bt2.setOnClickListener(onclicklistener);
bt3.setOnClickListener(onclicklistener);
bt4.setOnClickListener(onclicklistener);
bt5.setOnClickListener(onclicklistener);
sb=(SeekBar)findViewById(seekBar);
sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
current=sb.getProgress();
mPlayer.seekTo(current);
}
});
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
nextSong();
}
});
}
public void nextSong(){
Music m;
current=0;
try {
switch(nowState){
case 0://单曲循环
m=musicArrayList.get(location_now);
if(location_now==0){
location_pre=musicArrayList.size();
}else {
location_pre = location_now - 1;
}
mPlayer.reset();
mPlayer.setDataSource(m.getUrl());
mPlayer.prepare();
mPlayer.start();
sb.setProgress(0);
sb.setMax(m.getDuration());
break;
case 1://顺序播放
m=musicArrayList.get((++location_now)%sum_music);
location_pre=location_now%sum_music;
mPlayer.reset();
mPlayer.setDataSource(m.getUrl());
mPlayer.prepare();
mPlayer.start();
sb.setProgress(0);
sb.setMax(m.getDuration());
break;
case 2://随机播放 random
location_pre=location_now%sum_music;
Random random=new Random();
int randomInt=random.nextInt(musicArrayList.size());
location_now=randomInt;
m=musicArrayList.get(randomInt);
location_pre=random.nextInt(musicArrayList.size());
mPlayer.reset();
mPlayer.setDataSource(m.getUrl());
mPlayer.prepare();
mPlayer.start();
sb.setProgress(0);
sb.setMax(m.getDuration());
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
public String ShowTime(int time){
time/=1000;
int minute=time/60;
int second=time%60;
minute%=60;
return String.format("%02d:%02d",minute,second);
}
Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case 0://更新进度
int position=mPlayer.getCurrentPosition();
int time=mPlayer.getDuration();
int max=sb.getMax();
sb.setProgress(position*max/time);
break;
default:
break;
}
}
};
Runnable update = new Runnable() {//更新状态
@Override
public void run() {
sb.setProgress(current);
int time=mPlayer.getDuration();
nowtime.setText(ShowTime(mPlayer.getCurrentPosition()));
totaltime.setText(ShowTime(time));
handler.postDelayed(update,50);
}
};
@Override
protected void onDestroy() {
super.onDestroy();
if( mPlayer!=null ){
mPlayer.stop();
mPlayer.release();
}
Toast.makeText(getApplicationContext(), "退出啦", Toast.LENGTH_SHORT).show();
mPlayer=null;
}
}
public class BootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.intent.action.NEW_OUTGOING_CALL")) {
String phoneNum = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
Toast.makeText(context, "监听到拨打电话:" + phoneNum, Toast.LENGTH_LONG).show();
}
Intent intent1=new Intent(context,RecorderService.class);
if (intent.getAction().equals("BC_")){
Toast.makeText(context,"结束录音",Toast.LENGTH_LONG).show();
context.stopService(intent1);
}
else {
Toast.makeText(context,"开始录音",Toast.LENGTH_LONG).show();
context.startService(intent1);
}
}
}
class MyFilter implements FilenameFilter {
private String type;
public MyFilter(String type){ //构造函数
this.type = type;
}
@Override //实现FilenameFilter接口accept()方法
public boolean accept(File dir,String name) { //dir当前目录, name文件名
return name.endsWith(type); //返回true的文件则合格
}
}
String recorder_path="";
MediaPlayer mp=new MediaPlayer();
ArrayList
private void getFileFromRecord(){
recorderList =new ArrayList
File sdpath=Environment.getExternalStorageDirectory(); //获得手机SD卡路径
File path=new File(sdpath+"//recorder//"); //获得SD卡的recorder文件夹,返回以.3gp结尾的文件 (自定义文件过滤)
File[ ] songFiles = path.listFiles( new MyFilter(".3gp") );
for (File file :songFiles){
recorderList.add(file.getAbsolutePath());
}
ArrayAdapter
MainActivity.this,
android.R.layout.simple_list_item_single_choice,
recorderList );
ListView li=(ListView)findViewById(R.id.lv);
li.setAdapter(adapter);
li.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView> parent, View view, int position, long id) {
recorder_path=((TextView)view).getText().toString();
try{
mp.reset(); //播放器重置
mp.setDataSource(recorder_path); mp.prepare(); //准备播放
}catch (Exception e){
e.printStackTrace();
}
mp.start(); //播放
} //end onItemClick
}); //end setOnItemClick
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getFileFromRecord();
Button bt=(Button)findViewById(R.id.button);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getFileFromRecord();
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
if(mp!=null ){
mp.stop();
mp.release();
}
}
}
private MediaRecorder recorder; //录音的一个实例
//创建保存录音的目录
private void createRecorderFile() {
String absolutePath = Environment.getExternalStorageDirectory().getAbsolutePath();
String filePath=absolutePath+"/recorder";
File file=new File(filePath);
if (!file.exists()){
file.mkdir();
}
}
private String getCurrentTime(){//获取当前时间,以其为名来保存录音
SimpleDateFormat format=new SimpleDateFormat("yyyyMMddHHmmss");
Date date=new Date();
String str=format.format(date);
return str;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
if(recorder==null) {//获得电话管理器
recorder = new MediaRecorder();//初始化录音对象
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);//设置录音的输入源(麦克)
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);//设置音频格式(3gp)
createRecorderFile();//创建保存录音的文件夹
recorder.setOutputFile("sdcard/recorder" + "/" + getCurrentTime() + ".3gp"); //设置录音保存的文件
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);//设置音频编码
try {
recorder.prepare();//准备录音
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public DBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS person ("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "name VARCHAR(20),"
+ "age SMALLINT)");
//数据库第一次被创建时将调用onCreate,通常将创建表的操作放在这里
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//当数据库版本发生变化时会调用onUpgrade
// 这里可写更新数据表的操作(谨慎使用),也可空着不写
db.execSQL("DROP TABLE IF EXISTS person"); //删除数据表,谨慎使用
onCreate(db); //重新建表
}
}
public void insert(Person person){
DBHelper helper = new DBHelper(getApplicationContext(), "test.db", null,1);
SQLiteDatabase db=helper.getWritableDatabase();
String sql="INSERT INTO person VALUES (NULL, ?, ?)";
db.execSQL(sql, new Object[ ] {
person.name, person.age
} );
db.close();
Toast.makeText(getApplicationContext(), " 记录添加成功 ", Toast.LENGTH_SHORT).show();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert);
Button bt1= (Button)findViewById(R.id.newRec);
bt1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
EditText et1=(EditText)findViewById(R.id.editText1);
EditText et2=(EditText)findViewById(R.id.editText2);
Person person=new Person(et1.getText().toString(), Integer.parseInt(et2.getText().toString()));
insert(person); //代码后页
setResult(RESULT_OK, null);
finish();
}
});
Button bt2= (Button)findViewById(R.id.quxiao);
bt2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
finish();
}
});
}
}
public int id;
public String name;
public int age;
public Person() { }
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
private static int db_version=1;
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==100)
if(resultCode==RESULT_OK){
onCreate(null);
}
if(requestCode==200)
if(resultCode==RESULT_OK){
onCreate(null);
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo){
menu.setHeaderTitle("操作");
getMenuInflater().inflate(R.menu.manage,menu);
}
public void delete(MenuItem item){
final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
if(info.id>0){
new AlertDialog.Builder(this)
.setTitle("删除" + info.id)
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
DBHelper helper = new DBHelper(getApplicationContext(), "test.db", null,1);
SQLiteDatabase db=helper.getWritableDatabase();
db.execSQL( "Delete from person where id=?", new Object[ ]{ info.id } );
db.close();
Toast.makeText(getApplicationContext(), " 记录删除成功 ", Toast.LENGTH_SHORT).show();
onCreate(null); //重新加载一次Activity,刷新
}
}) .setNegativeButton("取消", null) .show();
}
}
public void update(MenuItem item){
final AdapterView.AdapterContextMenuInfo info= (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
Intent intent =new Intent(ShowActivity.this, UpdateActivity.class);
Bundle bundle=new Bundle();
bundle.putString("id", String.valueOf(info.id));
bundle.putString("username",((TextView)info.targetView.findViewById(R.id.txtName)).getText().toString());
bundle.putString("age",((TextView)info.targetView.findViewById(R.id.txtAge)).getText().toString());
intent.putExtras(bundle);
startActivityForResult(intent, 200);
}
@Override
public boolean onContextItemSelected(MenuItem item){
switch(item.getItemId()){
case R.id.delete:
delete(item);
return true;
case R.id.update:
update(item);
return true;
default:
return false;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show);
DBHelper helper = new DBHelper(getApplicationContext(), "test.db", null,1);
SQLiteDatabase db=helper.getWritableDatabase();
Cursor cursor = db.rawQuery( "SELECT id as _id, name,age FROM person",null);
String[] from = { "_id", "name", "age" };
int[] to = { R.id.txtID, R.id.txtName, R.id.txtAge };
SimpleCursorAdapter adapter = new SimpleCursorAdapter( this, R.layout.listview, cursor, from, to);
ListView li=(ListView)findViewById(R.id.listView1);
li.setAdapter(adapter);
registerForContextMenu(li);
TextView tv=(TextView)findViewById(R.id.textView1);
tv.setText("查询到"+cursor.getCount()+"条记录");
Button bt1= (Button)findViewById(R.id.button1); // 注意 id 值
bt1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent=new Intent(ShowActivity.this,InsertActivity.class);
startActivityForResult(intent, 100);
}
});
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
Intent intent=getIntent();
Bundle bundle=intent.getExtras();
String id=bundle.getString("id");
String name=bundle.getString("username");
String age=bundle.getString("age");
final EditText et1=(EditText)findViewById(R.id.editText1);
final EditText et2=(EditText)findViewById(R.id.editText2);
final EditText et3=(EditText)findViewById(R.id.editText3);
et1.setText(id);
et2.setText(name);
et3.setText(age);
Button bt1= (Button)findViewById(R.id.button1);
bt1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
DBHelper helper = new DBHelper(getApplicationContext(), "test.db", null,1);
SQLiteDatabase db=helper.getWritableDatabase(); //更新数据,id值不能修改
db.execSQL("Update person set name=? , age=? where id=?", new Object[ ]{
et2.getText().toString(),
et3.getText().toString(),
et1.getText().toString()
} );
db.close();
Toast.makeText(getApplicationContext(),
" 记录修改成功 ",
Toast.LENGTH_SHORT)
.show();
setResult(RESULT_OK, null);
finish(); //不能少
}
});
Button bt2= (Button)findViewById(R.id.button2);
bt2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
finish();
}
});
}
}
Document doc = null;
private List
private ListView lvNews;
private NewsAdapter adapter;
private String url = "http://mobile.csdn.net/";
String title, href, time, content,img;
public void parseHtml(){
try {
doc = Jsoup.connect(url).get();
} catch (IOException e) {
e.printStackTrace();
}
Elements elements = doc.select("div.unit");
for (Element ele : elements) {
title = ele.getElementsByTag("h1").first().text();
href = ele.getElementsByTag("h1").first()
.getElementsByTag("a").first().attr("href");
time = ele.getElementsByTag("h4").first().text();
content = ele.getElementsByTag("dd").first().text();
img=ele.getElementsByTag("img").attr("src");
newsList.add(new News(title,content,time,img));
Message msg=new Message();
handler.sendMessage(msg);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
lvNews= (ListView) findViewById(R.id.lv);
newsList=new ArrayList
adapter=new NewsAdapter(this,newsList);
lvNews.setAdapter(adapter);
new Thread(new Runnable() {
@Override
public void run() {
parseHtml();
}
}).start();
}
private Handler handler=new Handler()
{
public void handleMessage(android.os.Message msg){
adapter.notifyDataSetChanged();
}
};
}
TextView tv_title;
TextView tv_detail ;
TextView tv_comment ;
ImageView img;
private List
private Context context;
public NewsAdapter(Context context, List
this.context=context;
this.newsList=newsList;
}
@Override
public int getCount() {
return newsList.size();
}
@Override
public News getItem(int position) {
return newsList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null){
convertView= LayoutInflater.from(context).inflate(R.layout.listview_item,null);
}
tv_title = (TextView) convertView.findViewById(R.id.tv_title);
tv_comment = (TextView) convertView.findViewById(R.id.tv_comment);
tv_detail = (TextView) convertView.findViewById(R.id.tv_detail);
tv_detail.setMovementMethod(ScrollingMovementMethod.getInstance());
img=(ImageView)convertView.findViewById(R.id.iv_pic);
News news=newsList.get(position);
tv_title.setText(news.getTitle());
tv_comment.setText(news.getComment());
tv_detail.setText(news.getDetail());
String pic_url=news.getImage();
HttpUtils.setPicBitMap(img,pic_url);
return convertView;
}
}
private String title;//新闻的标题
private String detail; //新闻的详细介绍
private String comment; //新闻的发表时间、阅读次数、评论数量,
private String image;
public News(String title,String detail,String comment,String image){
setTitle(title);
setDetail(detail);
setComment(comment);
setImage(image);
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
//此处省略一些get、set方法
public static void setPicBitMap(final ImageView img, final String pic_url){
new Thread(new Runnable() {
@Override
public void run() {
try {
HttpURLConnection conn=(HttpURLConnection)new URL(pic_url).openConnection();
conn.connect();
InputStream is=conn.getInputStream();
Bitmap bitmap= BitmapFactory.decodeStream(is);
img.setImageBitmap(bitmap);
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
public class HttpClientActivity extends Activity {
EditText mobileCode;
EditText username;
EditText psd;
EditText et;
TextView result;
TextView res;
TextView tv;
Handler mHandler = new Handler();
HttpURLConnection conn;
String title,href,time,content;
String myurl1="http://mobile.csdn.net/";
Document doc= null;
private void parseHtml(){
try {
doc = Jsoup.connect(myurl1).get();
} catch (IOException e) {
e.printStackTrace();
}
Elements elements=doc.select("div.unit");
for(Element ele:elements){
title=ele.getElementsByTag("h1").first().text();
href=ele.getElementsByTag("h1").first()
.getElementsByTag("a").first().attr("href");
time=ele.getElementsByTag("h4").first().text();
content=ele.getElementsByTag("dd").first().text();
Log.i("info",title+"\n"+href+"\n"+time+"\n"+content);
}
}
public String filterHtml(String source) {
if(null == source){
return "";
}
return source.trim();
}
public String crawler (String httpUrl){
String resultData="";
try {
url = new URL(httpUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
}
if (url != null) {
try {
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Charset", "UTF-8");
int code=conn.getResponseCode();
if(code==HttpURLConnection.HTTP_OK){
BufferedReader reader=new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line="";
while((line=reader.readLine())!=null){
resultData+=line+"\n";
}
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return resultData;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_http_client);
result = (TextView) findViewById(R.id.get);
result.setMovementMethod(ScrollingMovementMethod.getInstance());
new Thread(new Runnable() {
@Override
public void run() {
final String r= crawler(myurl1);
mHandler.post(new Runnable() {
@Override
public void run() {
}
});
}
}).start();
}
}