- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
您好,我正在创建一个客户端-服务器 应用程序,使用安卓设备作为客户端。在我的应用程序中,我的客户端(android 设备)发送请求并且服务器对请求有响应。 我注意到任何导致主线程等待的方法都必须在不同的线程上完成。我正在尝试这样做,但在我的例子中使用了 ThreadExecutor
。我实现了一个 helper Runnable
类,并将我的 ObjectInputStream
传递给但由于某种原因,它始终为 null。我在这里检查了一些问题,但似乎大多数问题都是关于如何从一项 Activity 转移到另一项 Activity 的。但是,我想从我的 activity
传递给我的助手 class
,但我不确定该怎么做。
这是我的代码,我希望它更有意义。
package com.dozie.service;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StringWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import com.dcloud.common.Event;
import com.dcloud.common.Message;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class RegisterActivity extends Activity {
private Button registerButton;
private Button cancelButton;
private TextView errorText;
private EditText firstnameField, lastnameField, passwordField, cPasswordField, usernameField;
private String fname, lname, pword, cPword, uname;
private Socket socket;
private TextWatcher fnameWatcher, lnameWatcher, pwordWatcher, cPwordWatcher, unameWatcher;
protected ObjectOutputStream os;
protected ObjectInputStream is;
private ExecutorService threadPool;
private RegisterWorker worker;
public static final String PASSWORD_PATTERN = "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{6,20})";
public static final String USERNAME_PATTERN = "^[A-z0-9_-]{5,20}$";
public static final String TAG = RegisterActivity.class.getName();
public static final int SAMEFIRSTUSER = 100; //same first name and username,
public static final int SAMELASTUSER = 200; //same last name and username
public static final int SAMEPASSFIRST = 300; //same password and firstname
public static final int SAMEPASSLAST = 400; //same password and lastname
public static final int SAMEPASSUSER = 500; //same password and username
public static final int USERNOTMATCH = 600; //username does not match
public static final int PASSNOTMATCH = 700; //password does not match
public static final int CPASS_DIFF = 800; //password and confirm password are different
public static final int GOODINPUT = 1; //every input is good
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
registerButton = (Button) findViewById(R.id.register_id);
cancelButton = (Button) findViewById(R.id.cancel_id);
firstnameField = (EditText) findViewById(R.id.firstname_id);
lastnameField = (EditText) findViewById(R.id.lastname_id);
passwordField = (EditText) findViewById(R.id.rpassword_id);
cPasswordField = (EditText) findViewById(R.id.rcpassword_id);
usernameField = (EditText) findViewById(R.id.rusername_id);
errorText = (TextView) findViewById(R.id.errorText_id);
fname="";lname="";pword="";cPword="";uname="";
//initialize TextWatchers
initializeWatchers();
// add TextWatchers
firstnameField.addTextChangedListener(fnameWatcher);
lastnameField.addTextChangedListener(lnameWatcher);
passwordField.addTextChangedListener(pwordWatcher);
cPasswordField.addTextChangedListener(cPwordWatcher);
usernameField.addTextChangedListener(unameWatcher);
cancelButton.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
firstnameField.setText("");
lastnameField.setText("");
passwordField.setText("");
cPasswordField.setText("");
usernameField.setText("");
setResult(RESULT_CANCELED);
finish();
}
});
}
@Override
public void onStart()
{
super.onStart();
Log.d(TAG, "onStart()");
Intent intent = getIntent();
final String address = intent.getStringExtra("ipAddress");
final int port = intent.getIntExtra("port", 6060);
threadPool = Executors.newFixedThreadPool(2);
new Thread(new Runnable()
{
@Override
public void run() {
// TODO Auto-generated method stub
try {
Log.i(TAG, "Trying to Connect to "+ address + " on " + port);
socket = new Socket(address, port);
Log.i(TAG, "Connection established!");
os = new ObjectOutputStream(new DataOutputStream(socket.getOutputStream()));
is = new ObjectInputStream(new DataInputStream(socket.getInputStream()));
Log.i(TAG, "Client connected to server.");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
Log.e(TAG, "UnknownHostException", e);
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(TAG, "I/O Exception", e);
}
}
}).start();
// threadPool.execute(worker = new RegisterWorker(is));;
}
@Override
public void onPause()
{
super.onPause();
Log.d(TAG, "onPause()");
threadPool.shutdown();
Message out = new Message("disconnect");
out.setRequest(Event.Request.DISCONNECT);
try {
os.writeObject(out);
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(TAG, "I/O Exception", e);
}
finally
{
try {
is.close();
os.close();
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Log.i(TAG, "socket closed");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_register, menu);
return true;
}
public int validateInput(String [] input)
{
String firstname = input[0];
String lastname = input[1];
String password = input[2];
String cpassword = input[3];
String username = input[4];
Pattern pattern = Pattern.compile(PASSWORD_PATTERN);
Matcher matcher = pattern.matcher(password);
Pattern p = Pattern.compile(USERNAME_PATTERN);
Matcher m = p.matcher(username);
if(firstname.equals(username))
return RegisterActivity.SAMEFIRSTUSER;
if(lastname.equals(username))
return RegisterActivity.SAMELASTUSER;
if(firstname.equals(password))
return RegisterActivity.SAMEPASSFIRST;
if(lastname.equals(password))
return RegisterActivity.SAMEPASSLAST;
if(password.equals(username))
return RegisterActivity.SAMEPASSUSER;
if(!password.equals(cpassword))
return RegisterActivity.CPASS_DIFF;
if(!matcher.matches())
return RegisterActivity.PASSNOTMATCH;
if(!m.matches())
return RegisterActivity.USERNOTMATCH;
return RegisterActivity.GOODINPUT;
}
public void registerUser(View v)
{
String [] input = getUserInformation();
int result = validateInput(input);
switch(result)
{
case RegisterActivity.GOODINPUT:
Intent info = new Intent();
info.putExtra("username", input[4]);
registerUser(input);
if(worker.getServerResponse() != null)
{
if(worker.getServerResponse().getResponse() == Event.Response.REQUEST_SUCCESSFUL)
{
threadPool.shutdown();
setResult(RESULT_OK, info);
finish();
Log.i(TAG, "registerUser(): data input successful!");
}
else if(worker.getServerResponse().getResponse() == Event.Response.REQUEST_UNSUCCESSFUL)
{
threadPool.execute(worker);
Log.i(TAG, "registerUser(): data input unsuccessful!");
}
}
break;
case RegisterActivity.SAMEFIRSTUSER:
errorText.setText("username should not be the same as firstname");
Log.i(TAG, "registerUser(): username same as firstname");break;
case RegisterActivity.SAMELASTUSER:
errorText.setText("username should not be the same as lastname");
Log.i(TAG, "registerUser(): username same as lastname");break;
case RegisterActivity.SAMEPASSFIRST:
errorText.setText("password should not be the same as firstname");
Log.i(TAG, "registerUser(): password same as firstname");break;
case RegisterActivity.SAMEPASSLAST:
errorText.setText("password should not be the same as lastname");
Log.i(TAG, "registerUser(): password same as lastname");break;
case RegisterActivity.SAMEPASSUSER:
errorText.setText("password should not be the same as username");
Log.i(TAG, "registerUser(): password same as username");break;
case RegisterActivity.CPASS_DIFF:
errorText.setText("password and confirm password are not the same");
Log.i(TAG, "registerUser(): password and confirm password not the same");break;
case RegisterActivity.PASSNOTMATCH:
errorText.setText("password format wrong. Password should contain 6-20 characters\n" +
"characters containing at least 1 digit, 1 lower case alphabet and 1 upper case character");
Log.i(TAG, "registerUser(): password format not correct");break;
case RegisterActivity.USERNOTMATCH:
errorText.setText("username format wrong. username should contain 5-20 characters " +
"and should have to special characters");
Log.i(TAG, "registerUser(): username format not correct");break;
default:
Log.i(TAG, "registerUser(): Code not handled");break;
}
}
public String [] getUserInformation()
{
String firstname = firstnameField.getText().toString();
String lastname = lastnameField.getText().toString();
String password = passwordField.getText().toString();
String cpassword = cPasswordField.getText().toString();
String username = usernameField.getText().toString();
String [] input = {firstname, lastname, password, cpassword, username};
return input;
}
public void initializeWatchers()
{
fnameWatcher = new TextWatcher()
{
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
fname = firstnameField.getText().toString();
fname.trim();
updateButton();
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
};
lnameWatcher = new TextWatcher()
{
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
lname = lastnameField.getText().toString();
lname.trim();
updateButton();
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
};
pwordWatcher = new TextWatcher()
{
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
pword = passwordField.getText().toString();
pword.trim();
updateButton();
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
};
cPwordWatcher = new TextWatcher()
{
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
cPword = cPasswordField.getText().toString();
cPword.trim();
updateButton();
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
};
unameWatcher = new TextWatcher()
{
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
uname = usernameField.getText().toString();
uname.trim();
updateButton();
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
};
}
public void updateButton()
{
boolean enabled = fname.length()>0 && lname.length()>0 && pword.length()>0
&& cPword.length()>0 && uname.length() >0;
registerButton.setEnabled(enabled);
}
public void registerUser(String [] input)
{
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("Register");
doc.appendChild(rootElement);
Element user = doc.createElement("user");
rootElement.appendChild(user);
Element firstname = doc.createElement("firstname");
firstname.appendChild(doc.createTextNode(input[0]));
user.appendChild(firstname);
Element lastname = doc.createElement("lastname");
lastname.appendChild(doc.createTextNode(input[1]));
user.appendChild(lastname);
Element password = doc.createElement("password");
password.appendChild(doc.createTextNode(input[2]));
user.appendChild(password);
Element username = doc.createElement("username");
username.appendChild(doc.createTextNode(input[4]));
user.appendChild(username);
StringWriter writer = new StringWriter();
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
String content = writer.toString();
Message out = new Message(content);
out.setRequest(Event.Request.REGISTER);
os.writeObject(out);
Log.d(TAG, "registerUser(): Register message sent");
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
Log.e(TAG, "onActivityReturn(): ParserConfigurationException error", e);
} catch (TransformerException e) {
// TODO Auto-generated catch block
Log.e(TAG, "onActivityReturn(): TransformerException error", e);
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(TAG, "onActivityReturn(): IOException error", e);
}
}
}
<p>And for my runnable class</p>
package com.dozie.service;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.OptionalDataException;
import android.util.Log;
import com.dcloud.common.Event;
import com.dcloud.common.Message;
public class RegisterWorker implements Runnable{
private ObjectInputStream is;
private Message in;
public static final String TAG = RegisterWorker.class.getName();
public RegisterWorker(ObjectInputStream is)
{
this.is = is;
if(this.is == null)
System.out.println("null");
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
while((in = (Message) is.readObject())!=null)
{
if(in.getResponse() == Event.Response.REQUEST_SUCCESSFUL)
{
Log.d(TAG, "Login Response: "+in.getMessage());
}
else if(in.getResponse() == Event.Response.REQUEST_UNSUCCESSFUL)
{
Log.d(TAG, "Login Response: "+in.getMessage());
//give reason for rejection
}
}
} catch (OptionalDataException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Message getServerResponse()
{
return in;
}
}
最佳答案
我认为您正在编写的代码比实际需要的要复杂得多。如果你想将变量传递给 Thread
,我认为你正在尝试这样做,只需这样做:
public Worker extends AsyncTask<Arguments, Void, Void> {
// method names may be slightly incorrect, writing this from memory
public void runInBackground(Arguments...args) {
// do what you want to do in the background
}
}
然后开始你的话题:
Arguments args = new Arguments(arg1, arg2); // whatever you want to pass along
new Worker().execute(args);
Arguments
可以是任何类,以此为例。
希望这对您有所帮助。
关于java - 如何将变量从 Activity 传递到 Android 中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13657008/
这个问题在这里已经有了答案: 关闭 10 年前。 Possible Duplicate: How to nest OR statements in JavaScript? 有没有办法做到这一点:
在 JavaScript 中有没有办法让一个变量总是等于一个变量?喜欢var1 = var2但是当var2更新,也是var1 . 例子 var var1 = document.getElementBy
我正在努力理解这代表什么 var1 = var2 == var3 我的猜测是这等同于: if (var2 == var3): var1 = var2 最佳答案 赋值 var1 = var2
这个问题已经有答案了: What does the PHP error message "Notice: Use of undefined constant" mean? (2 个回答) 已关闭 8
我在临时表中有几条记录,我想从每条记录中获取一个值并将其添加到一个变量中,例如 color | caption -------------------------------- re
如何将字符串转为变量(字符串变量--> $variable)? 或者用逗号分隔的变量列表然后转换为实际变量。 我有 2 个文件: 列名文件 行文件 我需要根据字符串匹配行文件中的整行,并根据列名文件命
我有一个我无法解决的基本 php 问题,我也想了解为什么! $upperValueCB = 10; $passNodeMatrixSource = 'CB'; $topValue= '$uppe
这可能吗? php $variable = $variable1 || $variable2? 如果 $variable1 为空则使用 $variable2 是否存在类似的东西? 最佳答案 PHP 5
在 Perl 5.20 中,for 循环似乎能够修改模块作用域的变量,但不能修改父作用域中的词法变量。 #!/usr/bin/env perl use strict; use warnings; ou
为什么这不起作用: var variable; variable = variable.concat(variable2); $('#lunk').append(variable) 我无法弄清楚这一点
根据我的理解,在32位机器上,指针的sizeof是32位(4字节),而在64位机器上,它是8字节。无论它们指向什么数据类型,它们都有固定的大小。我的计算机在 64 位上运行,但是当我打印包含 * 的大
例如: int a = 10; a += 1.5; 这运行得很完美,但是 a = a+1.5; 此作业表示类型不匹配:无法从 double 转换为 int。所以我的问题是:+= 运算符 和= 运算符
您好,我写了这个 MySQL 存储过程,但我一直收到这个语法错误 #1064 - You have an error in your SQL syntax; check the manual that
我试图在我的场景中显示特定的奖牌,这取决于你的高分是基于关卡的目标。 // Get Medal Colour if levelHighscore goalScore { sc
我必须维护相当古老的 Visual C++ 源代码的大型代码库。我发现代码如下: bIsOk = !!m_ptr->isOpen(some Parameters) bIsOk的数据类型是bool,is
我有一个从 MySQL 数据库中提取的动态产品列表。在 list 上有一个立即联系 按钮,我正在使用一个 jquery Modal 脚本,它会弹出一个表单。 我的问题是尝试将产品信息变量传递给该弹出窗
这个问题在这里已经有了答案: 关闭 10 年前。 Possible Duplicate: What is the difference between (type)value and type(va
jQuery Core Style Guidelines建议两种不同的方法来检查变量是否已定义。 全局变量:typeof variable === "undefined" 局部变量:variable
这个问题已经有答案了: 已关闭11 年前。 Possible Duplicate: “Variable” Variables in Javascript? 我想肯定有一种方法可以在 JavaScrip
在语句中使用多重赋值有什么优点或缺点吗?在简单的例子中 var1 = var2 = true; 赋值是从右到左的(我相信 C# 中的所有赋值都是如此,而且可能是 Java,尽管我没有检查后者)。但是,
我是一名优秀的程序员,十分优秀!