ArrayList<ArrayList<Integer>>的add函数 10C

ArrayList> resultsList = new ArrayList>();
ArrayList path=new ArrayList();
resultsList.add(new ArrayList(path));
//resultsList.add(path);

ArrayList path=new ArrayList();
path已经有数据了,朝resultsList添加的时候,为什么还需要实例化path,而不是直接add(path);这样输出resultsList是空的

7个回答

是可以的 但是按你的写法 你打印的时候 得这样:
ArrayList resultsList = new ArrayList();
ArrayList path=new ArrayList();
path.add(2);
resultsList.add(path);
System.out.println(((ArrayList)resultsList.get(0)).get(0));

这个问题过去一年多了,我也是今天才遇到这个问题,查找资料的时候百度到这个问题,我已经解决,现在写下来,为后来者铺路!
我的问题来源于leetcode 题,使用回溯法,代码中有一段和楼主遇到的问题一模一样,最后竟然输出为空。
贴一下我的代码

class Solution {

    List<List<Integer>> list = new ArrayList<List<Integer>>();
    boolean[] used;
    public List<List<Integer>> permute(int[] nums) {
        if(nums == null || nums.length == 0){
            return list;
        }
        used = new boolean[nums.length];
        ArrayList<Integer> p = new ArrayList<Integer>();
        generatePermutation(nums,0,p);
        return list;
    }
    //p中保存有index个元素的全排列。这个方法的目的是向这个排列的末尾添加第index+1个元素,使p成为有index+1个元素的全排列
    public void generatePermutation(int[] nums,int index,ArrayList<Integer> p){
        if(index == nums.length ){
            ArrayList<Integer> tem = new ArrayList<>();
            tem.addAll(p);
            list.add(tem);
            return;
        }
        for(int i = 0 ; i < nums.length ; i++){
            if(!used[i]){
                p.add(nums[i]);
                used[i] = true;
                generatePermutation(nums,index+1,p);
                p.remove(p.size()-1);
                used[i] = false;
            }
        }
        return;
    }
}

在这个部分:

        if(index == nums.length ){
            ArrayList<Integer> tem = new ArrayList<>();
            tem.addAll(p);
            list.add(tem);
            return;
        }

改为

        if(index == nums.length ){
            list.add(p);
            return;
        }

输出就为空了。原因是:我们add(p),也就是楼主这里的add(path),我们这是将path的地址给add进去了,并没有将真正的列表add进热resultlist,这样导致的结果就是 当你的path中的值改变后,resultlist中也随之改变,楼主不出意外的话,你最后的path变为空了,所以最后输出全空。贴一段简单代码自己运行感受下:

        ArrayList<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        List<List<Integer>>  res = new ArrayList<>();
        System.out.println(res);
        res.add(list);
        list.add(50);
        res.add(list);
        System.out.println(res+"发现两个元素竟然一样");
DW1202
DW1202 谢谢,我刷题时也遇到了,
10 个月之前 回复

可以直接add的,输出失控是什么意思?是指内容为空?还是指什么为空?

对于数组本身,new后确实实例化了,它的length等属性也可以使用。但是对于数组成员来说,如果需要实例化,还需要分别new。

有问题 可以直接私信我

ArrayList里存放的是索引,,如果,直接add(path),,相当于添加了多个重复的path对象。

所以,,每次添加都需要 new创建新的对象。

Small_Mouse0
小鼠标丶 这样输出resultsList是空的,,,你没添加数据,,只开辟了内存
2 年多之前 回复

如果,直接add(path),这样好像不行,
应该addAll(path);

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
Integer 对象在函数之间的引用传递起不到全局的作用
``` //实现排序二叉树的第k个节点的查找 TreeNode target = KthNode(p,2); public static TreeNode KthNode(TreeNode pRoot, int k) { if(pRoot == null || k < 1 ){ return null; } //ArrayList<Integer> list = new ArrayList<Integer>(); //list.add(k); return KthNode(pRoot,new Integer(k)); } public static TreeNode KthNode(TreeNode p,Integer K){ TreeNode target = null; if(p.left != null){ target = KthNode(p.left,K); } if(target == null){ K--; if(K == 0){ target = p; } } if(target == null && p.right != null){ target = KthNode(p.right,K); } return target; } ``` 本意是使用Integer对象的引用再函数间传递,使得函数内的修改可以反映到上一层,但是现在下层函数的修改却不能体现到上一层函数,而使用list对象就可以
页面置换算法的OPT算法的具体代码解释看不懂,主要问题是 在超出list容量之后的部分,以及LRU算法及其调用的MyStack栈的具体解释?????
``` public class OPT { private final int capacity = 3;// 构造一个初始容量为3的空列表 private int[] index = new int[2];//申请数组下标的容量为2 private List<Integer> list = new ArrayList<Integer>(capacity);//定义一个有界阻塞容器capacity即队列 public OPT(int[] arr) { for (int i = 0; i < arr.length; i++) { if (list.size() < capacity) { // 小于list初始容量 if (!list.contains(arr[i])) { // list没有该页面,将其添加进list尾部 list.add(arr[i]);//列表+1 } else { continue; } } else {// 超出list容量 index[0] = 100; index[1] = 101; if (!list.contains(arr[i])) { // 下一个页面如果不在list中 int a = 0; for (int j = i; j < arr.length; j++) { if (list.contains(arr[j])) { // arr[j]这个页面会在测试数据中会出现较早 if (index[0] != list.indexOf(arr[j])) { //indexOf()的用法:查找arr[j]中,第一次出现指定字符串的位置。 位置不是下标为0 index[a++] = list.indexOf(arr[j]);// 返回此列表中首次出现的指定元素的索引 if (a == 2) { break; } } } } list.set(noExist(), arr[i]);// 置换掉永不使用的,或许在最长时间内不再访问的页面 } else { // 下一个页面在list中 continue;//列表保持不变 } } traverse();//调用traverse函数 } System.out.println("访问页面需从外存调入的次数为:"+(num-1));//计算访问页面需要从外存调入的次数 System.out.println("缺页率为:"+(1-(float)(num-1)/arr.length));//计算缺页率 } ``` [https://blog.csdn.net/AdvancingStone/article/details/79110586]( "这是我的参考代码,我需要的帮助是具体解释OPT和LRU及其调用的MyStack栈的每行代码的具体注释")
java 子线程结束结束 内部子线程也结束 具体看代码注释
import java.util.ArrayList; import org.junit.Test; /** * 代码很简单的 就是起了一个线程 然后在一个list里面放了1000个数字 然后打印以下 * * 但是test方法 用junit起的 不能完全打印 而main可以 * * 最终是想要使得这个test方法能和main的效果一样 * */ public class TestSub { @Test public void test() { /** * 此处是在junit测试下面执行的线程 但是list里面的值不能被完全打印出来 * 我猜想这个方法是在一个子进程里面进行的 而里面又有一个子线程 但是最外层的子线程(test方法)一结束 里面的子线程也全部结束 */ new Thread(new Runnable() { @Override public void run() { long start = System.currentTimeMillis(); ArrayList<Integer> list = new ArrayList<Integer>(); for (int i = 0; i < 1000; i++) { list.add(i); } for (Integer value : list) { System.out.println("list size : " + list.size() + " current value : " + value); } long end = System.currentTimeMillis(); System.out.println("takes time :" + (end - start)); } }).start(); System.out.println("线程执行结束 test方法执行完毕"); } /** * main函数的线程 与 上面测试方法的子线程不同 它执行完方法后 里面的子线程仍旧会执行完毕 * 如何让上面的test方法与main函数执行的结果一样 * * @param args */ public static void main(String[] args) { new Thread(new Runnable() { @Override public void run() { long start = System.currentTimeMillis(); ArrayList<Integer> list = new ArrayList<Integer>(); for (int i = 0; i < 1000; i++) { list.add(i); } for (Integer value : list) { System.out.println("list size : " + list.size() + " current value : " + value); } long end = System.currentTimeMillis(); System.out.println("takes time :" + (end - start)); } }).start(); System.out.println("主线程执行结束 main方法执行完毕"); } }
Android中用线程访问网络之后得到的数据怎么在其他函数(非UI)中使用?
只贴出了一部分代码,稍微解释一下,即在类中的onCreateView函数中开了一个线程,用来访问网络爬数据,然后生成了5个list,现在想要在getDateFromURL方法中使用这几个list,如何实现? 尝试了使用handler给全局变量赋值,但是getDateFromURL方法中的list都为空, 本人菜鸟,刚学一个月,很多东西都是跌跌撞撞摸索的,求大神指点啊。这地方卡了好久了。目前能想到的思路就两个:1,通过全局变量过度;2,通过数据库来过渡。第二个还没尝试,不知道是否可行。 public class DeckviewFragment extends Fragment { public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mDefaultThumbnail = BitmapFactory.decodeResource(getResources(), R.drawable.default_thumbnail); mDefaultHeaderIcon = getResources().getDrawable(R.drawable.banana); view1 = inflater.inflate(R.layout.deckview, container, false); mDeckView = (DeckView) view1.findViewById(R.id.deckview); count = (TextView) mDeckView.findViewById(R.id.count_num); comment = (TextView) mDeckView.findViewById(R.id.comment_num); new Thread(networkTask).start(); ........ } Runnable networkTask=new Runnable() { @Override public void run() { try { StringBuffer buffer=new StringBuffer(); ArrayList<String> mcountlist=new ArrayList<String>(); ArrayList<String> mcomlist=new ArrayList<String>(); ArrayList<String> mtitlelist=new ArrayList<String >(); ArrayList<String> mpiclist=new ArrayList<String>(); ArrayList<String> mhreflist=new ArrayList<String >(); Document doc = Jsoup.connect("http://www.-------").get(); Elements elements = doc.getElementsByClass("mainer"); for (Element e:elements){ Elements counts=e.getElementsByClass("title");// if(counts.size()!=3){ for (Element count : counts) { buffer.append(count.toString()); mhreflist.add(count.attr("href")); } } Elements pics =e.getElementsByClass("preview"); for(Element pic:pics){ mpiclist.add(pic.attr("src")); } } Pattern p1=Pattern.compile("点击数\\:\\s(.*?)\\s\\/"); Matcher m1=p1.matcher(buffer); while (m1.find()){ mcountlist.add(m1.group(1));//group(1)去掉了:和/ } Pattern p2=Pattern.compile("评论数\\:\\s(.*?)\""); Matcher m2=p2.matcher(buffer); while (m2.find()){ mcomlist.add(m2.group(1)); } Pattern p3=Pattern.compile("标题\\:\\s(.*?)\\r"); Matcher m3=p3.matcher(buffer); while (m3.find()){ mtitlelist.add(m3.group(1)); } } catch (IOException e) { e.printStackTrace(); } } }; void getDateFromURL(Integer num,Integer key) { if (mEntries == null) { mEntries = new ArrayList<>(); for (int i=0; i < num; i++) { Datum datum = new Datum(); datum.count_num=mcountlist.get(i); datum.comment_num=mcomlist.get(i); datum.headerTitle =mtitlelist.get(i); datum.link =mpiclist.get(i); mEntries.add(datum); } } }
java add函数,添加进去全部变成最后一组数据
String[] turn1 = idList.split(","); String[] turn2 = labelList.split(","); Attribute attribute = new Attribute(); List<Attribute> Temp = new ArrayList<Attribute>(); for(int i=0;i<turn1.length;i++){ long getId; getId = Integer.parseInt(turn1[i]); attribute.setId(getId); attribute.setLabel(turn2[i]); Temp.add(attribute); } for(int i=0;i<3;i++) System.out.println(Temp.get(i)); 就是我现在turn1.length只有3组数据,Add进去Temp之后应该是有三组不同的数据才对。但是现在我Add进去之后虽然是有三组对象,但是里面的数据竟然全部是最后一组的数据。 我现在debug模式下看到三次attribute的数据都是不同的,现在是每循环一次当前的attribute就会把Temp里面的前一组数据给覆盖掉,这是为什么? 输出数据 isPK=false,oid=0,id=1354,name=<null>,label=额定电压 isPK=false,oid=0,id=1354,name=<null>,label=额定电压 isPK=false,oid=0,id=1354,name=<null>,label=额定电压
JAVA初学者练习题,求找错
``` package report5; import java.util.ArrayList; public class Student { int id; String name; ArrayList<Integer> quizResult =new ArrayList<Integer>(10) ; public Student() {} public Student( int id){ this.id=id; } public Student(int id, String name){ this.id=id; this.name=name; } public void setID(int id){ this.id=id; } public void setName(String name){ this.name=name; } void setAllResult(int a, int b, int c, int d, int e){ quizResult.add(a); quizResult.add(b); quizResult.add(c); quizResult.add(d); quizResult.add(e); } void setUpdate(int index, int value){ quizResult.set(index,value ); } int sum() { int sum=0; for(int i:quizResult) sum+=quizResult.get(i) ; return sum; } void print(){ System.out.printf("%d %s ",id,name); for(int i=0; i<quizResult.size() ;i++) System.out.printf("%d ",quizResult.get(i) ) ; System.out.printf("(Total %d,Average %d",sum(),sum()/5); } } ``` 测试class ``` package report5; public class test { static void method1() { Student aaa=new Student(); Student bbb=new Student(234567); Student ccc=new Student(345678,"hongg"); aaa.setID(123456); aaa.setName("chengwuql"); aaa.setAllResult(7, 9, 7, 9, 6); bbb.setName("kang"); bbb.setAllResult(7, 5, 1, 8, 8); ccc.setAllResult(8, 9, 8, 4, 8); aaa.print(); bbb.print(); ccc.print(); } public static void main(String[] args) { method1(); } } ``` 题目是 使用 给定的部分代码 然后完成。。。 求 aaa bbb ccc 三人五次的成绩 和平均成绩 考察 重载的构造函数 输出结果 ``` 123456 chengwuql 7 9 7 Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 7 out-of-bounds for length 5 at java.base/jdk.internal.util.Preconditions.outOfBounds(Unknown Source) at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Unknown Source) at java.base/jdk.internal.util.Preconditions.checkIndex(Unknown Source) at java.base/java.util.Objects.checkIndex(Unknown Source) at java.base/java.util.ArrayList.get(Unknown Source) at report5.Student.sum(Student.java:47) at report5.Student.print(Student.java:54) at report5.test.method1(test.java:17) at report5.test.main(test.java:24) ``` 本人不太会用arraylist ,应该是这里出问题了,谢谢
小白问题,调用方法的求和问题
想实现分日期累加求和并添加到excel中, 可是传到excel中的数据把每一天的数据都打出来了。帮忙看一下问题出在哪了?我感觉我这个写法,循环内每次执行存的都是一个新的数组里,循环到下一次就跟这次的没关系了 public void processSum(XSSFRow inputRow, XSSFRow outputRow) throws IOException { double sum = 0; double a = 0; String cellValue = ""; SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd"); Date date = inputRow.getCell( Integer.parseInt(source.getProperty("日期列")) - 1) .getDateCellValue(); cellValue = formatter.format(date); ArrayList<String> date1 = new ArrayList<String>(); ArrayList<Double> value1 = new ArrayList<Double>(); ArrayList<String> date2 = new ArrayList<String>(); ArrayList<Double> value2 = new ArrayList<Double>(); value1.add(inputRow.getCell( Integer.parseInt(source.getProperty("求和列")) - 1) .getNumericCellValue()); date1.add(cellValue); for (int c = 0; c < date1.size(); c++) { try { if (date1.get(c).equals(date1.get(c + 1))) { a = value1.get(c); sum = a + sum; } else { a = value1.get(c); sum = a + sum; date2.add(date1.get(c)); value2.add(sum); sum = 0.0; } } catch (Exception e) { a = value1.get(c); sum = a + sum; date2.add(date1.get(c)); value2.add(sum); } } for (int k = 0; k < date2.size(); k++) { outputRow.createCell(14).setCellValue(value2.get(k)); outputRow.createCell(3).setCellValue(date2.get(k)); outputRow.createCell(4).setCellValue(date2.get(k)); } } 主函数里的方法,调用的processSum求和方法 for (i = o; i < lastnum; i++) { XSSFRow readrow = readsheet.getRow(i);// 获取输入行 Process p = new ProcessRow(); if (p.panduan2(readrow)) { XSSFSheet sheet = sc.getSheetAt(0); XSSFRow outputrow = sheet.createRow(j++); p.processSum(readrow, outputrow); } }
小白求教,分日期求和问题
想实现分日期累加求和并添加到excel中, 可是传到excel中的数据把每一天的数据都打出来了。帮忙看一下问题出在哪了? double sum = 0; double a = 0; String cellValue = ""; SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd"); Date date = inputRow.getCell( Integer.parseInt(source.getProperty("日期列")) - 1) .getDateCellValue(); cellValue = formatter.format(date); ArrayList<String> date1 = new ArrayList<String>(); ArrayList<Double> value1 = new ArrayList<Double>(); ArrayList<String> date2 = new ArrayList<String>(); ArrayList<Double> value2 = new ArrayList<Double>(); value1.add(inputRow.getCell( Integer.parseInt(source.getProperty("求和列")) - 1) .getNumericCellValue()); date1.add(cellValue); for (int c = 0; c < date1.size(); c++) { try { if (date1.get(c).equals(date1.get(c + 1))) { a = value1.get(c); sum = a + sum; } else { a = value1.get(c); sum = a + sum; date2.add(date1.get(c)); value2.add(sum); sum = 0.0; } } catch (Exception e) { a = value1.get(c); sum = a + sum; date2.add(date1.get(c)); value2.add(sum); } } for (int k = 0; k < date2.size(); k++) { outputRow.createCell(14).setCellValue(value2.get(k)); outputRow.createCell(3).setCellValue(date2.get(k)); outputRow.createCell(4).setCellValue(date2.get(k)); } } 主函数里的方法,调用的processSum求和方法 for (i = o; i < lastnum; i++) { XSSFRow readrow = readsheet.getRow(i);// 获取输入行 Process p = new ProcessRow(); if (p.panduan2(readrow)) { XSSFSheet sheet = sc.getSheetAt(0); XSSFRow outputrow = sheet.createRow(j++); p.processSum(readrow, outputrow); } }
【小白Java问题】为什么这个while循环达到条件了却终止不了?
``` package CityDistance; import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; public class CityDistance { private ArrayList<String> city = new ArrayList<String>(); private int answer = 0; HashMap<String, Integer> distance = new HashMap<String, Integer>(); public void input() { Scanner in = new Scanner(System.in); String temp = null; while ((temp = in.next()) != "###") { city.add(temp); } int number = city.size(); for ( int i = 0; i < number; i++ ) { for ( int j = 0; j < number; j++ ) { String key = "" + city.get(i) + city.get(j); distance.put(key, in.nextInt()); } } in.close(); } public int FindDistance(String A, String B) { String str = A + B; answer = distance.get(str); System.out.println(answer); return answer; } public static void main(String[] args) { Scanner in = new Scanner(System.in); CityDistance cd = new CityDistance(); cd.input(); cd.FindDistance(in.next(), in.next()); in.close(); } } ``` 输入如下: aaa bbb ccc ### 0 1 2 1 0 3 2 3 0 aaa bbb input 函数里的第一个 while ,已经设定好了遇到 "###" 的输入就停止往 city 里加东西,但调试时发现 while 并没有停止,反而把后面的0、1、2都添到 city 里去了…… ![图片说明](https://img-ask.csdn.net/upload/201511/05/1446738161_940952.jpg) 跪求大神解答!
关于Java的走迷宫问题
题目是这样的: 用户输入一个值,生成一个n*n的矩阵,然后每个符号之间用空格隔开,要求从A到B,如果当前位置的坐标是“+”那么下一个坐标则必须为“-”,找出最短的路径的步数 我的代码是把所有的情况写出来,但是出错了,请各位大神看看哪里有问题 import java.util.ArrayList; import java.util.Scanner; public class Main { //矩阵的大小 static int n; //用于记录是否走到了终点,true表示到了,false表示没有到,默认false static boolean flag = false; //用于存放所有的结果 static ArrayList<Integer> list = new ArrayList<Integer>(); public static void main(String[] args) { Scanner sc = new Scanner(System.in); n = sc.nextInt(); sc.nextLine(); String[][] map = Produce(); //测试代码 for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ System.out.print(map[i][j]); } System.out.println(); } //得到"A"的坐标,"B"的坐标 int[] a = Local(map, "A"); int[] b = Local(map, "B"); //测试坐标是否正确 System.out.println(a[0] + " " + a[1]); System.out.println(b[0] + " " + b[1]); //开始移动 Move(map, a, b, 0); System.out.println("========================="); for(int i = 0; i < list.size(); i++){ System.out.println(list.get(i)); } System.out.println("end!"); } private static void Move(String[][] m, int[] a, int[] b, int s) { //用于记录走过的步数 int sum = s; String[][] map = m; //表示当前坐标 int[] local = a; //表示终点坐标 int[] end = b; MoveUp(map, local, end, sum); System.out.println(flag); //判断上一步是否到达了终点 if(flag){ //加入List集合,然后初始化,接着其他方案 list.add(sum+1); flag = false; } //重新赋值 sum = s; map = m; local = a; end = b; MoveRight(map, local, end, sum); System.out.println(flag); if(flag){ //加入List集合,然后初始化,接着其他方案 list.add(sum+1); flag = false; } //重新赋值 sum = s; map = m; local = a; end = b; MoveDown(map, local, end, sum); System.out.println(flag); if(flag){ //加入List集合,然后初始化,接着其他方案 list.add(sum+1); flag = false; } //重新赋值 sum = s; map = m; local = a; end = b; MoveLeft(map, local, end, sum); System.out.println(flag); if(flag){ //加入List集合,然后初始化,接着其他方案 list.add(sum+1); flag = false; } } private static void MoveLeft(String[][] map, int[] local, int[] end, int sum) { // //重新定义,用于保护现场,避免下一次走错 // String[][] map = m; // int[] local = a; // int[] end = b; // int sum = s; //首先判断当前的坐标能不能向左移动 if(local[1] != 0){ //判断是否到了终点 if((local[0] == end[0]) && (local[1]-1 == end[1])){ //设置到达了终点 flag = true; return; } else{ if(map[local[0]][local[1]].equals("A")){ //把当前位置置为空,避免下一次重复走 map[local[0]][local[1]] = " "; //改变坐标 local[1]--; sum++;//步数加1 //调用Move函数,接着往下走 Move(map, local, end, sum); } else if(map[local[0]][local[1]].equals("+") && map[local[0]][local[1]-1].equals("-")){ //把当前位置置为空,避免下一次重复走 map[local[0]][local[1]] = " "; //改变坐标 local[1]--; sum++;//步数加1 //调用Move函数,接着往下走 Move(map, local, end, sum); } else if(map[local[0]][local[1]].equals("-") && map[local[0]][local[1]-1].equals("+")){ //把当前位置置为空,避免下一次重复走 map[local[0]][local[1]] = " "; //改变坐标 local[1]--; sum++;//步数加1 //调用Move函数,接着往下走 Move(map, local, end, sum); } } } } private static void MoveDown(String[][] map, int[] local, int[] end, int sum) { // //重新定义,用于保护现场,避免下一次走错 // String[][] map = m; // int[] local = a; // int[] end = b; // int sum = s; //首先判断当前的坐标能不能向下移动 if(local[0] != n-1){ //判断是否到了终点 if((local[0]+1 == end[0]) && (local[1] == end[1])){ //设置到达了终点 flag = true; return; } else{ if(map[local[0]][local[1]].equals("A")){ //把当前位置置为空,避免下一次重复走 map[local[0]][local[1]] = " "; //改变坐标 local[0]++; sum++;//步数加1 //调用Move函数,接着往下走 Move(map, local, end, sum); } else if(map[local[0]][local[1]].equals("+") && map[local[0]+1][local[1]].equals("-")){ //把当前位置置为空,避免下一次重复走 map[local[0]][local[1]] = " "; //改变坐标 local[0]++; sum++;//步数加1 //调用Move函数,接着往下走 Move(map, local, end, sum); } else if(map[local[0]][local[1]].equals("-") && map[local[0]+1][local[1]].equals("+")){ //把当前位置置为空,避免下一次重复走 map[local[0]][local[1]] = " "; //改变坐标 local[0]++; sum++;//步数加1 //调用Move函数,接着往下走 Move(map, local, end, sum); } } } } private static void MoveRight(String[][] map, int[] local, int[] end, int sum) { // //重新定义,用于保护现场,避免下一次走错 // String[][] map = m; // int[] local = a; // int[] end = b; // int sum = s; //首先判断当前的坐标能不能向右移动 if(local[1] != n-1){ //判断是否到了终点 if((local[0] == end[0]) && (local[1]+1 == end[1])){ //设置到达了终点 flag = true; return; } else{ if(map[local[0]][local[1]].equals("A")){ map[local[0]][local[1]] = " "; //改变坐标 local[1]++; sum++;//步数加1 //调用Move函数,接着往下走 Move(map, local, end, sum); } else if(map[local[0]][local[1]].equals("+") && map[local[0]][local[1]+1].equals("-")){ //把当前位置置为空,避免下一次重复走 map[local[0]][local[1]] = " "; //改变坐标 local[1]++; sum++;//步数加1 //调用Move函数,接着往下走 Move(map, local, end, sum); } else if(map[local[0]][local[1]].equals("-") && map[local[0]][local[1]+1].equals("+")){ //把当前位置置为空,避免下一次重复走 map[local[0]][local[1]] = " "; //改变坐标 local[1]++; sum++;//步数加1 //调用Move函数,接着往下走 Move(map, local, end, sum); } } } } private static void MoveUp(String[][] map, int[] local, int[] end, int sum) { // //重新定义,用于保护现场,避免下一次走错 // String[][] map = m; // int[] local = a; // int[] end = b; // int sum = s; //首先判断当前的坐标能不能向上移动 if(local[0] != 0){ //判断是否到了终点 if((local[0]-1 == end[0]) && (local[1] == end[1])){ //设置到达了终点 flag = true; return; } else{ if(map[local[0]][local[1]].equals("A")){ //把当前位置置为空,避免下一次重复走 map[local[0]][local[1]] = " "; //改变坐标 local[0]--; sum++;//步数加1 //调用Move函数,接着往下走 Move(map, local, end, sum); } else if(map[local[0]][local[1]].equals("+") && map[local[0]-1][local[1]].equals("-")){ //把当前位置置为空,避免下一次重复走 map[local[0]][local[1]] = " "; //改变坐标 local[0]--; sum++;//步数加1 //调用Move函数,接着往下走 Move(map, local, end, sum); } else if(map[local[0]][local[1]].equals("-") && map[local[0]-1][local[1]].equals("+")){ //把当前位置置为空,避免下一次重复走 map[local[0]][local[1]] = " "; //改变坐标 local[0]--; sum++;//步数加1 //调用Move函数,接着往下走 Move(map, local, end, sum); } } } } //得到str的坐标 private static int[] Local(String[][] map, String str) { int[] local = new int[2]; for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ if(map[i][j].equals(str)){ local[0] = i; local[1] = j; return local; } } } return local; } //产生一个n*n的阵列 private static String[][] Produce(){ Scanner sc = new Scanner(System.in); String[] m = new String[n]; String[][] map = new String[n][n]; //控制台输入 for(int i = 0; i < n; i++){ m[i] = sc.nextLine(); } //对输入的数据进行转换成去掉空格的 for(int i = 0; i < n; i++){ map[i] = m[i].split(" "); } return map; } }
请问mpandroidchart如何实现动画连续不断的重载,动画如何暂停
新手程序员一枚,现在需要我要做一个连续不断的波形图,因为要实现手势操作,所以采用了mpandroidchart ,我在示例代码上面进行改动的,但是我无论如何只能实现一次动画效果。求大神们帮助,现在附上代码 public class LineWaveActivity extends DemoBase implements OnSeekBarChangeListener, OnChartGestureListener, OnChartValueSelectedListener { private LineChart mChart; private SeekBar mSeekBarX, mSeekBarY; private TextView tvX, tvY; // -----------------波形曲线可能会用到的参数(尖波)-------------- private List<Map<String, Object>> month = new ArrayList<Map<String, Object>>(); private List<Map<String, Object>> data = new ArrayList<Map<String, Object>>(); // 数据 // x轴数据——单位秒(s) private String[] mTimes = new String[] { "00:00s", "00:10s", "00:20s", "00:30s", "00:40s", "00:50s", "00:60s", "00:70s", "00:80s", "00:90s", "00:10s", "01:10s", "01:20s", "01:30s", "01:40s", "01:50s", "01:60s", "01:70s", "01:80s", "01:90s", "02:00s", "02:10s", "02:20s", "02:30s", "02:40s", "02:50s", "02:60s", "02:70s", "02:80s", "02:90s", "03:00s", "03:10s", "03:20s", "03:30s", "03:40s", "03:50s", "03:60s", "03:70s", "03:80s", "03:90s", "04:00s", "04:10s", "04:20s", "04:30s", "04:40s", "04:50s", "04:60s", "04:70s", "04:80s", "04:90s", "05:00s", "05:10s", "05:20s", "05:30s", "05:40s", "05:50s", "05:60s", "05:70s", "05:80s", "05:90s", "06:00s" }; // y轴数据——单位(n/m^2) private int[] arrs = { 0, 0, 0, 0, 0, 0, 5, -10, 15, -20, 25, -25, 20, -15, 10, -5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, -10, 15, -20, 25, -25, 20, -15, 10, -5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, -10, 15, -20, 25, -25, 20, -15, 10, -5, 0, 0, 0, 0, 0 }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 设置窗体全屏 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_linechart); // ---------------波形曲线操作代码块---------------------- Map<String, Object> map = null; for (int i = 0; i < mTimes.length; i++) { map = new HashMap<String, Object>(); map.put("times", mTimes[i]); month.add(map); } Map<String, Object> dataMap = null; for (int i = 0; i < arrs.length; i++) { dataMap = new HashMap<String, Object>(); dataMap.put("ranges", arrs[i]); data.add(dataMap); } // ---------------波形曲线操作代码块---------------------- tvX = (TextView) findViewById(R.id.tvXMax); tvY = (TextView) findViewById(R.id.tvYMax); mSeekBarX = (SeekBar) findViewById(R.id.seekBar1); mSeekBarY = (SeekBar) findViewById(R.id.seekBar2); mSeekBarX.setProgress(250); mSeekBarY.setProgress(100); mSeekBarY.setOnSeekBarChangeListener(this); mSeekBarX.setOnSeekBarChangeListener(this); mChart = (LineChart) findViewById(R.id.chart1); // ChartGestureListener手势监听器,可以使得 chart与手势操作进行交互。 mChart.setOnChartGestureListener(this); // 设置表格上的点,被点击的时候,的回调函数 mChart.setOnChartValueSelectedListener(this); // 设置图表内格子背景是否显示,默认是false mChart.setDrawGridBackground(false); // 数据描述 // 如果没有数据的时候,会显示这个"You need to provide data for the chart.",类似listview的emtpyview mChart.setDescription(""); mChart.setNoDataTextDescription("你需要为图表添加必要的数据!"); // 设置点击value的时候,是否高亮显示 mChart.setHighlightEnabled(true); // 设置是否可以手势操作 mChart.setTouchEnabled(true); // 启用/禁用拖动(平移)图表。 mChart.setDragEnabled(true); // 启用/禁用缩放图表上的两个轴。 mChart.setScaleEnabled(true); // 启用/禁用x轴缩放 mChart.setScaleXEnabled(true); // 启用/禁用y轴缩放 mChart.setScaleYEnabled(true); // 如果设置为false,那么x轴,y轴可以分别放大 mChart.setPinchZoom(false); // 设置背景颜色 // mChart.setBackgroundColor(Color.GRAY); MyMarkerView mv = new MyMarkerView(this, R.layout.custom_marker_view); mChart.setMarkerView(mv); // 设置x轴相关参数 LimitLine llXAxis = new LimitLine(10f, "警戒线"); llXAxis.setLineWidth(4f); llXAxis.enableDashedLine(10f, 10f, 10f); llXAxis.setLabelPosition(LimitLabelPosition.RIGHT_BOTTOM); llXAxis.setTextSize(10f); XAxis xAxis = mChart.getXAxis(); // xAxis.setValueFormatter(new MyCustomXAxisValueFormatter()); // xAxis.addLimitLine(llXAxis); // add x-axis limit line Typeface tf = Typeface.createFromAsset(getAssets(), "OpenSans-Regular.ttf"); LimitLine ll1 = new LimitLine(50f, "Upper Limit"); // 设置警戒线粗细 ll1.setLineWidth(10f); // 设置警戒线间隔大小(间隔宽度,线段位置,线段宽度) ll1.enableDashedLine(40f, 40f, 40f); ll1.setLabelPosition(LimitLabelPosition.RIGHT_TOP); ll1.setTextSize(10f); // 设置字体样式 ll1.setTypeface(tf); LimitLine ll2 = new LimitLine(-50f, "Lower Limit"); ll2.setLineWidth(10f); ll2.enableDashedLine(40f, 40f, 40f); ll2.setLabelPosition(LimitLabelPosition.RIGHT_BOTTOM); ll2.setTextSize(10f); ll2.setTypeface(tf); YAxis leftAxis = mChart.getAxisLeft(); leftAxis.removeAllLimitLines(); // reset all limit lines to avoid // overlapping lines leftAxis.addLimitLine(ll1); leftAxis.addLimitLine(ll2); // 设置y轴最大值 leftAxis.setAxisMaxValue(50f); // 设置y轴最小值 leftAxis.setAxisMinValue(-50f); // 设置y轴起始点是否为0 leftAxis.setStartAtZero(false); // leftAxis.setYOffset(20f); // 设置横向表格为虚线 leftAxis.enableGridDashedLine(10f, 10f, 0f); leftAxis.setDrawLimitLinesBehindData(true); // 设置隐藏右边的坐标轴 mChart.getAxisRight().setEnabled(false); // 设置相对于x,y的放大倍率 // mChart.getViewPortHandler().setMaximumScaleY(20f); // mChart.getViewPortHandler().setMaximumScaleX(20f); // mChart.setVisibleXRange(20);//设置频幕能显示点的数量,要和MAX和Min结合起来使用 // mChart.setVisibleYRange(20f, AxisDependency.LEFT); // mChart.centerViewTo(20, 50, AxisDependency.LEFT); //设置绘图事件,单位——毫秒,绘图程序入口!!!!!!!!!!!!! setData(45, 100); mChart.animateX(6000, Easing.EasingOption.EaseInOutQuart); mChart.invalidate();// 界面刷新 Legend l = mChart.getLegend(); // l.setPosition(LegendPosition.LEFT_OF_CHART);//设置中轴线向右移 l.setForm(LegendForm.LINE);// 设置图表最下面显示的类型 } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { tvX.setText("" + (mSeekBarX.getProgress())); tvY.setText("" + (mSeekBarY.getProgress())); setData(mSeekBarX.getProgress(), mSeekBarY.getProgress()); // 刷新图标 mChart.invalidate(); } // 进度条拖动开始时候调用 @Override public void onStartTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub } // 进度条拖动完成之后调用 @Override public void onStopTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub } private void setData(int count1, int count2) { count1 = month.size(); count2 = data.size(); ArrayList<String> xVals = new ArrayList<String>(); ArrayList<Entry> yVals = new ArrayList<Entry>(); // x轴显示数据操作 for (int i = 0; i < count1; i++) { Map<String, Object> data = month.get(i); xVals.add(data.get("times").toString()); } // y轴显示数据操作 for (int i = 0; i < count2; i++) { Map<String, Object> data2 = data.get(i); yVals.add(new Entry(Integer .parseInt(data2.get("ranges").toString()), i)); } // create a dataset and give it a type LineDataSet set1 = new LineDataSet(yVals, "——————"); set1.setFillAlpha(110);// 设置填充颜色透明度 set1.setFillColor(Color.RED); // 设置线的样式 set1.enableDashedLine(10f, 5f, 0f); // set1.enableDashedHighlightLine(10f, 5f, 0f); set1.setColor(Color.BLACK); set1.setCircleColor(Color.BLACK); set1.setLineWidth(1f); set1.setCircleSize(4f); set1.setDrawCircleHole(true);// 点的圆圈样式,true为空心点,flase为实心点 set1.setValueTextSize(9f); set1.setFillAlpha(65); set1.setFillColor(Color.BLACK); // set1.setDrawFilled(true); // set1.setShader(new LinearGradient(0, 0, 0, mChart.getHeight(), // Color.BLACK, Color.WHITE, Shader.TileMode.MIRROR)); ArrayList<LineDataSet> dataSets = new ArrayList<LineDataSet>(); dataSets.add(set1); // add the datasets // create a data object with the datasets LineData data = new LineData(xVals, dataSets); // set data Log.i("SumLog", "开始为图形设置数据"); mChart.setData(data); } @Override public void onChartGestureStart(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture) { Log.i("Gesture", "START"); } @Override public void onChartGestureEnd(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture) { Log.i("Gesture", "END, lastGesture: " + lastPerformedGesture); if (lastPerformedGesture != ChartTouchListener.ChartGesture.SINGLE_TAP) mChart.highlightValues(null); } @Override public void onChartLongPressed(MotionEvent me) { Log.i("LongPress", "Chart longpressed."); } @Override public void onChartDoubleTapped(MotionEvent me) { Log.i("DoubleTap", "Chart double-tapped."); } @Override public void onChartSingleTapped(MotionEvent me) { Log.i("SingleTap", "Chart single-tapped."); } @Override public void onChartFling(MotionEvent me1, MotionEvent me2, float velocityX, float velocityY) { Log.i("Fling", "Chart flinged. VeloX: " + velocityX + ", VeloY: " + velocityY); } @Override public void onChartScale(MotionEvent me, float scaleX, float scaleY) { Log.i("Scale / Zoom", "ScaleX: " + scaleX + ", ScaleY: " + scaleY); } @Override public void onChartTranslate(MotionEvent me, float dX, float dY) { Log.i("Translate / Move", "dX: " + dX + ", dY: " + dY); } @Override public void onValueSelected(Entry e, int dataSetIndex, Highlight h) { Log.i("Entry selected", e.toString()); Log.i("", "low: " + mChart.getLowestVisibleXIndex() + ", high: " + mChart.getHighestVisibleXIndex()); } @Override public void onNothingSelected() { Log.i("Nothing selected", "Nothing selected."); } } 请问各位,如何实现一个可用按钮控制的连续不断的波形效果,比较急额,卡了四天了
android studio做了个APP,其它用了JSOUP,碰到dopostback函数,无法加载
HfztbAcitivity package linpeng.ztb; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import android.app.Activity; import android.app.AlertDialog.Builder; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.opengl.Visibility; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.AnimationSet; import android.view.animation.RotateAnimation; import android.view.animation.ScaleAnimation; import android.view.animation.TranslateAnimation; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.GridView; import android.widget.HorizontalScrollView; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast; public class HfztbActivity extends Activity implements OnClickListener { private GridView xml_gridview; private ListView xml_newslist; private Button foot_loadmore, prepare_refresh, gotoright, up, down, gotoother, gotoother2, gotoother3, gotoother4, gotoother5; private TextView foot_text; private ProgressBar foot_progressbar; private HorizontalScrollView horizontalScrollView; private SimpleAdapter listview_adapter; private ProgressBar refresh; private String list_button = "title1"; private int changenewslist = 1; private int[][] location = new int[5][2]; private boolean fist_open_title1 = true, fist_open_title2 = true, fist_open_title3 = true, fist_open_title4 = true, fist_open_title5 = true, goto_other_visiably = false;//fist_open_title6 = true, //fist_open_title7 = true, private boolean is_first_open = true; private final int FLINGDIS = 900; private List<Map<String, Object>> newslist = new ArrayList<Map<String, Object>>(); private List<Map<String, Object>> tempnewslist = new ArrayList<Map<String, Object>>(); private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.arg1 > -1) { prepare_refresh.setVisibility(0); refresh.setVisibility(8); Log.i("list_button", new IntToStrong().getname(msg.arg1) + list_button); changeFirstOpen(msg.arg1); if (list_button.equals(new IntToStrong().getname(msg.arg1))) { getNewsList(msg.arg1, false); } } if (msg.arg1 == -1) { prepare_refresh.setVisibility(0); refresh.setVisibility(8); Toast.makeText(HfztbActivity.this, "网络不通,请稍候再试", Toast.LENGTH_SHORT).show(); } } private void changeFirstOpen(int arg1) { if (arg1 == 0 && fist_open_title1) { fist_open_title1 = false; } else if (arg1 == 1 && fist_open_title2) { fist_open_title2 = false; } else if (arg1 == 2 && fist_open_title3) { fist_open_title3 = false; } else if (arg1 == 3 && fist_open_title4) { fist_open_title4 = false; } else if (arg1 == 4 && fist_open_title5) { fist_open_title5 = false; // } else if (arg1 == 5 && fist_open_title6) { // fist_open_title6 = false; // } else if (arg1 == 6 && fist_open_title7) { // fist_open_title7 = false; } } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.main); xml_gridview = (GridView) findViewById(R.id.xml_gridview); xml_gridview.setSelector(new ColorDrawable(Color.TRANSPARENT)); xml_newslist = (ListView) findViewById(R.id.newslist); prepare_refresh = (Button) findViewById(R.id.prepare_refresh); refresh = (ProgressBar) findViewById(R.id.refresh); gotoright = (Button) findViewById(R.id.gotoright); horizontalScrollView = (HorizontalScrollView) findViewById(R.id.horizontalScrollView); up = (Button) findViewById(R.id.up); down = (Button) findViewById(R.id.down); gotoother = (Button) findViewById(R.id.gotoother); gotoother2 = (Button) findViewById(R.id.gotoother2); gotoother3 = (Button) findViewById(R.id.gotoother3); gotoother4 = (Button) findViewById(R.id.gotoother4); gotoother5 = (Button) findViewById(R.id.gotoother5); LayoutInflater layoutInflater = getLayoutInflater(); View footView = layoutInflater.inflate(R.layout.foot, null); xml_newslist.addFooterView(footView); foot_loadmore = (Button) findViewById(R.id.foot_loadmore); foot_text = (TextView) findViewById(R.id.foot_text); foot_progressbar = (ProgressBar) findViewById(R.id.foot_progressbar); foot_loadmore.setOnClickListener(this); prepare_refresh.setOnClickListener(this); gotoright.setOnClickListener(this); up.setOnClickListener(this); down.setOnClickListener(this); gotoother.setOnClickListener(this); gotoother2.setOnClickListener(this); gotoother3.setOnClickListener(this); gotoother4.setOnClickListener(this); gotoother5.setOnClickListener(this); getNewsList(0, false); SimpleAdapter gridview_adapter = new SimpleAdapter(this, new ListData().getGridviewdata(), R.layout.gridview, new String[] { "grid_title" }, new int[] { R.id.grid_title }); listview_adapter = new SimpleAdapter(this, newslist, R.layout.newslistdetails, new String[] { "news_isend", "news_title", "news_time" }, new int[] { R.id.news_isend, R.id.news_title, R.id.news_time }); is_first_open = false; xml_gridview.setAdapter(gridview_adapter); xml_gridview.setOnItemClickListener(new onGridViewItemClick()); xml_newslist.setOnItemClickListener(new onListViewItemClick()); xml_newslist.setAdapter(listview_adapter); } private void getloction() { gotoother.getLocationOnScreen(location[0]); gotoother2.getLocationOnScreen(location[1]); gotoother3.getLocationOnScreen(location[2]); gotoother4.getLocationOnScreen(location[3]); gotoother5.getLocationOnScreen(location[4]); Log.i("x", location[0][0] + " " + location[0][1]); } private void getNewsList(int table_number, boolean is_fresh) { boolean has_fresh = false; String table_name = new IntToStrong().getname(table_number); DataBaseHelper dbh = new DataBaseHelper(this, table_name, null, 1); SQLiteDatabase sql = dbh.getReadableDatabase(); Cursor cursor = sql.query(table_name, new String[] { "newsclass", "newstitle", "newstime", "isread" }, "newsclass>?", new String[] { "-1" }, null, null, null); if (cursor.getCount() != 0 && is_fresh == false) { newslist.clear(); getNewsListByDatabase(cursor); prepare_refresh.setVisibility(0); refresh.setVisibility(8); if (!is_first_open) { listview_adapter.notifyDataSetChanged(); xml_newslist.setSelection(0); list_button = new IntToStrong().getname(table_number); } } else { list_button = new IntToStrong().getname(table_number); MyThread myThread = new MyThread(table_number, HfztbActivity.this); has_fresh = true; myThread.start(); } if (!has_fresh) { reFresh(table_name, table_number); } if (sql != null) { sql.close(); } if (dbh != null) { dbh.close(); } } private void reFresh(String table_name, int table_number) { if (fist_open_title1 && table_name == "title1") { MyThread myThread = new MyThread(table_number, HfztbActivity.this); myThread.start(); } else if (fist_open_title2 && table_name == "title2") { MyThread myThread = new MyThread(table_number, HfztbActivity.this); myThread.start(); } else if (fist_open_title3 && table_name == "title3") { MyThread myThread = new MyThread(table_number, HfztbActivity.this); myThread.start(); } else if (fist_open_title4 && table_name == "title4") { MyThread myThread = new MyThread(table_number, HfztbActivity.this); myThread.start(); } else if (fist_open_title5 && table_name == "title5") { MyThread myThread = new MyThread(table_number, HfztbActivity.this); myThread.start(); //} else if (fist_open_title6 && table_name == "title6") { // MyThread myThread = new MyThread(table_number, HfztbActivity.this); // myThread.start(); //} else if (fist_open_title7 && table_name == "title7") { // MyThread myThread = new MyThread(table_number, HfztbActivity.this); // myThread.start(); } } private void getNewsListByDatabase(Cursor cursor) { newslist.clear(); while (cursor.moveToNext()) { Map<String, Object> map = new HashMap<String, Object>(); map.put("news_title", cursor.getString(cursor.getColumnIndex("newstitle"))); map.put("news_time", cursor.getString(cursor.getColumnIndex("newstime"))); map.put("news_isend", cursor.getString(cursor.getColumnIndex("isread"))); newslist.add(map); } } class onGridViewItemClick implements OnItemClickListener { public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { int table_number = arg2; TextView gridviewback = (TextView) arg1; for (int i = 0; i < arg0.getCount(); i++) { TextView gridview_text_temp = (TextView) arg0.getChildAt(i); gridview_text_temp.setBackgroundDrawable(null); gridview_text_temp.setTextColor(getResources().getColor( R.color.grid_title_color)); } gridviewback.setBackgroundResource(R.drawable.gridviewbackground); gridviewback.setTextColor(Color.WHITE); if (arg2 >= 0 && arg2 <= 6) { getNewsList(table_number, false); Log.i("after", "thread"); } } } class onListViewItemClick implements OnItemClickListener { public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { DataBaseHelper dbh = new DataBaseHelper(HfztbActivity.this, list_button, null, 1); SQLiteDatabase sq = dbh.getReadableDatabase(); Cursor cursor = sq.query(list_button, new String[] { "newsclass", "newstitle", "newstime", "isread", "url" }, "newsclass=?", new String[] { arg2 + "" }, null, null, null); cursor.moveToNext(); Intent intent = new Intent(HfztbActivity.this, News.class);// ��ת������ҳ if (!cursor.isAfterLast()) { intent.putExtra("newsurl", cursor.getString(cursor.getColumnIndex("url"))); intent.putExtra("newstitle", cursor.getString(cursor.getColumnIndex("newstitle"))); intent.putExtra("newstime", cursor.getString(cursor.getColumnIndex("newstime"))); intent.putExtra("type", list_button); startActivity(intent); } if (dbh != null) { dbh.close(); sq.close(); } } } public class MyThread extends Thread { private int table_number; private Context context; public MyThread(int table_number, Context context) { this.table_number = table_number; this.context = context; } @Override public void run() { getNewsList(table_number); } protected void getNewsList(int table_number) { try { Document doc; String url = "http://ggzy.jiangxi.gov.cn/jxzbw/jyxx/002004/00200400" + (table_number + 1) + "/MoreInfo.aspx?CategoryNum=00200400"+ (table_number + 1); doc = Jsoup.connect(url).get(); new ListData().getListData(doc, table_number, context, url); Message msg = handler.obtainMessage(); msg.arg1 = table_number; handler.sendMessage(msg); } catch (IOException e) { Log.i("tag", "error"); Message msg = handler.obtainMessage(); msg.arg1 = -1; handler.sendMessage(msg); e.printStackTrace(); } } } public void onClick(View v) { if (v.getId() == foot_loadmore.getId()) { foot_loadmore.setVisibility(8); foot_text.setVisibility(0); foot_progressbar.setVisibility(0); } if (v.getId() == prepare_refresh.getId()) { prepare_refresh.setVisibility(8); refresh.setVisibility(0); getNewsList(new IntToStrong().table_name_to_int(list_button), true); } if (v.getId() == gotoright.getId()) { horizontalScrollView.fling(FLINGDIS); Log.i("" + horizontalScrollView.getScrollY(), horizontalScrollView.getScrollX() + ""); } if (v.getId() == up.getId()) { xml_newslist.setSelection(0); } if (v.getId() == down.getId()) { Log.i("asff", xml_newslist.getScrollY() + ""); xml_newslist.setSelection(1000); } if (v.getId() == gotoother.getId()) { getloction(); if (!goto_other_visiably) { setVisiablyAndAnimation(false, -1); } else { Log.i("x", location[0][0] + " " + location[0][1]); setVisiablyAndAnimation(true, 0); } } if (v.getId() == gotoother2.getId()) { setVisiablyAndAnimation(false, 0); } if (v.getId() == gotoother3.getId()) { setVisiablyAndAnimation(false, 1); } if (v.getId() == gotoother4.getId()) { setVisiablyAndAnimation(false, 2); } if (v.getId() == gotoother5.getId()) { setVisiablyAndAnimation(false, 3); } } private void setVisiablyAndAnimation(boolean b, int which) { if (!b && which > -1) { ScaleAnimation[] scaleAnimations = getScaleAnimation(which); gotoother2.startAnimation(scaleAnimations[0]); gotoother3.startAnimation(scaleAnimations[1]); gotoother4.startAnimation(scaleAnimations[2]); gotoother5.startAnimation(scaleAnimations[3]); gotoother2.setVisibility(8); gotoother3.setVisibility(8); gotoother4.setVisibility(8); gotoother5.setVisibility(8); goto_other_visiably = false; } else if (which == -1) { TranslateAnimation[] translateAnimations = getTranslateAnimation(which); gotoother2.startAnimation(translateAnimations[0]); gotoother3.startAnimation(translateAnimations[1]); gotoother4.startAnimation(translateAnimations[2]); gotoother5.startAnimation(translateAnimations[3]); gotoother2.setVisibility(0); gotoother3.setVisibility(0); gotoother4.setVisibility(0); gotoother5.setVisibility(0); goto_other_visiably = true; } else { TranslateAnimation[] translateAnimations = getTranslateAnimation(which); gotoother2.startAnimation(translateAnimations[0]); gotoother3.startAnimation(translateAnimations[1]); gotoother4.startAnimation(translateAnimations[2]); gotoother5.startAnimation(translateAnimations[3]); gotoother2.setVisibility(8); gotoother3.setVisibility(8); gotoother4.setVisibility(8); gotoother5.setVisibility(8); goto_other_visiably = false; } } private TranslateAnimation[] getTranslateAnimation(int which) { TranslateAnimation[] translateAnimations = new TranslateAnimation[4]; if (which == -1) { translateAnimations[0] = new TranslateAnimation(Animation.ABSOLUTE, location[0][0] - location[1][0], Animation.RELATIVE_TO_SELF, 0f, Animation.ABSOLUTE, location[0][1] - location[1][1], Animation.RELATIVE_TO_SELF, 0f); translateAnimations[1] = new TranslateAnimation(Animation.ABSOLUTE, location[0][0] - location[2][0], Animation.RELATIVE_TO_SELF, 0f, Animation.ABSOLUTE, location[0][1] - location[2][1], Animation.RELATIVE_TO_SELF, 0f); translateAnimations[2] = new TranslateAnimation(Animation.ABSOLUTE, location[0][0] - location[3][0], Animation.RELATIVE_TO_SELF, 0f, Animation.ABSOLUTE, location[0][1] - location[3][1], Animation.RELATIVE_TO_SELF, 0f); translateAnimations[3] = new TranslateAnimation(Animation.ABSOLUTE, location[0][0] - location[4][0], Animation.RELATIVE_TO_SELF, 0f, Animation.ABSOLUTE, location[0][1] - location[4][1], Animation.RELATIVE_TO_SELF, 0f); translateAnimations[0].setDuration(100); translateAnimations[1].setDuration(150); translateAnimations[2].setDuration(200); translateAnimations[3].setDuration(250); } else { translateAnimations[0] = new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0f, Animation.ABSOLUTE, location[0][0] - location[1][0], Animation.RELATIVE_TO_SELF, 0f, Animation.ABSOLUTE, location[0][1] - location[1][1]); translateAnimations[1] = new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0f, Animation.ABSOLUTE, location[0][0] - location[2][0], Animation.RELATIVE_TO_SELF, 0f, Animation.ABSOLUTE, location[0][1] - location[2][1]); translateAnimations[2] = new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0f, Animation.ABSOLUTE, location[0][0] - location[3][0], Animation.RELATIVE_TO_SELF, 0f, Animation.ABSOLUTE, location[0][1] - location[3][1]); translateAnimations[3] = new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0f, Animation.ABSOLUTE, location[0][0] - location[4][0], Animation.RELATIVE_TO_SELF, 0f, Animation.ABSOLUTE, location[0][1] - location[4][1]); translateAnimations[0].setDuration(250); translateAnimations[1].setDuration(200); translateAnimations[2].setDuration(150); translateAnimations[3].setDuration(100); } return translateAnimations; } private ScaleAnimation[] getScaleAnimation(int which) { ScaleAnimation[] scaleAnimations = new ScaleAnimation[4]; scaleAnimations[0] = new ScaleAnimation(1, 0.1f, 1, 0.1f); scaleAnimations[1] = new ScaleAnimation(1, 0.1f, 1, 0.1f); scaleAnimations[2] = new ScaleAnimation(1, 0.1f, 1, 0.1f); scaleAnimations[3] = new ScaleAnimation(1, 0.1f, 1, 0.1f); scaleAnimations[which] = new ScaleAnimation(1, 1.7f, 1, 1.7f); scaleAnimations[0].setDuration(150); scaleAnimations[1].setDuration(150); scaleAnimations[2].setDuration(150); scaleAnimations[3].setDuration(150); return scaleAnimations; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { Builder builder = new Builder(this); builder.setMessage("确定退出吗?"); builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { System.exit(0); } }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }); builder.show(); } return true; } } Listdata package linpeng.ztb; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import android.widget.Toast; public class ListData { public List<Map<String, String>> getGridviewdata() { List<Map<String, String>> list = new ArrayList<Map<String, String>>(); HashMap<String, String> hash = new HashMap<String, String>(); hash.put("grid_title", "采购公告"); list.add(hash); hash = new HashMap<String, String>(); hash.put("grid_title", "变更公告"); list.add(hash); hash = new HashMap<String, String>(); hash.put("grid_title", "答疑澄清"); list.add(hash); hash = new HashMap<String, String>(); hash.put("grid_title", "结果公示"); list.add(hash); hash = new HashMap<String, String>(); hash.put("grid_title", "单一来源"); list.add(hash); //hash = new HashMap<String, String>(); //hash.put("grid_title", "标前公示ʾ"); //list.add(hash); //hash = new HashMap<String, String>(); //hash.put("grid_title", "巢湖"); //list.add(hash); return list; } public void getListData(Document doc, int table_number, Context context, String url) { try { Element ele = doc.select("td[height=500]").first(); Elements eles = ele.select("a"); int newsclass = 0; String table_name = new IntToStrong().getname(table_number); if (ele.text().length() > 1) { DataBaseHelper dbh = new DataBaseHelper(context, table_name, null, 1); Log.i("shanchu", "ca"); dbh.dellAll(); } if (table_number != 3 && table_number != 5) { for (Element ele2 : eles) { String inittext = ele2.text(); String isend = "报名结束"; String changetext = inittext.replace("【正在报名】", "");// 替换文中的【正在报名】 String newsurl = ele2.attr("abs:href"); if (changetext.length() != inittext.length()) { isend = "正在报名"; } else { changetext = changetext.replace("【报名结束】", "");// 替换文中的【报名结束】 } if (ele2.text().replace("更多信息", "").length() >= 2) { DataBaseHelper dbh = new DataBaseHelper(context, table_name, null, 1); SQLiteDatabase sqh = dbh.getWritableDatabase(); dbh.addnewslist(newsclass, changetext, ele2.parent() .parent().select("td").last().text(), isend, newsurl); newsclass++; } } } else { for (Element ele2 : eles) { String inittext = ele2.text(); String newsurl = ele2.attr("abs:href"); String name = new IntToStrong().getname(table_number); if (ele2.text().replace("更多信息", "").length() >= 2) { DataBaseHelper dbh = new DataBaseHelper(context, name, null, 1); SQLiteDatabase sqh = dbh.getWritableDatabase(); dbh.addnewslist(newsclass, inittext, ele2.parent() .parent().select("td").last().text(), "", newsurl); newsclass++; } } } } catch (Exception e) { Log.i("s", "网络不通"); // Toast.makeText(context, "网络不通,请稍候再试",Toast.LENGTH_SHORT).show(); } } } NEWS package linpeng.ztb; import java.util.HashMap; import java.util.Map; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import android.R.integer; import android.app.Activity; import android.app.AlertDialog.Builder; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.RemoteViews.ActionException; import android.widget.TextView; import android.widget.Toast; public class News extends Activity { private TextView news_details_text, news_details_title, news_details_time; private ProgressBar news_details_progress; private int flag = 1, arg2, text_size;// flag=1表示从网络获取数据=0表示从数据库获取数据 private String kind, url; private String newsdetailstext = "", downloadtext = "", downloadaddress = "", type; private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.arg1) { case 1: if (newsdetailstext.length() > 3) { putData(); } else { Toast.makeText(News.this, "网络不通,请稍后再试", Toast.LENGTH_SHORT) .show(); } news_details_text.setText(newsdetailstext); news_details_progress.setVisibility(8); break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.news); Intent intent = getIntent(); SharedPreferences s = getSharedPreferences("text_size", 0); text_size = s.getInt("text_size", 20); url = intent.getStringExtra("newsurl"); type = intent.getStringExtra("type"); String newstitle = intent.getStringExtra("newstitle"); String newstime = intent.getStringExtra("newstime"); news_details_text = (TextView) findViewById(R.id.news_details_text); news_details_title = (TextView) findViewById(R.id.news_details_title); news_details_time = (TextView) findViewById(R.id.news_details_time); news_details_progress = (ProgressBar) findViewById(R.id.news_details_progress); news_details_progress.setVisibility(0); news_details_title.setText(newstitle); news_details_time.setText(newstime); news_details_text.setTextSize(text_size); flag = 0; DataBaseHelper dbh = new DataBaseHelper(this, new IntToStrong().TypeToType(type), null, 1); SQLiteDatabase sql = dbh.getReadableDatabase(); Cursor cursor = sql.query(new IntToStrong().TypeToType(type), new String[] { "newsurl", "newstitle", "newstime", "newsdetails", "newsdownloadtext1", "newsdownloadurl1", "newsdownloadtext2", "newsdownloadurl2" }, "newsurl=?", new String[] { url }, null, null, null); cursor.moveToNext(); if (cursor.getCount() == 0) { new NewsThread().start(); } else { news_details_text.setText(cursor.getString(cursor .getColumnIndex("newsdetails"))); news_details_progress.setVisibility(8); } if (sql != null) { sql.close(); } } protected void putData() { DataBaseHelper dbh = new DataBaseHelper(this, new IntToStrong().TypeToType(type), null, 1); SQLiteDatabase sql = dbh.getWritableDatabase(); dbh.addetails(url, news_details_title.getText().toString(), news_details_time.getText().toString(), newsdetailstext, null, null, null, null); if (dbh != null) { dbh.close(); sql.close(); } } private void getNews() { try { String host = android.net.Proxy.getDefaultHost(); int port = android.net.Proxy.getDefaultPort(); Document doc = Jsoup.connect(url).get(); Element ele = doc.getElementById("TDContent"); int j = 1; if (ele.children().text().length() < 2) { System.out.println(1); newsdetailstext = newsdetailstext + ele.text(); } for (Element ele2 : ele.children()) { j++; newsdetailstext = newsdetailstext + ele2.text(); newsdetailstext = newsdetailstext + "\n"; newsdetailstext = newsdetailstext + "\n"; } if (j == 2) { newsdetailstext = ""; for (Element ele2 : ele.children()) { for (Element ele3 : ele2.children()) { System.out.println(3); newsdetailstext = newsdetailstext + ele3.text(); newsdetailstext = newsdetailstext + "\n"; newsdetailstext = newsdetailstext + "\n"; } } } } catch (Exception e) { e.printStackTrace(); } } private class NewsThread extends Thread { @Override public void run() { getNews(); Message msg = handler.obtainMessage(); msg.arg1 = 1; handler.sendMessage(msg); } } @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(menu.NONE, 1, 1, "字体大小"); menu.add(menu.NONE, 2, 1, "使用浏览器打开此页面"); menu.add(menu.NONE, 3, 1, "拨打此页面中电话"); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case 1: Builder builder = new Builder(this); builder.setTitle("字体大小"); builder.setSingleChoiceItems(new String[] { "大", "中", "小" }, new IntToStrong().text_size_to_order(text_size), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (which == 0) { news_details_text.setTextSize(24); SharedPreferences sp = getSharedPreferences( "text_size", 0); sp.edit().putInt("text_size", 24).commit(); dialog.cancel(); } else if (which == 1) { news_details_text.setTextSize(20); SharedPreferences sp = getSharedPreferences( "text_size", 0); sp.edit().putInt("text_size", 20).commit(); dialog.cancel(); } else if (which == 2) { news_details_text.setTextSize(16); SharedPreferences sp = getSharedPreferences( "text_size", 0); sp.edit().putInt("text_size", 16).commit(); dialog.cancel(); } } }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }); builder.show(); break; case 2: Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(intent); break; case 3: Builder builder2=new Builder(this); Map telephone=getTelePhone(); //LayoutInflater inflater=getLayoutInflater(); //View layout=inflater.inflate(R.layout.telephone,(ViewGroup)findViewById(R.id.news_tele)); Intent intent1 = new Intent(Intent.ACTION_CALL,Uri.parse("tel:"+ telephone.get("tele"+1))); startActivity(intent1); //builder2.setView(layout); //builder2.show(); break; default: break; } return true; } private Map getTelePhone() { Map telephone = new HashMap<String, String>(); if (news_details_text.length() > 5) { int temp_index_telephone=1; String text = news_details_text.getText().toString(); for (int i = 1; i <= text.length() - 1; i++) { if (text.charAt(i) == '电' && text.charAt(i + 1) == '话' || text.charAt(i) == '电' && text.charAt(i + 2) == '话') { int k = 3; if(text.charAt(i+2)=='话'){ k=4; } String temp_telephone=""; while (text.charAt(i + k) == '1' || text.charAt(i + k) == '2' || text.charAt(i + k) == '3' || text.charAt(i + k) == '4' || text.charAt(i + k) == '5' || text.charAt(i + k) == '6' || text.charAt(i + k) == '7' || text.charAt(i + k) == '8' || text.charAt(i + k) == '9' || text.charAt(i + k) == '-' || text.charAt(i + k) == '0') { temp_telephone=temp_telephone+text.charAt(i+k); k++; } if(temp_telephone.length()>5){ temp_telephone=temp_telephone.replace("-",""); telephone.put("tele"+temp_index_telephone, temp_telephone); Log.i("sasaa", "" + temp_telephone); temp_index_telephone++; temp_telephone=""; } } } } return telephone; } }
没看到Panel控件展开或收缩的效果
1.没看到Panel控件展开或收缩的效果 2.TextView的宽度不是设为fill_parent吗?可图上没看到啊 ![图片说明](https://img-ask.csdn.net/upload/201706/05/1496658615_658250.png) ``` package com.example.panel; import android.content.Context; import android.os.AsyncTask; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; public class Panel extends LinearLayout{ private final static int HANDLE_WIDTH=30; private final static int MOVE_WIDTH=20; private Button btnHandle; private LinearLayout panelContainer; private int mRightMargin=0; private Context mContext; private PanelClosedEvent panelClosedEvent=null; private PanelOpenedEvent panelOpenedEvent=null; public Panel(Context context,View otherView,int width,int height) { //otherView自动布局以适应Panel展开/收缩的空间变化 super(context); this.mContext=context; //改变Panel附近组件的属性 LayoutParams otherLP=(LayoutParams)otherView.getLayoutParams(); otherLP.weight=1;//支持压挤 otherView.setLayoutParams(otherLP); //设置Panel本身的属性 LayoutParams lp=new LayoutParams(width,height); lp.rightMargin=-lp.width+HANDLE_WIDTH; //Panel的Container在屏幕不可 //Handle在可视区域 mRightMargin=Math.abs(lp.rightMargin); this.setLayoutParams(lp); this.setOrientation(LinearLayout.HORIZONTAL); //设置Handle的属性 btnHandle=new Button(context); btnHandle.setLayoutParams(new LayoutParams(HANDLE_WIDTH,height)); btnHandle.setOnClickListener(new OnClickListener(){ @Override public void onClick(View arg0) { LayoutParams lp=(LayoutParams)Panel.this.getLayoutParams(); if (lp.rightMargin<0) //CLOSE的状态 { new AsynMove().execute(new Integer[]{MOVE_WIDTH});//正数展开 } else if (lp.rightMargin>=0) //OPEN的状态 { new AsynMove().execute(new Integer[]{-MOVE_WIDTH});//负数收缩 } } }); //btnHandle.setOnTouchListener(HandleTouchEvent); this.addView(btnHandle); //设置Container的属性 panelContainer=new LinearLayout(context); panelContainer.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT)); this.addView(panelContainer); } //定义收缩时的回调函数 public void setPanelClosedEvent(PanelClosedEvent event) { this.panelClosedEvent=event; } //定义展开时的回调函数 public void setPanelOpenedEvent(PanelOpenedEvent event) { this.panelOpenedEvent=event; } //把View放在Panel的Container public void fillPanelContainer(View v) { panelContainer.addView(v); } //异步移动Panel class AsynMove extends AsyncTask<Integer,Integer,Void> { @Override protected Void doInBackground(Integer... params){ int times; if (mRightMargin%Math.abs(params[0])==0)//整除 { times=mRightMargin/Math.abs(params[0]); } else //有余数 { times=mRightMargin/Math.abs(params[0])+1; } for (int i=0;i<times;i++) { publishProgress(params); try { Thread.sleep(Math.abs(params[0])); } catch (InterruptedException e) { e.printStackTrace(); } } return null; } @Override protected void onProgressUpdate(Integer... params) { LayoutParams lp=(LayoutParams)Panel.this.getLayoutParams(); if (params[0]<0) { lp.rightMargin=Math.max(lp.rightMargin+params[0], (-mRightMargin)); } else { lp.rightMargin=Math.min(lp.rightMargin+params[0], 0); } if (lp.rightMargin==0&&panelOpenedEvent!=null)//展开之后 { panelOpenedEvent.onPanelOpened(Panel.this);//调用OPEN回调函数 } else if (lp.rightMargin==(mRightMargin)&&panelClosedEvent!=null)//收缩之后 { panelClosedEvent.onPanelClosed(Panel.this);//调用CLOSE回调函数 } Panel.this.setLayoutParams(lp); } } } ``` ``` package com.example.panel; import java.util.ArrayList; import java.util.HashMap; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.GridView; import android.widget.LinearLayout; import android.widget.SimpleAdapter; import android.widget.TextView; public class main extends Activity{ /* (non-Javadoc) * @see android.app.Activity#onCreate(android.os.Bundle) */ private GridView gridview; private LinearLayout container; Panel panel; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); this.setTitle("抽屉构建"); gridview=(GridView)findViewById(R.id.gridview); container=(LinearLayout)findViewById(R.id.container); panel=new Panel(this,gridview,200,LayoutParams.FILL_PARENT); container.addView(panel);//加入Panel控件 //新建测试组件 TextView tvTest=new TextView(this); tvTest.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT)); tvTest.setText("测试组件,红字白底"); tvTest.setTextColor(Color.RED); tvTest.setBackgroundColor(Color.WHITE); //加入Panel里面 panel.fillPanelContainer(tvTest); panel.setPanelClosedEvent(new PanelClosedEven()); panel.setPanelOpenedEvent(new PanelOpenedEven()); //往GridView中填充测试数据 ArrayList<HashMap<String,Object>> lstImageItem=new ArrayList<HashMap<String,Object>>(); for (int i=0;i<100;i++) { HashMap<String,Object> map=new HashMap<String,Object>(); map.put("ItemImage", R.drawable.ic_launcher); map.put("ItemText", "NO"+String.valueOf(1)); lstImageItem.add(map); } SimpleAdapter saImageItems=new SimpleAdapter(this,lstImageItem,R.layout.item,new String[]{"ItemImage","ItemText"},new int[]{R.id.ItemImage,R.id.ItemText}); gridview.setAdapter(saImageItems); gridview.setOnItemClickListener(new ItemClickListener()); } class PanelClosedEven implements PanelClosedEvent { @Override public void onPanelClosed(View panel) { Log.e("panelClosedEvent","panelClosedEvent"); } } class PanelOpenedEven implements PanelOpenedEvent { @Override public void onPanelOpened(View panel) { Log.e("panelOpenedEvent","panelOpenedEvent"); } } class ItemClickListener implements OnItemClickListener { @Override public void onItemClick(AdapterView<?> arg0,View arg1,int arg2,long arg3) { @SuppressWarnings("unchecked") HashMap<String,Object> item=(HashMap<String,Object>) arg0.getItemAtPosition(arg2); setTitle((String)item.get("ItemText")); } } } ``` 3.往GridView中填充数据也什么都没看到
不相交类集迷宫求解路径
``` import javax.swing.*; import java.awt.*; import java.util.*; import java.util.List; /** * Created by 伟大的华仔 on 2017-11-30. */ public class Maze extends JFrame { private int row;//行数 private int col; //列数 private DisJoinSet disjSet; private int winHeight=1000;// 行高 private int winWidth=1000;//行宽 public Maze(int row,int col){ this.row = row; this.col = col; this.setTitle("迷宫");//设置标题 this.setSize(winWidth,winHeight);//设置组件大小 this.setVisible(true);//显示或隐藏此 Window this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置用户在此窗体上发起 "close" 时默认执行的操作 EXIT_ON_CLOSE(在 JFrame 中定义):使用 System exit 方法退出应用程序 } public static void main(String[] args) { /** * 定义迷宫的大小,必须是正方形的 * */ int rowCount = 100; int colCount = 100; Maze maze = new Maze(rowCount,colCount); } @Override public void paint(Graphics g){ super.paint(g); /** * 申请一个String集合,放置合并的节点 * */ List<Integer>DisList = new LinkedList<>(); //背景为白色 g.setColor(Color.white); g.fillRect(0, 0, winWidth, winHeight);//窗口填充矩形 g.setColor(Color.black); final int extraWidth = 20; final int cellWidth = (winWidth-2*extraWidth)/row;//定义每个格子的宽度 final int cellHeight = (winHeight-4*extraWidth)/col;//定义每个格子的高度 for(int i=0;i<row;i++) { for(int j=0;j<col;j++) { //初始化m*n矩阵格子 g.drawRect(i*cellWidth+extraWidth,j*cellHeight+2*extraWidth, cellWidth, cellHeight); } } int lastPos = getLastElePos();//迷宫最后一个格式的代表数字 //起点,终点特殊处理 g.setColor(Color.red); g.fillRect(extraWidth, 2*extraWidth, cellWidth, cellHeight); g.fillRect((lastPos% row)*cellWidth + extraWidth,(lastPos/ row)*cellHeight + 2*extraWidth, cellWidth, cellHeight); this.setDisjSet(new DisJoinSet(row*col)); // 路径记录操作 ArrayList<LinkedList<Integer>> adjoinTable = new ArrayList(); Stack<Integer> pathSearch = new Stack<Integer>(); pathSearch.push(0); for (int i = 0;i<row*col;i++){ LinkedList<Integer> temp = new LinkedList<Integer>(); temp.add(i); adjoinTable.add(temp); temp.clear(); } g.setColor(Color.white); //用后景色擦色 while(disjSet.find(0) != disjSet.find(lastPos)){//如果起点和终点还没在同一个等价类 /* * 在迷宫内随机挖一个点,再找到该点周围一点,使这两个点落在同一个等价类 */ Random random = new Random(); int randPos = random.nextInt(lastPos+1);//+1是为了能随机到最后一位 int rowIndex = randPos % row; int colIndex = randPos / col; List<Integer> neighborPos = getNeighborNums(rowIndex, colIndex) ; int randNeighbor = neighborPos.get(random.nextInt(neighborPos.size())); if(disjSet.find(randPos) == disjSet.find(randNeighbor)){//两点在同一个等价类 continue; }else{ int aRoot = disjSet.find(randPos); int bRoot = disjSet.find(randNeighbor); disjSet.union(aRoot, bRoot); DisList.add(randPos); DisList.add(randNeighbor); // /** // * 打印搜索过程 // * */ // System.out.println("***过程分析*****************"+Arrays.toString(this.disjSet.getEleRoots())); int maxNum = Math.max(randPos, randNeighbor);//取得较大点 int x1=0,y1=0,x2=0,y2=0; if(Math.abs(randPos-randNeighbor) == 1){//说明在同一行,用竖线隔开 x1= x2=(maxNum% row)*cellWidth + extraWidth; y1=(maxNum/ row)*cellHeight + 2*extraWidth; y2=y1+cellHeight; }else{//说明在同一列,用横线隔开 y1=y2=(maxNum/ row)*cellHeight + 2*extraWidth; x1=(maxNum% row)*cellWidth + extraWidth; x2=x1+cellWidth; } g.drawLine(x1, y1, x2, y2); } } long start = System.currentTimeMillis(); /** * 打印数组 * */ // System.out.println("***最终结构********************"+Arrays.toString(this.disjSet.getEleRoots())); // for (Iterator it = DisList.iterator();it.hasNext();){ // System.out.println("***节点***"+it.next()); // } for (int i = 0;i<DisList.size();i=i+2){ adjoinTable.get(DisList.get(i)).add(DisList.get(i+1)); adjoinTable.get(DisList.get(i+1)).add(DisList.get(i)); } // for (int i = 0;i<adjoinTable.size();i++){ // System.out.println("链表内容"+Arrays.toString(adjoinTable.get(i).toArray())); // } /** * 算法步骤 * 1、检索i节点的联通节点 * 2、存在就放入栈中(前提为栈中没有该元素),不存在弹出栈顶元素(删除邻接表中的数据),或者为终点元素结束 * 3、重复步骤1 * */ while (true){//while开始 if (pathSearch.isEmpty()){ System.out.println("栈为空,迷宫没有路径"); break; } if (pathSearch.peek()==(row*col-1)){ System.out.println("迷宫已破解"); break; } if (adjoinTable.get(pathSearch.peek()).size()==1 && pathSearch.peek() != 0){ Integer temp = pathSearch.pop(); if(pathSearch.isEmpty()){ System.out.println("栈为空,迷宫没有路径"); break; }else { adjoinTable.get(pathSearch.peek()).remove(temp); adjoinTable.get(temp).remove(pathSearch.peek()); } }else { if (pathSearch.search(adjoinTable.get(pathSearch.peek()).get(0))!= -1 ){ if (adjoinTable.get(pathSearch.peek()).size()>1){ pathSearch.push(adjoinTable.get(pathSearch.peek()).get(1)); // Iterator<Integer> boy = adjoinTable.get(pathSearch.peek()).listIterator(); // while (boy.hasNext()){ // int girl = boy.next(); // if (!pathSearch.contains(girl)){ // pathSearch.push(girl); // } // } } }else { pathSearch.push(adjoinTable.get(pathSearch.peek()).get(0)); } } }//while结束 /** * 输出路径 * */ // System.out.println("迷宫路径"+Arrays.toString(pathSearch.toArray())); g.setColor(Color.red); while (!pathSearch.isEmpty()){ int boy = pathSearch.pop(); //左右 g.fillOval((boy% row)*cellWidth + cellWidth/4+extraWidth,(boy/ row)*cellHeight + cellHeight/4+2*extraWidth, cellWidth/2, cellHeight/2); } // long end = System.currentTimeMillis(); System.out.println("时间流程:"+Long.toString(end-start)+"ms"); adjoinTable.clear(); pathSearch.clear(); } /** * 取得目标坐标点周围四个有效点 */ public List<Integer> getNeighborNums(int rowIndex,int colIndex){ List<Integer> neighborPos = new ArrayList<Integer>(4); //右元素 if(isPointInMaze(rowIndex+1,colIndex)){ neighborPos.add(getCoordinateNum(rowIndex+1,colIndex)); } //下元素 if(isPointInMaze(rowIndex,colIndex+1)){ neighborPos.add(getCoordinateNum(rowIndex,colIndex+1)); } //左元素 if(isPointInMaze(rowIndex-1,colIndex)){ neighborPos.add(getCoordinateNum(rowIndex-1,colIndex)); } //上元素 if(isPointInMaze(rowIndex,colIndex-1)){ neighborPos.add(getCoordinateNum(rowIndex,colIndex-1)); } return neighborPos; } public int getLastElePos(){ return row*col-1; } public DisJoinSet getDisjSet() { return disjSet; } public void setDisjSet(DisJoinSet disjSet) { this.disjSet = disjSet; } /** * 根据坐标返回对应的值 * 例如在4*3矩阵,(0,0)返回0;(3,2)返回10 */ public int getCoordinateNum(int x,int y){ return y*col + x; } /** * 判断给定坐标是否在迷宫矩阵内 */ public boolean isPointInMaze(int x,int y){ if(x < 0 || y < 0) return false; return x < row && y <col; } } ``` 目前状态:100x100的求解需要5s,200x200的需要20s左右。 问题:paint函数重画存在闪烁问题。求解路径算法需要优化。
spring-data-elasticsearch 一对多
现在有三个实体类 关系是一个产品有多个属性 一个属性有多个属性值 如下: 实体类EsProduct: ``` @Document(indexName = "product", type = "productInfo",shards = 2,replicas = 1,refreshInterval = "-1") public class EsProduct implements Serializable { private static final long serialVersionUID = 2372551074091780419L; @Id private Long id; @Field(analyzer = "ik_max_word",type = FieldType.Text) private String productSn; private Long brandId; @Field(analyzer = "ik_max_word",type = FieldType.Text) private String brandName; private Long productCategoryId; @Field(analyzer = "ik_max_word",type = FieldType.Text) private String productName; private Long sale; @Field(analyzer = "ik_max_word",type = FieldType.Text) private String subTitle; private BigDecimal price; @Field(analyzer = "ik_max_word",type = FieldType.Text) private String keywords; private List<EsProductAttribute> attributeList; private EsProductCategory productCategorie; ``` 实体类EsProductAttribute: ``` public class EsProductAttribute implements Serializable { private static final long serialVersionUID = 4965902919813623705L; @Id private Long id; @Field(analyzer = "ik_max_word",type = FieldType.Text) private String paProductAttributeName;//属性名称 private List<EsProductAttributeValue> attributeValues; ``` 实体类EsProductAttributeValue: ``` public class EsProductAttributeValue implements Serializable { private static final long serialVersionUID = 6713756365860464751L; private Long id; @Field(analyzer = "ik_max_word",type = FieldType.Text) private String pavProductAttributeValue; ``` 之前的搜索是这样的,可以成功搜索 控制层代码: ``` @ApiOperation(value = "简单搜索:根据关键字,品牌名称或者产品名称,产品编号,副标题搜索(字符串:Text类型最大拆分)") @RequestMapping(value = "/search/keyword", method = RequestMethod.GET) @ResponseBody public CommonResult<CommonPage<EsProduct>> searchKeyword(@RequestParam(required = false) String keyword, @RequestParam(required = false, defaultValue = "0") Integer pageNum, @RequestParam(required = false, defaultValue = "5") Integer pageSize) { Page<EsProduct> esProductPage = esProductService.searchKeyword(keyword, pageNum, pageSize); return CommonResult.success(CommonPage.restPage(esProductPage)); } ``` 业务实现层代码: ``` @Autowired private EsProductRepository productRepository; @Override public Page<EsProduct> searchKeyword(String keyword, Integer pageNum, Integer pageSize) { Pageable pageable = PageRequest.of(pageNum, pageSize); return productRepository.findByKeywordsOrProductNameOrBrandNameOrProductSnOrSubTitle(keyword,keyword,keyword,keyword,keyword,pageable); } ``` EsProductRepository接口 ``` public interface EsProductRepository extends ElasticsearchRepository<EsProduct, Long> { /** * 根据关键字,产品名称,品牌名称,产品编号搜索 * @param keywords * @param productName * @param brandName * @param page * @return */ Page<EsProduct> findByKeywordsOrProductNameOrBrandNameOrProductSnOrSubTitle(String keywords,String productName,String brandName,String productSn,String subTitle,Pageable page); } ``` 都可以成功搜索 但是在进行属性和属性值搜索的时候告诉我说在EsProduct中找不到paProductAttributeName,我一想有道理,然后改变策略 单独写了一个接口测试 控制层 ``` @ApiOperation(value = "属性和属性值搜索、筛选、排序") @ApiImplicitParam(name = "sort", value = "排序字段:0->按相关度;1->按销量;2->价格从低到高;3->价格从高到低", defaultValue = "0", allowableValues = "0,1,2,3", paramType = "query", dataType = "integer") @RequestMapping(value = "/search", method = RequestMethod.GET) @ResponseBody public CommonResult<CommonPage<EsProduct>> search(@RequestParam(required = false) String keyword, @RequestParam(required = false, defaultValue = "0") Integer pageNum, @RequestParam(required = false, defaultValue = "5") Integer pageSize, @RequestParam(required = false, defaultValue = "0") Integer sort) { Page<EsProduct> esProductPage = esProductService.search(keyword,pageNum, pageSize, sort); return CommonResult.success(CommonPage.restPage(esProductPage)); } ``` 业务实现层: ``` @Override public Page<EsProduct> search(String keyword,Integer pageNum, Integer pageSize,Integer sort) { Pageable pageable = PageRequest.of(pageNum, pageSize); //将连接条件和聚合函数等组合 NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder(); //分页 nativeSearchQueryBuilder.withPageable(pageable); //搜索 if (StringUtils.isEmpty(keyword)) { nativeSearchQueryBuilder.withQuery(QueryBuilders.matchAllQuery()); } else { List<FunctionScoreQueryBuilder.FilterFunctionBuilder> filterFunctionBuilders = new ArrayList<>(); //QueryBuilders:简单的静态工厂”导入静态”使用。主要作用是查询条件(关系),如区间\精确\多值等条件 //属性名称 filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("paProductAttributeName", keyword), ScoreFunctionBuilders.weightFactorFunction(2))); //属性值 filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("value", keyword), ScoreFunctionBuilders.weightFactorFunction(2))); //产品名称 // filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("productName",keyword), // ScoreFunctionBuilders.weightFactorFunction(2))); // //关键字 // filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("keywords", keyword), // ScoreFunctionBuilders.weightFactorFunction(2))); // //产品编号 // filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("productSn", keyword), // ScoreFunctionBuilders.weightFactorFunction(2))); FunctionScoreQueryBuilder.FilterFunctionBuilder[] builders = new FunctionScoreQueryBuilder.FilterFunctionBuilder[filterFunctionBuilders.size()]; filterFunctionBuilders.toArray(builders); FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(builders) .scoreMode(FunctionScoreQuery.ScoreMode.SUM) .setMinScore(2); nativeSearchQueryBuilder.withQuery(functionScoreQueryBuilder); } // //排序 // if(sort==1){ // //按销量从高到低 // nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("sale").order(SortOrder.DESC)); // }else if(sort==2){ // //按价格从低到高 // nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("price").order(SortOrder.ASC)); // }else if(sort==3){ // //按价格从高到低 // nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("price").order(SortOrder.DESC)); // }else{ // //按相关度 // nativeSearchQueryBuilder.withSort(SortBuilders.scoreSort().order(SortOrder.DESC)); // } nativeSearchQueryBuilder.withSort(SortBuilders.scoreSort().order(SortOrder.DESC)); NativeSearchQuery searchQuery = nativeSearchQueryBuilder.build(); LOGGER.info("DSL:{}", searchQuery.getQuery().toString()); return productRepository.search(searchQuery); } ``` es中的数据是: ``` { "code": 200, "message": "操作成功", "data": { "pageNum": 0, "pageSize": 5, "totalPage": 4, "total": 17, "list": [ { "id": 40, "productSn": "C146179 ", "brandId": null, "brandName": "PSA(信昌电陶)", "productCategoryId": 54, "productName": "贴片电容/220nF(224)±10%250V编带", "sale": 1000, "subTitle": "贴片电容", "price": null, "keywords": "贴片电容/220nF(224) ±10% 250V 编带 ", "attributeList": [ { "id": 49, "paProductAttributeName": "容值", "attributeValues": [ { "id": 240, "pavProductAttributeValue": "0.1pf" }, { "id": 241, "pavProductAttributeValue": "0.2pf" }, { "id": 242, "pavProductAttributeValue": "0.25pf" }, { "id": 243, "pavProductAttributeValue": "0.3pf" }, { "id": 244, "pavProductAttributeValue": "0.4pf" } ] }, { "id": 51, "paProductAttributeName": "额定电压", "attributeValues": [ { "id": 290, "pavProductAttributeValue": "4v" }, { "id": 292, "pavProductAttributeValue": "10v" }, { "id": 296, "pavProductAttributeValue": "30v" } ] } ], "productCategorie": { "id": 54, "productCategoryName": "贴片电容" } }, { "id": 41, "productSn": "C394163 ", "brandId": null, "brandName": "PSA(信昌电陶)", "productCategoryId": 54, "productName": "贴片电容/10nF(103) ±10% 1KV", "sale": 1000, "subTitle": "贴片电容", "price": null, "keywords": "贴片电容/10nF(103) ±10% 1KV ", "attributeList": [ { "id": 49, "paProductAttributeName": "容值", "attributeValues": [ { "id": 245, "pavProductAttributeValue": "0.5pf" }, { "id": 246, "pavProductAttributeValue": "0.6pf" }, { "id": 247, "pavProductAttributeValue": "0.68pf" } ] }, { "id": 50, "paProductAttributeName": "精度", "attributeValues": [ { "id": 272, "pavProductAttributeValue": "+0.05pf" }, { "id": 273, "pavProductAttributeValue": "+0.1pf" }, { "id": 274, "pavProductAttributeValue": "+0.25pf" } ] }, { "id": 51, "paProductAttributeName": "额定电压", "attributeValues": [ { "id": 291, "pavProductAttributeValue": "6.3v" }, { "id": 293, "pavProductAttributeValue": "16v" }, { "id": 297, "pavProductAttributeValue": "35v" } ] } ], "productCategorie": { "id": 54, "productCategoryName": "贴片电容" } }, { "id": 44, "productSn": "C342641 ", "brandId": null, "brandName": "TDK", "productCategoryId": 54, "productName": "贴片电容/47nF(473) ±5% 100V 编带", "sale": 1000, "subTitle": "贴片电容", "price": null, "keywords": "贴片电容/47nF(473) ±5% 100V 编带 ", "attributeList": [ { "id": 49, "paProductAttributeName": "容值", "attributeValues": [ { "id": 254, "pavProductAttributeValue": "1.3pf" }, { "id": 255, "pavProductAttributeValue": "1.4pf" }, { "id": 256, "pavProductAttributeValue": "2pf" }, { "id": 257, "pavProductAttributeValue": "2.1pf" } ] }, { "id": 50, "paProductAttributeName": "精度", "attributeValues": [ { "id": 278, "pavProductAttributeValue": "+5%" } ] } ], "productCategorie": { "id": 54, "productCategoryName": "贴片电容" } }, { "id": 48, "productSn": "C11366 ", "brandId": null, "brandName": " AVX", "productCategoryId": 55, "productName": "钽电容/22uF(226) ±10% 10V", "sale": 1000, "subTitle": "钽电容", "price": null, "keywords": "钽电容/22uF(226) ±10% 10V ", "attributeList": [ { "id": 49, "paProductAttributeName": "容值", "attributeValues": [ { "id": 269, "pavProductAttributeValue": "0.1pf" }, { "id": 270, "pavProductAttributeValue": "0.2pf" } ] }, { "id": 50, "paProductAttributeName": "精度", "attributeValues": [ { "id": 271, "pavProductAttributeValue": "+0.02pf" }, { "id": 284, "pavProductAttributeValue": "-20%,+80%" } ] } ], "productCategorie": { "id": 55, "productCategoryName": "钽电容" } }, { "id": 52, "productSn": "C391913 ", "brandId": null, "brandName": "SAMYOUNG(韩国三莹)", "productCategoryId": 56, "productName": "贴片电解电容/10uF ±20% 50V", "sale": 1000, "subTitle": "贴片电解电容", "price": null, "keywords": "贴片电解电容/10uF ±20% 50V ", "attributeList": [], "productCategorie": { "id": 56, "productCategoryName": "贴片电解电容" } } ] } } ``` 然后搜索了半天一点反应也没有,也没有头绪,求助大神指点
android 关于listview convertview的一些问题,求解!
![图片说明](https://img-ask.csdn.net/upload/201603/14/1457947694_116075.png) 做的是一个聊天界面,这是adapter代码。 运行时只能输入一次,输第二次时,参数convertview是第二次view的对象,不知道为什么啊。 ``` package com.example.chattest; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; public class ChatActivity extends Activity implements OnClickListener { private Button btnSend; private ListView lvChat; private EditText etSendContent; //聊天内容的适配器 private ChatMsgViewAdapter chatMsgAdapter; //聊天内容 private List<ChatMsgInfo> chatMsgDataArrays = new ArrayList<ChatMsgInfo>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //不显示标题栏 requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.chat); initView(); initData(); } //初始化视图 private void initView() { lvChat = (ListView) findViewById(R.id.chat_listview); btnSend = (Button) findViewById(R.id.btn_send); btnSend.setOnClickListener(this); etSendContent = (EditText) findViewById(R.id.et_sendmessage); } //聊天数据 //private final static int COUNT = 10 private String text = new String("第1种写法果然最慢,第二种写法由于用了StringBuffer,快了很多。奇怪的是" + "第4种写法竟然也很快,比用StringBuffer还快,怎么回事?其实慢,第二种写" + "法由于用了StringBuffer,快了很多。奇怪的是第4种写法竟然也很快,比用StringBuffer还快,怎" + "比用StringBuffer还快,怎么回事?其r还快,怎么回事?其回事?其如果你调试过字符串连接的执行过程就会知"); private String date = new String("2016-3-10 18:11"); //初始化数据 private void initData() { ChatMsgInfo msgExample = new ChatMsgInfo("XiaoMing", date, text, true); chatMsgDataArrays.add(msgExample); chatMsgAdapter = new ChatMsgViewAdapter(this, chatMsgDataArrays); //listview绑定adapter lvChat.setAdapter(chatMsgAdapter); } @Override public void onClick(View v) { // TODO Auto-generated method stub switch(v.getId()) { case R.id.btn_send: send(); break; } } //发送按钮的响应函数 private void send() { //获取输入文本框内容 String sendContent = etSendContent.getText().toString(); if (sendContent.length() > 0) { ChatMsgInfo msg = new ChatMsgInfo("XiaoHong", getDate(), sendContent, false); chatMsgDataArrays.add(msg); //通过一个外部的方法控制如果适配器的内容改变时需要强制调用getView来刷新每个Item的内容。 Log.d("chattest", "after setchanged!"); chatMsgAdapter.notifyDataSetChanged(); etSendContent.setText(""); //定位到最后一行 Log.d("chattest", "after setSelection!"); lvChat.setSelection(lvChat.getCount() -1 ); } } //获取时间 private String getDate() { Calendar c = Calendar.getInstance(); String year = String.valueOf(c.get(Calendar.YEAR)); String month = String.valueOf(c.get(Calendar.MONTH)); String day = String.valueOf(c.get(Calendar.DAY_OF_MONTH) + 1); String hour = String.valueOf(c.get(Calendar.HOUR_OF_DAY)); String mins = String.valueOf(c.get(Calendar.MINUTE)); StringBuffer buffer = new StringBuffer(); buffer.append(year + "-" + month + "-" + day + " " + hour + ":" + mins); return buffer.toString(); } } ``` ``` package com.example.chattest; import java.util.List; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; public class ChatMsgViewAdapter extends BaseAdapter { private static final int TYPE_COM_MSG = 0; private static final int TYPE_TO_MSG = 1; //private static final int TAG_KEY_ITEM_TYPE = 0; //private static final int TAG_KEY_VIEWHOLDER = 1; private List<ChatMsgInfo> data;//数据list private LayoutInflater myInflater;//layout convert view对象 private Context context;//环境 //构造 public ChatMsgViewAdapter(Context context, List<ChatMsgInfo> data) { this.context = context; this.data = data; myInflater = LayoutInflater.from(context); } @Override public int getItemViewType(int position) { // TODO Auto-generated method stub ChatMsgInfo msg = data.get(position); if (msg.getMsgType()) { return TYPE_COM_MSG; } else { return TYPE_TO_MSG; } } @Override public int getViewTypeCount() { // TODO Auto-generated method stub return 2; } //获取ListView的个数 @Override public int getCount() { return data.size(); } //获取项 @Override public Object getItem(int position) { return data.get(position); } //获取项的id @Override public long getItemId(int position) { return position; } //获取view @Override public View getView(int position, View convertView, ViewGroup parent) { ChatMsgInfo chatMsg = data.get(position);//聊天数据 boolean isComMsg = chatMsg.getMsgType();//数据类型(发送、接收) LeftItemViewHolder leftViewHolder = null; RightItemViewHolder rightViewHolder = null; int viewType = getItemViewType(position); System.out.println(position + " " + convertView); if (convertView == null || ((Integer)convertView.getTag(R.id.tag_item_viewtype)) != viewType) { //区分消息类别,展示不同的界面 if (viewType == TYPE_COM_MSG) { convertView = myInflater.inflate(R.layout.chat_msg_text_left_item, null); leftViewHolder = new LeftItemViewHolder(); leftViewHolder.tvSendTime = (TextView) convertView.findViewById(R.id.tv_sendtime); leftViewHolder.tvUserName = (TextView) convertView.findViewById(R.id.tv_username); leftViewHolder.tvContent = (TextView) convertView.findViewById(R.id.tv_chatcontent); leftViewHolder.isComMsg = isComMsg; convertView.setTag(R.id.tag_item_viewholder, leftViewHolder); } else { convertView = myInflater.inflate(R.layout.chat_msg_text_right_item, null); rightViewHolder = new RightItemViewHolder(); rightViewHolder.tvSendTime = (TextView) convertView.findViewById(R.id.tv_sendtime); rightViewHolder.tvContent = (TextView) convertView.findViewById(R.id.tv_chatcontent); rightViewHolder.isComMsg = isComMsg; convertView.setTag(R.id.tag_item_viewtype, rightViewHolder); } convertView.setTag(R.id.tag_item_viewtype, viewType); } else { if (viewType == TYPE_COM_MSG) { leftViewHolder = (LeftItemViewHolder) convertView.getTag(R.id.tag_item_viewholder); } else { rightViewHolder = (RightItemViewHolder) convertView.getTag(R.id.tag_item_viewholder); } } if (viewType == TYPE_COM_MSG) { leftViewHolder.tvUserName.setText(chatMsg.getName()); leftViewHolder.tvSendTime.setText(chatMsg.getDate()); leftViewHolder.tvContent.setText(chatMsg.getText()); } else { rightViewHolder.tvSendTime.setText(chatMsg.getDate()); rightViewHolder.tvContent.setText(chatMsg.getText()); } System.out.println(position + " " + convertView); return convertView; } //保存项,显示项的内容 static class LeftItemViewHolder { public TextView tvSendTime; public TextView tvUserName; public TextView tvContent; public boolean isComMsg = true; } static class RightItemViewHolder { public TextView tvSendTime; public TextView tvContent; public boolean isComMsg = true; } } ```
java分页运行后无法点击换页,其他正常,求大神指教
public class PageBean { private static final int size=5; private int count;//总条数 private int pageSize;//每页条数 private int pageCount;//总页数 private int curPage;//当前页 public PageBean(){ this.pageSize=size; curPage=1; } public PageBean(int pageSize){ this.pageSize=pageSize; curPage=1; } // public int getPCount(){ // System.out.println("==============="+pageCount); // return pageCount; // } public int getCount() { //System.out.println("============"+count); return count; } public void setCount(int count) { this.count = count; //计算总页数 this.pageCount=count%this.pageSize==0?count/this.pageSize:count/this.pageSize+1; System.out.println("====~~~~"+pageCount); } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getPageCount() { //this.pageCount=this.count%this.pageSize==0?this.count/this.pageSize:this.count/this.pageSize+1; System.out.println("==============="+pageCount); return this.pageCount; } public void setPageCount(int pageCount) { this.pageCount = pageCount; } public int getCurPage() { return curPage; } public void setCurPage(int curPage) { this.curPage = curPage; } public int prePage(){ if(this.curPage==1){ return 1; } return this.curPage-1; } public int nextPage(){ if(this.curPage==pageCount){ return pageCount; } return curPage+1; } public int getStart(){ return this.pageSize*(this.curPage-1); } public class DbDao { private Statement st; public DbDao(Statement st) { // TODO 自动生成的构造函数存根 this.st = st; } public int insert(String sql) { int t = 0; try { t = st.executeUpdate(sql); } catch (SQLException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } return t; } public int update(String sql) { int t = 0; try { t = st.executeUpdate(sql); } catch (SQLException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } return t; } public int del(String sql) { int t = 0; try { t = st.executeUpdate(sql); } catch (SQLException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } return t; } public ResultSet query(String sql) { ResultSet rs=null; try { rs = st.executeQuery(sql); } catch (SQLException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } return rs; } public ResultSet pageQuery(String sql,PageBean page) { ResultSet rs=null; try { int count=queryCount(sql); if(count==0){ return null; } page.setCount(count); sql=sql+" limit "+page.getStart()+","+page.getPageSize(); rs = st.executeQuery(sql); } catch (SQLException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } return rs; } public int queryCount(String sql){ String countsql="select count(*) c from ("+sql+")t"; ResultSet rs=this.query(countsql); try { if(rs.next()){ return rs.getInt(1); } } catch (SQLException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); return 0; } return 0; } @Override protected void finalize() throws Throwable { // TODO 自动生成的方法存根 super.finalize(); if(st!=null) { st.close(); } } public <E> List<E> queryObjectList(String sql,String ClassName) throws SQLException, IllegalArgumentException, IllegalAccessException, InstantiationException, ClassNotFoundException { //连接数据库 ResultSet rs=this.query(sql); ResultSetMetaData meta=rs.getMetaData(); int count=meta.getColumnCount();//字段的数量 Class cla=Class.forName(ClassName); Field[] fs=cla.getDeclaredFields(); List<E> list=new ArrayList<E>(); while(rs.next()) { Object obj=cla.newInstance(); for(int i=1;i<=count;i++)//数组的字段 { for(Field f:fs)//类里的属性 { //类的字段名称==数据库字段名称 赋值 if(f.getName().equals(meta.getColumnName(i))) //属性是否和字段一样 { if("INT".equals(meta.getColumnTypeName(i))) { f.set(obj, rs.getInt(meta.getColumnName(i))); } if("VARCHAR".equals(meta.getColumnTypeName(i))) { f.set(obj, rs.getString(meta.getColumnName(i))); } } } } list.add((E)obj); } rs.close(); return list; } public class Testservlet extends HttpServlet { /** * */ private static final long serialVersionUID = -5562520410425589914L; @Override protected void service(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { // TODO 自动生成的方法存根 try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); }//驱动 String url = "jdbc:mysql://127.0.0.1:3306/mysql_test";//url Connection conn=null; Statement st=null; try { conn = DriverManager.getConnection(url, "root", "heihei77"); st=conn.createStatement(); } catch (SQLException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } String name=""; Integer age=0; if(req.getParameter("username")!=null&&req.getParameter("username").trim()!=""){ name=req.getParameter("username").trim(); } if(req.getParameter("age")!=null&&req.getParameter("age").trim()!=""){ age=Integer.parseInt(req.getParameter("age").trim()); } //查询当前表格的数据 DbDao dbDao = new DbDao(st); //ResultSet rs=null; PageBean pageBean=new PageBean(); String page=req.getParameter("page");//?????????????????????? if(page!=null&&!"".equals(page)){ pageBean.setCurPage(Integer.parseInt(page.trim())); } List<User> list=new ArrayList<User>(); try { ResultSet rs=dbDao.pageQuery("select id,name,age from sqlpp",pageBean); if(rs!=null){ while(rs.next()){ User u=new User(); u.setAge(rs.getInt("age")); u.setId(rs.getInt("id")); u.setName(rs.getString("name")); list.add(u); }} rs.close(); } catch (SQLException e1) { // TODO 自动生成的 catch 块 e1.printStackTrace(); } //保存list req req.setAttribute("list", list); req.setAttribute("pageBean", pageBean); req.getRequestDispatcher("userList.jsp").forward(req, response); }
不知道哪里报空指针错误,找不到
``` package com.example.dan1244; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; import android.widget.Toast; public class MyDB { public SQLiteDatabase db=null; //数据库类 private final static String DATABASE_NAME= "db1.db";//数据库名称 private final static String TABLE_NAME="table01"; //数据表名称 private final static String _ID = "_id"; //数据表字段/ private final static String NAME = "name"; private final static String PRICE = "price"; private final static String NO = "no"; /*建立数据表的字段*/ private final static String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" + _ID + " integer primary key autoincrement," + NAME + " text,"+ NO + " text);"; private Context mCtx = null; /** public MyDB(Context ctx,String name,CursorFactory factory,int version) {//构造函数 super(ctx,name,factory,version); this.mCtx=ctx; //传入建立对象的Activity } public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_TABLE); Toast.makeText(mCtx,"创建成功!",Toast.LENGTH_LONG).show(); } public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion) { }**/ public void open() throws SQLException { //打开已经存在的数据库 //super.onOpen(db); db = mCtx.openOrCreateDatabase(DATABASE_NAME, 0, null); try { db.execSQL(CREATE_TABLE);//建立数据表 }catch (Exception e) { Toast.makeText(mCtx,"创建失败!",Toast.LENGTH_LONG).show(); } } public void close() { //关闭数据库 db.close(); } // public Cursor getAll() { //查询所有数据,取出所有的字段 // return db.rawQuery("SELECT * FROM " + TABLE_NAME, null); // } public Cursor getAll() { //查询所有数据,只取出三个字段 return db.query(TABLE_NAME, new String[] {_ID, NAME, PRICE}, null, null, null, null, null,null); } // public Cursor get(long rowId) throws SQLException { // 查询指定ID的数据,只取出三个字段 // Cursor mCursor = db.query(TABLE_NAME, // new String[] {_ID, NAME, PRICE}, // _ID +"=" + rowId, null, null, null, null,null); // if (mCursor != null) { // mCursor.moveToFirst(); // } // return mCursor; // } public long append(String no,String name) { //新增一条记录 ContentValues args = new ContentValues(); args.put(NO, no); args.put(NAME, name); return db.insert(TABLE_NAME, null, args); } public boolean delete(long rowId) { //删除指定的数据 return db.delete(TABLE_NAME, _ID + "=" + rowId, null) > 0; } public boolean update(long rowId, String name,int price) { //更新指定的数据 ContentValues args = new ContentValues(); args.put(NAME, name); args.put(PRICE, price); return db.update(TABLE_NAME, args,_ID + "=" + rowId, null) > 0; } public void droptable() { // TODO Auto-generated method stub db.execSQL("DROP TABLE "+TABLE_NAME); } public Cursor get(String s) throws SQLException { // TODO Auto-generated method stub Cursor mCursor = db.query(TABLE_NAME, new String[] {_ID, NAME, NO}, NO +"=" + "'"+s+"'", null, null, null, null,null); return mCursor; } } ``` ``` package com.example.dan1244; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; public class MainActivity extends Activity implements OnClickListener { private MyDB db=null; Cursor cursor; Button bu1; Button bu2; EditText ed1, ed2, ed3; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bu1=(Button) findViewById(R.id.button1); bu2=(Button) findViewById(R.id.button2); ed1=(EditText) findViewById(R.id.editText1); ed2=(EditText) findViewById(R.id.editText2); ed3=(EditText) findViewById(R.id.editText3); bu1.setOnClickListener(this); bu2.setOnClickListener(this); db=new MyDB(); db.open(); } @Override public void onClick(View v) { // TODO Auto-generated method stub try { switch (v.getId()) { case R.id.button1: String dc=ed1.getText().toString(); String js=ed2.getText().toString(); db.append(dc,js); Toast.makeText(MainActivity.this, "添加成功", Toast.LENGTH_LONG).show(); break; case R.id.button2: String s=ed3.getText().toString(); cursor=db.get(s); Bundle data=new Bundle(); data.putSerializable("data", converCursorToList(cursor)); Intent i=new Intent(MainActivity.this, Sdier.class); i.putExtras(data); startActivity(i); break; } } catch (Exception e) { // TODO: handle exception Toast.makeText(MainActivity.this, "失败", Toast.LENGTH_LONG).show(); Log.e("--------", e.getMessage()); } } protected ArrayList<Map<String, String> > converCursorToList(Cursor cursor){ ArrayList<Map<String, String>> result = new ArrayList<Map<String,String>>(); //遍历Cursor结果集 while(cursor.moveToNext()){ //将结果集集中地数据存入Arraylist中 Map<String,String> map = new HashMap<String, String>(); map.put("name", cursor.getString(1)); map.put("no", cursor.getString(2)); result.add(map); } return result; } @Override protected void onDestroy() { super.onDestroy(); db.droptable(); db.close(); } @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 boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } } ``` ![图片说明](https://img-ask.csdn.net/upload/201705/01/1493619445_327748.jpg)
统计一篇文章中单词个数的问题,效率很烂
程序可以运行,就是在打印输出的时候,会花费很多时间,请教大虾们怎么优化这段代码 [code="java"] for (int i = 0; i < size2; i++) { System.out.print(keys2[i] + "\t\t"); for (int j = 0; j < size; j++) { Map<String, Integer> temp = list.get(j); if (temp.containsKey(keys2[i])) { System.out.print(temp.get(keys2[i])); break; } } System.out.println(); } [/code] 本人感激不尽 这是完整程序: [code="java"] package countwords; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; /** * @author qingyun * @version 2010.02.03 * */ public class CountWords { // private static List<Map<String, Integer>> list; // 单词分界符 private static final String regex = "\\W"; // 排除 数字 干扰 private static final String regex_digital = "\\d*"; public static void main(String[] args) throws IOException { list = new ArrayList<Map<String, Integer>>(); File file = new File("D://file.txt"); if (!file.exists()) { System.out.println("file not exists!"); return; } else { long currentTime = System.currentTimeMillis(); count(file); System.out.println("count cost time :" + (System.currentTimeMillis() - currentTime)); } long currentTime1 = System.currentTimeMillis(); print(list); System.out.println("print cost time :" + (System.currentTimeMillis() - currentTime1)); } /** * 统计函数 * * @param file * @throws IOException */ public static void count(File file) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(file)); String line = null; while ((line = reader.readLine()) != null) { /** * */ String[] temp = line.split(regex); for (int i = 0; i < temp.length; i++) { Map<String, Integer> map = new HashMap<String, Integer>(); String key = temp[i]; /** * 当时空置时的处理 不能用 == 来做判断 */ if ("".equals(key) || key.matches(regex_digital)) { continue; } else { // 使被统计的单词不区分大小写 key = key.toLowerCase(); } int num = 1; /** * first add */ if (list.isEmpty()) { map.put(key, num); list.add(map); } else { // 遍历 list for (int j = 0; j < list.size(); j++) { Map<String, Integer> index = list.get(j); // 如果存在,就将key对应 value 加一 ,然后删除此节点,再添加到list当中 if (index.containsKey(key)) { num = index.get(key); num++; index.remove(key); } } map.put(key, num); list.add(map); } } } } /** * 打印函数 * * 考虑直接遍历此list,产生输出,但是发现效率不佳 * */ private static void print(List<Map<String, Integer>> list) { int size = list.size(); Set<String> keys = new HashSet<String>(); for (int i = 0; i < size; i++) { Map<String, Integer> map = list.get(i); keys.addAll(map.keySet()); } System.out.println("keys size : " + keys.size()); Object[] keys2 = keys.toArray(); int size2 = keys2.length; Arrays.sort(keys2); System.out.print("word" + "\t\t"); System.out.println("total"); long now = System.currentTimeMillis(); /** * 就这个地方的遍历花费很多时间,请教这个地方的代码优化 */ for (int i = 0; i < size2; i++) { System.out.print(keys2[i] + "\t\t"); for (int j = 0; j < size; j++) { Map<String, Integer> temp = list.get(j); if (temp.containsKey(keys2[i])) { System.out.print(temp.get(keys2[i])); break; } } System.out.println(); } System.out.println("-----" + (System.currentTimeMillis() - now)); } } [/code]
终于明白阿里百度这样的大公司,为什么面试经常拿ThreadLocal考验求职者了
点击上面↑「爱开发」关注我们每晚10点,捕获技术思考和创业资源洞察什么是ThreadLocalThreadLocal是一个本地线程副本变量工具类,各个线程都拥有一份线程私...
《奇巧淫技》系列-python!!每天早上八点自动发送天气预报邮件到QQ邮箱
将代码部署服务器,每日早上定时获取到天气数据,并发送到邮箱。 也可以说是一个小人工智障。 思路可以运用在不同地方,主要介绍的是思路。
加快推动区块链技术和产业创新发展,2019可信区块链峰会在京召开
11月8日,由中国信息通信研究院、中国通信标准化协会、中国互联网协会、可信区块链推进计划联合主办,科技行者协办的2019可信区块链峰会将在北京悠唐皇冠假日酒店开幕。   区块链技术被认为是继蒸汽机、电力、互联网之后,下一代颠覆性的核心技术。如果说蒸汽机释放了人类的生产力,电力解决了人类基本的生活需求,互联网彻底改变了信息传递的方式,区块链作为构造信任的技术有重要的价值。   1...
阿里面试官问我:如何设计秒杀系统?我的回答让他比起大拇指
你知道的越多,你不知道的越多 点赞再看,养成习惯 GitHub上已经开源 https://github.com/JavaFamily 有一线大厂面试点脑图和个人联系方式,欢迎Star和指教 前言 Redis在互联网技术存储方面使用如此广泛,几乎所有的后端技术面试官都要在Redis的使用和原理方面对小伙伴们进行360°的刁难。 作为一个在互联网公司面一次拿一次Offer的面霸,打败了...
C语言魔塔游戏
很早就很想写这个,今天终于写完了。 游戏截图: 编译环境: VS2017 游戏需要一些图片,如果有想要的或者对游戏有什么看法的可以加我的QQ 2985486630 讨论,如果暂时没有回应,可以在博客下方留言,到时候我会看到。 下面我来介绍一下游戏的主要功能和实现方式 首先是玩家的定义,使用结构体,这个名字是可以自己改变的 struct gamerole { char n...
面试官问我:什么是消息队列?什么场景需要他?用了会出现什么问题?
你知道的越多,你不知道的越多 点赞再看,养成习惯 GitHub上已经开源 https://github.com/JavaFamily 有一线大厂面试点脑图、个人联系方式和人才交流群,欢迎Star和完善 前言 消息队列在互联网技术存储方面使用如此广泛,几乎所有的后端技术面试官都要在消息队列的使用和原理方面对小伙伴们进行360°的刁难。 作为一个在互联网公司面一次拿一次Offer的面霸...
Android性能优化(4):UI渲染机制以及优化
文章目录1. 渲染机制分析1.1 渲染机制1.2 卡顿现象1.3 内存抖动2. 渲染优化方式2.1 过度绘制优化2.1.1 Show GPU overdraw2.1.2 Profile GPU Rendering2.2 卡顿优化2.2.1 SysTrace2.2.2 TraceView 在从Android 6.0源码的角度剖析View的绘制原理一文中,我们了解到View的绘制流程有三个步骤,即m...
微服务中的Kafka与Micronaut
今天,我们将通过Apache Kafka主题构建一些彼此异步通信的微服务。我们使用Micronaut框架,它为与Kafka集成提供专门的库。让我们简要介绍一下示例系统的体系结构。我们有四个微型服务:订单服务,行程服务,司机服务和乘客服务。这些应用程序的实现非常简单。它们都有内存存储,并连接到同一个Kafka实例。 我们系统的主要目标是为客户安排行程。订单服务应用程序还充当网关。它接收来自客户的请求...
致 Python 初学者们!
作者| 许向武 责编 | 屠敏 出品 | CSDN 博客 前言 在 Python 进阶的过程中,相信很多同学应该大致上学习了很多 Python 的基础知识,也正在努力成长。在此期间,一定遇到了很多的困惑,对未来的学习方向感到迷茫。我非常理解你们所面临的处境。我从2007年开始接触 Python 这门编程语言,从2009年开始单一使用 Python 应对所有的开发工作,直至今...
究竟你适不适合买Mac?
我清晰的记得,刚买的macbook pro回到家,开机后第一件事情,就是上了淘宝网,花了500元钱,找了一个上门维修电脑的师傅,上门给我装了一个windows系统。。。。。。 表砍我。。。 当时买mac的初衷,只是想要个固态硬盘的笔记本,用来运行一些复杂的扑克软件。而看了当时所有的SSD笔记本后,最终决定,还是买个好(xiong)看(da)的。 已经有好几个朋友问我mba怎么样了,所以今天尽量客观...
程序员一般通过什么途径接私活?
二哥,你好,我想知道一般程序猿都如何接私活,我也想接,能告诉我一些方法吗? 上面是一个读者“烦不烦”问我的一个问题。其实不止是“烦不烦”,还有很多读者问过我类似这样的问题。 我接的私活不算多,挣到的钱也没有多少,加起来不到 20W。说实话,这个数目说出来我是有点心虚的,毕竟太少了,大家轻喷。但我想,恰好配得上“一般程序员”这个称号啊。毕竟苍蝇再小也是肉,我也算是有经验的人了。 唾弃接私活、做外...
字节跳动面试官这样问消息队列:分布式事务、重复消费、顺序消费,我整理了一下
你知道的越多,你不知道的越多 点赞再看,养成习惯 GitHub上已经开源 https://github.com/JavaFamily 有一线大厂面试点脑图、个人联系方式和人才交流群,欢迎Star和完善 前言 消息队列在互联网技术存储方面使用如此广泛,几乎所有的后端技术面试官都要在消息队列的使用和原理方面对小伙伴们进行360°的刁难。 作为一个在互联网公司面一次拿一次Offer的面霸...
Python爬虫爬取淘宝,京东商品信息
小编是一个理科生,不善长说一些废话。简单介绍下原理然后直接上代码。 使用的工具(Python+pycharm2019.3+selenium+xpath+chromedriver)其中要使用pycharm也可以私聊我selenium是一个框架可以通过pip下载 pip installselenium -ihttps://pypi.tuna.tsinghua.edu.cn/simple/ ...
阿里程序员写了一个新手都写不出的低级bug,被骂惨了。
这种新手都不会范的错,居然被一个工作好几年的小伙子写出来,差点被当场开除了。
Java工作4年来应聘要16K最后没要,细节如下。。。
前奏: 今天2B哥和大家分享一位前几天面试的一位应聘者,工作4年26岁,统招本科。 以下就是他的简历和面试情况。 基本情况: 专业技能: 1、&nbsp;熟悉Sping了解SpringMVC、SpringBoot、Mybatis等框架、了解SpringCloud微服务 2、&nbsp;熟悉常用项目管理工具:SVN、GIT、MAVEN、Jenkins 3、&nbsp;熟悉Nginx、tomca...
SpringBoot2.x系列教程(三十六)SpringBoot之Tomcat配置
Spring Boot默认内嵌的Tomcat为Servlet容器,关于Tomcat的所有属性都在ServerProperties配置类中。同时,也可以实现一些接口来自定义内嵌Servlet容器和内嵌Tomcat等的配置。 关于此配置,网络上有大量的资料,但都是基于SpringBoot1.5.x版本,并不适合当前最新版本。本文将带大家了解一下最新版本的使用。 ServerProperties的部分源...
Python绘图,圣诞树,花,爱心 | Turtle篇
每周每日,分享Python实战代码,入门资料,进阶资料,基础语法,爬虫,数据分析,web网站,机器学习,深度学习等等。 公众号回复【进群】沟通交流吧,QQ扫码进群学习吧 微信群 QQ群 1.画圣诞树 import turtle screen = turtle.Screen() screen.setup(800,600) circle = turtle.Turtle()...
作为一个程序员,CPU的这些硬核知识你必须会!
CPU对每个程序员来说,是个既熟悉又陌生的东西? 如果你只知道CPU是中央处理器的话,那可能对你并没有什么用,那么作为程序员的我们,必须要搞懂的就是CPU这家伙是如何运行的,尤其要搞懂它里面的寄存器是怎么一回事,因为这将让你从底层明白程序的运行机制。 随我一起,来好好认识下CPU这货吧 把CPU掰开来看 对于CPU来说,我们首先就要搞明白它是怎么回事,也就是它的内部构造,当然,CPU那么牛的一个东...
破14亿,Python分析我国存在哪些人口危机!
一、背景 二、爬取数据 三、数据分析 1、总人口 2、男女人口比例 3、人口城镇化 4、人口增长率 5、人口老化(抚养比) 6、各省人口 7、世界人口 四、遇到的问题 遇到的问题 1、数据分页,需要获取从1949-2018年数据,观察到有近20年参数:LAST20,由此推测获取近70年的参数可设置为:LAST70 2、2019年数据没有放上去,可以手动添加上去 3、将数据进行 行列转换 4、列名...
听说想当黑客的都玩过这个Monyer游戏(1~14攻略)
第零关 进入传送门开始第0关(游戏链接) 请点击链接进入第1关: 连接在左边→ ←连接在右边 看不到啊。。。。(只能看到一堆大佬做完的留名,也能看到菜鸡的我,在后面~~) 直接fn+f12吧 &lt;span&gt;连接在左边→&lt;/span&gt; &lt;a href="first.php"&gt;&lt;/a&gt; &lt;span&gt;←连接在右边&lt;/span&gt; o...
在家远程办公效率低?那你一定要收好这个「在家办公」神器!
相信大家都已经收到国务院延长春节假期的消息,接下来,在家远程办公可能将会持续一段时间。 但是问题来了。远程办公不是人在电脑前就当坐班了,相反,对于沟通效率,文件协作,以及信息安全都有着极高的要求。有着非常多的挑战,比如: 1在异地互相不见面的会议上,如何提高沟通效率? 2文件之间的来往反馈如何做到及时性?如何保证信息安全? 3如何规划安排每天工作,以及如何进行成果验收? ...... ...
作为一个程序员,内存和磁盘的这些事情,你不得不知道啊!!!
截止目前,我已经分享了如下几篇文章: 一个程序在计算机中是如何运行的?超级干货!!! 作为一个程序员,CPU的这些硬核知识你必须会! 作为一个程序员,内存的这些硬核知识你必须懂! 这些知识可以说是我们之前都不太重视的基础知识,可能大家在上大学的时候都学习过了,但是嘞,当时由于老师讲解的没那么有趣,又加上这些知识本身就比较枯燥,所以嘞,大家当初几乎等于没学。 再说啦,学习这些,也看不出来有什么用啊!...
这个世界上人真的分三六九等,你信吗?
偶然间,在知乎上看到一个问题 一时间,勾起了我深深的回忆。 以前在厂里打过两次工,做过家教,干过辅导班,做过中介。零下几度的晚上,贴过广告,满脸、满手地长冻疮。 再回首那段岁月,虽然苦,但让我学会了坚持和忍耐。让我明白了,在这个世界上,无论环境多么的恶劣,只要心存希望,星星之火,亦可燎原。 下文是原回答,希望能对你能有所启发。 如果我说,这个世界上人真的分三六九等,...
2020年全新Java学习路线图,含配套视频,学完即为中级Java程序员!!
新的一年来临,突如其来的疫情打破了平静的生活! 在家的你是否很无聊,如果无聊就来学习吧! 世上只有一种投资只赚不赔,那就是学习!!! 传智播客于2020年升级了Java学习线路图,硬核升级,免费放送! 学完你就是中级程序员,能更快一步找到工作! 一、Java基础 JavaSE基础是Java中级程序员的起点,是帮助你从小白到懂得编程的必经之路。 在Java基础板块中有6个子模块的学...
B 站上有哪些很好的学习资源?
哇说起B站,在小九眼里就是宝藏般的存在,放年假宅在家时一天刷6、7个小时不在话下,更别提今年的跨年晚会,我简直是跪着看完的!! 最早大家聚在在B站是为了追番,再后来我在上面刷欧美新歌和漂亮小姐姐的舞蹈视频,最近两年我和周围的朋友们已经把B站当作学习教室了,而且学习成本还免费,真是个励志的好平台ヽ(.◕ฺˇд ˇ◕ฺ;)ノ 下面我们就来盘点一下B站上优质的学习资源: 综合类 Oeasy: 综合...
爬取薅羊毛网站百度云资源
这是疫情期间无聊做的爬虫, 去获取暂时用不上的教程 import threading import time import pandas as pd import requests import re from threading import Thread, Lock # import urllib.request as request # req=urllib.request.Requ...
如何优雅地打印一个Java对象?
你好呀,我是沉默王二,一个和黄家驹一样身高,和刘德华一样颜值的程序员。虽然已经写了十多年的 Java 代码,但仍然觉得自己是个菜鸟(请允许我惭愧一下)。 在一个月黑风高的夜晚,我思前想后,觉得再也不能这么蹉跎下去了。于是痛下决心,准备通过输出的方式倒逼输入,以此来修炼自己的内功,从而进阶成为一名真正意义上的大神。与此同时,希望这些文章能够帮助到更多的读者,让大家在学习的路上不再寂寞、空虚和冷。 ...
雷火神山直播超两亿,Web播放器事件监听是怎么实现的?
Web播放器解决了在手机浏览器和PC浏览器上播放音视频数据的问题,让视音频内容可以不依赖用户安装App,就能进行播放以及在社交平台进行传播。在视频业务大数据平台中,播放数据的统计分析非常重要,所以Web播放器在使用过程中,需要对其内部的数据进行收集并上报至服务端,此时,就需要对发生在其内部的一些播放行为进行事件监听。 那么Web播放器事件监听是怎么实现的呢? 01 监听事件明细表 名...
3万字总结,Mysql优化之精髓
本文知识点较多,篇幅较长,请耐心学习 MySQL已经成为时下关系型数据库产品的中坚力量,备受互联网大厂的青睐,出门面试想进BAT,想拿高工资,不会点MySQL优化知识,拿offer的成功率会大大下降。 为什么要优化 系统的吞吐量瓶颈往往出现在数据库的访问速度上 随着应用程序的运行,数据库的中的数据会越来越多,处理时间会相应变慢 数据是存放在磁盘上的,读写速度无法和内存相比 如何优化 设计...
HTML5适合的情人节礼物有纪念日期功能
前言 利用HTML5,css,js实现爱心树 以及 纪念日期的功能 网页有播放音乐功能 以及打字倾诉感情的画面,非常适合情人节送给女朋友 具体的HTML代码 具体只要修改代码里面的男某某和女某某 文字段也可自行修改,还有代码下半部分的JS代码需要修改一下起始日期 注意月份为0~11月 也就是月份需要减一。 当然只有一部分HTML和JS代码不够运行的,文章最下面还附加了完整代码的下载地址 &lt;!...
相关热词 c# 时间比天数 c# oracle查询 c# 主动推送 事件 c# java 属性 c# 控制台 窗体 c# 静态类存值 c#矢量作图 c#窗体调用外部程式 c# enum是否合法 c# 如何卸载引用
立即提问