REST サービスからの応答に応答する単純なログイン ページを作成しています。XML で返され、サービスが正常に動作していることをブラウザーで確認した場合の応答。
ログインボタンをクリックするたびに、アプリケーションが強制的に閉じられ、デバッグしましたが、まだ理解できません。
startLogin が AsyncTask に変更されました
メイン アクティビティでは、ボタン クリック リスナーで startLogin を呼び出します。
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.loginButton).setOnClickListener(
new OnClickListener(){
public void onClick(View view){
new startLogin().execute("");
}
});
}
以下は、私が作成した非同期タスクです
private class startLogin extends AsyncTask<String, Void, String> {
final EditText User= (EditText) findViewById(R.id.usernameEditText);
final EditText Pass= (EditText) findViewById(R.id.passwordEditText);
final TextView testLabel = (TextView) findViewById(R.id.testLabel);
@Override
protected String doInBackground(String... params) {
String finished= "have finished the login task.";
int z = 0;
String username = User.getText().toString();
String password = Pass.getText().toString();
String getOne = "http://demo.relocationmw.com/ws_docmgmt/mobile.asmx/GetLogin?userName=";
String getTwo = "&passWord=";
String URL = getOne + username + getTwo + password;
String KEY_ITEM = "Response";
String KEY_SUCCESS = "Success";
String KEY_FAIL = "Fail";
String KEY_UID = "UID";
testLabel.setText("Success to Async");
String xml = getXMLFromUrl(URL);
Document doc = getDomElement(xml);
if(xml != null)
{
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
Element e = (Element) nl.item(z);
String successString = getValue(e,KEY_SUCCESS);
String UIDString = getValue(e,KEY_UID);
String failString = getValue(e,KEY_FAIL);
String loginError = "Please check username and password.";
if(failString.equals("Fail")){
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(MainActivity.this, loginError, duration);
toast.setGravity(Gravity.TOP|Gravity.RIGHT, 0, 0);
toast.show();
}
else{
if(successString.equals("Success")){
Intent intent = new Intent (MainActivity.this, HomeActivity.class);
startActivity(intent);
}
}
}else
{
Toast toast = Toast.makeText(MainActivity.this, "No Connection to Retrieve Data.", Toast.LENGTH_LONG);
toast.show();
}
return finished;
}
@Override
protected void onPostExecute(String result) {
}
@Override
protected void onPreExecute() {
}
@Override
protected void onProgressUpdate(Void... values) {
}
//XML Parsing Start
public String getXMLFromUrl(String url){
String xml = null;
try{
DefaultHttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = client.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
}catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
// Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// Auto-generated catch block
e.printStackTrace();
}
return xml;
}
public Document getDomElement(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
// return DOM
return doc;
}
public String getValue(Element item, String str) {
NodeList n = ((Document) item).getElementsByTagName(str);
return getElementValue(n.item(0));
}
public final String getElementValue( Node elem ) {
Node child;
if( elem != null){
if (elem.hasChildNodes()){
for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
if( child.getNodeType() == Node.TEXT_NODE ){
return child.getNodeValue();
}
}
}
}
return "";
}
//XML Parsing Stop
}
}
XML「メインアクティビティ」:
<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="@color/BackgroundGrey"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="@+id/loginButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="90dp"
android:text="@string/loginbuttonlabel" />
<EditText
android:id="@+id/passwordEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/loginButton"
android:layout_centerHorizontal="true"
android:layout_margin="5dp"
android:background="@color/White"
android:ems="10"
android:inputType="text|textPassword" />
<EditText
android:id="@+id/usernameEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/passwordEditText"
android:layout_centerHorizontal="true"
android:layout_margin="5dp"
android:background="@color/White"
android:ems="10"
android:inputType="text|textPassword" >
<requestFocus />
</EditText>
<TextView
android:id="@+id/testLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/loginButton"
android:layout_alignParentTop="true"
android:layout_marginTop="93dp"
android:text="TextView" />
</RelativeLayout>
LogCat エラー:
02-20 02:56:39.927: E/AndroidRuntime(1018): FATAL EXCEPTION: AsyncTask #1
02-20 02:56:39.927: E/AndroidRuntime(1018): java.lang.RuntimeException: An error occured while executing doInBackground()
02-20 02:56:39.927: E/AndroidRuntime(1018): at android.os.AsyncTask$3.done(AsyncTask.java:299)
02-20 02:56:39.927: E/AndroidRuntime(1018): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
02-20 02:56:39.927: E/AndroidRuntime(1018): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
02-20 02:56:39.927: E/AndroidRuntime(1018): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
02-20 02:56:39.927: E/AndroidRuntime(1018): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
02-20 02:56:39.927: E/AndroidRuntime(1018): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
02-20 02:56:39.927: E/AndroidRuntime(1018): at java.lang.Thread.run(Thread.java:856)
02-20 02:56:39.927: E/AndroidRuntime(1018): Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
02-20 02:56:39.927: E/AndroidRuntime(1018): at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:4746)
02-20 02:56:39.927: E/AndroidRuntime(1018): at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:823)
02-20 02:56:39.927: E/AndroidRuntime(1018): at android.view.View.requestLayout(View.java:15468)
02-20 02:56:39.927: E/AndroidRuntime(1018): at android.view.View.requestLayout(View.java:15468)
02-20 02:56:39.927: E/AndroidRuntime(1018): at android.view.View.requestLayout(View.java:15468)
02-20 02:56:39.927: E/AndroidRuntime(1018): at android.view.View.requestLayout(View.java:15468)
02-20 02:56:39.927: E/AndroidRuntime(1018): at android.widget.RelativeLayout.requestLayout(RelativeLayout.java:318)
02-20 02:56:39.927: E/AndroidRuntime(1018): at android.view.View.requestLayout(View.java:15468)
02-20 02:56:39.927: E/AndroidRuntime(1018): at android.widget.TextView.checkForRelayout(TextView.java:6313)
02-20 02:56:39.927: E/AndroidRuntime(1018): at android.widget.TextView.setText(TextView.java:3567)
02-20 02:56:39.927: E/AndroidRuntime(1018): at android.widget.TextView.setText(TextView.java:3425)
02-20 02:56:39.927: E/AndroidRuntime(1018): at android.widget.TextView.setText(TextView.java:3400)
02-20 02:56:39.927: E/AndroidRuntime(1018): at com.testingapp.MainActivity$startLogin.doInBackground(MainActivity.java:83)
02-20 02:56:39.927: E/AndroidRuntime(1018): at com.testingapp.MainActivity$startLogin.doInBackground(MainActivity.java:1)
02-20 02:56:39.927: E/AndroidRuntime(1018): at android.os.AsyncTask$2.call(AsyncTask.java:287)
02-20 02:56:39.927: E/AndroidRuntime(1018): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
02-20 02:56:39.927: E/AndroidRuntime(1018): ... 3 more
問題を Async Activity に絞り込むことができました。どんな助けでも大歓迎です!