怎样理解java中Function<? super V, ? extends T>这样的声明?

小白刚学java,有点C++基础,core java 10看到泛型这一章觉得和C++的泛型差别太过巨大,理解非常费劲,语法看着也及其别扭,JDK的有些API有些函数声明都看不懂。。。
比如Comparator里面的这个方法:
public static Comparator comparing(
Function<? super T, ? extends U> keyExtractor, Comparator<? super U> keyComparator)
怎么理解Function<? super T, ? extends U>这个声明呢,网上查了半天都在讲生产者消费者的的准则,
但好像和这个又对不上号,苦思冥想快2天了。。。求解
PS:还有为啥我觉得java的泛型系统像是个半成品,好多莫名其妙的限制啊!!??

8个回答

再补充下,为什么参数是super返回值是extends
如果我们把函数想象成一个机器,比如面包机
参数是它需要的原料,比如白面粉
返回值是它能做的成品,比如面包

显然,对于原料我们需要提供的是白面粉或者它的派生类,比如一级白面粉、xx牌白面粉……但是如果是黑面粉,或者大米,这个面包机都不能工作。
而对于结果,恰恰相反,如果你要一个面包,这个机器能满足你,如果你要点心,也没有问题,任何基类都没有问题。但是如果你要切片面包或者法国面包,这个机器未必能满足你的要求了。

类似的,对于定义Lambda寒暑,我们需要让参数“严格”,用super,只能是派生类。对于返回值,我们需要让参数“宽松”,用extends,必须是基类。

qq52878691
qq52878691 有点明白了,谢啦,采纳你
2 年多之前 回复
caozhy
贵阳老马马善福专业维修游泳池堵漏防水工程 super是只允许派生类,也就是“严格”,参数必须严格。要面粉才能做面包,你绝对不能提供大米、粮食
2 年多之前 回复
caozhy
贵阳老马马善福专业维修游泳池堵漏防水工程 回复qq52878691: 我说的宽松,是从调用者来说,我需要食物、零食、面点、面包都可以用面包机。
2 年多之前 回复
qq52878691
qq52878691 面包,不是面板,打错了
2 年多之前 回复
qq52878691
qq52878691 感谢您的细心回答,但请问是不是说反了?既然参数要严格,那不是应该用extends吗?还有,返回值可以宽松又是什么道理呢,而且如果可以取任意基类应该用super啊?比如一个机器,我想让它给我生产面板,结果它只给我面粉,这样真的好嘛?能不能说的再透彻点?
2 年多之前 回复

通配符: “?”就是一个占位符,它不表示任何具体的类型,而是表示符合定义规则的一个或者多个类型的一个占位标志
边界:
<? extends T> 表示上界通配符 它表示T以及T的子类, 类型最高是T
<? super T> 表示下界通配符 它表示T以及T的超类,类型最高可到Object ,最低是T
<? extends T> 表示上界通配符 它表示T以及T的子类, 类型最高是T

这是java 8的lambda表达式,keyExtractor是相当于一个回调函数,它的参数是T,返回U,keyComparator是另一个回调函数。
从字面理解,第一个是提取需要比较的属性,第二个是比较。

lambda表达式参考:https://www.cnblogs.com/aoeiuv/p/5911692.html

java的泛型系统像是个半成品
这个是因为java是编译型语言,它必须在编译的程序的时候确定类型,所以它实际上用了“类型擦除”,也就是编译的时候将泛型类型替换成实际类型了。
这么做的好处是,编译器可以充分检查类型是否匹配,比如super,它可以判断这个类型是不是你要的派生类型。同时不用修改jvm的实现,直接就能运行,因为对于jvm,它根本就看不到泛型,看到的就是替换(或者说擦除)以后的类型。
坏处就是不能在运行的时候动态加载和创造泛型出来。

设置泛型对象的上限使用extends,表示参数类型只能是该类型或该类型的子类:

声明对象:类名<?extends 类> 对象名

定义类:类名<泛型标签 extends 类>{}

设置泛型对象的下限使用super,表示参数类型只能是该类型或该类型的父类:

声明对象:类名<?super 类> 对象名称

定义类:类名<泛型标签 extends类>{}

Function,这是函数式编程的核心内容。

这种泛型写法,我也见过,不过忘了啥意思,一般我还是可以推测的,T可以自己填写类型,比如String,T就代表了这个类型String,传入的继承必须这个类型,第一个难道是,传入的需要是泛型的父类?将你看的源码这里的方法贴出来,我研究研究,格式:包+类+方法名,我会自己去找

qq52878691
qq52878691 这个是jdk源码,java.util.Comparator.comparing
2 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
java 中用户名密码验证的代码怎么写?急!!在线等

import java.awt.GridLayout; import java.awt.event.*; import javax.swing.*; import com.sdu.wh.bll.UserQueryBll; import com.sdu.wh.dao.*; import com.sdu.wh.sql.*; public class LoginFrame extends JDialog implements ActionListener { private JTextField textName = new JTextField(); private JPasswordField textPW = new JPasswordField(); private JButton btnOK = new JButton("登录"); private JButton btnCancel = new JButton("取消"); //构造方法,参数1:宿主窗口, 参数2:是否模态窗口 public LoginFrame(JFrame jf, boolean model) { //调用父类 JDialog 的构造方法 super(jf, model); this.setTitle("学生选课管理系统登录"); this.setSize(300, 180); this.setLocation(500, 400); getContentPane().setLayout(new GridLayout(3,2,10,10)); getContentPane().add(new JLabel("用户名:")); getContentPane().add(textName); getContentPane().add(new JLabel("密码:")); getContentPane().add(textPW); getContentPane().add(btnOK); btnOK.addActionListener(this); getContentPane().add(btnCancel); btnCancel.addActionListener(this); this.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); this.setVisible(true); } public void actionPerformed(ActionEvent e) { if(e.getActionCommand()== "登录") { //登录密码的验证方法 //通过用户名到数据库中查到该用户名的密码 //与输入的密码比较 String uid=textName.getText(); String password=new String(textPW.getPassword()); String t=null; String sql="select 用户名,密码,角色,学院 from users where 用户名="+uid; SqlExecute excute=new SqlExecute(); User user = null; try { //如果两个输入框都不空 if(!uid.equals("")){ user = excute.getUser(sql); } } catch (Exception e1) { e1.printStackTrace(); } boolean isPass=!uid.equals("")&& uid.equals(user.getUid()) && !password.equals("") && password.equals(user.getPassword()); //如果通过验证 if(isPass) { //记录登录用户的id,学院,角色信息 StudentMainFrame.cUser.setUid(user.getUid()); StudentMainFrame.cUser.setDepart(user.getDepart()); StudentMainFrame.cUser.setType(user.getType()); //登录成功后销毁该登录窗口 this.dispose(); } else { //没有通过验证,弹出登陆错误提示信息 JOptionPane.showMessageDialog(this, "用户名或密码不正确!\r\n请重新填写。"); } } else //点取消按钮放弃登录,退出程序 System.exit(0); } }

.Java 中多个 class 的使用问题

**背景:**这是一个教科书上的计算器代码,因为代码中只有第一个是public class,所以我放到同一个.java文件中。 **过程:**用sublime将代码抄到电脑里,在Eclipse中打开却发现是 class 调用错误。检查了一边发现代码和书中相同,找不到错误的地方,随后我为各个class建了各自的.java文档,想这次如果有错误就是书中代码错了,但……显示正常,运行ok。 坑爹,我把代码粘贴回原来的.java文档,复制文档+换文件夹,拷贝的文件没有显示错误。但是class的名字是黄色未被调用(这不是废话么?不能调用你还运行个什么)。我再点击修复,得到 private static final long serialVersionUID = 1L; **秉着打破砂锅问到底的精神,所以**为什么第一次写上代码时是显示错误,复制粘贴之后又 ok 了呢? private static final long serialVersionUID = 1L; 这个量的意义何在? **而且:**只有 DigitButton 调用是 ok 的,剩下的AddButton、SubtractButton、MultiplyButton、ClearButton…ect 全是提示错误。OperatorButton 类被继承也是不可以的。 /** This program implements a simple four-function calculator */ public class come extends Program{ /* Initializes the user interface */ public void init(){ setLayout(new TableLayout(5,4)); display = new CalculatorDisplay(); add(display, "gridwidth=4 height=" + BUTTON_SIZE); addButtons(); addActionListeners(); } public void actionPerformed(ActionEvent e) { Object source = e.getSource(); if(source instanceof CalculatorButton){ ((CalculatorButton) source).action(display); } } private void addButtons(){ String constraint = "width=" + BUTTON_SIZE + " height=" + BUTTON_SIZE; add(new DigitButton(7), constraint); add(new DigitButton(8), constraint); add(new DigitButton(9), constraint); add(new AddButton(), constraint); add(new DigitButton(4), constraint); add(new DigitButton(5), constraint); add(new DigitButton(6), constraint); add(new SubtractButton(), constraint); add(new DigitButton(1), constraint); add(new DigitButton(2), constraint); add(new DigitButton(3), constraint); add(new MultiplyButton(), constraint); add(new ClearButton(), constraint); add(new DigitButton(0), constraint); add(new EqualsButton(), constraint); add(new DivideButton(), constraint); } private static final int BUTTON_SIZE = 40; private CalculatorDisplay display; } class CalculatorDisplay extends IntField{ /* Creates a new calculator display that is not directly editable by the user */ public CalculatorDisplay(){ setEditable(false); setFont(new Font("SansSerif", Font.PLAIN, 24)); setValue(0); startNewValue = false; op = null; } /* Adds a digit to the display, clearing the old value if startNewValue is set */ public void addDigit(int digit){ int value = (startNewValue) ? 0 : getValue(); setValue(10 * value + digit); startNewValue = false; } /* Sets a new operator, applying the previous one if one exists */ public void setOperator(OperatorButton button){ if (op == null){ memory = getValue(); } else { memory = op.apply(memory, getValue()); setValue(memory); } op = button; startNewValue = true; } /* private instance variables */ private OperatorButton op; /* The last operator button pressed */ private int memory; /* The value to which the operator is applied */ private boolean startNewValue; /* Set after an operator to start a new value */ } /* This abstract class is the superclass for every calculator button. Every button must define an action method, which is called whenever the button is cliked. */ abstract class CalculatorButton extends JButton { /* Creates a new CalculatorButton with the specified name */ public CalculatorButton(String name) { super(name); setFont(new Font("SansSerif", Font.PLAIN, 24)); } /* Called when the button is clicked (every subclass must implement this method) */ public abstract void action(CalculatorDisplay display); } /* This class is used for each of the digit buttons. The action consists of adding the digit used as a label on the button, which is returned by getText. */ class DigitButton extends CalculatorButton { /* Creates a new DigitButton for the digit n */ public DigitButton(int n) { super("" + n); } /* Adds this digit to the display */ public void action(CalculatorDisplay display) { display.addDigit(Integer.parseInt(getText())); } } /* This abstract class is the superclass of the various operator buttons. Each concrete subclass must override the apply method. */ abstract class OperatorButton extends CalculatorButton{ /* Creates a new OperatorButton with the specified name */ public OperatorButton(String name) { super(name); } /* Informs the display that this operator button has been clicked */ public void action(CalculatorDisplay display) { display.setOperator(this); } /* Applies this operator (every subclass must implement this method) */ public abstract int apply(int lhs, int rhs); } /* The classes AddButton, SubtractButton, MultipButton, and DicideButton are the same except for their label and the implementation of apply. */ class AddButton extends OperatorButton { public AddButton() { super("+"); } public int apply(int lhs, int rhs) { return lhs + rhs; } } class SubtractButton extends OperatorButton { public SubtractButton() { super("-"); } public int apply(int lhs, int rhs) { return lhs - rhs; } } class MultiplyButton extends OperatorButton { public MultiplyButton() { super("x"); } public int apply(int lhs, int rhs) { return lhs * rhs; } } class DivideButton extends OperatorButton { public DivideButton() { super("/"); } public int apply(int lhs, int rhs) { return lhs / rhs; } } /* The EqualsButton class displays the current value. As it happens, this Operation can be implemented simply by setting the operator to null. */ class EqualsButton extends CalculatorButton { public EqualsButton() { super("C"); } public void action(CalculatorDisplay display) { display.setOperator(null); display.setValue(0); } } public class ClearButton extends CalculatorButton { public ClearButton(){ super("C"); } public void action(CalculatorDisplay display) { display.setOperator(null); display.setValue(0); } }

Go中是否有类似于Java的ConcurrentMap.computeIfAbsent的函数?

<div class="post-text" itemprop="text"> <p>I tried to find this function in Go's standard library and many other cache libraries that resemble to Java's ConcurrentMap.computeIfAbsent. I found sync.Map in the standard library which looks like what I'm looking for. I’d like to use sync.Map as a concurrent map. The problem is that the following function does not provide a defer computation as Java's ConcurrentMap does.</p> <p><code>func (m *Map) LoadOrStore(key, value interface{}) (actual interface{}, loaded bool)</code></p> <blockquote> <p>LoadOrStore returns the existing value for the key if present. Otherwise, it stores and returns the given value. The loaded result is true if the value was loaded, false if stored.</p> </blockquote> <p>It’s atomic, but the function doesn’t make sense to me. I don’t understand its purpose since I'm new to the language. I don’t know why the second param is a value not a function. Since the param will be evaluated eagerly, I have no idea how is this function useful when the value is recomputed every time anyway.</p> <p>It would be much more useful IMO if the function signature is like</p> <p><code>func (m *Map) LoadOrStore(key interface{}, f func() interface{}) (actual interface{}, loaded bool)</code></p> <p><s>I mean why do we need a map when we have a value already? Pretty sure I miss something.</s></p> <p>Let me elaborate that a bit. I don't get the reason why the function takes a value as parameter instead of a function and I'm pretty sure that I miss something. I want to get a value out of a map in a concurrent manner. When a key doesn't exist, I want to compute the value and put it into the map atomically. I know I shouldn't compare it with the ConcurrentMap in Java since the language and paradigm are different, but it could be useful to say where I'm from and it could benefit anyone who is learning Go to get a little bit of better understanding on this difference.</p> <p>Here is the similar function in Java ConcurrentMap.</p> <p><code>computeIfAbsent(K key, Function&lt;? super K,? extends V&gt; mappingFunction)</code></p> <blockquote> <p>If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this map unless null.</p> </blockquote> <p>The question is why <code>LoadOrStore</code> function takes a value instead of a function? Any insight on why the API is designed this way would be appreciated. Also Is there a way to accomplish the same thing as I do in Java <code>computeIfAbsent</code> without using an explicit lock around the map?</p> <p><strong>Updated</strong> I found that it's very easy to modify the sync.Map.LoadOrStore to take a function instead of a value.</p> <p><a href="https://play.golang.org/p/VBIaS8ZV38o" rel="nofollow noreferrer">https://play.golang.org/p/VBIaS8ZV38o</a></p> <p>Not sure that it will work as expected though. </p> </div>

java 8 排序遇到的问题

public static <T, U extends Comparable<? super U>> Comparator<T> comparing( Function<? super T, ? extends U> keyExtractor) { Objects.requireNonNull(keyExtractor); return (Comparator<T> & Serializable) (c1, c2) -> keyExtractor.apply(c1).compareTo(keyExtractor.apply(c2)); } 为什么这个方法参数为Object 类型就会报错 不能引用非静态方法 ,其他类型就可以

JAVA 实现接口方法时报错 implement a supertype method

public interface MultimediaControl { public void play(); public void stop(); public void previous(); public void next(); } public class AudioPlayer extends Product implements MultimediaControl { String audioSpecification; ItemType mediaType; @Override //The method play() of type AudioPlayer must override or implement a supertype method public void play() { System.out.println("Playing"); } @Override //The method stop() of type AudioPlayer must override or implement a supertype method public void stop() { System.out.println("Stopped"); } @Override //The method previous() of type AudioPlayer must override or implement a supertype method public void previous() { System.out.println("To the previous"); } @Override public void next() //The method next() of type AudioPlayer must override or implement a supertype method{ System.out.println("To the Next"); } public AudioPlayer(String name, ItemType Type) { super(name); //The constructor Product(String) is undefined mediaType = Type; } } 还有构造函数中调用父类带参构造函数, 父类中的构造函数 : public Product(String Name) { name = Name; serialNumber = currentProductionNumber; manufacturedOn = new Date(); } 明明有带String参数的构造?为什么会提示这些错误呢

如何使用httpresponse将html中的值返回到android java类中

<div class="post-text" itemprop="text"> <p>I need to get a return from my html page using javascript function. I always have do this using echo in a php code and it works, but now it is difficult for me because i don't know how to do it using html and javascript This is the javascript code ( I want to get the Json Object as return ):</p> <pre><code>&lt;?php $Via = $_GET["Via"]; ?&gt; &lt;p id=Via name = Via&gt; &lt;/p&gt; &lt;script&gt; var Via = '&lt;?php echo $Via; ?&gt;'; setTimeout(init(),1); function init() { setTimeout( function(){initMapi(); },100); } function initMapi() { var geocoder = new google.maps.Geocoder(); var latlng = geocodeAddress(geocoder,Via + ",Trieste"); } function geocodeAddress(geocoder,address) { geocoder.geocode({'address': address}, function(results, status) { if (status === 'OK') { } else { alert('Geocode was not successful for the following reason: ' + status); } var latitude = results[0].geometry.location.lat().toFixed(5); var longitude = results[0].geometry.location.lng().toFixed(5); var latlng = {lat: parseFloat(latitude), lng: parseFloat(longitude)}; var coord = '[{"lat":' + latitude + '},{"lng":' + longitude + '}]'; var arr = JSON.parse(coord); document.getElementById('Via').innerHTML = coord; return coord; }); } function geocodeLatLng(geocoder , latlng) { geocoder.geocode({'location': latlng } , function(results, status) { if (status === 'OK') { if (results[0]) { document.getElementById('Via').value = mysql_real_escape_string(results[0].formatted_address); } else { window.alert('No results found'); } } else { window.alert('Geocoder failed due to: ' + status); } }); } &lt;/script&gt; &lt;script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB6m6fhBX0vIYDPoDJQTTUPefbFpsvYs6w"&gt; &lt;/script&gt; </code></pre> <p>And then My Android class : </p> <pre><code> package info.androidhive.materialdesign.BackgroudWorker; /** * Created by Alessandro on 27/02/2017. */ import android.content.Context; import android.os.AsyncTask; import com.google.android.gms.maps.model.LatLng; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONObject; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URI; import java.net.URL; import java.net.URLEncoder; import info.androidhive.materialdesign.utility.Bus; import xdroid.toaster.Toaster; public class BackgroundWorkerConvertAddressIntoLatLng extends AsyncTask&lt;String,Void,String&gt; { Context context; public boolean next = false; public Bus bus ; public String street ; public LatLng coords = null; public BackgroundWorkerConvertAddressIntoLatLng(Context ctx, Bus bus,String street) { context = ctx; this.street = street; this.bus = bus; } @Override protected String doInBackground(String... params) { if(params[0] == "coords" &amp;&amp; bus.Nome_Linea.equals("29 Andata")) { manageBusses(params); } return null; } @Override protected void onProgressUpdate(Void... values) { super.onProgressUpdate(values); } public void manageBusses(String... params){ try{ String value=null; String link = "http://2.234.155.73/android_TT/getCoordinates.php?Via=" + URLEncoder.encode(street+ ", Trieste", "UTF-8") ; URL url = new URL(link); HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(); request.setURI(new URI(link)); HttpResponse response = client.execute(request); BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer sb = new StringBuffer(""); String line=""; while (true) { line = in.readLine(); if(line.contains("&lt;p id")){ if(line.indexOf("&lt;p id=Via name = Via&gt;&lt;/p&gt;") == -1){ sb.append(line); break; }else{ in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); } }else { } } value = sb.toString(); in.close(); Toaster.toast("string " + value); String json_string = EntityUtils.toString(response.getEntity()); JSONArray jArray = new JSONArray(json_string); // JSONArray jArray = new JSONArray(value); // Extract data from json and store into ArrayList as class objects Toaster.toast("jArray " + jArray); for (int i = 0; i &lt; jArray.length(); i++) { JSONObject json_data = jArray.getJSONObject(i); double lat = json_data.getDouble("lat"); double lng = json_data.getDouble("lng"); coords = new LatLng(lat,lng); Toaster.toast("coords " + coords.toString()); next = true; } } catch(Exception e){ } } } </code></pre> <p>Pleas help me... i really don't know what i should do .</p> </div>

JAVA 计算器,求大神,急急急,帮帮忙

import java.awt.Frame; import java.awt.Panel; import java.awt.GridLayout; import java.awt.FlowLayout; import java.awt.*; import java.awt.event.*; import java.util.Enumeration; import java.util.Stack; import java.lang.Integer; public class ComputerFrame extends Frame implements ActionListener { Panel numberPanel; TextField text; Panel operatorPanel; Button[] num; Button[] oper; public ComputerFrame() { super("这是一个计算机"); init(); } public void init() { operatorPanel=new Panel(); numberPanel=new Panel(); text=new TextField(15); num=new Button[10]; oper=new Button[7]; oper[0]=new Button("C"); oper[1]=new Button("←"); oper[2]=new Button("+"); oper[3]=new Button("-"); oper[4]=new Button("*"); oper[5]=new Button("/"); oper[6]=new Button("="); setSize(200,500); setFont(new Font("Dialog",Font.PLAIN,30)); setLayout(new FlowLayout()); numberPanel.setLayout(new GridLayout(4,3,5,5)); operatorPanel.setLayout(new GridLayout(4,2,5,5)); add(text); add(numberPanel); add(operatorPanel); for(int i=1;i<10;i++) { num[i]=new Button(String.valueOf(i)); numberPanel.add(num[i]); num[i].addActionListener(this); } num[0]=new Button(String.valueOf(0)); numberPanel.add(num[0]); num[0].addActionListener(this); for(int i=0;i<=6;i++) { operatorPanel.add(oper[i]); oper[i].addActionListener(this); } } public void actionPerformed(ActionEvent e) { String t=text.getText(); int len=t.length(); int[] nums=new int[2]; String oparator=""; for(int i=0;i<=9;i++) { if(e.getSource()==num[i]) text.setText(t+num[i].getLabel()); } for(int i=2;i<6;i++) { if(e.getSource()==oper[i]) {text.setText(t+oper[i].getLabel()); oparator=oper[i].getLabel(); } } //清空 if(e.getSource()==oper[0]) { text.setText(null); } //删去 if(e.getSource()==oper[1]) { text.setText(t.substring(0,len-1)); } //等于 if(e.getSource()==oper[6]) { text.setText(this.calculator(t)); } } public String calculator(String t){ char lastoper='='; char c; char operator; int num1; int num2; String num=" "; String result; Stack operstack=new Stack(); Stack numstack=new Stack(); operstack.push(new Character('=')); numstack.push(new Character('0')); for(int i=0;i <t.length();i++) { c=t.charAt(i); //情况一 数字 if(Character.isDigit(c)) { num=num+String.valueOf(c); } //情况二 运算符 else if((c=='+')||(c=='-')||(c=='*')||(c=='/')||(c=='=')) { if(!num.equals(" ")) { numstack.push(new Integer(num)); num=""; char s=((Character)operstack.peek()).charValue(); while(getRual(s)>getRual(c))//比较优先权 { operator=((Character)operstack.pop()).charValue(); num1=((Integer)numstack.pop()).intValue(); num2=((Integer)numstack.pop()).intValue(); numstack.push(cal(num1,num2,operator)); } if(getRual(s)<=getRual(c)) { operstack.push(new Character(c)); lastoper=c; continue; } } } } Enumeration items=operstack.elements(); while(items.hasMoreElements()) { operator=((Character)operstack.pop()).charValue(); num1=((Integer)numstack.pop()).intValue(); num2=((Integer)numstack.pop()).intValue(); numstack.push(cal(num1,num2,operator)); } result=((Integer)operstack.pop()).toString(); return result; } public static int getRual(char c) { switch(c) { case '+':return 1; case '-':return 1; case '*':return 2; case '/':return 2; case '=':return 0; default: return -1; } } public static int cal(int num1,int num2,char c) { switch(c) { case '+':return num1+num2; case '-':return num1-num2; case '*':return num1*num2; case '/':return num1/num2; default: return -1; } } public static void main(String args[]) { ComputerFrame demo=new ComputerFrame(); demo.setSize(300,400); demo.show(); }

通过PHP将信息从MySQL传递到Android - 转换结果时出错java.lang.NullPointerException:lock == null

<div class="post-text" itemprop="text"> <p>I am new to Android and I am trying to make am simple APP the access a server and read a table in a database. I used this example <a href="http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/" rel="nofollow">http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/</a> and tried to make some adaptations.</p> <p>There has been many errors that I was able to solve searching here, but on this case I haven´t been luck so far.</p> <p>As suggest, I did some debbuging and the app stops working when to line 108</p> <pre><code> try{ //Verificando a TAG Sucesso int sucess = json.getInt(TAG_SUCESSO); </code></pre> <p>For the varibles, just befor that, json appears as null.</p> <p>As it seens I am having trouble to get the response from my PHP code (it shows the right array and executed) to the app.</p> <p>Here is the Logcat error</p> <pre><code>12-22 11:50:35.609 1273-1293/br.com.agenciaeisberg.qm E/Buffer Error﹕ Error converting result java.lang.NullPointerException: lock == null 12-22 11:50:35.859 1273-1293/br.com.agenciaeisberg.qm E/JSON Parser﹕ Error parsing data org.json.JSONException: End of input at character 0 of 12-22 11:50:35.859 1273-1293/br.com.agenciaeisberg.qm W/dalvikvm﹕ threadid=12: thread exiting with uncaught exception (group=0xb2a24ba8) 12-22 11:50:36.799 1273-1293/br.com.agenciaeisberg.qm E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1 Process: br.com.agenciaeisberg.qm, PID: 1273 java.lang.RuntimeException: An error occured while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:300) at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355) at java.util.concurrent.FutureTask.setException(FutureTask.java:222) at java.util.concurrent.FutureTask.run(FutureTask.java:242) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) at java.lang.Thread.run(Thread.java:841) Caused by: java.lang.NullPointerException at br.com.agenciaeisberg.qm.ListagemHospitaisActivity$LoadListagemHospitais.doInBackground(ListagemHospitaisActivity.java:104) at br.com.agenciaeisberg.qm.ListagemHospitaisActivity$LoadListagemHospitais.doInBackground(ListagemHospitaisActivity.java:76) at android.os.AsyncTask$2.call(AsyncTask.java:288) at java.util.concurrent.FutureTask.run(FutureTask.java:237)             at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)             at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)             at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)             at java.lang.Thread.run(Thread.java:841) 12-22 11:50:38.039 1273-1273/br.com.agenciaeisberg.qm W/EGL_emulation﹕ eglSurfaceAttrib not implemented 12-22 11:50:39.259 1273-1273/br.com.agenciaeisberg.qm E/WindowManager﹕ android.view.WindowLeaked: Activity br.com.agenciaeisberg.qm.ListagemHospitaisActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{b2ce6d30 V.E..... R......D 0,0-320,96} that was originally added here at android.view.ViewRootImpl.&lt;init&gt;(ViewRootImpl.java:348) at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248) at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69) at android.app.Dialog.show(Dialog.java:286) at br.com.agenciaeisberg.qm.ListagemHospitaisActivity$LoadListagemHospitais.onPreExecute(ListagemHospitaisActivity.java:88) at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587) at android.os.AsyncTask.execute(AsyncTask.java:535) at br.com.agenciaeisberg.qm.ListagemHospitaisActivity.onCreate(ListagemHospitaisActivity.java:59) at android.app.Activity.performCreate(Activity.java:5231) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) at android.app.ActivityThread.access$800(ActivityThread.java:135) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5017) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) at dalvik.system.NativeStart.main(Native Method) </code></pre> <p>Here is the Activity</p> <pre><code>package br.com.agenciaeisberg.qm; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.http.NameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.ListActivity; import android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; public class ListagemHospitaisActivity extends ListActivity { // Progress Dialog private ProgressDialog pDialog; // Creating JSON Parser object JSONParser jParser = new JSONParser(); ArrayList&lt;HashMap&lt;String, String&gt;&gt; ListaHospitais; //url para lista hospitais private static String url_lista_hospitais = "http://127.0.0.1/QM/lista_hospitais.php"; //JSON Node names private static final String TAG_HOSPITAIS = "hospitais"; private static final String TAG_PID = "pid"; private static final String TAG_NOME = "nome"; private static final String TAG_SUCESSO = "sucesso"; //private static final String TAG_LOTACAO = "lotacao"; //private static final String TAG_DATA_LOTACAO = "data_lotacao"; //hospitais JSONARRAY JSONArray hospitais = null; @Override public void onCreate (Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.lista_hospitais); //Hashmap for ListView ListaHospitais = new ArrayList&lt;HashMap&lt;String,String&gt;&gt;(); // Carregando hospitais no backgroung new LoadListagemHospitais().execute(); // Get ListView //ListView lv = getListView(); //Selecionando um Hospital //Executa atividade Hospital //Criar código depois -&gt; pesquisar linhas abaixo // on seleting single product // launching Edit Product Screen } /** * Background Async Task para carregar todos os hospitais através de um HTTP Request */ class LoadListagemHospitais extends AsyncTask &lt;String, String, String&gt;{ /** * Before starting background thread Show Progress Dialog * */ @Override protected void onPreExecute(){ super.onPreExecute(); pDialog = new ProgressDialog(ListagemHospitaisActivity.this); pDialog.setMessage("Aguarde, carregando Hospitais"); pDialog.setIndeterminate(false); pDialog.setCancelable(false); pDialog.show(); } /** * Buscando os hospitais do URL * */ protected String doInBackground (String... args) { //Criação dos parâmetros List&lt;NameValuePair&gt; params = new ArrayList&lt;NameValuePair&gt;(); // Buscando o string JSON do URL JSONObject json = jParser.makeHttpRequest(url_lista_hospitais,"GET", params); // Check your log cat for JSON reponse Log.d("Listagem Hospitais: ", json.toString()); try{ //Verificando a TAG Sucesso int sucess = json.getInt(TAG_SUCESSO); if (sucess == 1){ //existe hospital cadastrado // Buscando Array dos hospitais hospitais = json.getJSONArray(TAG_HOSPITAIS); //loop por todos os Hospitais for (int i = 0; i &lt; hospitais.length(); i++) { JSONObject c = hospitais.getJSONObject(i); // Armazenando as variáveis String id = c.getString(TAG_PID); String nome = c.getString(TAG_NOME); // creando novo HashMap HashMap&lt;String, String&gt; map = new HashMap&lt;String, String&gt;(); // adicionando cada child node ao HashMap . key =&gt; value map.put(TAG_PID, id); map.put(TAG_NOME, nome); // adicionando HashList à ArrayList ListaHospitais.add(map); } }else{ // no products found // Launch Add New product Activity Intent i = new Intent(getApplicationContext(), MainActivity.class); // Closing all previous activities i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(i); } }catch (JSONException e) { e.printStackTrace(); } return null; } /** * After completing background task Dismiss the progress dialog * **/ protected void onPostExecute(String file_url) { // Dismiss a caixa de dialogo depois de buscar todos os items pDialog.dismiss(); // atualizando UI from Background Thread runOnUiThread(new Runnable() { public void run() { /** * Updating parsed JSON data into ListView * */ ListAdapter adapter = new SimpleAdapter( ListagemHospitaisActivity.this, ListaHospitais, R.layout.lista_hospitais, new String[] { TAG_PID, TAG_NOME}, new int[] { R.id.pid, R.id.nome }); // updating listview setListAdapter(adapter); } }); } } } </code></pre> <p>Here is the JSONParser Class</p> <pre><code>package br.com.agenciaeisberg.qm; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; public class JSONParser { static InputStream is = null; static JSONObject jObj = null; static String json = ""; // constructor public JSONParser() { } // function get json from url // by making HTTP POST or GET mehtod public JSONObject makeHttpRequest(String url, String method, List&lt;NameValuePair&gt; params) { // Making HTTP request try { // check for request method if(method == "POST"){ // request method is POST // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new UrlEncodedFormEntity(params)); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); }else if(method == "GET"){ // request method is GET DefaultHttpClient httpClient = new DefaultHttpClient(); String paramString = URLEncodedUtils.format(params, "utf-8"); url += "?" + paramString; HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + " "); } is.close(); json = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } // try parse the string to a JSON object try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } // return JSON String return jObj; } } </code></pre> <p>Here is the php Code</p> <pre><code>&lt;?php /* * O código a seguir lista todos os hospitais */ //array para Resposta JSON $response = array(); require_once 'geral.inc.php'; // connecting to db $con = mysqli_connect($hostname, $username, $senha, $banco); // Listar todos os Hospitais $result = mysqli_query($con, 'SELECT * FROM hospitais'); $response['hospitais'] = array(); while ($row = mysqli_fetch_array($result)){ //array temporário $hospital = array (); $hospital['pid'] = $row['PID']; $hospital['nome'] = $row['NomeHospital']; $hospital['lotacao'] = $row['ultima_lotacao']; $hospital['data_lotacao'] = $row['d_h_ultima_lotacao']; // Exibe o resultado um a um da array array_push($response["hospitais"], $hospital); } $response["successo"] = 1; // echoing JSON response echo json_encode($response); ?&gt; </code></pre> </div>

MediaRecorder录屏,Socket传输录屏内容报错java.lang.IllegalStateException

用模拟器调试可以运行,用真机测试在 mediaRecorder.prepare();抛异常 ``` package www.xjw.com.mymiracast2.screenrecordservice; import android.app.Notification; import android.app.Service; import android.content.Context; import android.content.Intent; import android.hardware.display.DisplayManager; import android.hardware.display.VirtualDisplay; import android.media.MediaRecorder; import android.media.projection.MediaProjection; import android.media.projection.MediaProjectionManager; import android.os.IBinder; import android.os.ParcelFileDescriptor; import java.net.Socket; /** * Created by dzjin on 2018/1/9. */ public class ScreenRecordService extends Service { private int resultCode; private Intent resultData=null; private MediaProjection mediaProjection=null; private MediaRecorder mediaRecorder=null; private VirtualDisplay virtualDisplay=null; private int mScreenWidth; private int mScreenHeight; private int mScreenDensity; private static String filePathName; private Socket receiver = null; private ParcelFileDescriptor pfd = null; private Context context=null; private String host = null; private int port = 8989; @Override public void onCreate() { super.onCreate(); //startForeground(2, new Notification()); } /** * 每次客户端通过调用startService(Intent)显式启动服务时,系统调用startService(Intent), *提供它提供的参数和表示启动请求的唯一整数标记。 * 不要直接调用这个方法。 * @param intent * @param flags * @param startId * @return */ @Override public int onStartCommand(Intent intent, int flags, int startId) { try{ resultCode=intent.getIntExtra("resultCode",-1); resultData=intent.getParcelableExtra("resultData"); mScreenWidth=intent.getIntExtra("mScreenWidth",0); mScreenHeight=intent.getIntExtra("mScreenHeight",0); mScreenDensity=intent.getIntExtra("mScreenDensity",0); filePathName=intent.getStringExtra("filePathName"); host=intent.getStringExtra("host"); port=intent.getIntExtra("port",8989); receiver = new Socket(host, port); pfd = ParcelFileDescriptor .fromSocket(receiver); mediaProjection=createMediaProjection(); mediaRecorder=createMediaRecorder(); virtualDisplay=createVirtualDisplay(); mediaRecorder.start(); }catch (Exception e) { e.printStackTrace(); } /** * START_NOT_STICKY: *从onStartCommand返回的常量(Intent, int, int):如果这个服务的进程是 *在启动时被杀死(从onStartCommand(Intent, int, int)返回后), *没有新的start意图交付给它,然后将服务从 *启动状态,在以后显式调用Context.startService(Intent)之前不要重新创建。 *服务将不会接收带有空意图的onStartCommand(Intent, int, int)调用 *因为如果没有等待交付的意图,它将不会重新启动。 */ return Service.START_NOT_STICKY; } public MediaProjection createMediaProjection(){ /** *使用getSystemService(类)检索MediaProjectionManager实例 *管理媒体放映会议。 */ return ((MediaProjectionManager)getSystemService(Context.MEDIA_PROJECTION_SERVICE)) .getMediaProjection(resultCode,resultData); /** *检索从成功的屏幕捕获请求中获得的MediaProjection。 *如果startActivityForResult()的结果不是RESULT_OK,则*将为null。 */ } private MediaRecorder createMediaRecorder(){ //用于录制音频和视频。录音控制是基于一个简单的状态机。 MediaRecorder mediaRecorder=new MediaRecorder(); //设置要录音的源。 //mediaRecorder.setAudioSource(MediaRecorder. AudioSource.CAMCORDER); //设置要录制的视频源。 mediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE); //设置录制过程中产生的输出的格式。 //3GPP媒体文件格式 mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_2_TS); //设置录音格式 //mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); //设置录像编码比特率。 //param:以比特/秒为单位的视频编码比特率 mediaRecorder.setVideoEncodingBitRate(5*mScreenWidth*mScreenHeight); //设置录像编码器用于录像。 mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264); //设置要拍摄的视频的宽度和高度。 mediaRecorder.setVideoSize(mScreenWidth,mScreenHeight); //设置要捕获视频的帧速率。 mediaRecorder.setVideoFrameRate(60); try{ mediaRecorder.setOutputFile(pfd.getFileDescriptor()); //mediaRecorder.setOutputFile(filePathName); **此次抛异常** //准备记录器开始捕捉和编码数据。 mediaRecorder.prepare(); }catch (Exception e){ e.printStackTrace(); } return mediaRecorder; } private VirtualDisplay createVirtualDisplay(){ /** *名称字符串:虚拟显示的名称,必须是非空的。这个值不能为空。 width int:虚拟显示的宽度,以像素为单位。必须大于0。 高度int:虚拟显示器的高度,以像素为单位。必须大于0。 dpi int: dpi中虚拟显示的密度。必须大于0。 标志int:虚拟显示标志的组合。有关标志的完整列表,请参见DisplayManager。 surface surface:虚拟显示内容应该呈现到的表面,如果一开始没有,则为null。 回调virtualdisplay。回调:当虚拟显示的状态改变时调用的回调,如果没有,则为空。 处理程序处理程序:应该在其上调用回调的处理程序,如果应该在调用线程的主循环程序上调用回调,则为null。 */ /** * DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR *虚拟显示标志:当没有显示内容时,允许在私有显示上镜像内容。 */ return mediaProjection.createVirtualDisplay("mediaProjection",mScreenWidth,mScreenHeight,mScreenDensity, DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,mediaRecorder.getSurface(),null,null); } @Override public void onDestroy() { super.onDestroy(); if(virtualDisplay!=null){ virtualDisplay.release(); virtualDisplay=null; } if(mediaRecorder!=null){ mediaRecorder.stop(); mediaRecorder=null; } if(mediaProjection!=null){ mediaProjection.stop(); mediaProjection=null; } } @Override public IBinder onBind(Intent intent) { System.out.println("==============================="); return null; } } ``` I/MediaRecorder: enter in file frameworks/av/media/libmedia/mediarecorder.cpp, function prepare, line 461 I/IMediaRecorder: prepare (BpMediaRecorder client) in file frameworks/av/media/libmedia/IMediaRecorder.cpp, function prepare, line 249 W/com.mymiracast2: type=1400 audit(0.0:104572): avc: denied { read write } for path="socket:[8870267]" dev="sockfs" ino=8870267 scontext=u:r:mediaserver:s0 tcontext=u:r:untrusted_app:s0:c512,c768 tclass=tcp_socket permissive=0 E/MediaRecorder: prepare failed: -38 W/zygote64: Got a deoptimization request on un-deoptimizable method void android.media.MediaRecorder._prepare() W/System.err: java.lang.IllegalStateException W/System.err: at android.media.MediaRecorder._prepare(Native Method) W/System.err: at android.media.MediaRecorder.prepare(MediaRecorder.java:1017) W/System.err: at www.xjw.com.mymiracast2.screenrecordservice.ScreenRecordService.createMediaRecorder(ScreenRecordService.java:137) W/System.err: at www.xjw.com.mymiracast2.screenrecordservice.ScreenRecordService.onStartCommand(ScreenRecordService.java:79) W/System.err: at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:4151) W/System.err: at android.app.ActivityThread.-wrap21(Unknown Source:0) W/System.err: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2119) W/System.err: at android.os.Handler.dispatchMessage(Handler.java:108) W/System.err: at android.os.Looper.loop(Looper.java:166) W/System.err: at android.app.ActivityThread.main(ActivityThread.java:7529) W/System.err: at java.lang.reflect.Method.invoke(Native Method) W/System.err: at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245) W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921) E/MediaRecorder: SurfaceMediaSource could not be initialized! W/System.err: java.lang.IllegalStateException: failed to get surface at android.media.MediaRecorder.getSurface(Native Method) W/System.err: at www.xjw.com.mymiracast2.screenrecordservice.ScreenRecordService.createVirtualDisplay(ScreenRecordService.java:160) at www.xjw.com.mymiracast2.screenrecordservice.ScreenRecordService.onStartCommand(ScreenRecordService.java:80) W/System.err: at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:4151) at android.app.ActivityThread.-wrap21(Unknown Source:0) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2119) at android.os.Handler.dispatchMessage(Handler.java:108) W/System.err: at android.os.Looper.loop(Looper.java:166) at android.app.ActivityThread.main(ActivityThread.java:7529) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245) W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921) D/StrictMode: StrictMode policy violation; ~duration=7334 ms: android.os.StrictMode$StrictModeNetworkViolation: policy=65543 violation=4 at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1466) at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:356) at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:201) at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:183) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:356) at java.net.Socket.connect(Socket.java:616) at java.net.Socket.connect(Socket.java:565) at java.net.Socket.<init>(Socket.java:445) at java.net.Socket.<init>(Socket.java:217) at www.xjw.com.mymiracast2.screenrecordservice.ScreenRecordService.onStartCommand(ScreenRecordService.java:74) at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:4151) at android.app.ActivityThread.-wrap21(Unknown Source:0) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2119) at android.os.Handler.dispatchMessage(Handler.java:108) at android.os.Looper.loop(Looper.java:166) at android.app.ActivityThread.main(ActivityThread.java:7529) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921) D/StrictMode: StrictMode policy violation; ~duration=7332 ms: android.os.StrictMode$StrictModeNetworkViolation: policy=65543 violation=4 ``` ```

Android编程:java.lang.String类型的值无法转换为JSONObject

<div class="post-text" itemprop="text"> <p>I'm trying to do a login page from an Android activity connecting the database. I'm getting this error "org.json.JSONException: Value </p><p>I am new to Android programming and I tried for three days. Thank you.</p> <p>Here is activity code</p> <pre><code>private void Validation() { strEmail = etEmail.getText().toString().trim(); strPassword = etPass.getText().toString().trim(); class validate extends AsyncTask&lt;String, String, JSONObject&gt; { ProgressDialog loading; @Override protected void onPreExecute() { super.onPreExecute(); loading = ProgressDialog.show(SignIn.this,"Progressing...","Wait...",false,false); } @Override protected JSONObject doInBackground(String... params) { UserFunctions userFunction = new UserFunctions(); JSONObject json = userFunction.userValidation(strEmail,strPassword); return json; } @Override protected void onPostExecute(JSONObject jsonObject) { super.onPostExecute(jsonObject); loading.dismiss(); try { String successID = jsonObject.getString("success"); // String userID = jsonObject.getString("userID"); if (successID.equals("1")) { Toast.makeText(getApplicationContext(),successID,Toast.LENGTH_SHORT).show(); } else if (successID.equals("0")) { Toast.makeText(getApplicationContext(),successID,Toast.LENGTH_SHORT).show(); } } catch (Exception e) { e.printStackTrace(); } } } validate vld = new validate(); vld.execute(); } </code></pre> <p>Here is the userFunction Activity:</p> <pre><code> private static String userValidationURL = "http://58.26.106.181/b160088b/android/userSignSignIn.php"; public JSONObject userValidation(String email , String strPassword) { // Building Parameters String data = ""; try { Log.e("email",email); data = URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode(email, "UTF-8"); data = URLEncoder.encode("Password", "UTF-8") + "=" + URLEncoder.encode(strPassword, "UTF-8"); } catch (Exception e) { e.printStackTrace(); } JSONObject json = jsonParser.getJSONFromUrl(userValidationURL, data); return json; } </code></pre> <p>Here is the PHP file:</p> <pre><code>&lt;?php include ("config.php"); //$email = "nomoneynotalk94@gmail.com"; $email = $_POST['email']; $pass = $_POST['Password']; $sql_query = "SELECT * FROM user where email ='".$email."' AND password ='".$pass."' "; $result = mysqli_query($conn,$sql_query); $num_rows = mysqli_num_rows($result); if($num_rows &gt; 0 ) { // return login sucessful $row = mysqli_fetch_array($result); $response["success"] = 1; } else { //return login failed $response["success"] = 0; } echo json_encode($response); ?&gt; </code></pre> <p>Here is the error:</p> <pre><code>06-21 15:07:14.246 16569-16953/zr.suc.june19 W/System.err: org.json.JSONException: Value &lt;br of type java.lang.String cannot be converted to JSONObject 06-21 15:07:14.246 16569-16953/zr.suc.june19 W/System.err: at org.json.JSON.typeMismatch(JSON.java:111) 06-21 15:07:14.246 16569-16953/zr.suc.june19 W/System.err: at org.json.JSONObject.&lt;init&gt;(JSONObject.java:160) 06-21 15:07:14.246 16569-16953/zr.suc.june19 W/System.err: at org.json.JSONObject.&lt;init&gt;(JSONObject.java:173) 06-21 15:07:14.246 16569-16953/zr.suc.june19 W/System.err: at zr.suc.june19.BackEnd.JSONParser.getJSONFromUrl(JSONParser.java:59) 06-21 15:07:14.246 16569-16953/zr.suc.june19 W/System.err: at zr.suc.june19.BackEnd.UserFunctions.userValidation(UserFunctions.java:53) 06-21 15:07:14.246 16569-16953/zr.suc.june19 W/System.err: at zr.suc.june19.BeforeLogin.SignIn$1validate.doInBackground(SignIn.java:89) 06-21 15:07:14.246 16569-16953/zr.suc.june19 W/System.err: at zr.suc.june19.BeforeLogin.SignIn$1validate.doInBackground(SignIn.java:75) 06-21 15:07:14.246 16569-16953/zr.suc.june19 W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:288) 06-21 15:07:14.246 16569-16953/zr.suc.june19 W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237) 06-21 15:07:14.246 16569-16953/zr.suc.june19 W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 06-21 15:07:14.246 16569-16953/zr.suc.june19 W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 06-21 15:07:14.246 16569-16953/zr.suc.june19 W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 06-21 15:07:14.246 16569-16953/zr.suc.june19 W/System.err: at java.lang.Thread.run(Thread.java:818) </code></pre> </div>

Android登录注册系统,PHP,MySQL错误'java.lang.NoSuchMethodError:org.apache.http.impl.client.DefaultHttpClient.execute'

<div class="post-text" itemprop="text"> <p>I have develop Android Login Registration System with PHP, MySQL. This is Simple questions but confuses me. i got many error as below log.</p> <blockquote> <p>Caused by: java.lang.NoSuchMethodError: org.apache.http.impl.client.DefaultHttpClient.execute at com.chinatown.wangjian.chinatown_loginv10.Library.JSONParser.getJSONFromUrl(JSONParser.java:45) at com.chinatown.wangjian.chinatown_loginv10.Library.UserFunctions.loginUser(UserFunctions.java:42) at com.chinatown.wangjian.chinatown_loginv10.Login$ProcessLogin.doInBackground(Login.java:194) at com.chinatown.wangjian.chinatown_loginv10.Login$ProcessLogin.doInBackground(Login.java:170) at com.chinatown.wangjian.chinatown_loginv10.Register$ProcessRegister.onPreExecute(Register.java:197) at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586) at android.os.AsyncTask.execute(AsyncTask.java:534) at com.chinatown.wangjian.chinatown_loginv10.Register$NetCheck.onPostExecute(Register.java:167) at com.chinatown.wangjian.chinatown_loginv10.Register$NetCheck.onPostExecute(Register.java:119) &gt;at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586) at android.os.AsyncTask.execute(AsyncTask.java:534) at com.chinatown.wangjian.chinatown_loginv10.Login$NetCheck.onPostExecute(Login.java:159) at com.chinatown.wangjian.chinatown_loginv10.Login$NetCheck.onPostExecute(Login.java:110)</p> </blockquote> <p>there are part of my java code:</p> <p><strong>JSONParser.java</strong></p> <pre><code> HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); </code></pre> <p><strong>UserFunctions</strong></p> <pre><code>public JSONObject registerUser(String mobile, String email, String uname, String password){ // Building Parameters List params = new ArrayList(); params.add(new BasicNameValuePair("tag", register_tag)); params.add(new BasicNameValuePair("mobile", mobile)); params.add(new BasicNameValuePair("email", email)); params.add(new BasicNameValuePair("uname", uname)); params.add(new BasicNameValuePair("password", password)); JSONObject json = jsonParser.getJSONFromUrl(registerURL,params); return json; } </code></pre> <p><strong>Register.java</strong></p> <pre><code> private class ProcessRegister extends AsyncTask&lt;String, String, JSONObject&gt; { private ProgressDialog pDialog; String email,password,mobile,uname; @Override protected void onPreExecute() { // TODO Auto-generated method stub super.onPreExecute(); inputUsername = (EditText) findViewById(R.id.uname); inputPassword = (EditText) findViewById(R.id.password); mobile = inputMobile.getText().toString(); email = inputEmail.getText().toString(); uname= inputUsername.getText().toString(); password = inputPassword.getText().toString(); pDialog = new ProgressDialog(Register.this); pDialog.setTitle("正在链接服务器"); pDialog.setMessage("注册中 ..."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); } protected JSONObject doInBackground(String... args) { UserFunctions userFunction = new UserFunctions(); JSONObject json = userFunction.registerUser(mobile, email, uname, password); return json; } private class NetCheck extends AsyncTask&lt;String,String,Boolean&gt; { private ProgressDialog nDialog; @Override protected void onPreExecute(){ super.onPreExecute(); nDialog = new ProgressDialog(Register.this); nDialog.setMessage("加载中.."); nDialog.setTitle("正在检查网络"); nDialog.setIndeterminate(false); nDialog.setCancelable(true); nDialog.show(); } </code></pre> <p>I have refer the website try to fixed <a href="https://community.oracle.com/thread/2279492?start=0" rel="nofollow noreferrer">https://community.oracle.com/thread/2279492?start=0</a> and upgrade the httpcore-4.1.jar to latest version as below libs folder image. but it is not work for my project. I'm a newbie at this stuff so any help will be appreciated. Thanks in Advance!</p> <p><a href="https://i.stack.imgur.com/RWJGk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RWJGk.png" alt="libs folder"></a></p> </div>

【新手跪求大神T_T】FLEX上传java服务器端的时候一直提示路径不对 我都快被整疯了

自己想设计flex上传的功能 所以在网上寻找上传的例子 但是没有一个能运行成功的 所有的例子都报这个错误: Error #2044: 未处理的 IOErrorEvent:。 text=Error #2038: 文件 I/O 错误。 java文件我用tomcat加载的时候没问题为什么还出现这个错误呢 web.xml中 url-pattern :/servlet/UploadFile servlet-name: UploadFile flex的代码是这样的 <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" horizontalAlign="left" fontSize="12" initialize="init()" viewSourceURL="srcview/index.html"> <mx:NumberFormatter id="filesizeFormatter" useThousandsSeparator="true"/> <mx:Script> <![CDATA[ import mx.events.CollectionEvent; import mx.formatters.NumberFormatter; import mx.formatters.CurrencyFormatter; import mx.collections.ArrayCollection; import mx.controls.Alert; private var fileRefs: FileReferenceList = new FileReferenceList(); //这个地址是我测试用的服务器地址 private var urlrequest: URLRequest = new URLRequest("http://localhost:8080/abc/servlet/UploadFile"); [Bindable] private var selectedFiles: ArrayCollection = new ArrayCollection([]); private var singleThreadFiles: Array = []; [Bindable] private var useSingleThread: Boolean = true; private function init(): void { Security.allowDomain("*"); fileRefs.addEventListener(Event.SELECT, fileSelectHandler); fileRefs.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); fileRefs.addEventListener(Event.COMPLETE, completeHandler); addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); } private function selectFile(): void { fileRefs.browse([new FileFilter("Images (*.jpg, *.jpeg, *.gif, *.png)", "*.jpg;*.jpeg;*.gif;*.png"), new FileFilter("所有文件(*.*)", "*.*") ]); } private function fileSelectHandler(event: Event): void { for each (var f: FileReference in fileRefs.fileList) { selectedFiles.addItem(f); } } private function uploadFile(): void { for each (var f: FileReference in selectedFiles) { try { f.upload(urlrequest); } catch (e: Error) { Alert.show(e.message); } } } private function singleThreadUploadFile(): void { //FIFO:逐个从列表中取出,进行同步上传 if (singleThreadFiles.length > 0) { var f: FileReference = singleThreadFiles.pop() as FileReference; f.addEventListener(Event.COMPLETE, doSingleUploadFileComplete); f.upload(urlrequest); } } private function doSingleUploadFileComplete(event: Event): void { var f: FileReference = event.target as FileReference; f.removeEventListener(Event.COMPLETE, doSingleUploadFileComplete); singleThreadUploadFile(); } private function ioErrorHandler(e:IOErrorEvent): void { Alert.show(e.text); } private function completeHandler(e: Event): void { img.source = e.target.data; } private function showImage(e: Event): void { var f: FileReference = (e.target as DataGrid).selectedItem as FileReference; f.addEventListener(Event.COMPLETE, completeHandler); f.load(); } public function removeFile(f: FileReference): void { var index: int = selectedFiles.getItemIndex(f); if (index != -1) selectedFiles.removeItemAt(index); } ]]> </mx:Script> <mx:VBox> <mx:HBox width="100%"> <mx:Button id="selectFileButton" label="浏览" click="selectFile()"/> <mx:Box width="100%" horizontalAlign="right"> <mx:Button click="selectedFiles.removeAll();" label="清空"/> </mx:Box> </mx:HBox> <mx:DataGrid id="files" dataProvider="{selectedFiles}" change="showImage(event)"> <mx:columns> <mx:DataGridColumn width="150" headerText="文件名" dataField="name" /> <mx:DataGridColumn headerText="大小(字节)" dataField="size"> <mx:itemRenderer> <mx:Component> <mx:Label text="{outerDocument.filesizeFormatter.format(data.size)}" textAlign="right"/> </mx:Component> </mx:itemRenderer> </mx:DataGridColumn> <mx:DataGridColumn headerText="上传进度" width="300"> <mx:itemRenderer> <mx:Component> <mx:HBox fontSize="10" fontWeight="normal" fontThickness="1"> <mx:Script> <![CDATA[ import flash.profiler.showRedrawRegions; import mx.controls.Alert; import mx.controls.ProgressBar; private function initProgressBar(event: Event): void { //使progressbar与file关联,从而产生进度条 var pb: ProgressBar = event.target as ProgressBar; pb.label = "%3%%"; pb.setProgress(0, 100); var f: FileReference = data as FileReference; //使用闭包方法,更新进度条 f.addEventListener(ProgressEvent.PROGRESS, function(event: ProgressEvent): void { pb.setProgress(event.bytesLoaded, event.bytesTotal); } ); f.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, function (event: DataEvent): void { //服务器端一定要返回数据,否则,这个方法就不起作用了 pb.label = event.data; } ); } ]]> </mx:Script> <mx:ProgressBar verticalCenter="true" width="100%" paddingLeft="5" paddingRight="5" maximum="100" minimum="0" labelPlacement="center" mode="manual" label="%3%%" textAlign="left" creationComplete="initProgressBar(event)"/> <mx:LinkButton label="Cancel"> <mx:click> <![CDATA[ var f: FileReference = data as FileReference; f.cancel(); ]]> </mx:click> </mx:LinkButton> <mx:LinkButton label="Delete"> <mx:click> <![CDATA[ var f: FileReference = data as FileReference; outerDocument.removeFile(f); ]]> </mx:click> </mx:LinkButton> </mx:HBox> </mx:Component> </mx:itemRenderer> </mx:DataGridColumn> </mx:columns> </mx:DataGrid> </mx:VBox> <mx:HBox> <mx:Button label="上传"> <mx:click> <![CDATA[ if (useSingleThread) { //逐个上传 singleThreadFiles = selectedFiles.toArray().concat(); singleThreadFiles.reverse(); singleThreadUploadFile(); } else { //多个文件同时上传 uploadFile(); } ]]> </mx:click> </mx:Button> <mx:CheckBox id="checkboxSingleThread" label="同时上传多个文件" selected="{!useSingleThread}" change="useSingleThread = !checkboxSingleThread.selected"/> </mx:HBox> <mx:Image id="img" width="400" height="300"/> </mx:Application> 用在JAVA服务器端的是 import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; public class UploadFile extends HttpServlet { private static final long serialVersionUID = 5425836142860976977L; /** *//** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * @param request servlet request * @param response servlet response */ // 定义文件的上传路径 private String uploadPath = "d:\\files\\"; // 限制文件的上传大小 private int maxPostSize = 100 * 1024 * 1024; //最大100M public UploadFile() { super(); } public void destroy() { super.destroy(); } protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("Access !"); response.setContentType("text/html;charset=UTF-8"); //保存文件到服务器中 DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(4096); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("utf-8"); upload.setSizeMax(maxPostSize); try { List fileItems = upload.parseRequest(request); Iterator iter = fileItems.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { String name = item.getName(); System.out.println(name); try { item.write(new File(uploadPath + name)); response.getWriter().write("上传成功。"); } catch (Exception e) { e.printStackTrace(); response.getWriter().write(e.getMessage()); } } } } catch (FileUploadException e) { e.printStackTrace(); response.getWriter().write(e.getMessage()); System.out.println(e.getMessage() + "结束"); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** *//** * Handles the HTTP <code>POST</code> method. * @param request servlet request * @param response servlet response */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** *//** * Returns a short description of the servlet. */ public String getServletInfo() { return "Short description"; } }

我怎么能解决java.lang.IllegalStateException:无法执行活动的方法?

<div class="post-text" itemprop="text"> <p>I'm creating apps with login and register function.I'm using the wamp server in order to do the database for my application.But when I run the application on my phone, it keeps showing the following errors; and nothing is being stored in the local host database. I was struggling with this problem about 2 weeks time and still cannot solve it. Can someone help me out?</p> <pre><code>16071/com.example.chang.e_ktm E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.chang.e_ktm, PID: 16071 java.lang.IllegalStateException: Could not execute method of the activity at android.view.View$1.onClick(View.java:4074) at android.view.View.performClick(View.java:4848) at android.view.View$PerformClick.run(View.java:20300) at android.os.Handler.handleCallback(Handler.java:815) at android.os.Handler.dispatchMessage(Handler.java:104) at android.os.Looper.loop(Looper.java:210) at android.app.ActivityThread.main(ActivityThread.java:5830) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1113) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:879) Caused by: java.lang.reflect.InvocationTargetException at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at android.view.View$1.onClick(View.java:4069) at android.view.View.performClick(View.java:4848) at android.view.View$PerformClick.run(View.java:20300) at android.os.Handler.handleCallback(Handler.java:815) at android.os.Handler.dispatchMessage(Handler.java:104) at android.os.Looper.loop(Looper.java:210) at android.app.ActivityThread.main(ActivityThread.java:5830) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1113) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:879) Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first. at android.view.ViewGroup.addViewInner(ViewGroup.java:4088) at android.view.ViewGroup.addView(ViewGroup.java:3938) at android.view.ViewGroup.addView(ViewGroup.java:3910) at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:464) at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:445) at android.app.Activity.setContentView(Activity.java:2218) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at android.view.View$1.onClick(View.java:4069) at android.view.View.performClick(View.java:4848) at android.view.View$PerformClick.run(View.java:20300) at android.os.Handler.handleCallback(Handler.java:815) at android.os.Handler.dispatchMessage(Handler.java:104) at android.os.Looper.loop(Looper.java:210) at android.app.ActivityThread.main(ActivityThread.java:5830) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1113) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:879) </code></pre> <p>This is my Register.java file</p> <pre><code> package com.example.chang.e_ktm; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import java.lang.String; public class RegisterActivity extends Activity { Button reg_button; EditText etName, etUserName, etPassword, etAge, etEmail; String name, user_name, password, email; int age; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); etName = (EditText) findViewById(R.id.etName); etUserName = (EditText) findViewById(R.id.etUserName); etPassword = (EditText) findViewById(R.id.etPassword); etAge = (EditText) findViewById(R.id.etAge); etEmail = (EditText) findViewById(R.id.etEmail); reg_button = (Button)findViewById(R.id.bRegister); } public void userReg(View view) { name = etName.getText().toString(); user_name = etUserName.getText().toString(); password = etPassword.getText().toString(); age = Integer.parseInt(etAge.getText().toString()); email = etEmail.getText().toString(); String method = "register"; BackgroundTask backgroundTask = new BackgroundTask(this); backgroundTask.execute(method, name,user_name,password,age,email); finish(); } } </code></pre> <p>and this one is the BackgroundTask.java file</p> <pre><code> package com.example.chang.e_ktm; import android.content.Context; import android.os.AsyncTask; import android.widget.Toast; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; /** * Created by Chang on 21/9/2016. */ public class BackgroundTask extends AsyncTask&lt;String,Void,String&gt; { Context ctx; BackgroundTask(Context ctx) { this.ctx = ctx; } @Override protected void onPreExecute(){ super.onPreExecute(); } @Override protected String doInBackground(String... params) { String reg_url = "http://192.168.0.104/register.php"; String login_url = "http://192.168.0.104/login.php"; String method = params[0]; if(method.equals("register")) { String name = params[1]; String user_name = params[2]; String password = params[3]; int age = Integer.parseInt(params[4]); String email = params[5]; try{ URL url = new URL(reg_url); HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection(); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setDoOutput(true); OutputStream OS = httpURLConnection.getOutputStream(); BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS,"UTF-8")); String data = URLEncoder.encode("user", "UTF-8") + "="+URLEncoder.encode(name,"UTF-8") +"&amp;"+ URLEncoder.encode("user_name", "UTF-8") + "="+URLEncoder.encode(user_name, "UTF-8") +"&amp;"+ URLEncoder.encode("password", "UTF-8") + "="+URLEncoder.encode(password, "UTF-8") +"&amp;"+ URLEncoder.encode("age", "UTF-8") + "="+URLEncoder.encode(String.valueOf(age), "UTF-8") +"&amp;"+ URLEncoder.encode("email", "UTF-8") + "="+URLEncoder.encode(email, "UTF-8"); bufferedWriter.write(data); bufferedWriter.flush(); bufferedWriter.close(); OS.close(); InputStream IS = httpURLConnection.getInputStream(); IS.close(); return "Registration Success"; }catch(IOException e) { e.printStackTrace(); } } return null; } @Override protected void onProgressUpdate(Void...values){ super.onProgressUpdate(values); } @Override protected void onPostExecute(String result){ Toast.makeText(ctx,result,Toast.LENGTH_LONG).show(); } public void execute(String method, String name, String username, String password, int age, String email) { } } </code></pre> </div>

用hibernate来进行数据库查询时,需要按汉字拼音排序,急求

这是查询语句 ``` public List<MapCoordinates> getCoor() { Query query=getSession().createQuery("select new MapCoordinates(mapId, title,fwnr,fwsj, address, coordinate, tel) from MapCoordinates m order by convert_gbk(m.title) asc"); List<MapCoordinates> list = query.list(); return list; } ``` ** 也已经新增了一个拓展方言** ``` package com.jeecms.cms; import org.hibernate.Hibernate; import org.hibernate.dialect.MySQL5InnoDBDialect; import org.hibernate.dialect.function.SQLFunctionTemplate; /** * MySQL扩展方言 * @author */ public class MySQLExtendDialect extends MySQL5InnoDBDialect { public MySQLExtendDialect(){ super(); //registerFunction("convert", new SQLFunctionTemplate(Hibernate.STRING, "convert(?1 using ?2)") ); registerFunction("convert_gbk", new SQLFunctionTemplate(Hibernate.STRING, "convert(?1 using gbk)") ); } } ``` 也配置了 hibernate.dialect=com.jeecms.cms.MySQLExtendDialect 报错 ``` 15:05:43.984 ERROR org.hibernate.util.JDBCExceptionReporter - FUNCTION ntsmkweb.convert_gbk does not exist 一月 12, 2016 3:05:44 下午 org.apache.catalina.core.StandardWrapperValve invoke 严重: Servlet.service() for servlet JeeCmsFront threw exception com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: FUNCTION ntsmkweb.convert_gbk does not exist at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:526) at com.mysql.jdbc.Util.handleNewInstance(Util.java:406) at com.mysql.jdbc.Util.getInstance(Util.java:381) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1030) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3536) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3468) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1957) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2107) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2648) at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2086) at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2237) at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeQuery(NewProxyPreparedStatement.java:76) at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:208) at org.hibernate.loader.Loader.getResultSet(Loader.java:1812) at org.hibernate.loader.Loader.doQuery(Loader.java:697) at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:259) at org.hibernate.loader.Loader.doList(Loader.java:2232) at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2129) at org.hibernate.loader.Loader.list(Loader.java:2124) at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:401) at org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:363) at org.hibernate.engine.query.HQLQueryPlan.performList(HQLQueryPlan.java:196) at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1149) at org.hibernate.impl.QueryImpl.list(QueryImpl.java:102) at com.jeecms.cms.dao.assist.impl.CmsMapDaoImpl.getCoor(CmsMapDaoImpl.java:67) at com.jeecms.cms.manager.assist.impl.CmsMapMngImpl.getList(CmsMapMngImpl.java:100) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:309) at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202) at com.sun.proxy.$Proxy92.getList(Unknown Source) at com.jeecms.cms.action.admin.assist.MapAction.list1(MapAction.java:46) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176) at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:426) at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560) at javax.servlet.http.HttpServlet.service(HttpServlet.java:637) at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:198) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at com.jeecms.common.web.ProcessTimeFilter.doFilter(ProcessTimeFilter.java:38) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:198) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:845) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Thread.java:744) ```

Android登录活动 - 解析数据时出错org.json.JSONException:类型java.lang.String的值无法转换为JSONObject

<div class="post-text" itemprop="text"> <p>Im making a log in activity to connect to a MySQL database. For some reason I keep getting this</p> <pre><code>08-13 08:45:59.739 1144-1159/com.amity.paul.amity E/JSON Parser﹕ Error parsing data org.json.JSONException: Value  of type java.lang.String cannot be converted to JSONObject 08-13 08:45:59.739 1144-1159/com.amity.paul.amity W/dalvikvm﹕ threadid=11: thread exiting with uncaught exception (group=0xb3ad0ba8) 08-13 08:46:02.409 1144-1159/com.amity.paul.amity E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1 Process: com.amity.paul.amity, PID: 1144 java.lang.RuntimeException: An error occured while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:300) at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355) at java.util.concurrent.FutureTask.setException(FutureTask.java:222) at java.util.concurrent.FutureTask.run(FutureTask.java:242) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) at java.lang.Thread.run(Thread.java:841) Caused by: java.lang.NullPointerException at com.amity.paul.amity.login$AttemptLogin.doInBackground(login.java:129) at com.amity.paul.amity.login$AttemptLogin.doInBackground(login.java:93) at android.os.AsyncTask$2.call(AsyncTask.java:288) at java.util.concurrent.FutureTask.run(FutureTask.java:237)             at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)             at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)             at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)             at java.lang.Thread.run(Thread.java:841) </code></pre> <p>I have no idea what is wrong. Below are the related files: login.java</p> <pre><code>package com.amity.paul.amity; import java.util.ArrayList; import java.util.List; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import library.JSONParser; public class login extends Activity implements OnClickListener{ private EditText user, pass; private Button mSubmit, mRegister; // Progress Dialog private ProgressDialog pDialog; // JSON parser class JSONParser jsonParser = new JSONParser(); //php login script location: //localhost : //testing on your device //put your local ip instead, on windows, run CMD &gt; ipconfig //or in mac's terminal type ifconfig and look for the ip under en0 or en1 // private static final String LOGIN_URL = "http://xxx.xxx.x.x:1234/webservice/login.php"; //testing on Emulator: private static final String LOGIN_URL = "http://192.168.2.157/amity/login.php"; //testing from a real server: //private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/login.php"; //JSON element ids from repsonse of php script: private static final String TAG_SUCCESS = "success"; private static final String TAG_MESSAGE = "message"; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.login); //setup input fields user = (EditText)findViewById(R.id.username); pass = (EditText)findViewById(R.id.password); //setup buttons mSubmit = (Button)findViewById(R.id.login); mRegister = (Button)findViewById(R.id.register); //register listeners mSubmit.setOnClickListener(this); mRegister.setOnClickListener(this); } @Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.login: new AttemptLogin().execute(); break; case R.id.register: Intent i = new Intent(this, register.class); startActivity(i); break; default: break; } } class AttemptLogin extends AsyncTask&lt;String, String, String&gt; { /** * Before starting background thread Show Progress Dialog * */ boolean failure = false; @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(login.this); pDialog.setMessage("Attempting login..."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); } @Override protected String doInBackground(String... args) { // TODO Auto-generated method stub // Check for success tag int success; String username = user.getText().toString(); String password = pass.getText().toString(); try { // Building Parameters List&lt;NameValuePair&gt; params = new ArrayList&lt;NameValuePair&gt;(); params.add(new BasicNameValuePair("username", username)); params.add(new BasicNameValuePair("password", password)); Log.d("request!", "starting"); // getting product details by making HTTP request JSONObject json = jsonParser.makeHttpRequest( LOGIN_URL, "POST", params); // check your log for json response Log.d("Login attempt", json.toString()); // json success tag success = json.getInt(TAG_SUCCESS); if (success == 1) { Log.d("Login Successful!", json.toString()); //save user data SharedPreferences sp = PreferenceManager .getDefaultSharedPreferences(login.this); SharedPreferences.Editor edit = sp.edit(); edit.putString("username",username); edit.commit(); Intent i = new Intent(login.this, home.class); finish(); startActivity(i); return json.getString(TAG_MESSAGE); }else{ Log.d("Login Failure!", json.getString(TAG_MESSAGE)); return json.getString(TAG_MESSAGE); } } catch (JSONException e) { e.printStackTrace(); } return null; } /** * After completing background task Dismiss the progress dialog * **/ protected void onPostExecute(String file_url) { // dismiss the dialog once product deleted pDialog.dismiss(); if (file_url != null){ Toast.makeText(login.this, file_url, Toast.LENGTH_LONG).show(); } } } } </code></pre> <p>JSONParser:</p> <pre><code>package library; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; public class JSONParser { static InputStream is = null; static JSONObject jObj = null; static String json = ""; // constructor public JSONParser() { } public JSONObject getJSONFromUrl(final String url) { // Making HTTP request try { // Construct the client and the HTTP request. DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); // Execute the POST request and store the response locally. HttpResponse httpResponse = httpClient.execute(httpPost); // Extract data from the response. HttpEntity httpEntity = httpResponse.getEntity(); // Open an inputStream with the data content. is = httpEntity.getContent(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { // Create a BufferedReader to parse through the inputStream. BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); // Declare a string builder to help with the parsing. StringBuilder sb = new StringBuilder(); // Declare a string to store the JSON object data in string form. String line = null; // Build the string until null. while ((line = reader.readLine()) != null) { sb.append(line + " "); } // Close the input stream. is.close(); // Convert the string builder data to an actual string. json = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } // Try to parse the string to a JSON object try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } // Return the JSON Object. return jObj; } // function get json from url // by making HTTP POST or GET mehtod public JSONObject makeHttpRequest(String url, String method, List&lt;NameValuePair&gt; params) { // Making HTTP request try { // check for request method if(method == "POST"){ // request method is POST // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new UrlEncodedFormEntity(params)); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); }else if(method == "GET"){ // request method is GET DefaultHttpClient httpClient = new DefaultHttpClient(); String paramString = URLEncodedUtils.format(params, "utf-8"); url += "?" + paramString; HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + " "); } is.close(); json = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } // try parse the string to a JSON object try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } // return JSON String return jObj; } } </code></pre> <p>login.php</p> <pre><code>&lt;?php //load and connect to MySQL database stuff require("config.inc.php"); if (!empty($_POST)) { //gets user's info based off of a username. $query = " SELECT id, username, password FROM users WHERE username = :username "; $query_params = array( ':username' =&gt; $_POST['username'] ); try { $stmt = $db-&gt;prepare($query); $result = $stmt-&gt;execute($query_params); } catch (PDOException $ex) { // For testing, you could use a die and message. //die("Failed to run query: " . $ex-&gt;getMessage()); //or just use this use this one to product JSON data: $response["success"] = 0; $response["message"] = "Database Error1. Please Try Again!"; die(json_encode($response)); } //This will be the variable to determine whether or not the user's information is correct. //we initialize it as false. $validated_info = false; //fetching all the rows from the query $row = $stmt-&gt;fetch(); if ($row) { //if we encrypted the password, we would unencrypt it here, but in our case we just //compare the two passwords if ($_POST['password'] === $row['password']) { $login_ok = true; } } // If the user logged in successfully, then we send them to the private members-only page // Otherwise, we display a login failed message and show the login form again if ($login_ok) { $response["success"] = 1; $response["message"] = "Login successful!"; die(json_encode($response)); } else { $response["success"] = 0; $response["message"] = "Invalid Credentials!"; die(json_encode($response)); } } else { ?&gt; &lt;h1&gt;Login&lt;/h1&gt; &lt;form action="login.php" method="post"&gt; Username:&lt;br /&gt; &lt;input type="text" name="username" placeholder="username" /&gt; &lt;br /&gt;&lt;br /&gt; Password:&lt;br /&gt; &lt;input type="password" name="password" placeholder="password" value="" /&gt; &lt;br /&gt;&lt;br /&gt; &lt;input type="submit" value="Login" /&gt; &lt;/form&gt; &lt;a href="register.php"&gt;Register&lt;/a&gt; &lt;?php } ?&gt; </code></pre> <p>I am extremely new to mobile development so please make it easy to understand. Cheers!</p> </div>

java ajax没有刷新成制定界面而是跳出一个代码窗口

``` <?xml version="1.0" encoding="UTF-8"?> <web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <!-- 定义Filter --> <filter> <!-- 指定Filter的名字,不能为空 --> <filter-name>struts2</filter-name> <!-- 指定Filter的实现类,此处使用的是Struts2提供的拦截器类 --> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <!-- 定义Filter所拦截的URL地址 --> <filter-mapping> <!-- Filter的名字,该名字必须是filter元素中已声明过的过滤器名字 --> <filter-name>struts2</filter-name> <!-- 定义Filter负责拦截的URL地址 --> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 欢迎页面 --> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app> ``` ``` package com.action; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; public class LoginAction extends ActionSupport{ private static final long serialVersionUID = 1L; //name 属性 private String name; //password 属性 private String password; //name属性 getter方法 public String getName() { return name; } //name属性setter方法 public void setName(String name) { this.name = name; } //password属性getter方法 public String getPassword() { return password; } //password属性setter方法 public void setPassword(String password) { this.password = password; } //重载execute()方法 public String execute() throws Exception { //httpservletresponse 类型变量 HttpServletResponse response=ServletActionContext.getResponse(); //设置返回内容类型 response.setContentType("text/xml;charset=UTF-8"); //设置头 response.setHeader("Cache-Control", "no-cache"); //输出success response.getWriter().println("success"); //检查name password属性 if(name.equals("tom")&&password.equals("123")) { response.getWriter().println("welcome login!"); }else { response.getWriter().println("error,please input again!"); } //返回success return SUCCESS; } } ``` ``` <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <!-- 包package struts2_ajax_demo --> <package name="Struts2_AJAX_DEMO" namespace="/" extends="struts-default"> <!-- login action --> <action name="login" class="com.action.LoginAction"> <!-- result 返回success。jsp --> <result>/success.jsp</result> </action> </package> </struts> ``` ``` <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <%@ taglib prefix="sx" uri="/struts-dojo-tags"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <sx:head/> <script type="text/javascript"> /*定义xmlhttprequest变量*/ var XHR= false; function CreateXHR(){ try{ /*检查能否用activexobject*/ XHR = new ActiveXObject("msxml2.XMLHTTP"); }catch(e1){ try{ /*检查能否用activexobject*/ XHR = new ActiveXObject("microsoft.XMLHTTP"); }catch(e2){ try{ /*检查能否用本地javascript对象*/ XHR = new XMLHttpRequest(); }catch(e3){ //创建失败 XHR = false; } } } } function sendRequest(){ //创建xmlhttprequest对象 CreateXHR(); if(XHR){ //创建成功 //得到name的值 var name=document.getElementById("name").value; //得到password的值 var password=document.getElementById("password").value; //要访问的uri var uri="http://localhost:8080/AjaxDemo/login.action?name="+name+"&password="+password; //var uri="http://localhost:8080/AjaxDemo/login.action?name=1&password=1"; //访问open XHR.open("GET",uri,true); //设置事件触发器 XHR.onreadystatechange = resultHander; //发送请求 XHR.send(null); } } function resultHander(){ //检查状态 if (XHR.readyState == 4 && XHR.status == 200){ //显示提示框 alert(XHR.responseText); } } </script> </head> <body> <center> Name: <input type="text" id="name" /><br /> password: <input type="password" id="password" /><br /> <!-- 单击触发ajax --> <input type="button" value="ok" onclick="sendRequest();" /> </center> </body> </html> ``` ``` package com.action; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class Login extends HttpServlet{ /** * */ private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub super.doGet(req, resp); } } ``` ``` <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <center> <h2> success </h2> </center> </body> </html> ``` 截图 ![图片说明](https://img-ask.csdn.net/upload/201705/09/1494296228_856933.png)

获取错误转换结果java.lang.NullPointerException&错误解析数据org.json.JSONException:输入结束时的字符0

<div class="post-text" itemprop="text"> <p>Hello I am new to Android and I am currently developing a simple login and registration android app using MySql, PHP and JSON. I have created a Database and tables in xampp(local server). Whenever I tried to register I am getting a ton of errors. There are already similar questions like this but the answers didn't help me out. Thanks in Advance.</p> <p>Here is my code</p> <ol> <li><p>JSONParser</p> <pre><code>import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; public class JSONParser { static InputStream is = null; static JSONObject jObj = null; static String json = ""; // constructor public JSONParser() { } public JSONObject getJSONFromUrl(String url) { // Making HTTP request try { // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + " "); } is.close(); json = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } // try parse the string to a JSON object try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } // return JSON String return jObj; } // function get json from url // by making HTTP POST or GET mehtod public JSONObject makeHttpRequest(String url, String method, List&lt;NameValuePair&gt; params) { // Making HTTP request try { // check for request method if(method == "POST"){ // request method is POST // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new UrlEncodedFormEntity(params)); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); }else if(method == "GET"){ // request method is GET DefaultHttpClient httpClient = new DefaultHttpClient(); String paramString = URLEncodedUtils.format(params, "utf-8"); url += "?" + paramString; HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + " "); } is.close(); json = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } // try parse the string to a JSON object try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } // return JSON String return jObj; } } </code></pre></li> <li><p>Register.java</p> <pre><code> import android.app.Activity; import android.os.Bundle; import java.util.ArrayList; import java.util.List; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONException; import org.json.JSONObject; import android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; // Creating the Java class public class Register extends Activity implements OnClickListener{ // Creating variables for username and password... private EditText user,pass; private Button register; // Creating the progressDialog... private ProgressDialog pDialog; // Creating reference for the JSONParser... JSONParser jsonparser = new JSONParser(); // Getting the url to run the php register script.. // Here I am using a localserver since I dont have access to a real server.. private static final String LOGIN_URL = "http://http://127.0.0.1/webservice/register.php"; // Creating ids for messages... private static final String TAG_SUCCESS = "success"; private static final String TAG_MESSAGE = "message"; // Creating the onCreate method... @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.register); // getting references for the username,password and the button elements user = (EditText) findViewById(R.id.get_username); pass = (EditText) findViewById(R.id.get_password); register = (Button) findViewById(R.id.submit); // Creating onClickListener for the button... register.setOnClickListener(this); } @Override public void onClick(View v) { // getting method for create new user... new CreateUser().execute(); Intent intent = new Intent(this, Usersuccess.class); } // Creating a new class called CreateUser... class CreateUser extends AsyncTask&lt;String, String, String&gt;{ /** * Before starting background thread Show Progress Dialog * */ boolean failure = false; @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(Register.this); pDialog.setMessage("Creating User..."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); } @Override protected String doInBackground(String... params) { // Check for success tag int success; String username = user.getText().toString(); String password = pass.getText().toString(); try { // Building Parameters List&lt;NameValuePair&gt; params1 = new ArrayList&lt;NameValuePair&gt;(); params1.add(new BasicNameValuePair("username", username)); params1.add(new BasicNameValuePair("password", password)); Log.d("request!", "starting"); //Posting user data to script JSONObject json = jsonparser.makeHttpRequest( LOGIN_URL, "POST", params1); // full json response Log.d("Login attempt", json.toString()); // json success element success = json.getInt(TAG_SUCCESS); if (success == 1) { Log.d("User Created!", json.toString()); finish(); return json.getString(TAG_MESSAGE); }else{ Log.d("Login Failure!", json.getString(TAG_MESSAGE)); return json.getString(TAG_MESSAGE); } } catch (JSONException e) { e.printStackTrace(); } return null; } /** * After completing background task Dismiss the progress dialog * **/ protected void onPostExecute(String file_url) { // dismiss the dialog once product deleted pDialog.dismiss(); if (file_url != null){ Toast.makeText(Register.this, file_url, Toast.LENGTH_LONG).show(); } } } } </code></pre></li> <li><p>Login.java</p> <pre><code>import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; //Creating the class that extends the Activity class public class LoginScreen extends Activity implements OnClickListener{ @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.login_screen); Button Signup = (Button) findViewById(R.id.signup); Signup.setOnClickListener(this); } @Override public void onClick(View v) { // Creating intent for Signup process.. Intent i = new Intent(LoginScreen.this,Register.class); startActivity(i); } } </code></pre></li> </ol> <p>This is my logcat:</p> <p></p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>10-31 12:45:28.441: D/request!(359): starting 10-31 12:45:30.041: W/System.err(359): java.net.UnknownHostException: http 10-31 12:45:30.041: W/System.err(359): at java.net.InetAddress.lookupHostByName(InetAddress.java:506) 10-31 12:45:30.051: W/System.err(359): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:294) 10-31 12:45:30.051: W/System.err(359): at java.net.InetAddress.getAllByName(InetAddress.java:256) 10-31 12:45:30.051: W/System.err(359): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:136) 10-31 12:45:30.051: W/System.err(359): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164) 10-31 12:45:30.061: W/System.err(359): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119) 10-31 12:45:30.061: W/System.err(359): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:359) 10-31 12:45:30.071: W/System.err(359): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555) 10-31 12:45:30.071: W/System.err(359): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) 10-31 12:45:30.080: W/System.err(359): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465) 10-31 12:45:30.080: W/System.err(359): at com.augustasoftsol.gmoapp.JSONParser.makeHttpRequest(JSONParser.java:96) 10-31 12:45:30.080: W/System.err(359): at com.augustasoftsol.gmoapp.Register$CreateUser.doInBackground(Register.java:99) 10-31 12:45:30.080: W/System.err(359): at com.augustasoftsol.gmoapp.Register$CreateUser.doInBackground(Register.java:1) 10-31 12:45:30.091: W/System.err(359): at android.os.AsyncTask$2.call(AsyncTask.java:185) 10-31 12:45:30.101: W/System.err(359): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306) 10-31 12:45:30.101: W/System.err(359): at java.util.concurrent.FutureTask.run(FutureTask.java:138) 10-31 12:45:30.101: W/System.err(359): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088) 10-31 12:45:30.132: W/System.err(359): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581) 10-31 12:45:30.132: W/System.err(359): at java.lang.Thread.run(Thread.java:1019) 10-31 12:45:30.132: E/Buffer Error(359): Error converting result java.lang.NullPointerException 10-31 12:45:30.141: E/JSON Parser(359): Error parsing data org.json.JSONException: End of input at character 0 of 10-31 12:45:30.151: W/dalvikvm(359): threadid=9: thread exiting with uncaught exception (group=0x40015560) 10-31 12:45:30.171: E/AndroidRuntime(359): FATAL EXCEPTION: AsyncTask #1 10-31 12:45:30.171: E/AndroidRuntime(359): java.lang.RuntimeException: An error occured while executing doInBackground() 10-31 12:45:30.171: E/AndroidRuntime(359): at android.os.AsyncTask$3.done(AsyncTask.java:200) 10-31 12:45:30.171: E/AndroidRuntime(359): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274) 10-31 12:45:30.171: E/AndroidRuntime(359): at java.util.concurrent.FutureTask.setException(FutureTask.java:125) 10-31 12:45:30.171: E/AndroidRuntime(359): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308) 10-31 12:45:30.171: E/AndroidRuntime(359): at java.util.concurrent.FutureTask.run(FutureTask.java:138) 10-31 12:45:30.171: E/AndroidRuntime(359): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088) 10-31 12:45:30.171: E/AndroidRuntime(359): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581) 10-31 12:45:30.171: E/AndroidRuntime(359): at java.lang.Thread.run(Thread.java:1019) 10-31 12:45:30.171: E/AndroidRuntime(359): Caused by: java.lang.NullPointerException 10-31 12:45:30.171: E/AndroidRuntime(359): at com.augustasoftsol.gmoapp.Register$CreateUser.doInBackground(Register.java:103) 10-31 12:45:30.171: E/AndroidRuntime(359): at com.augustasoftsol.gmoapp.Register$CreateUser.doInBackground(Register.java:1) 10-31 12:45:30.171: E/AndroidRuntime(359): at android.os.AsyncTask$2.call(AsyncTask.java:185) 10-31 12:45:30.171: E/AndroidRuntime(359): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306) 10-31 12:45:30.171: E/AndroidRuntime(359): ... 4 more 10-31 12:45:32.121: E/WindowManager(359): Activity com.augustasoftsol.gmoapp.Register has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@405a3fe0 that was originally added here 10-31 12:45:32.121: E/WindowManager(359): android.view.WindowLeaked: Activity com.augustasoftsol.gmoapp.Register has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@405a3fe0 that was originally added here 10-31 12:45:32.121: E/WindowManager(359): at android.view.ViewRoot.&lt;init&gt;(ViewRoot.java:258) 10-31 12:45:32.121: E/WindowManager(359): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148) 10-31 12:45:32.121: E/WindowManager(359): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91) 10-31 12:45:32.121: E/WindowManager(359): at android.view.Window$LocalWindowManager.addView(Window.java:424) 10-31 12:45:32.121: E/WindowManager(359): at android.app.Dialog.show(Dialog.java:241) 10-31 12:45:32.121: E/WindowManager(359): at com.augustasoftsol.gmoapp.Register$CreateUser.onPreExecute(Register.java:82) 10-31 12:45:32.121: E/WindowManager(359): at android.os.AsyncTask.execute(AsyncTask.java:391) 10-31 12:45:32.121: E/WindowManager(359): at com.augustasoftsol.gmoapp.Register.onClick(Register.java:63) 10-31 12:45:32.121: E/WindowManager(359): at android.view.View.performClick(View.java:2485) 10-31 12:45:32.121: E/WindowManager(359): at android.view.View$PerformClick.run(View.java:9080) 10-31 12:45:32.121: E/WindowManager(359): at android.os.Handler.handleCallback(Handler.java:587) 10-31 12:45:32.121: E/WindowManager(359): at android.os.Handler.dispatchMessage(Handler.java:92) 10-31 12:45:32.121: E/WindowManager(359): at android.os.Looper.loop(Looper.java:123) 10-31 12:45:32.121: E/WindowManager(359): at android.app.ActivityThread.main(ActivityThread.java:3683) 10-31 12:45:32.121: E/WindowManager(359): at java.lang.reflect.Method.invokeNative(Native Method) 10-31 12:45:32.121: E/WindowManager(359): at java.lang.reflect.Method.invoke(Method.java:507) 10-31 12:45:32.121: E/WindowManager(359): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) 10-31 12:45:32.121: E/WindowManager(359): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 10-31 12:45:32.121: E/WindowManager(359): at dalvik.system.NativeStart.main(Native Method) 10-31 12:45:35.381: I/Process(359): Sending signal. PID: 359 SIG: 9</code></pre> </div> </div> </div>

swt BrowserFunction返回值js脚本获取的值为null

``` import org.eclipse.swt.browser.Browser; import org.eclipse.swt.browser.BrowserFunction; final class CallJava extends BrowserFunction { public CallJava(Browser arg0, String arg1) { super(arg0, arg1); } @Override public Object function(Object[] arg0) { System.out.println("java代码执行了,参数是:"+arg0[0]); return super.function(new Object []{"ok1111"}); } } ``` ``` <script type="text/javascript"> function test() { var arguments = 'abc'; var s = myCallJava('abc'); alert(s);//此时执行CallJava类中的function方法,arguments为传入参数 } </script> ``` java代码执行了。 BrowserFunction返回值为obj。但是js脚本得到的返回值为null?哪里有问题?

java.net.unknownhostexception无法解析主机

<div class="post-text" itemprop="text"> <p>Ive just been trying to get a simple login script working, my PHP is out of date its crappy, but i have an iOS version of this same app that works fine logging in, i know nothings wrong with my php scripts, and i need them to stay the same, or i suppose i could create a new one intitled <code>android_login.php</code> but lets work with what i got for now.</p> <p>My error is common, but i have tried all the common fixes, including recreating VDM device, and even now using my physical phone to test. My phones outputting <code>java.net.unknownhostexception unable to resolve host</code> <strong>into my <code>et_un</code> TextEdit</strong> heres my code</p> <p>I am including the following into the <code>AndroidManifest.xml</code></p> <pre><code>&lt;uses-permission android:name="android.permission.INTERNET" /&gt; &lt;uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /&gt; </code></pre> <p>heres my LoginActivity.java <strong>UPDATED</strong></p> <pre><code>package com.example.atmebeta; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.AsyncHttpResponseHandler; import com.loopj.android.http.RequestParams; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class LoginActivity extends Activity { EditText un,pw; TextView error; Button ok; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.login); un=(EditText)findViewById(R.id.et_un); pw=(EditText)findViewById(R.id.et_pw); ok=(Button)findViewById(R.id.btn_login); error=(TextView)findViewById(R.id.tv_error); ok.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AsyncHttpClient client = new AsyncHttpClient(); RequestParams parameters = new RequestParams(); parameters.put("email", un.getText().toString()); parameters.put("password", pw.getText().toString()); client.get("http://www.thatonewebsite.com/login.php", parameters, new AsyncHttpResponseHandler() { public final void onSuccess(String response) { error.setText("Correct Username or Password"); } public void onFailure(Throwable e, String response) { error.setText("Sorry!! Incorrect Username or Password"); } }); } }); } } </code></pre> <p>the login.xml</p> <pre><code>&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#DDDDDD" tools:context=".LoginActivity"&gt; &lt;TextView android:id="@+id/tv_un" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="62dp" android:text="User Name:" android:textColor="#444444" android:textSize="10pt" /&gt; &lt;EditText android:id="@+id/et_un" android:layout_width="150dip" android:layout_height="wrap_content" android:layout_alignLeft="@+id/et_pw" android:layout_below="@+id/tv_un" android:background="@android:drawable/editbox_background" android:ems="10" /&gt; &lt;EditText android:id="@+id/et_pw" android:layout_width="150dip" android:layout_height="wrap_content" android:layout_below="@+id/tv_pw" android:layout_centerHorizontal="true" android:background="@android:drawable/editbox_background" android:ems="10" android:password="true" /&gt; &lt;TextView android:id="@+id/tv_pw" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/et_un" android:layout_centerHorizontal="true" android:layout_marginTop="14dp" android:text="Password:" android:textColor="#444444" android:textSize="10pt" /&gt; &lt;Button android:id="@+id/btn_login" android:layout_width="100dip" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:text="Login" /&gt; &lt;TextView android:id="@+id/tv_error" android:layout_width="fill_parent" android:layout_height="40dip" android:layout_below="@+id/btn_login" android:layout_centerHorizontal="true" android:layout_marginTop="40dp" android:textColor="#AA0000" android:textSize="7pt" /&gt; &lt;/RelativeLayout&gt; </code></pre> <p>and if its needed the login.php</p> <pre><code>&lt;?php if (isset($_GET["email"]) &amp;&amp; isset($_GET["password"]) ){ $email = $_GET["email"]; $password = $_GET["password"]; $result = login( $email, $password); echo $result; } function makeSqlConnection() { $DB_Host = "localhost"; $DB_Name = "bdname"; $DB_User = "dbuser"; $DB_Pass = "dbpass"; $con = mysql_connect($DB_Host,$DB_User,$DB_Pass) or die(mysql_error()); mysql_select_db($DB_Name,$con) or die(mysql_error()); return $con; } function disconnectSqlConnection($con) { mysql_close($con); } function login($eMail, $password) { //require (FILE); $con = makeSqlConnection(); $sql = "SELECT * FROM user WHERE email = '$eMail' AND password = '$password'"; $res = mysql_query($sql,$con) or die(mysql_error()); $fetch = mysql_fetch_array($res); $res1 = mysql_num_rows($res); disconnectSqlConnection($con); if ($res1 != 0) { return $fetch['email']; }else{ return 0; }// end else } ?&gt; </code></pre> </div>

大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了

大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

Java基础知识面试题(2020最新版)

文章目录Java概述何为编程什么是Javajdk1.5之后的三大版本JVM、JRE和JDK的关系什么是跨平台性?原理是什么Java语言有哪些特点什么是字节码?采用字节码的最大好处是什么什么是Java程序的主类?应用程序和小程序的主类有何不同?Java应用程序与小程序之间有那些差别?Java和C++的区别Oracle JDK 和 OpenJDK 的对比基础语法数据类型Java有哪些数据类型switc...

我以为我学懂了数据结构,直到看了这个导图才发现,我错了

数据结构与算法思维导图

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...

Linux 会成为主流桌面操作系统吗?

整理 |屠敏出品 | CSDN(ID:CSDNnews)2020 年 1 月 14 日,微软正式停止了 Windows 7 系统的扩展支持,这意味着服役十年的 Windows 7,属于...

讲一个程序员如何副业月赚三万的真实故事

loonggg读完需要3分钟速读仅需 1 分钟大家好,我是你们的校长。我之前讲过,这年头,只要肯动脑,肯行动,程序员凭借自己的技术,赚钱的方式还是有很多种的。仅仅靠在公司出卖自己的劳动时...

学习总结之HTML5剑指前端(建议收藏,图文并茂)

前言学习《HTML5与CSS3权威指南》这本书很不错,学完之后我颇有感触,觉得web的世界开明了许多。这本书是需要有一定基础的web前端开发工程师。这本书主要学习HTML5和css3,看...

女程序员,为什么比男程序员少???

昨天看到一档综艺节目,讨论了两个话题:(1)中国学生的数学成绩,平均下来看,会比国外好?为什么?(2)男生的数学成绩,平均下来看,会比女生好?为什么?同时,我又联想到了一个技术圈经常讨...

搜狗输入法也在挑战国人的智商!

故事总是一个接着一个到来...上周写完《鲁大师已经彻底沦为一款垃圾流氓软件!》这篇文章之后,鲁大师的市场工作人员就找到了我,希望把这篇文章删除掉。经过一番沟通我先把这篇文章从公号中删除了...

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

新一代神器STM32CubeMonitor介绍、下载、安装和使用教程

关注、星标公众号,不错过精彩内容作者:黄工公众号:strongerHuang最近ST官网悄悄新上线了一款比较强大的工具:STM32CubeMonitor V1.0.0。经过我研究和使用之...

记一次腾讯面试,我挂在了最熟悉不过的队列上……

腾讯后台面试,面试官问:如何自己实现队列?

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

冒泡排序动画(基于python pygame实现)

本项目效果初始截图如下 动画见本人b站投稿:https://www.bilibili.com/video/av95491382 本项目对应github地址:https://github.com/BigShuang python版本:3.6,pygame版本:1.9.3。(python版本一致应该就没什么问题) 样例gif如下 ======================= 大爽歌作,mad

Redis核心原理与应用实践

Redis核心原理与应用实践 在很多场景下都会使用Redis,但是到了深层次的时候就了解的不是那么深刻,以至于在面试的时候经常会遇到卡壳的现象,学习知识要做到系统和深入,不要把Redis想象的过于复杂,和Mysql一样,是个读取数据的软件。 有一个理解是Redis是key value缓存服务器,更多的优点在于对value的操作更加丰富。 安装 yum install redis #yum安装 b...

现代的 “Hello, World”,可不仅仅是几行代码而已

作者 |Charles R. Martin译者 | 弯月,责编 | 夕颜头图 |付费下载自视觉中国出品 | CSDN(ID:CSDNnews)新手...

带了6个月的徒弟当了面试官,而身为高级工程师的我天天修Bug......

即将毕业的应届毕业生一枚,现在只拿到了两家offer,但最近听到一些消息,其中一个offer,我这个组据说客户很少,很有可能整组被裁掉。 想问大家: 如果我刚入职这个组就被裁了怎么办呢? 大家都是什么时候知道自己要被裁了的? 面试软技能指导: BQ/Project/Resume 试听内容: 除了刷题,还有哪些技能是拿到offer不可或缺的要素 如何提升面试软实力:简历, 行为面试,沟通能...

!大部分程序员只会写3年代码

如果世界上都是这种不思进取的软件公司,那别说大部分程序员只会写 3 年代码,恐怕就没有程序员这种职业。

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

2020阿里全球数学大赛:3万名高手、4道题、2天2夜未交卷

阿里巴巴全球数学竞赛( Alibaba Global Mathematics Competition)由马云发起,由中国科学技术协会、阿里巴巴基金会、阿里巴巴达摩院共同举办。大赛不设报名门槛,全世界爱好数学的人都可参与,不论是否出身数学专业、是否投身数学研究。 2020年阿里巴巴达摩院邀请北京大学、剑桥大学、浙江大学等高校的顶尖数学教师组建了出题组。中科院院士、美国艺术与科学院院士、北京国际数学...

为什么你不想学习?只想玩?人是如何一步一步废掉的

不知道是不是只有我这样子,还是你们也有过类似的经历。 上学的时候总有很多光辉历史,学年名列前茅,或者单科目大佬,但是虽然慢慢地长大了,你开始懈怠了,开始废掉了。。。 什么?你说不知道具体的情况是怎么样的? 我来告诉你: 你常常潜意识里或者心理觉得,自己真正的生活或者奋斗还没有开始。总是幻想着自己还拥有大把时间,还有无限的可能,自己还能逆风翻盘,只不是自己还没开始罢了,自己以后肯定会变得特别厉害...

HTTP与HTTPS的区别

面试官问HTTP与HTTPS的区别,我这样回答让他竖起大拇指!

程序员毕业去大公司好还是小公司好?

虽然大公司并不是人人都能进,但我仍建议还未毕业的同学,尽力地通过校招向大公司挤,但凡挤进去,你这一生会容易很多。 大公司哪里好?没能进大公司怎么办?答案都在这里了,记得帮我点赞哦。 目录: 技术氛围 内部晋升与跳槽 啥也没学会,公司倒闭了? 不同的人脉圈,注定会有不同的结果 没能去大厂怎么办? 一、技术氛围 纵观整个程序员技术领域,哪个在行业有所名气的大牛,不是在大厂? 而且众所...

男生更看重女生的身材脸蛋,还是思想?

往往,我们看不进去大段大段的逻辑。深刻的哲理,往往短而精悍,一阵见血。问:产品经理挺漂亮的,有点心动,但不知道合不合得来。男生更看重女生的身材脸蛋,还是...

程序员为什么千万不要瞎努力?

本文作者用对比非常鲜明的两个开发团队的故事,讲解了敏捷开发之道 —— 如果你的团队缺乏统一标准的环境,那么即使勤劳努力,不仅会极其耗时而且成果甚微,使用...

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

立即提问
相关内容推荐