如何使以下java代码成为异步任务
如何将以下代码与异步任务合并。我看到了很多教程,并对代码进行了修改,但无法完全做到这一点。这段代码非常好,工作正常,但有人建议我将其设置为异步任务,以便在登录成功消息消失时调用Move\u to\u next方法来启动新活动。所以请有人添加异步任务代码,使其正常工作 代码-如何使以下java代码成为异步任务,java,android,asynchronous,Java,Android,Asynchronous,如何将以下代码与异步任务合并。我看到了很多教程,并对代码进行了修改,但无法完全做到这一点。这段代码非常好,工作正常,但有人建议我将其设置为异步任务,以便在登录成功消息消失时调用Move\u to\u next方法来启动新活动。所以请有人添加异步任务代码,使其正常工作 代码- 公共类LoActivity扩展活动{ 意图一; 按钮符号; 文本视图错误; 复选框检查; 字符串名称=”,传递=”; 字节[]数据; HttpPost-HttpPost; 字符串缓冲区; HttpResponse响应; Ht
公共类LoActivity扩展活动{
意图一;
按钮符号;
文本视图错误;
复选框检查;
字符串名称=”,传递=”;
字节[]数据;
HttpPost-HttpPost;
字符串缓冲区;
HttpResponse响应;
HttpClient-HttpClient;
输入流输入流;
共享参考应用程序的首选项;
列出nameValuePairs;
EditText-editTextId,editTextP;
@凌驾
创建时的公共void(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
signin=(按钮)findViewById(R.id.signin);
editTextId=(EditText)findViewById(R.id.editTextId);
editTextP=(EditText)findViewById(R.id.editTextP);
app_preferences=PreferenceManager.getDefaultSharedReferences(此选项);
check=(复选框)findViewById(R.id.check);
String Str_user=app_preferences.getString(“用户名”,“0”);
String Str_pass=app_preferences.getString(“密码”,“0”);
String Str_check=app_preferences.getString(“checked”,“no”);
如果(Str_check.equals(“yes”))
{
editTextId.setText(Str_用户);
editTextP.setText(Str_pass);
check.setChecked(true);
}
signin.setOnClickListener(新视图.OnClickListener()
{
公共void onClick(视图v)
{
name=editTextId.getText().toString();
pass=editTextP.getText().toString();
String Str_check2=app_preferences.getString(“checked”,“no”);
如果(Str_check2.equals(“yes”))
{
SharedReferences.Editor=app_preferences.edit();
编辑器.putString(“用户名”,名称);
编辑器.putString(“密码”,pass);
commit();
}
if(name.equals(“”)| pass.equals(“”)
{
Toast.makeText(Lo.this,“空白字段..请输入”,Toast.LENGTH_SHORT.show();
}
其他的
{
试一试{
httpclient=新的DefaultHttpClient();
httppost=新的httppost(“http://abc.com/register.php");
//添加您的数据
nameValuePairs=新的ArrayList(2);
添加(新的BasicNameValuePair(“UserEmail”,name.trim());
添加(新的BasicNameValuePair(“密码”,pass.trim());
setEntity(新的UrlEncodedFormEntity(nameValuePairs));
//执行HTTP Post请求
response=httpclient.execute(httppost);
inputStream=response.getEntity().getContent();
数据=新字节[256];
buffer=新的StringBuffer();
int len=0;
而(-1!=(len=inputStream.read(data)))
{
append(新字符串(数据,0,len));
}
inputStream.close();
}
捕获(例外e)
{
Toast.makeText(LoActivity.this,“error”+e.toString(),Toast.LENGTH_SHORT).show();
}
if(缓冲区字符(0)='Y')
{
Toast.makeText(LoActivity.this,“登录成功”,Toast.LENGTH_SHORT.show();
}
其他的
{
Toast.makeText(LoActivity.this,“无效用户名或密码”,Toast.LENGTH_SHORT.show();
}
}
}
});
check.setOnClickListener(新视图.OnClickListener()
{
公共void onClick(视图v)
{
//根据现在是否选中,对单击执行操作
SharedReferences.Editor=app_preferences.edit();
如果(((复选框)v).isChecked())
{
putString(“选中”、“是”);
commit();
}
其他的
{
编辑器.putString(“选中”、“否”);
commit();
}
}
});
}
公共无效移动到下一个()
{
startActivity(新意图(LoActivity.this,qnacActivity.class));
}
}
试试这个:
if(name.equals("") || pass.equals(""))
{
Toast.makeText(Lo.this, "Blank Field..Please Enter", Toast.LENGTH_SHORT).show();
}else{
RequestClient reqClient = new RequestClient(ClassName.this);
String AppResponse = null;
AppResponse = reqClient.execute().get()
}
在应用程序响应中,您将获得响应,并根据您的要求更改其数据类型
创建一个类RequestClient.java
public class RequestClient extends AsyncTask<String, Void, String>{
Context context;
public RequestClient(Context c) {
context = c;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... aurl){
String responseString="";
HttpClient client = null;
try {
client = new DefaultHttpClient();
HttpGet get = new HttpGet(aurl[0]);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
responseString = EntityUtils.toString(resEntityGet);
Log.i("GET RESPONSE", responseString);
}
} catch (Exception e) {
Log.d("ANDRO_ASYNC_ERROR", "Error is "+e.toString());
}
Log.d("ANDRO_ASYNC_RESPONSE", responseString);
client.getConnectionManager().shutdown();
return responseString;
}
@Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
}
}
public类RequestClient扩展异步任务{
语境;
公共请求客户端(上下文c){
上下文=c;
}
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
}
@凌驾
受保护的字符串背景(字符串…aurl){
字符串responseString=“”;
HttpClient=null;
试一试{
client=新的DefaultHttpClient();
HttpGet=newhttpget(aurl[0]);
HttpResponse responseGet=client.execute(get);
HttpEntity-resEntityGet=responseGet.getEntity();
如果
public class RequestClient extends AsyncTask<String, Void, String>{
Context context;
public RequestClient(Context c) {
context = c;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... aurl){
String responseString="";
HttpClient client = null;
try {
client = new DefaultHttpClient();
HttpGet get = new HttpGet(aurl[0]);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
responseString = EntityUtils.toString(resEntityGet);
Log.i("GET RESPONSE", responseString);
}
} catch (Exception e) {
Log.d("ANDRO_ASYNC_ERROR", "Error is "+e.toString());
}
Log.d("ANDRO_ASYNC_RESPONSE", responseString);
client.getConnectionManager().shutdown();
return responseString;
}
@Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
}
}
Context mContext=this;
String[] result = new String[2];
signin.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
AsyncGetAccessToken aSyncGetToken=new AsyncGetAccessToken();
aSyncGetToken.execute()}});
private class AsyncGetAccessToken extends AsyncTask<Void, Void, String>
{
@Override
protected String doInBackground(Void... Data) {
name = editTextId.getText().toString();
pass = editTextP.getText().toString();
String Str_check2 = app_preferences.getString("checked", "no");
if(Str_check2.equals("yes"))
{
SharedPreferences.Editor editor = app_preferences.edit();
editor.putString("username", name);
editor.putString("password", pass);
editor.commit();
}
if(name.equals("") || pass.equals(""))
{
Toast.makeText(Lo.this, "Blank Field..Please Enter", Toast.LENGTH_SHORT).show();
}
else
{
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://abc.com/register.php");
// Add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("UserEmail", name.trim()));
nameValuePairs.add(new BasicNameValuePair("Password", pass.trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
response = httpclient.execute(httppost);
inputStream = response.getEntity().getContent();
data = new byte[256];
buffer = new StringBuffer();
int len = 0;
while (-1 != (len = inputStream.read(data)) )
{
buffer.append(new String(data, 0, len));
}
result[0] = response.getStatusLine().getStatusCode()+"";
result[1] = buffer .toString();
inputStream.close();
}
catch (Exception e)
{
Toast.makeText(LoActivity.this, "error"+e.toString(), Toast.LENGTH_SHORT).show();
}
if(buffer.charAt(0)=='Y')
{
Toast.makeText(LoActivity.this, "login successfull", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(LoActivity.this, "Invalid Username or password", Toast.LENGTH_SHORT).show();
}
}
return result;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
showLoading();
}
@Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
hideLoading();
}
}
private void hideLoading()
{
if (pDialogTh.isShowing()) {
pDialogTh.cancel();
}
}
private ProgressDialog pDialogTh = null;
private void showLoading()
{
// if(pDialog==null)
pDialogTh = ProgressDialog.show(mContext, "", "Loading...",
true, true);
pDialogTh.setCancelable(false);
if (!pDialogTh.isShowing()) {
pDialogTh.show();
}
}
signin.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
...
if(name.equals("") || pass.equals(""))
{
Toast.makeText(Lo.this, "Blank Field..Please Enter", Toast.LENGTH_SHORT).show();
}
else
{
...
YourAsyncClass test = new YourAsyncClass(this);
//you can give various string parameters, in this case, u can send the url, make it an constant
test.execute(YOUR_URL_LIKE_CONSTANT);
}
if(buffer.charAt(0)=='Y')
{
Toast.makeText(LoActivity.this, "login successfull", Toast.LENGTH_SHORT).show();
}
...
public class YourAsynClass extends AsyncTask<String, Void, String> {
...
public YourAsynClass () {
...
}
//this method is executed before the real task
@Override
protected void onPreExecute() {
super.onPreExecute();
...
//here you can call some load dialog box
}
@Override
protected String doInBackground(String... params){
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://abc.com/register.php");
// Add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("UserEmail", name.trim()));
nameValuePairs.add(new BasicNameValuePair("Password", pass.trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
response = httpclient.execute(httppost);
inputStream = response.getEntity().getContent();
data = new byte[256];
buffer = new StringBuffer();
int len = 0;
while (-1 != (len = inputStream.read(data)) )
{
buffer.append(new String(data, 0, len));
}
inputStream.close();
}
catch (Exception e)
{
Toast.makeText(LoActivity.this, "error"+e.toString(), Toast.LENGTH_SHORT).show();
}
return buffer.toString();
}
@Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
//u can hide the load dialog here
}
public class LoActivity extends Activity {
Intent i;
Button signin;
TextView error;
CheckBox check;
String name = "", pass = "";
byte[] data;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
InputStream inputStream;
SharedPreferences app_preferences;
List<NameValuePair> nameValuePairs;
EditText editTextId, editTextP;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
signin = (Button) findViewById(R.id.signin);
editTextId = (EditText) findViewById(R.id.editTextId);
editTextP = (EditText) findViewById(R.id.editTextP);
app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
check = (CheckBox) findViewById(R.id.check);
String Str_user = app_preferences.getString("username", "0");
String Str_pass = app_preferences.getString("password", "0");
String Str_check = app_preferences.getString("checked", "no");
if (Str_check.equals("yes")) {
editTextId.setText(Str_user);
editTextP.setText(Str_pass);
check.setChecked(true);
}
signin.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
name = editTextId.getText().toString();
pass = editTextP.getText().toString();
String Str_check2 = app_preferences.getString("checked", "no");
if (Str_check2.equals("yes")) {
SharedPreferences.Editor editor = app_preferences.edit();
editor.putString("username", name);
editor.putString("password", pass);
editor.commit();
}
if (name.equals("") || pass.equals("")) {
Toast.makeText(Lo.this, "Blank Field..Please Enter", Toast.LENGTH_SHORT).show();
} else {
new LoginTask().execute();
}
}
});
check.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on clicks, depending on whether it's now
// checked
SharedPreferences.Editor editor = app_preferences.edit();
if (((CheckBox) v).isChecked()) {
editor.putString("checked", "yes");
editor.commit();
} else {
editor.putString("checked", "no");
editor.commit();
}
}
});
}
public void Move_to_next() {
startActivity(new Intent(LoActivity.this, QnActivity.class));
}
private class LoginTask extends AsyncTask<Void, Void, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Show progress dialog here
}
@Override
protected String doInBackground(Void... arg0) {
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://abc.com/register.php");
// Add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("UserEmail", name.trim()));
nameValuePairs.add(new BasicNameValuePair("Password", pass.trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
response = httpclient.execute(httppost);
inputStream = response.getEntity().getContent();
data = new byte[256];
buffer = new StringBuffer();
int len = 0;
while (-1 != (len = inputStream.read(data))) {
buffer.append(new String(data, 0, len));
}
inputStream.close();
return buffer.toString();
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Hide progress dialog here
if (buffer.charAt(0) == 'Y') {
Toast.makeText(LoActivity.this, "login successfull", Toast.LENGTH_SHORT).show();
Move_to_next();
} else {
Toast.makeText(LoActivity.this, "Invalid Username or password", Toast.LENGTH_SHORT).show();
}
}
}
}