質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
Java

Javaは、1995年にサン・マイクロシステムズが開発したプログラミング言語です。表記法はC言語に似ていますが、既存のプログラミング言語の短所を踏まえていちから設計されており、最初からオブジェクト指向性を備えてデザインされています。セキュリティ面が強力であることや、ネットワーク環境での利用に向いていることが特徴です。Javaで作られたソフトウェアは基本的にいかなるプラットフォームでも作動します。

Android

Androidは、Google社が開発したスマートフォンやタブレットなど携帯端末向けのプラットフォームです。 カーネル・ミドルウェア・ユーザーインターフェイス・ウェブブラウザ・電話帳などのアプリケーションやソフトウェアをひとつにまとめて構成。 カーネル・ライブラリ・ランタイムはほとんどがC言語/C++、アプリケーションなどはJavaSEのサブセットとAndroid環境で書かれています。

Android Studio

Android Studioは、 Google社によって開発された、 Androidのネイティブアプリケーション開発に特化した統合開発ツールです。

Q&A

1回答

324閲覧

asyncTaskでの非同期処理について

JunZenpou

総合スコア24

Java

Javaは、1995年にサン・マイクロシステムズが開発したプログラミング言語です。表記法はC言語に似ていますが、既存のプログラミング言語の短所を踏まえていちから設計されており、最初からオブジェクト指向性を備えてデザインされています。セキュリティ面が強力であることや、ネットワーク環境での利用に向いていることが特徴です。Javaで作られたソフトウェアは基本的にいかなるプラットフォームでも作動します。

Android

Androidは、Google社が開発したスマートフォンやタブレットなど携帯端末向けのプラットフォームです。 カーネル・ミドルウェア・ユーザーインターフェイス・ウェブブラウザ・電話帳などのアプリケーションやソフトウェアをひとつにまとめて構成。 カーネル・ライブラリ・ランタイムはほとんどがC言語/C++、アプリケーションなどはJavaSEのサブセットとAndroid環境で書かれています。

Android Studio

Android Studioは、 Google社によって開発された、 Androidのネイティブアプリケーション開発に特化した統合開発ツールです。

0グッド

0クリップ

投稿2018/02/09 05:12

編集2022/01/12 10:55

アンドロイドアプリで、ログイン処理を作っています。そこで、ログイン処理が上手くいったら画面遷移して、ログインが失敗したら、画面遷移せず、エラーを表示するようにしたいです。以下のようにコードを作成しました。

public class LoginActivity extends AppCompatActivity implements View.OnClickListener, ListView.OnItemClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); // NavigationDrawerの設定を行う DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.DrawerLayout); mDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.app_name, R.string.app_name); // ドロワーのトグルを有効にする mDrawerToggle.setDrawerIndicatorEnabled(true); drawerLayout.addDrawerListener(mDrawerToggle); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setHomeButtonEnabled(true); } // Button findViewById(R.id.loginButton); // EditText loginText = (EditText)findViewById(R.id.loginid); passwdText = (EditText)findViewById(R.id.passwd); // TextView connect_TextView = (TextView)findViewById(R.id.connect_textview); login_TextView = (TextView)findViewById(R.id.login_textview); passwd_TextView = (TextView)findViewById(R.id.passwd_textview); drawerListView = (ListView) findViewById(R.id.DrawerMenu); setListView(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // ドロワーのトグルの状態を同期する if (mDrawerToggle != null) { mDrawerToggle.syncState(); } } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.DrawerLayout); switch (position) { case 0: Intent home = new Intent(this, LoginHomeActivity.class); startActivity(home); break; case 1: break; } drawerLayout.closeDrawers(); } // 画面回転時に何か処理させたい時 @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); if (mDrawerToggle != null) { mDrawerToggle.onConfigurationChanged(newConfig); } } @Override public boolean onOptionsItemSelected(MenuItem item) { // ActionBarDrawerToggleにドロワーメニューを渡す。 if (mDrawerToggle.onOptionsItemSelected(item)) { return true; } return super.onOptionsItemSelected(item); } protected void setListView(){ // データアダプタ adapter = new ArrayAdapter<String>( this, android.R.layout.simple_list_item_1, menuItems); drawerListView.setAdapter(adapter); // アイテムの選択 drawerListView.setOnItemClickListener(this); } // MD5を作成 public String createMD5hash() { String str = "connect from application"; String md5_str = ""; try { byte[] str_bytes = str.getBytes("UTF-8"); MessageDigest md = MessageDigest.getInstance("MD5"); byte[] md5_bytes = md.digest(str_bytes); BigInteger big_int = new BigInteger(1, md5_bytes); md5_str = big_int.toString(16); }catch(Exception e){ System.out.format("md5作成エラー"); } return md5_str; } @Override public void onClick(View v) { String error = ""; int id = v.getId(); DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.DrawerLayout); switch (id) { case R.id.userImageButton: Intent userinfo = new Intent(this, LoginHomeActivity.class); startActivity(userinfo); drawerLayout.closeDrawers(); break; case R.id.loginButton: String hash = createMD5hash(); String loginid = loginText.getText().toString(); String passwd = passwdText.getText().toString(); // login_text if(loginText.length() == 0){ login_TextView.setText("IDを入力してください"); break; } else { login_TextView.setText(""); } // password_text if(passwdText.length() == 0){ passwd_TextView.setText("パスワードを入力してください"); break; } else { passwd_TextView.setText(""); } // 通信処理 http_request(hash, loginid, passwd, error); if (error != "error"){ // 画面遷移 Intent home = new Intent(this, HomeActivity.class); startActivity(home); } break; } } // サーバー通信処理 private void http_request(String... params){ // TextView connect_TextView = (TextView)findViewById(R.id.connect_textview); login_TextView = (TextView)findViewById(R.id.login_textview); passwd_TextView = (TextView)findViewById(R.id.passwd_textview); String error = ""; Request request = new Request(connect_TextView, connect_TextView, passwd_TextView, error); request.execute(params); }

AsyckTask

1// 非同期処理で通信処理を行うクラス 2 public class Request extends AsyncTask<String, Void, JSONObject> { 3 private TextView _connect_TextView; 4 private TextView _login_TextView; 5 private TextView _passwd_TextView; 6 private String _error; 7 8 9 // コンストラクタ 10 public Request(TextView mconnect_TextView, TextView mlogijn_TextView, TextView mpasswd_TextView, String merror){ 11 _connect_TextView = mconnect_TextView; 12 _login_TextView = mlogijn_TextView; 13 _passwd_TextView = mpasswd_TextView; 14 _error = merror; 15 } 16 17 @Override 18 protected JSONObject doInBackground(String... params) { 19 20 // サーバーに送るjson 21 final String json = "{" + 22 "\"hash\":" + "\"" + params[0] + "\"," + 23 "\"user\":" + "{" + "\"loginid\":" + "\"" + params[1] + "\"," + 24 "\"passwd\":" + "\"" + params[2] + "\"" + "}" + 25 "}"; 26 27 String result = null; 28 29 try{ 30 String buffer = ""; 31 // url 32 HttpURLConnection con = null; 33 URL url = new URL("url"); 34 con = (HttpURLConnection) url.openConnection(); 35 36 // POST送信 37 con.setRequestMethod("POST"); 38 39 // リダイレクトボディの出力を行う 40 con.setDoOutput(true); 41 42 // リダイレクトの許可 43 con.setInstanceFollowRedirects(false); 44 45 // ヘッダーの設定 46 con.setRequestProperty("Content-Type", "application/json; charset=utf-8"); 47 48 // 出力ストリーム 49 OutputStream os = con.getOutputStream(); 50 PrintStream ps = new PrintStream(os); 51 52 ps.print(json); 53 ps.close(); 54 55 BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); 56 buffer = reader.readLine(); 57 JSONObject jsonObject= new JSONObject(buffer); 58 59 return new JSONObject(buffer); 60 61 } catch (MalformedURLException e) { 62 e.printStackTrace(); 63 } catch (IOException e) { 64 e.printStackTrace(); 65 } catch (JSONException e) { 66 e.printStackTrace(); 67 } 68 69 return null; 70 } 71 72 73 public void onPostExecute(JSONObject result) { 74 try { 75 if(result.getString("error") != null){ 76 _connect_TextView.setText("IDかパスワードが間違っています。"); 77 _error = "error"; 78 } 79 } catch (JSONException e) { 80 e.printStackTrace(); 81 } 82 } 83 } 84}

上記のLoginActivityの

// 通信処理 http_request(hash, loginid, passwd, error); if (error != "error"){ // 画面遷移 Intent home = new Intent(this, HomeActivity.class); startActivity(home); }

で、responseでエラーが帰ってこなかったら、画面遷移させて、エラーが帰ってきたら、画面遷移させない処理をしたいです。ここで、error変数はデータ通信のresponseをasyncTaskで代入しています。

asynkTaskが非同期なので、上記のhttp_request関数(asynkTaskクラスを含む)処理が終わる前に、次の処理にいってしまう?ため、error関数がresponseとして帰ってくる前に、画面遷移の処理が走ってしまいます。

なので、上記のhttp_request関数(asynkTaskクラスを含む)処理を非同期ではなく、同期処理をしたいのですが、どのようにコード作成をすれば良いでしょいか?

ご教授お願いします。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

String errorを非同期に仕込むのではなく、カスタムのListnerを設定すればいいのではないでしょうか
リンク内容
リンク内容

投稿2018/03/14 10:30

aja

総合スコア3733

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだベストアンサーが選ばれていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問