Android初学模块代码2

本文详细介绍了Android应用开发过程中的关键步骤,包括文件读写、数据库操作、网络请求、UI交互、单元测试等核心模块的实现方法。此外,文章还涵盖了如何在Android应用中集成各种实用组件和功能,如图片加载、页面滑动切换、动态加载UI元素等。通过实例演示和代码注释,读者可以深入理解并掌握Android开发的基本技巧。

<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/mobile"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button"
android:id="@+id/button"
/>
</LinearLayout>

 

 


单元测试
1:<application>
<uses-library android:name="android.test.runner"/>
</application>

<maifest>
<instrumentation android:name="android.test.InstrumentationTestRunner"
android:targetPackage="wuqi.file" android:label="Test for file"
></instrumentation>
</manifest>

2:public String  read(String filename)在自己的类中写被测试的方法,如:fileservice类的service方法
3:建立测试类
public class Test extends AndroidTestCase {
private static final String TAG="Test"; 
public void testRead() throws Throwable
{FileService service=new FileService(this.getContext());
String result=service.read("aaa.txt");
 Log.i(TAG, result);
}
}对此进行右键单元测试即可

 

 


文件读写
public void save(String filename, String content) throws Exception {
FileOutputStream outStream=context.openFileOutput(filename, Context.MODE_PRIVATE);
outStream.write(content.getBytes()); 
if(outStream!=null){
outStream.close();}
}

public String  read(String filename) throws Exception{
FileInputStream inStream=context.openFileInput(filename);
ByteArrayOutputStream outStream=new ByteArrayOutputStream();
byte[] buffer=new byte[1024];
int len=0;
while((len=inStream.read(buffer))!=-1){
outStream.write(buffer, 0, len);}
byte[] data=outStream.toByteArray();
return new String(data);}

 

 

 


文件保存到sd卡

1:权限设置
<mainfest>
<!-- sd卡中创建和删除文件的权限-->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<!-- 向sd卡中写入数据的权限 -->   
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 
</manifest>
2:方法主题
public void savaToSDCard(String filename, String content) throws Exception {
File file=new File(new File("/mnt/sdcard"),filename);
//File file=new File(Environment.getExternalStorageDirectory(),filename);
FileOutputStream outStream=new FileOutputStream(file);
outStream.write(content.getBytes());
outStream.close();}
3:主应用调用
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
service.savaToSDCard(filename, content);
Toast.makeText(getApplicationContext(), R.string.success, 1).show();}


电话呼叫
String number=mobileText.getText().toString();
Intent intent=new Intent();
intent.setAction("android.intent.action.CALL");
//intent.addCategory("android.intent.catagory.DEFAULT");//系统自动添加,也可以直接省略
intent.setData(Uri.parse("tel:"+number));
startActivity(intent);

 

 

 

 

PULL解析xml

1:创建xml文件
2:为xml中的节点建立一个javabeen类
3:解析函数,如:been类节点为person,且有id,name,age属性:
public static List<Person> getPersons(InputStream xml) throws Exception
{List<Person> persons=null;
Person person=null;
XmlPullParser pullParser=Xml.newPullParser();
pullParser.setInput(xml, "UTF-8");
int event=pullParser.getEventType();

while(event!=pullParser.END_DOCUMENT)
{
 switch (event) {
 case XmlPullParser.START_DOCUMENT:
  persons=new ArrayList<Person>();
  break;
 case XmlPullParser.START_TAG:
  
  if(pullParser.getName().equals("person")){
     int id=Integer.parseInt(pullParser.getAttributeValue(0));
   person=new Person();
   person.setId(id);
     }
  
  if(pullParser.getName().equals("name")){
   person.setName(pullParser.nextText());
   
  }
  
  if(pullParser.getName().equals("age")){
   person.setAge(Integer.parseInt(pullParser.nextText()));
  }
  
  break;
  
 case XmlPullParser.END_TAG:
  if(pullParser.getName().equals("person"))
  {persons.add(person);
  person=null;}   
  break;
 
 }//switch
 
 event=pullParser.next();
}//while

 
 return persons;
}//getpersons

4:配置单元测试函数
public void testPerson() throws Exception{
InputStream xml=this.getClass().getClassLoader().getResourceAsStream("person.xml");
List<Person> persons=PersonService.getPersons(xml);
for(Person person:persons)
{Log.i(TAG, person.toString());//TAG为单元测试的类名
}

 

 

 

 


配置默认的参数
1:把参数保存到xxx.xml文件目录中
public void save(String name,Integer age) {
SharedPreferences preferences=context.getSharedPreferences("xxx",Context.MODE_PRIVATE);
Editor editor=preferences.edit();
 editor.putString("name", name);
 editor.putInt("age", age);
 editor.commit();//不能少
}
2:调用自动在控件中显示配置在以上配置文件中的值
public Map<String, String> getPreferences(){
 Map<String, String> perMap=new HashMap<String, String>() ;
 SharedPreferences preferences=context.getSharedPreferences("wuqi",Context.MODE_PRIVATE);
perMap.put("name", preferences.getString("name", ""));
perMap.put("age", preferences.getInt("age", 0)+"");
 return perMap;
}

 

 

 


SQLite数据库
1:获取操作对象类
class DBOpenHelper extends SQLiteOpenHelper {

public DBOpenHelper(Context context){
 super(context,"wuqi.db",null,2);
}

@Override
public void onCreate(SQLiteDatabase db) {//第一次创建数据库时调用
 db.execSQL("CREATE TABLE person(personid integer primary key autoincrement,name varchar(20))");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
 db.execSQL("ALTER TABLE person ADD phone VARCHAR(12) NULL");
}

}
2:增删改查求总分页
public class PersonService {

private DBOpenHelper dbOpenHelper;
public PersonService(Context context) {
 this.dbOpenHelper = new DBOpenHelper(context);
}

public void save(Person person)//添加
{
 SQLiteDatabase db=dbOpenHelper.getWritableDatabase();
 db.execSQL("insert into person(name,phone) values(?,?)",
   new Object[]{person.getName(),person.getPhone()});
}

public void delete(Integer id)
{
 SQLiteDatabase db=dbOpenHelper.getWritableDatabase();
 db.execSQL("delete from person where personid=?",
   new Object[]{id});
}

public void update(Person person)
{
 SQLiteDatabase db=dbOpenHelper.getWritableDatabase();
 db.execSQL("update person set name=?,phone=? where personid=?",
   new Object[]{person.getName(),person.getPhone(),person.getId()});
}

public Person find(Integer id)//查找
{
 SQLiteDatabase db=dbOpenHelper.getReadableDatabase();
 Cursor cursor=db.rawQuery("select * from person where personid=?",new String[]{id.toString()} );
 if(cursor.moveToFirst())
 { int personid=cursor.getInt(cursor.getColumnIndex("personid"));
  String name=cursor.getString(cursor.getColumnIndex("name"));
  String phone=cursor.getString(cursor.getColumnIndex("phone"));
  return new Person(personid, name, phone);
 }

 cursor.close();
 return null;
}

//offset  跳过前面多少条记录
//maxResult  每页获取的记录数
public List<Person> getScrollData(int offset,int maxResult)//分页
{List<Person> persons=new ArrayList<Person>();
SQLiteDatabase db=dbOpenHelper.getReadableDatabase();
Cursor cursor=db.rawQuery("select * from person order by personid asc limit ?,?",
  new String[]{offset+"",maxResult+""} );
while (cursor.moveToNext()) {
 int personid=cursor.getInt(cursor.getColumnIndex("personid"));
 String name=cursor.getString(cursor.getColumnIndex("name"));
 String phone=cursor.getString(cursor.getColumnIndex("phone"));
 persons.add(new Person(personid, name, phone));
}
cursor.close();
return persons;}


public long getCount()// 获取总数
{
 SQLiteDatabase db=dbOpenHelper.getReadableDatabase();
 Cursor cursor=db.rawQuery("select count(*) from person",null);
 cursor.moveToFirst();
 long result=cursor.getLong(0);
 cursor.close();
 return result;
}

public void payment()// sql事务。。。。
{
 SQLiteDatabase db=dbOpenHelper.getReadableDatabase();
 db.beginTransaction();//开启事务
 try{
  db.execSQL("update person set personid+=2 where personid=2");
 }finally{db.endTransaction();//结束事务
 }
}
}

 

 

 

 

 

从网络端获取图片
1:配置xml组件属性
<EditText
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:text="http://172.21.107.91:8080/web/gg.jpg"
 android:id="@+id/imagepath"
 /> 
<ImageView
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:id="@+id/imageView"
 />

<uses-permission android:name="android.permission.INTERNET"/>//网络端访问权限


2:主activity中注明按钮的单机事件
public void onClick(View v) {
String path=pathText.getText().toString();
byte[] data;
try {
data = ImageService.getImage(path);
//在ImageService类中实现getImage方法获得图片数据,如下。。
Bitmap bitmap=BitmapFactory.decodeByteArray(data, 0, data.length);
imageView.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}}

3:public class ImageService {
private static byte[] data={};
public static byte[] getImage(String path) throws Exception{
URL url=new URL(path);
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if (conn.getResponseCode()==200) {//200是成功响应的响应码
InputStream inputStream=conn.getInputStream();
return StreamTool.read(inputStream);
//在StreamTool中实现read方法将输入流转换为字节数组,如下。。
}
return null;}}

4:public class StreamTool {
public static byte[] read(InputStream inputStream) throws Exception {
ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
byte[] buffer=new byte[1024];
int len=0;
while((len=inputStream.read(buffer))!=-1)
{
outputStream.write(buffer,0,len);
}
inputStream.close();
return outputStream.toByteArray();
}
}

 

 

 

 


页面的滑动切换viewpage

1:  <android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" >

<android.support.v4.view.PagerTitleStrip
    android:id="@+id/pagertitle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="top" >
</android.support.v4.view.PagerTitleStrip>
</android.support.v4.view.ViewPager>

2:public class MainActivity extends Activity {

private ViewPager viewPager;
private PagerTitleStrip pagerTitleStrip;//每一页的标题
private List<View> list;//每一页的布局
private List<String> titlelist;//每一页的标题

@Override
protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);

 viewPager=(ViewPager)findViewById(R.id.viewpager);
 pagerTitleStrip=(PagerTitleStrip)findViewById(R.id.pagertitle);
//此处是动态加载页面,需要实现在layout里配置还相应的tab1-3.xml页面
 View view1=LayoutInflater.from(MainActivity.this).inflate(R.layout.tab1, null);
 View view2=LayoutInflater.from(MainActivity.this).inflate(R.layout.tab2, null);
 View view3=LayoutInflater.from(MainActivity.this).inflate(R.layout.tab3, null);

 list=new ArrayList<View>();
 list.add(view1);
 list.add(view2);
 list.add(view3);

 titlelist=new ArrayList<String>();
 titlelist.add("title1");
 titlelist.add("title2");
 titlelist.add("title3");

 viewPager.setAdapter(new MyAdapter());
}

class MyAdapter extends PagerAdapter{

 @Override
 public int getCount() {
  return list.size();
 }
 @Override
 public void destroyItem(View container, int position, Object object) {
  //super.destroyItem(container, position, object);
  ((ViewPager)container).removeView(list.get(position));
 }
 @Override
 public Object instantiateItem(View container, int position) {
  ((ViewPager)container).addView(list.get(position));
  return list.get(position);

 }
 @Override
 public CharSequence getPageTitle(int position) {
  return titlelist.get(position);
 }
 @Override
 public boolean isViewFromObject(View arg0, Object arg1) {
  // TODO Auto-generated method stub
  return arg0==arg1;
 }

}
}

 

 

 

 

 

checkBox动态加载

1:在main.xml中定义一个按钮,同时定义一个checkbox.xml,其内容如下
<CheckBox
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:id="@+id/checkbox"
>
</CheckBox>

2:在main_activity中动态加载
public class MainActivity extends Activity implements OnClickListener{

private List<CheckBox> checkBoxs=new ArrayList<CheckBox>();

@Override
protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 //setContentView(R.layout.activity_main);
 String[] checkboxtex=new String[] {"你好吗","你是男生吗","你搞基吗","你有菊花吗"};
 //动态加载布局
 LinearLayout linearLayout=(LinearLayout)getLayoutInflater().inflate(R.layout.activity_main, null);

 for(int i=0;i<checkboxtex.length;i++)
 {
  CheckBox checkBox=(CheckBox)getLayoutInflater().inflate(R.layout.checkbox, null);
  checkBoxs.add(checkBox);
  checkBoxs.get(i).setText(checkboxtex[i]);
  linearLayout.addView(checkBox,i);
 }
 setContentView(linearLayout);
 Button button=(Button)findViewById(R.id.button);
 button.setOnClickListener(this);
}

@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;
}

@Override
public void onClick(View v) {
 String s="";
 for (CheckBox checkBox:checkBoxs) {
  if(checkBox.isChecked())
  {s+=checkBox.getText()+"\n";}
 }
if("".equals(s)){s="没有选择任何一个";}
new AlertDialog.Builder(this).setMessage(s).setPositiveButton("关闭", null).show();

}

 

 

 

 

读取HTML页面的内容

1:util包创建通过输入流获得数据的类及方法
public class StreamTool {

 public static byte[] read(InputStream inputStream) throws Exception {

  ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
  byte[] buffer=new byte[1024];
  int len=0;
  while((len=inputStream.read(buffer))!=-1)
  {
   outputStream.write(buffer,0,len);
  }
  
  inputStream.close();
  return outputStream.toByteArray();
 }

}
2:通过输入网址获得网页的html源码,其中调用util包的类和方法
public class PageService {
 public static String getHtml(String path) throws Exception {
 
  URL url=new URL(path);
  HttpURLConnection conn=(HttpURLConnection)url.openConnection();
  conn.setConnectTimeout(5000);
  conn.setRequestMethod("GET");
  if(conn.getResponseCode()==200){
   InputStream inputStream=conn.getInputStream();
   byte[] data=StreamTool.read(inputStream);
   String html=new  String(data,"UTF-8");
   return html;
  }
  
  return null;
 }
}
3:主activity调用String html = PageService.getHtml(path);即可

 

 


Intent跳转并传值
activity1:
Intent intent = new Intent();
intent.putExtra("one", num1);
intent.setClass(activity1.this, activity2.class);
startActivity(intent);
activity2:
Intent intent = getIntent();
String num1 = intent.getStringExtra("one");

 

 


spinner下拉列表选项
1:main.xml中定义spinner控件
 <Spinner
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:id="@+id/spinner"
 />
 <Spinner
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:id="@+id/spinner2"
 />
2:自定义一个item.xml用于显示每个菜单选项的布局,等会用于第二个spinner上,如下:
  <ImageView
 android:id="@+id/imageview"
 android:layout_width="60dp"
 android:layout_height="60dp"
 android:paddingLeft="10dp"
 android:src="@drawable/icon" />

  <TextView
 android:id="@+id/textview"
 android:gravity="center_vertical"
 android:paddingLeft="10dp"
 android:textColor="#000"
 android:textSize="16dp"
 android:layout_width="wrap_content"
 android:layout_height="fill_parent"/>
2:主activity中实现,代码如下
protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 spinner=(Spinner)findViewById(R.id.spinner);  
 //List<String> list=MyAdapter.getdata();
 List<String> list =new ArrayList<String>();
 list.add("上海");
 list.add("北京");
 list.add("广州");
 ArrayAdapter<String> adapter=new ArrayAdapter<String>(MainActivity.this,
                     android.R.layout.simple_spinner_item,list);
 spinner.setAdapter(adapter);


 spinner2=(Spinner)findViewById(R.id.spinner2);
 List<Map<String,Object>> list2=new ArrayList<Map<String,Object>>();
 Map<String, Object> map1=new HashMap<String, Object>();  
 map1.put("Logo", R.drawable.icon1);
 map1.put("applicationname", "icon1");
 list2.add(map1);

 Map<String, Object> map2=new HashMap<String, Object>();
 map2.put("Logo", R.drawable.icon2);
 map2.put("applicationname", "icon2");
 list2.add(map2);

 SimpleAdapter simpleAdapter=new SimpleAdapter(MainActivity.this,
 list2, R.layout.item, new String[]{"Logo","applicationname"},
 new int[]{R.id.imageview,R.id.textview});

 spinner2.setAdapter(simpleAdapter);
 spinner2.setOnItemSelectedListener(new itemListener());
}

class itemListener implements AdapterView.OnItemSelectedListener{

 @Override
 public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
   long arg3) {
  // TODO Auto-generated method stub
  Map<String, Object> map=(Map<String, Object>)spinner2.getItemAtPosition(arg2);
     setTitle((String)map.get("applicationname"));//设置应用标题
 }

 @Override
 public void onNothingSelected(AdapterView<?> arg0) {
  // TODO Auto-generated method stub
  
 }
 
}

 

日期时间控件
1:main.xml中分别添加日期和时间的控件(textview用于显示修改后的值)
  <DatePicker
       android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/datePicker"/>
   
    <TimePicker
       android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/timePicker" />
   
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="18dp"
        android:id="@+id/textview" />
2:主函数实现俩个接口,
public class MainActivity extends Activity implements OnDateChangedListener,OnTimeChangedListener{

 private TextView textView;
 private DatePicker datePicker;
 private TimePicker timePicker;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  datePicker=(DatePicker)findViewById(R.id.datePicker);
  timePicker=(TimePicker)findViewById(R.id.timePicker);
  textView=(TextView)findViewById(R.id.textview);
  
  datePicker.init(2001, 1, 1, this);
  timePicker.setIs24HourView(true);
  timePicker.setOnTimeChangedListener(this);
  
 }

 @Override
 public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
  Toast.makeText(MainActivity.this, hourOfDay+""+minute+"", 1).show();
 }

 @Override
 public void onDateChanged(DatePicker view, int year, int monthOfYear,
   int dayOfMonth) {
  Calendar calendar=Calendar.getInstance();
  calendar.set(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth(), timePicker.getCurrentHour(), timePicker.getCurrentMinute());
  //格式化时间输出的格式
  SimpleDateFormat format=new SimpleDateFormat("yyyy年MM月dd日  HH:mm");
  textView.setText(format.format(calendar.getTime()));
 }

}

 

 

 

网络检查问题

public static boolean isConnect(Context context) {
         // 获取手机所有连接管理对象(包括对wi-fi,net等连接的管理)
     try {
         ConnectivityManager connectivity = (ConnectivityManager) context
                 .getSystemService(Context.CONNECTIVITY_SERVICE);
         if (connectivity != null) {
             // 获取网络连接管理的对象
             NetworkInfo info = connectivity.getActiveNetworkInfo();
             if (info != null&& info.isConnected()) {
                 // 判断当前网络是否已经连接
                 if (info.getState() == NetworkInfo.State.CONNECTED) {
                     return true;
                 }
             }
         }
     } catch (Exception e) {
 // TODO: handle exception
     Log.v("error",e.toString());
 }
         return false;
     }


 

转载于:https://www.cnblogs.com/qiwu/p/3228291.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值