2017-02-01 9 views
-3

私はアンドロイドスタジオでアプリを作っています。パスワードと電子メールが一致しないか、データベースに存在しないためにログインに失敗した場合は、アラートを表示するだけですが、今はクラッシュします。ここでログインが失敗するとアプリケーションがクラッシュする

はここでバックグラウンドタスク

import android.app.AlertDialog; 
import android.app.ProgressDialog; 
import android.content.Context; 
import android.content.Intent; 
import android.content.SharedPreferences; 
import android.os.AsyncTask; 
import android.os.Handler; 
import android.renderscript.ScriptGroup; 
import android.widget.Toast; 

import java.io.BufferedReader; 
import java.io.BufferedWriter; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.OutputStream; 
import java.io.OutputStreamWriter; 
import java.net.HttpURLConnection; 
import java.net.MalformedURLException; 
import java.net.URL; 
import java.net.URLEncoder; 
import java.nio.Buffer; 

import javax.net.ssl.HttpsURLConnection; 

/** 
* Created by Kelsea 
*/ 
public class BackgroundTask extends AsyncTask<String,Void,String> { 




    SharedPreferences preferences; 
    SharedPreferences.Editor editor; 

    Context context; 
    ProgressDialog pDialog; 

    BackgroundTask(Context ctx){ 
     this.context = ctx; 
    } 

    @Override 
    protected String doInBackground(String... params) { 

     preferences = context.getSharedPreferences("MYPREFS", Context.MODE_PRIVATE); 
     editor = preferences.edit(); 
     editor.putString("flag","0"); 
     editor.commit(); 

     String urlRegistration = "http://biomedengineering.x10host.com/BiomedicalEngineering-register.php"; 
     String urlLogin = "http://biomedengineering.x10host.com/BiomedicalEngineering-login.php"; 
     String task = params[0]; 

     if(task.equals("register")){ 
      String regName = params[1]; 
      String regEmail = params[2]; 
      String regPassword = params[3]; 

      try { 
       URL url = new URL(urlRegistration); 
       HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); 
       httpURLConnection.setRequestMethod("POST"); 
       httpURLConnection.setDoOutput(true); 
       OutputStream outputStream = httpURLConnection.getOutputStream(); 
       OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream,"UTF-8"); 
       BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter); 
       String myData = URLEncoder.encode("identifier_name","UTF-8")+"="+URLEncoder.encode(regName,"UTF-8")+"&" 
         +URLEncoder.encode("identifier_email","UTF-8")+"="+URLEncoder.encode(regEmail,"UTF-8")+"&" 
         +URLEncoder.encode("identifier_password","UTF-8")+"="+URLEncoder.encode(regPassword,"UTF-8"); 
       bufferedWriter.write(myData); 
       bufferedWriter.flush(); 
       bufferedWriter.close(); 
       InputStream inputStream = httpURLConnection.getInputStream(); 
       inputStream.close(); 

       editor.putString("flag","register"); 
       editor.commit(); 
       return "Successfully Registered " + regName; 
      } catch (MalformedURLException e) { 
       e.printStackTrace(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      }catch (NullPointerException e) { 
      e.printStackTrace(); 
     } 

     } 
     if(task.equals("login")){ 
      String loginEmail = params[1]; 
      String loginPassword = params[2]; 
      try { 
       URL url = new URL(urlLogin); 
       HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); 
       httpURLConnection.setRequestMethod("POST"); 
       httpURLConnection.setDoOutput(true); 
       httpURLConnection.setDoInput(true); 

       //send the email and password to the database 
       OutputStream outputStream = httpURLConnection.getOutputStream(); 
       OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream,"UTF-8"); 
       BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter); 
       String myData = URLEncoder.encode("identifier_loginEmail","UTF-8")+"="+URLEncoder.encode(loginEmail,"UTF-8")+"&" 
         +URLEncoder.encode("identifier_loginPassword","UTF-8")+"="+URLEncoder.encode(loginPassword,"UTF-8"); 
       bufferedWriter.write(myData); 
       bufferedWriter.flush(); 
       bufferedWriter.close(); 
       outputStream.close(); 

       //get response from the database 
       InputStream inputStream = httpURLConnection.getInputStream(); 
       InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"UTF-8"); 
       BufferedReader bufferedReader = new BufferedReader(inputStreamReader); 
       String dataResponse = ""; 
       String inputLine = ""; 
       while((inputLine = bufferedReader.readLine()) != null){ 
        dataResponse += inputLine; 
       } 
       bufferedReader.close(); 
       inputStream.close(); 
       httpURLConnection.disconnect(); 

       System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); 
       System.out.println(dataResponse); 

       editor.putString("flag","login"); 
       editor.commit(); 
       return dataResponse; 

      } catch (MalformedURLException e) { 
       e.printStackTrace(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      }catch (NullPointerException e) { 
      e.printStackTrace(); 
     } 
     } 

     return null; 
    } 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     pDialog = new ProgressDialog(context); 
     pDialog.setMessage("Attempting login..."); 
     pDialog.setIndeterminate(false); 
     pDialog.setCancelable(true); 
     pDialog.show(); 
    } 

    //This method will be called when doInBackground completes... and it will return the completion string which 
    //will display this toast. 
    @Override 
    protected void onPostExecute(String s) { 
     String flag = preferences.getString("flag","0"); 

     if(flag.equals("register")) { 
      Toast.makeText(context,s,Toast.LENGTH_LONG).show(); 
     } 
     if(flag.equals("login")){ 
      String test = "false"; 
      String name = ""; 
      String email = ""; 
      String[] serverResponse = s.split("[,]"); 
      test = serverResponse[0]; 
      name = serverResponse[1]; 
      email = serverResponse[2]; 

      if(test.equals("true")){ 
       editor.putString("name",name); 
       editor.commit(); 
       editor.putString("email",email); 
       editor.commit(); 
       Intent intent = new Intent(context, Home.class); 
       context.startActivity(intent); 
      }else{ 
       // Get a handler that can be used to post to the main thread 
       Handler mainHandler = new Handler(context.getMainLooper()); 

       Runnable myRunnable = new Runnable() { 
        @Override 
        public void run() { 
         display("Login failed....", "Something went wrong"); 
        } // This is your code 
       }; 
       mainHandler.post(myRunnable); 

      } 
     }else{ 

      Handler mainHandler = new Handler(context.getMainLooper()); 

      Runnable myRunnable = new Runnable() { 
       @Override 
       public void run() { 
        display("Login failed....", "Something went wrong"); 
       } // This is your code 
      }; 
      mainHandler.post(myRunnable); 

     } 
    } 


    @Override 
    protected void onProgressUpdate(Void... values) { 
     super.onProgressUpdate(values); 
    } 

    public void display(String title, String message){ 
     AlertDialog.Builder builder = new AlertDialog.Builder(context); 
     builder.setCancelable(true); 
     builder.setTitle(title); 
     builder.setMessage(message); 
     builder.show(); 
    } 


} 

ための私のコードです

    --------- beginning of crash 
E/AndroidRuntime: FATAL EXCEPTION: main 
        Process: ca.on.niagarahealth.biomedicalengineering, PID: 2469 
        java.lang.ArrayIndexOutOfBoundsException: length=1; index=1 
         at ca.on.niagarahealth.BackgroundTask.onPostExecute(BackgroundTask.java:170) 
         at ca.on.niagarahealth.BackgroundTask.onPostExecute(BackgroundTask.java:31) 
         at android.os.AsyncTask.finish(AsyncTask.java:651) 
         at android.os.AsyncTask.-wrap1(AsyncTask.java) 
         at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668) 
         at android.os.Handler.dispatchMessage(Handler.java:102) 
         at android.os.Looper.loop(Looper.java:148) 
         at android.app.ActivityThread.main(ActivityThread.java:5417) 
         at java.lang.reflect.Method.invoke(Native Method) 
         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
I/Process: Sending signal. PID: 2469 SIG: 9 
Application terminated. 
+1

スタックトレースを追加する必要があります。 –

+0

'context'が' getapplicationcontext 'または' activity.this'であることを確認します。 'getapplicationcontext'の代わりに' activity.this'を使用します。 – sajan

+0

はスタックトレース@MuratKを追加しました。 –

答えて

1

あなたは常に3つのエントリを返すsplit()方法を期待するので、あなたの問題は、ここにあるように思えます。あなたがコメントしたように、それはできません。したがって、serverResponse[1]serverResponse[2]を1ブロック下に移動する方が良いでしょう。

String[] serverResponse = s.split("[,]"); 
test = serverResponse[0]; 
name = serverResponse[1]; // remove here 
email = serverResponse[2]; // remove here 

    if(test.equals("true")){ 
     editor.putString("name", serverResponse[1]); // put it here 
     editor.commit(); 
     editor.putString("email",serverResponse[2]); // put it here 
     editor.commit(); 
     Intent intent = new Intent(context, Home.class); 
     context.startActivity(intent); 
     }else{ 

可能性のある項目があるかどうかを確認する必要があります。

+0

ありがとう!それは働いた –

+0

@kelseatomainoさて、この答えを受け入れるかもしれない。 –

関連する問題