Andriod所有实验程序代码

Andriod所有实验程序代码

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

实验要求:

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


 







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("输入格式错误!");
    }
}

/**
 * 中缀表达式转后缀表达式
 * 

* 遍历中缀的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 midToAfter(List midList) throws EmptyStackException { List afterList = new ArrayList(); Stack stack = new Stack(); 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 list) { str = new StringBuilder(""); state = 0; result = 0; Stack stack = new Stack(); 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 list = new ArrayList(); //匹配运算符、括号、整数、小数,注意-和*要加\\ Pattern p = Pattern.compile("[+\\-/\\*()]|\\d+\\.?\\d*"); Matcher m = p.matcher(s1); while (m.find()) { list.add(m.group()); } List afterList = this.midToAfter(list); this.countHouzhui(afterList); }

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

实验要求:

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

activity_main.xml


   
       
       
   

    
    


    
    

**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 list=new ArrayList();
    list.add("班级                       学号                      姓名");
    ArrayAdapter adapter=new ArrayAdapter(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

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”>





Layout.xml

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”>




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


    
        
            
            
        
    
    

实验五 使用线程 实验目的: 熟悉和掌握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


    
        
            

            

        
    
    
    

实验六 数据存储和访问 实验目的: 分别使用sqlite3工具和Android代码的方式建立SQLite数据库。在完成建立数据库的工作后,编程实现基本的数据库操作功能,包括数据的添加、删除和更新,

实验要求:

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




    


android:layout_width="match_parent"
android:layout_height="match_parent">

**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 list = new ArrayList();
    ArrayAdapter adapter = new ArrayAdapter(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

}
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


    
        
            

            
        
    

你可能感兴趣的:(Andriod所有实验程序代码)