閱讀575 返回首頁    go 阿裏雲 go 技術社區[雲棲]


主線程中的handle問題

昨天遇到的一個問題,就是我在主線程中生成了handler對象,但是在下邊進行消息的發送的時候意外的報了異常,說是

  1. E/AndroidRuntime( 1819): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()  
  2. E/AndroidRuntime( 1819):        at android.os.Handler.(Handler.java:121)  
  3. E/AndroidRuntime( 1819):        at android.widget.Toast.(Toast.java:68)  
  4. E/AndroidRuntime( 1819):        at android.widget.Toast.makeText(Toast.java:231

           意思就是說不能創建一個handler來代替線程中沒有被調用Looper.prepare(),然後我在代碼中添加了

Looper.prepare(),Looper.loop()這倆個方法。


package cn.wisenergy.tp;



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.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import cn.wisenergy.tp.commonality.HttpClientHelper;
import cn.wisenergy.tp.fragment.MainFragment2;
import cn.wisenergy.tp.fragment_person.ChooseFriendActivity;
import cn.wisenergy.tp.url.Urlhelp;


public class LoginActivity extends Activity implements OnClickListener {


private TextView login_binding;
private TextView login_binding_zhuce;
private TextView login_userName;
private EditText login_password;
private Button btn_login;

private SharedPreferences  spf;

private String name ;


private int userId;
private Handler handler = new Handler() {


public void handleMessage(android.os.Message msg) {


switch (msg.what) {
case 0:
Toast.makeText(LoginActivity.this, "登陸成功", Toast.LENGTH_SHORT).show();

Editor edit=spf.edit();

edit.putInt("userId", userId);
edit.putString("userName", name);
edit.putString("password", login_password.getText().toString());
edit.commit();
Intent intent = new Intent();
intent.setClass(LoginActivity.this, MainFragment2.class);


startActivity(intent);

finish();
break;


case 1:


Toast.makeText(LoginActivity.this, "登陸失敗", Toast.LENGTH_SHORT)
.show();
break;
}


};
};
 
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
spf= getSharedPreferences("accountInfo", Context.MODE_PRIVATE);
name=spf.getString("userName", null);
setContentView(R.layout.login);
initViews();


}


public void initViews() {




login_userName  =(TextView)findViewById(R.id.login_userName);




login_userName.setText(name);

login_password =(EditText)findViewById(R.id.login_password);

login_binding = (TextView) findViewById(R.id.login_binding);
btn_login = (Button) findViewById(R.id.btn_logins);
login_binding_zhuce = (TextView) findViewById(R.id.login_binding_zhuce);

login_binding.setOnClickListener(this);
btn_login.setOnClickListener(this);
login_binding_zhuce.setOnClickListener(this);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, menu);
return true;
}


@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.login_binding:
// 切換到其它登陸方式
Intent intent = new Intent(LoginActivity.this, Login_bindingActivity.class);
startActivity(intent);
finish();
break;


case R.id.btn_logins:
// 登陸



submitLogin_info(name,login_password.getText().toString());






break;

case R.id.login_binding_zhuce:
//去注冊
Intent intent2 = new Intent(LoginActivity.this, RegActivity.class);
startActivity(intent2);
finish();
break;


default:
break;
}


}






public int relateResult(String str) throws JSONException {


if (str != null && !str.equals("")) {
JSONObject json = new JSONObject(str);


if (json != null) {
if (!json.isNull("status")) {
JSONObject status = json.getJSONObject("status");//


if (!status.isNull("code")) {


int code = status.getInt("code");
return code;


} else {


Log.e("json", "沒有code這個value");
}


}
}
} else {


Log.e("json", "json數據為空");
}
return 0;


}




public int relateResult1(String str) throws JSONException {


if (str != null && !str.equals("")) {
JSONObject json = new JSONObject(str);


if (json != null) {
if (!json.isNull("status")) {

 
int userId=json.getInt("data");
                    return userId;
}

} else {


Log.e("json", "json數據為空");
}
return 0;


}




public void submitLogin_info(final String name,
final String password) {



new Thread(new Runnable() {


@Override
public void run() {


Looper.prepare();
String result = HttpClientHelper.loadTextFromURL(Urlhelp.LOGIN+"loginName="+name+"&password="+password,name+":"+password,
LoginActivity.this);
Log.d("result", result);
if (result != null) {
int code;
try {
code = relateResult(result);
Log.d("CODE", code+"");
if (code == 2000) {

userId = relateResult1(result);

handler.sendEmptyMessage(0);
} else if (code == 4000) {
Toast.makeText(LoginActivity.this,
"指定用戶不存在", Toast.LENGTH_SHORT).show();


} else if (code == 4001) {
Toast.makeText(LoginActivity.this,
"用戶密碼錯誤", Toast.LENGTH_SHORT).show();


} else if (code == 4002) {
Log.d("CODE", code+"");
Toast.makeText(LoginActivity.this,
"當前用戶已被鎖定不可登錄(超出最大登錄次數)",
Toast.LENGTH_SHORT).show();
} else if (code == 4003) {
Toast.makeText(LoginActivity.this,
"用戶沒有權限訪問該資源", Toast.LENGTH_SHORT).show();


} else if (code == 4004) {


Toast.makeText(LoginActivity.this,
"用戶認證信息已過期,需要更新", Toast.LENGTH_SHORT)
.show();
} else if (code == 4005) {
Toast.makeText(LoginActivity.this,
"用戶未重新設置初試密碼", Toast.LENGTH_SHORT).show();


} else if (code == 4006) {
Toast.makeText(LoginActivity.this,
"當前用戶已被禁用(違規操作,管理員手動禁用)",
Toast.LENGTH_SHORT).show();
} else if (code == 4007) {
Toast.makeText(LoginActivity.this,
"接口參數非法:參數長度超出允許的最大值", Toast.LENGTH_SHORT)
.show();
} else if (code == 5009) {


Toast.makeText(LoginActivity.this,
"接口參數非法:參數長度超出允許的最小值", Toast.LENGTH_SHORT)
.show();
}
} catch (JSONException e) {


e.printStackTrace();
}


Looper.loop();
}
}
}).start();


}

}




最後更新:2017-04-03 05:40:00

  上一篇:go Storm專題二:Storm Trident API 使用詳解
  下一篇:go 【JSP開發】GET與POST提交區別