Andriod所有实验程序代码

Andriod所有实验程序代码

实验二 UI设计(一)
实验目的:
自主完成一个简单APP的设计工作,综合应用已经学到的Android UI设计技巧,重点注意合理使用布局。

实验要求:

  1. 完成一个计算器的设计,可以以手机自带的计算器为参考。设计过程中,注意考虑界面的美观性,不同机型的适应性,以及功能的完备性。
  2. 注意结合Activity的生命周期,考虑不同情况下计算器的界面状态。
  3. 如有余力,可以考虑实现一个高精度科学计算型的计算器。
    activity_main.xml
<?xml version="1.0" encoding="utf-8"?>


 







<Button
    android:id="@+id/jian"
    android:padding="0dp"
    android:layout_margin="0dp"
    android:layout_columnSpan="1"
    android:text="-" />

<Button
    android:id="@+id/four"
    android:padding="0dp"
    android:layout_margin="0dp"
    android:layout_columnSpan="1"
    android:text="4" />

<Button
    android:id="@+id/five"
    android:padding="0dp"
    android:layout_margin="0dp"
    android:layout_columnSpan="1"
    android:text="5" />

<Button
    android:id="@+id/sex"
    android:padding="0dp"
    android:layout_margin="0dp"
    android:layout_columnSpan="1"
    android:text="6" />

<Button
    android:id="@+id/add"
    android:padding="0dp"
    android:layout_margin="0dp"
    android:layout_columnSpan="1"
    android:text="+" />

<Button
    android:id="@+id/one"
    android:padding="0dp"
    android:layout_margin="0dp"
    android:layout_columnSpan="1"
    android:text="1" />
<Button
    android:id="@+id/two"
    android:padding="0dp"
    android:layout_margin="0dp"
    android:layout_columnSpan="1"
    android:text="2"/>

<Button
    android:id="@+id/three"
    android:padding="0dp"
    android:layout_margin="0dp"
    android:layout_columnSpan="1"
    android:text="3" />

<Button
    android:id="@+id/eql"
    android:padding="0dp"
    android:layout_margin="0dp"
    android:layout_gravity="fill_vertical"
    android:layout_rowSpan="2"
    android:layout_columnSpan="1"
    android:text="="
    android:layout_height="44dp" />

<Button
    android:id="@+id/baifenhao"
    android:padding="0dp"
    android:layout_margin="0dp"
    android:layout_columnSpan="1"
    android:text="%" />

<Button
    android:id="@+id/zero"
    android:padding="0dp"
    android:layout_margin="0dp"
    android:layout_columnSpan="1"
    android:text="0" />

<Button
    android:id="@+id/point"
    android:padding="0dp"
    android:layout_margin="0dp"
    android:layout_columnSpan="1"
    android:text="." />

MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import java.util.ArrayList;
import java.util.EmptyStackException;
import java.util.List;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MainActivity extends AppCompatActivity {
float number1;
float number2;
String yunsuan;
Button bt1;
Button bt2;
Button bt3;
Button bt4;
Button bt5;
Button bt6;
Button bt7;
Button bt8;
Button bt9;
Button bt0;
Button btchu;
Button btdelte_all;
Button btc;
Button btcheng;
Button btadd;
Button btbaifen;
Button btpoint;
Button btdelete;
Button bteql;
Button btjian;
EditText editText1;
EditText editText2;
public void init()
{
bt1=(Button)findViewById(R.id.one);
bt2=(Button)findViewById(R.id.two);
bt3=(Button)findViewById(R.id.three);
bt4=(Button)findViewById(R.id.four);
bt5=(Button)findViewById(R.id.five);
bt6=(Button)findViewById(R.id.sex);
bt7=(Button)findViewById(R.id.seven);
bt8=(Button)findViewById(R.id.eight);
bt9=(Button)findViewById(R.id.nine);
bt0=(Button)findViewById(R.id.zero);
btjian=(Button)findViewById(R.id.jian);
btchu=(Button)findViewById(R.id.chu);
btdelte_all=(Button)findViewById(R.id.all);
btc=(Button)findViewById(R.id.clear);
btcheng=(Button)findViewById(R.id.cheng);
btadd=(Button)findViewById(R.id.add);
btbaifen=(Button)findViewById(R.id.baifenhao);
btpoint=(Button)findViewById(R.id.point);
btdelete=(Button)findViewById(R.id.delete);
bteql=(Button)findViewById(R.id.eql);
editText1=(EditText)findViewById(R.id.edit1);
editText2=(EditText)findViewById(R.id.edit2);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.init();
bt0.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
String a=editText1.getText().toString();
a=a+“0”;
editText1.setText(a);
}
});
bt1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
String a=editText1.getText().toString();
a=a+“1”;
editText1.setText(a);
}
});
bt2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
String a=editText1.getText().toString();
a=a+“2”;
editText1.setText(a);
}
});
bt3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
String a=editText1.getText().toString();
a=a+“3”;
editText1.setText(a);
}
});
bt4.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
String a=editText1.getText().toString();
a=a+“4”;
editText1.setText(a);
}
});
bt5.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
String a=editText1.getText().toString();
a=a+“5”;
editText1.setText(a);
}
});
bt6.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
String a=editText1.getText().toString();
a=a+“6”;
editText1.setText(a);
}
});
bt7.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
String a=editText1.getText().toString();
a=a+“7”;
editText1.setText(a);
}
});
bt8.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
String a=editText1.getText().toString();
a=a+“8”;
editText1.setText(a);
}
});
bt9.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
String a=editText1.getText().toString();
a=a+“9”;
editText1.setText(a);
}
});
btdelte_all.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
editText1.setText("");
}
});
btdelete.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
if (!editText1.getText().toString().isEmpty()) {
String Text = editText1.getText().toString();
Text = Text.substring(0, Text.length() - 1);
editText1.setText(Text);
}
}
});

    bteql.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            editText2.setText(new Calculate(editText1.getText().toString()).str);
        }
    });
    btadd.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View v)
        {
            String a=editText1.getText().toString();
            number1=Integer.getInteger(a);
            a=a+"+";
            editText1.setText(a);
            yunsuan=yunsuan+"+";
        }
    });
    btjian.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View v)
        {
            String a=editText1.getText().toString();
            number1=Integer.getInteger(a);
            a=a+"-";
            editText1.setText(a);
            yunsuan=yunsuan+"+";
        }
    });
    btcheng.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View v)
        {
            String a=editText1.getText().toString();
            number1=Integer.getInteger(a);
            a=a+"X";
            editText1.setText(a);
            yunsuan=yunsuan+"+";
        }
    });
    btchu.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View v)
        {
            String a=editText1.getText().toString();
            a=a+"/";
            editText1.setText(a);
        }
    });
}

}
创建一个 Calculate类:
package com.example.administrator.computer;

import java.util.ArrayList;
import java.util.EmptyStackException;
import java.util.List;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Calculate {
public String s1;
StringBuilder str;

public Calculate(String m) {
    this.s1 = m;
    try {
        eval();
    } catch (Exception e) {
        str.delete(0, str.length());
        str.append("输入格式错误!");
    }
}

/**
 * 中缀表达式转后缀表达式
 * <p>
 * 遍历中缀的list
 * 1、数字时,加入后缀list
 * 2、“(”时,压栈
 * 3、 若为 ')',则依次弹栈,把弹出的运算符加入后缀表达式中,直到出现'(';
 * 4、若为运算符,对做如下处置
 * 1、如果栈为空,则压栈
 * 2、如果栈不为空:
 * 1、stack.peek().equals("(")  则压栈
 * 2、比较str和stack.peek()的优先级
 * 1、如果>,则运算符压栈
 * 2、<=的情况:当栈不为空时:
 * 1、stack.peek()是左括号,压栈
 * 2、<=,把peek加入后缀表达式,弹栈
 * 3、>,把运算符压栈,停止对栈的操作
 * 执行完栈的操作之后,还得判断:如果栈为空,运算符压栈
 */
public List<String> midToAfter(List<String> midList) throws EmptyStackException {
    List<String> afterList = new ArrayList<String>();
    Stack<String> stack = new Stack<String>();
    for (String str : midList) {
        int flag = this.matchWitch(str);
        switch (flag) {
            case 7:
                afterList.add(str);
                break;
            case 1:
                stack.push(str);
                break;
            case 2:
                String pop = stack.pop();
                while (!pop.equals("(")) {
                    afterList.add(pop);
                    pop = stack.pop();
                }
                break;
            default:
                if (stack.isEmpty()) {
                    stack.push(str);
                    break;
                } else {
                    if (stack.peek().equals("(")) {
                        stack.push(str);
                        break;
                    } else {
                        int ji1 = this.youxianji(str);
                        int ji2 = this.youxianji(stack.peek());
                        if (ji1 > ji2) {
                            stack.push(str);
                        } else {
                            while (!stack.isEmpty()) {
                                String f = stack.peek();
                                if (f.equals("(")) {
                                    stack.push(str);
                                    break;
                                } else {
                                    if (this.youxianji(str) <= this.youxianji(f)) {
                                        afterList.add(f);
                                        stack.pop();
                                    } else {
                                        stack.push(str);
                                        break;
                                    }
                                }
                            }
                            if (stack.isEmpty()) {
                                stack.push(str);
                            }
                        }
                        break;
                    }
                }
        }
    }
    while (!stack.isEmpty()) {
        afterList.add(stack.pop());
    }
    StringBuffer sb = new StringBuffer();
    for (String s : afterList) {
        sb.append(s + " ");
    }
    //System.out.println(sb.toString());
    return afterList;
}

/**
 * 判断运算符的优先级
 */
public int youxianji(String str) {
    int result = 0;
    if (str.equals("+") || str.equals("-")) {
        result = 1;
    } else {
        result = 2;
    }
    return result;
}

/**
 * 判断字符串属于操作数、操作符还是括号
 */
public int matchWitch(String s) {
    if (s.equals("(")) {
        return 1;
    } else if (s.equals(")")) {
        return 2;
    } else if (s.equals("+")) {
        return 3;
    } else if (s.equals("-")) {
        return 4;
    } else if (s.equals("*")) {
        return 5;
    } else if (s.equals("/")) {
        return 6;
    } else {
        return 7;
    }
}

/**
 * 计算a@b的简单方法
 */
public Double singleEval(Double pop2, Double pop1, String str) {
    Double value = 0.0;
    if (str.equals("+")) {
        value = pop2 + pop1;
    } else if (str.equals("-")) {
        value = pop2 - pop1;
    } else if (str.equals("*")) {
        value = pop2 * pop1;
    } else {
        value = pop2 / pop1;
    }
    return value;
}

private double result;

public double getResult() {
    return result;
}

public void setResult(double result) {
    this.result = result;
}

private int state;

public int getState() {
    return state;
}

public void setState(int state) {
    this.state = state;
}

public void countHouzhui(List<String> list) {
    str = new StringBuilder("");
    state = 0;
    result = 0;
    Stack<Double> stack = new Stack<Double>();
    for (String str : list) {
        int flag = this.matchWitch(str);
        switch (flag) {
            case 3:
            case 4:
            case 5:
            case 6:
                Double pop1 = stack.pop();
                Double pop2 = stack.pop();
                Double value = this.singleEval(pop2, pop1, str);
                stack.push(value);
                break;
            default:
                Double push = Double.parseDouble(str);
                stack.push(push);
                break;
        }
    }
    if (stack.isEmpty()) {
        state = 1;
    } else {
        result = stack.peek();
        str.append(stack.pop());
    }


}

public void eval() throws Exception {
    List<String> list = new ArrayList<String>();
    //匹配运算符、括号、整数、小数,注意-和*要加\\
    Pattern p = Pattern.compile("[+\\-/\\*()]|\\d+\\.?\\d*");
    Matcher m = p.matcher(s1);
    while (m.find()) {
        list.add(m.group());
    }
    List<String> afterList = this.midToAfter(list);
    this.countHouzhui(afterList);
}

}
实验三 UI设计(二)
实验目的:
学习使用ListView

实验要求:

  1. 实现一个列表,其中显示班级学号姓名,提供添加功能,如需要删去某一项,长按该项,通过弹出菜单显示删除功能。

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    tools:context="com.example.administrator.myapplication.MainActivity"
    android:orientation="vertical"
    android:weightSum="1">
   <LinearLayout
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:orientation="horizontal"
       android:weightSum="1">
       <TextView
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:layout_marginTop="5sp"
           android:text="班级:"/>
       <EditText
           android:id="@+id/edit_class"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:layout_marginTop="5sp"
           android:layout_weight="0.10" />
   </LinearLayout>
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:weightSum="1">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5sp"
        android:text="学号:"/>
    <EditText
        android:id="@+id/edit_number"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5sp"
        android:layout_weight="0.10" />
</LinearLayout>
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:weightSum="1">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5sp"
        android:text="姓名:"/>
    <EditText
        android:id="@+id/edit_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5sp"
        android:layout_weight="0.10" />
</LinearLayout>
<Button
    android:id="@+id/btn_add"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="添加"
    />
<ListView
    android:id="@+id/list_item"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
</ListView>
**MainActivity.xml** package com.example.administrator.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.PopupMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

import static android.widget.AdapterView.*;

public class MainActivity extends AppCompatActivity {

ListView listView1;
EditText edit_class;
EditText edit_name;
EditText edit_number;
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

     listView1=(ListView)findViewById(R.id.list_item);
     edit_class=(EditText)findViewById(R.id.edit_class);
   edit_name=(EditText)findViewById(R.id.edit_name);
    edit_number=(EditText)findViewById(R.id.edit_number);
    btn=(Button)findViewById(R.id.btn_add);
    List<String> list=new ArrayList<String>();
    list.add("班级                       学号                      姓名");
    ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,list);
    listView1.setAdapter(adapter);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String name= edit_name.getText().toString();
            String Class=edit_class.getText().toString();
            String id=edit_number.getText().toString();
            ArrayAdapter temp_adp=(ArrayAdapter) listView1.getAdapter();
            temp_adp.add(Class+"                 "+id+"                "+name);
            edit_class.setText("");
            edit_name.setText("");
            edit_number.setText("");
        }
    });

    listView1.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) {
            if(l>0)
            {
                PopupMenu popup=new PopupMenu(MainActivity.this,view);
                popup.getMenuInflater().inflate(R.menu.simple_menu1,popup.getMenu());
                popup.show();
                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener(){

                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                       switch(item.getItemId()){
                           case R.id.menu1:
                               ArrayAdapter temp_adp=(ArrayAdapter)listView1.getAdapter();
                               temp_adp.remove(temp_adp.getItem(i));
                               return true;
                           default:
                               return false;
                       }
                    }
                });
            }
        }
    });
}

}

实验四 组件通信
实验目的:
熟悉和掌握Android组件间通信的方式和技巧。
实验要求:

  1. 运行课本的示例程序,理解组件通信的方式和过程
    2.设计一个主Activity和一个子Activity(Sub-Activity),使用主Activity上的按钮启动子Activity,并将子Activity的一些信息返回给主Activity,并显示在主Activity上。
    可以自己设计界面和场景,也可以使用下面提供的内容:
    主Activity界面上有一个“登录”按钮和一个用了显示信息的TextView,点击“登录”按钮后打开一个新的Activity,新Activity上面有输入用户名的控件,在用户关闭这个Activity后,将用户输入的用户名到主Activity,并显示在主Activity的TextView中。
    Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>

<android.support.constraint.ConstraintLayout xmlns:android=“http://schemas.android.com/apk/res/android
xmlns:app=“http://schemas.android.com/apk/res-auto
xmlns:tools=“http://schemas.android.com/tools
android:layout_width=“match_parent”
android:layout_height=“match_parent”
tools:context=“com.example.administrator.process_information.MainActivity”>




</android.support.constraint.ConstraintLayout>
Layout.xml

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

<android.support.constraint.ConstraintLayout xmlns:android=“http://schemas.android.com/apk/res/android
xmlns:app=“http://schemas.android.com/apk/res-auto
xmlns:tools=“http://schemas.android.com/tools
android:layout_width=“match_parent”
android:layout_height=“match_parent”
tools:context=“com.example.administrator.process_information.MainActivity”>

<EditText
    android:id="@+id/editText"
    android:layout_width="128dp"
    android:layout_height="38dp"
    android:inputType="textPersonName"
    android:text="tommy"
    tools:layout_editor_absoluteX="202dp"
    tools:layout_editor_absoluteY="118dp" />


<Button
    android:id="@+id/btn_return"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="返回"
    tools:layout_editor_absoluteY="62dp"
    tools:layout_editor_absoluteX="25dp" />
</LinearLayout>

</android.support.constraint.ConstraintLayout>

MainActivity.xml
package com.example.administrator.process_information;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
private static final int LAYOUT=1;
Button btn;
TextView username;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn= (Button) findViewById(R.id.log);
username=(TextView)findViewById(R.id.username1);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(MainActivity.this, layout.class);
startActivityForResult(intent,LAYOUT);
}
});
}
protected void onActivityResult(int requestCode,int resultCode,Intent data)
{
super.onActivityResult(requestCode,resultCode,data);
String s;
if(data == null || data.getExtras()==null || data.getExtras().getString(“name”)==null){
s = “”;
}else {
s = data.getExtras().getString(“name”);
}
username.setText(s);
}
}
layout.xml
package com.example.administrator.process_information;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class layout extends Activity {
Button btn1;
EditText edit1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
btn1=(Button) findViewById(R.id.btn_return);
edit1=(EditText) findViewById(R.id.editText);

    btn1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent result=new Intent();
            Bundle b=new Bundle();
            b.putString("name",edit1.getText().toString());
            result.putExtras(b);
            setResult(RESULT_OK,result);
            finish();
        }
    });
}

}
AndroidManifest.xml

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

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".layout"
        android:label="@string/app_name"/>
</application>
实验五 使用线程 实验目的: 熟悉和掌握Android线程的使用 实验要求: 1. 完成一个秒表,具备启停功能,正确使用工作线程完成界面刷新 2. 分析秒表的计时是否准确,原因是什么,如何保证秒表计时准确 **Activity_main.xml** package com.example.administrator.time;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.walker.exp5.R;

public class MainService extends Service {
private Thread workthread;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}

@Override
public void onCreate() {
    super.onCreate();
    workthread  = new Thread(null,backgroudWork,"workThread");
    //Log.e("ATG","onCreate");
}

@Override
public void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);
    if(!workthread.isAlive()){
        workthread.start();
    }
    // Toast.makeText(this,"onStart()",Toast.LENGTH_SHORT).show();
    //Log.e("ATG","onStartCommand");
}

// @Override
// public int onStartCommand(Intent intent, int flags, int startId) {
// if(!workthread.isAlive()){
// workthread.start();
// }
// Log.e(“ATG”,“onStartCommand”);
// return super.onStartCommand(intent, flags, startId);
//
// }

@Override
public void onDestroy() {
    //super.onDestroy();
    workthread.interrupt();
    // Log.e("ATG","onDestroy");
    //Toast.makeText(this,"onDestroy()",Toast.LENGTH_SHORT).show();
}
private Runnable backgroudWork = new Runnable() {


    @Override
    public void run() {
        LayoutInflater layoutInflater = LayoutInflater.from(MainService.this);
        View view = layoutInflater.inflate(R.layout.activity_main,null);
        TextView tv_hh = view.findViewById(R.id.hh);
        TextView tv_mm = view.findViewById(R.id.mm);
        TextView tv_ss = view.findViewById(R.id.ss);
        int h = Integer.parseInt(tv_hh.getText().toString());
        int m = Integer.parseInt(tv_mm.getText().toString());
        int s = Integer.parseInt(tv_ss.getText().toString());
        long pre_long=System.currentTimeMillis();
        while (true) {
            try {
                Thread.sleep(50);
                long temp_long=System.currentTimeMillis();
                s=s+(int)(temp_long/10-pre_long/10);
                pre_long=temp_long;
                        while(s>=100){
                            s=s-100;
                            m=m+1;
                        }
                if (m>= 60) {
                    h++;
                    m = m-60;   //秒钟等于60,分钟加1,秒钟置0
                    if (h == 60) {
                        h = 0;
                    }
                }
                MainActivity.UpadteGUI(h,m,s);
            } catch (Exception e) {
                e.printStackTrace();
                break;
            }
        }
    }
};

}
MainActivity
package com.example.administrator.time;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.walker.exp5.R;

import java.text.NumberFormat;

public class MainActivity extends AppCompatActivity {
public Button bt1;
public Button bt2;
public Button bt3;
public static TextView hh;
public static TextView mm;
public static TextView ss;
public static int h;
public static int m;
public static int s;
private static Handler handler=new Handler();

public static void UpadteGUI(int hh, int mm, int ss) {
    h = hh;
    m = mm;
    s = ss;
    handler.post(RefreshLable);
}
private static Runnable RefreshLable = new Runnable() {
    @Override
    public void run() {
        NumberFormat nf = NumberFormat.getInstance();
        nf.setMinimumIntegerDigits(2);
        hh.setText(nf.format(h));
        mm.setText(nf.format(m));
        ss.setText(nf.format(s));
    }
};
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    hh=(TextView)findViewById(R.id.hh);
    mm=(TextView)findViewById(R.id.mm);
    ss=(TextView)findViewById(R.id.ss);

    bt1=(Button)findViewById(R.id.clear);
    bt2=(Button)findViewById(R.id.start);
    bt3=(Button)findViewById(R.id.stop);

    final Intent intent = new Intent(this, MainService.class);


    bt1.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view) {
            hh.setText("00");
            mm.setText("00");
            ss.setText("00");
            stopService(intent);
            Toast.makeText(MainActivity.this,"清零",Toast.LENGTH_SHORT).show();
        }
    });
    bt2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           String s = ss.getText().toString();
            ss.setText(s);
            startService(intent);
        }
    });
    bt3.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            stopService(intent);
            Toast.makeText(MainActivity.this,"暂停计时",Toast.LENGTH_SHORT).show();
        }
    });
}

}
MainService
package com.example.administrator.time;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.walker.exp5.R;

public class MainService extends Service {
private Thread workthread;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}

@Override
public void onCreate() {
    super.onCreate();
    workthread  = new Thread(null,backgroudWork,"workThread");
    //Log.e("ATG","onCreate");
}

@Override
public void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);
    if(!workthread.isAlive()){
        workthread.start();
    }
    // Toast.makeText(this,"onStart()",Toast.LENGTH_SHORT).show();
    //Log.e("ATG","onStartCommand");
}

// @Override
// public int onStartCommand(Intent intent, int flags, int startId) {
// if(!workthread.isAlive()){
// workthread.start();
// }
// Log.e(“ATG”,“onStartCommand”);
// return super.onStartCommand(intent, flags, startId);
//
// }

@Override
public void onDestroy() {
    //super.onDestroy();
    workthread.interrupt();
    // Log.e("ATG","onDestroy");
    //Toast.makeText(this,"onDestroy()",Toast.LENGTH_SHORT).show();
}
private Runnable backgroudWork = new Runnable() {


    @Override
    public void run() {
        LayoutInflater layoutInflater = LayoutInflater.from(MainService.this);
        View view = layoutInflater.inflate(R.layout.activity_main,null);
        TextView tv_hh = view.findViewById(R.id.hh);
        TextView tv_mm = view.findViewById(R.id.mm);
        TextView tv_ss = view.findViewById(R.id.ss);
        int h = Integer.parseInt(tv_hh.getText().toString());
        int m = Integer.parseInt(tv_mm.getText().toString());
        int s = Integer.parseInt(tv_ss.getText().toString());
        long pre_long=System.currentTimeMillis();
        while (true) {
            try {
                Thread.sleep(50);
                long temp_long=System.currentTimeMillis();
                s=s+(int)(temp_long/10-pre_long/10);
                pre_long=temp_long;
                        while(s>=100){
                            s=s-100;
                            m=m+1;
                        }
                if (m>= 60) {
                    h++;
                    m = m-60;   //秒钟等于60,分钟加1,秒钟置0
                    if (h == 60) {
                        h = 0;
                    }
                }
                MainActivity.UpadteGUI(h,m,s);
            } catch (Exception e) {
                e.printStackTrace();
                break;
            }
        }
    }
};

}
AndriodManifest.xml

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

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name="com.example.administrator.time.MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />

        </intent-filter>
    </activity>
    <service android:name="com.example.administrator.time.MainService">
    </service>
</application>
实验六 数据存储和访问 实验目的: 分别使用sqlite3工具和Android代码的方式建立SQLite数据库。在完成建立数据库的工作后,编程实现基本的数据库操作功能,包括数据的添加、删除和更新,

实验要求:

  1. 创建一个学生管理的应用,基本信息包含学生姓名,班级,学号。采用数据库存储这些信息。
  2. 应用应该至少包含信息录入和删除功能。
  3. 数据显示考虑采用ListView。
    实验报告:
  4. 按要求完成实验
  5. 将实验各步骤的结果截图,粘贴入实验报告
  6. 将实验报告和程序打包提交到作业系统
    Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>


<LinearLayout
    android:layout_width="368dp"
    android:layout_height="50dp"
    android:orientation="horizontal">
<TextView
    android:id="@+id/textView"
    android:layout_width="50dp"
    android:layout_height="29dp"
    android:text="班级:" />
    <EditText
        android:id="@+id/editText"
        android:layout_width="150dp"
        android:layout_height="40dp" />
</LinearLayout>

android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
    android:layout_width="80dp"
    android:layout_height="50dp"
    android:id="@+id/btn1"
    android:text="添加"/>
</ListView>
**MainActivity** package com.example.administrator.myapplication3;

import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupMenu;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends Activity {
private DBAdapter dbAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button btnAdd=(Button)findViewById(R.id.btn1);
final ListView lv1=(ListView)findViewById(R.id.listView);
final EditText addClassEditText = (EditText) findViewById(R.id.editText);
final EditText addSnoEditText = (EditText) findViewById(R.id.editText1);
final EditText addSnameEditText = (EditText) findViewById(R.id.editText2);

    dbAdapter=new DBAdapter(this);
    dbAdapter.open();
    List<String> list = new ArrayList<String>();
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
    lv1.setAdapter(adapter);

    btnAdd.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v){
            Student ss=new Student();
            String sno=addSnoEditText.getText().toString();
            String sname=addSnameEditText.getText().toString();
            String classes=addClassEditText.getText().toString();
            ArrayAdapter temp_adp=(ArrayAdapter)lv1.getAdapter();
            temp_adp.add(dbAdapter.insert(ss) + "  " + classes  + "  " + sno + "   " + sname);
        }
    });
    lv1.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener(){
        @TargetApi(Build.VERSION_CODES.HONEYCOMB)
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view,final int selected_position, long id){
            if(id>=0){
                PopupMenu popup = new PopupMenu(MainActivity.this, view);
                popup.getMenuInflater().inflate(R.menu.menu_main, popup.getMenu());
                popup.show();//当长按时显示菜单
                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    public boolean onMenuItemClick(MenuItem item) {
                        switch (item.getItemId()) {
                            case R.id.menu_main:
                                ArrayAdapter temp_adp = (ArrayAdapter) lv1.getAdapter();
                                temp_adp.remove(temp_adp.getItem(selected_position));//删除选择的信息
                                return true;
                            default:
                                return false;
                        }
                    }
                });
            }
            return true;
        }

    });
}

}
DBAdapter
package com.example.administrator.myapplication3;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

/**

  • Created by Administrator on 2018/10/30.
    */

public class DBAdapter {
private final Context context;
private SQLiteDatabase db;
private DBHelper dbHelper;
private static final String DB_NAME=“student.db”;
private static final String DB_TABLE=“studentinfo”;
private static final int DB_VERSION=1;
private final static String KEY_ID=“id”;
private final static String KEY_SNO=“sno”;
private final static String KEY_SNAME=“sname”;
private final static String KEY_CLASSES=“classes”;

public DBAdapter(Context _context){
    context=_context;
}

public void open()throws SQLiteException{
    dbHelper=new DBHelper(context,DB_NAME,null,DB_VERSION);
    try{
        db=dbHelper.getWritableDatabase();
    }
    catch(SQLiteException ex){
        db=dbHelper.getReadableDatabase();
    }
}
public long insert(Student s)
{
    ContentValues cv=new ContentValues();
    cv.put(KEY_SNO,s.getSno());
    cv.put(KEY_SNAME,s.getSname());
    cv.put(KEY_CLASSES,s.getClasses());
    return db.insert(DB_TABLE,null,cv);
}
public Student[] converToStudent (Cursor c){
    int resultsCount=c.getCount();
    if(resultsCount==0||!c.moveToFirst())
    {
        return null;
    }
    Student[]stu =new Student[resultsCount];
    for(int i=0;i<stu.length;i++)
    {
        stu[i]=new Student();
        String sno=c.getString(c.getColumnIndex("sno"));
        String sname=c.getString(c.getColumnIndex("sname"));
        String classes=c.getString(c.getColumnIndex("classes"));
        stu[i].id=c.getInt(0);
        stu[i].setSno(sno);
        stu[i].setSname(sname);
        stu[i].setClasses(classes);
        c.moveToNext();
    }
    return stu;
}


private   static class DBHelper extends SQLiteOpenHelper {

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

    private static final String SQL = "CREATE TABLE studentinfo ("
            + "id INTEGER PRIMARY KEY AUTOINCREMENT,"
            + "sno TEXT DEFAULT NONE,"
            + "sname TEXT DEFAULT NONE,"
            + "classes TEXT DEFAULT NONE"
            + ")";

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(SQL);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS" + DB_TABLE);
        onCreate(db);

    }
}
public void close() {
    if (db != null) {
        db.close();
        db = null;
    }
}

}
student
package com.example.administrator.myapplication3;

import java.io.Serializable;
/**

  • Created by Administrator on 2018/10/30.
    */

public class Student implements Serializable{
public int id=-1;
public String sno;
public String sname;
public String classes;
public Integer getID(){
return id;
}
public void setID(Integer id){
this.id=id;
}

public String getSno(){
    return sno;
}
public void setSno(String sno){
    this.sno=sno;
}
public String getSname(){
    return sname;
}
public void setSname(String sname){
    this.sname=sname;
}
public String getClasses(){
    return classes;
}
public void setClasses(String classes){
    this.classes=classes;
}
@Override
public String toString(){
    return id + sno + sname + classes;
}

}
AndriodMainfest.xml

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

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值