我的应用程序在模拟器上工作,但它在我的手机上不起作用

时间:2016-12-13 12:08:12

标签: android mobile

错误我面对的是当我在android工作室上的模拟器上运行此应用程序时,一切都很好并且运行良好,但是当我连接我的手机并尝试在其上运行应用程序时这是错误我是什么面对它......

D/ViewRootImpl: ViewPostImeInputStage processPointer 0
D/ViewRootImpl: ViewPostImeInputStage processPointer 1
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
W/DisplayListCanvas: DisplayListCanvas is started on unbinded RenderNode 
W/System.err: java.net.ConnectException: failed to connect to /10.0.2.2  
(port 80): connect failed: ECONNREFUSED (Connection refused)
W/System.err:     at libcore.io.IoBridge.connect(IoBridge.java:124)
W/System.err:     at 
java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
W/System.err:     at   
java.net.PlainSocketImpl.connect(PlainSocketImpl.java:452)
W/System.err:     at java.net.Socket.connect(Socket.java:884)
W/System.err:     at    
com.android.okhttp.internal.Platform.connectSocket(Platform.java:117)
W/System.err:     at    
com.android.okhttp.internal.http.SocketConnector.connectRawSocket
(SocketConnecto    r.java:434)
W/System.err:at
      com.android.okhttp.internal.http.SocketConnector.connectCleartext
 (SocketConnecto     r.java:105)
 W/System.err:
 at          com.android.okhttp.Connection.connect(Connection.java:1331)
 W/System.err:
 at com.android.okhttp.Connection.connectAndSetOwner(Connection.java:1410)
 W/System.err:
 at    com.android.okhttp.OkHttpClient$1.connectAndSetOwner
 (OkHttpClient.java:128)
 W/System.err:     at   
 com.android.okhttp.internal.http.HttpEngine.nextConnection
 (HttpEngine.java:466)
  W/System.err:     at com.android.okhttp.internal.http.HttpEngine.connect
  (HttpEngine.java:447)
  W/System.err:     at 
 com.android.okhttp.internal.http.HttpEngine.sendRequest

 (HttpEngine.java:353)
  W/System.err:     at   
  com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute
  (HttpURLConnectionImpl.java:476)
  W/System.err:     at     
  com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect
  (HttpURLConnectionImpl.java:118)
   W/System.err:     at
   com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream
   (HttpURLConnectionImpl.java:249)
   W/System.err:     at
   com.example.win10user.project.BackgroundWorker.doInBackground
   (BackgroundWorker.java:46)
   W/System.err:     at
  com.example.win10user.project.BackgroundWorker.doInBackground
 (BackgroundWorker.java:21)
   W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:295)
   W/System.err:     at     java.util.concurrent.FutureTask.run
  (FutureTask.java:237)
   W/System.err:     at   android.os.AsyncTask$SerialExecutor$1.run
   (AsyncTask.java:234)
    W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker
   (ThreadPoolExecutor.java:1113)
    W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run
   (ThreadPoolExecutor.java:588)
     W/System.err:     at java.lang.Thread.run(Thread.java:818)
     W/System.err: Caused by: android.system.ErrnoException: connect failed:
     ECONNREFUSED (Connection refused)
     W/System.err:     at libcore.io.Posix.connect(Native Method)
     W/System.err:     at   
     libcore.io.BlockGuardOs.connect(BlockGuardOs.java:111)
     W/System.err:     at 
       libcore.io.IoBridge.connectErrno(IoBridge.java:137)
     W/System.err:     at libcore.io.IoBridge.connect(IoBridge.java:122)
     W/System.err:  ... 23 more
     D/AndroidRuntime: Shutting down VM
     E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.win10user.project, PID: 10042
              java.lang.NullPointerException: Attempt to invoke virtual 
    method 'boolean java.lang.String.equals(java.lang.Object)' on a null        
   object reference
                  at  
   com.example.win10user.project.BackgroundWorker.onPostExecute
    (BackgroundWorker.java:120)
                  at 
    com.example.win10user.project.BackgroundWorker.onPostExecute
    (BackgroundWorker.java:21)
                  at android.os.AsyncTask.finish(AsyncTask.java:651)
                  at android.os.AsyncTask.access$500(AsyncTask.java:180)
                  at      android.os.AsyncTask$InternalHandler.handleMessage
       (AsyncTask.java:668)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:158)
                  at android.app.ActivityThread.main
       (ActivityThread.java:7229)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at         
     com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run
       (ZygoteInit.java:1230)
                  at      com.android.internal.os.ZygoteInit.main
      (ZygoteInit.java:1120)
      I/Process: Sending signal. PID: 10042 SIG: 9
      Application terminated.

这是backgroundWorker.java活动     package com.example.win10user.project;

public class BackgroundWorker extends AsyncTask<String,Void,String>  {
    Context context;
    AlertDialog alertDialog;
BackgroundWorker (Context ctx) {
    context = ctx;
}
@Override
protected String doInBackground(String... params) {
    String type = params[0];
    String myURL = "http://10.0.2.2:80/";
    String login_url = myURL+"login.php";
    String register_url = myURL+"sign.php";
    if(type.equals("login")) {
        try {

            String user_name = params[1];
            String password = params[2];
            URL url = new URL(login_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String post_data = URLEncoder.encode("user_name","UTF-8")+"="+URLEncoder.encode(user_name,"UTF-8")+"&"
                                +URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
            bufferedWriter.write(post_data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
            String result="";
            String line="";
            while((line = bufferedReader.readLine())!= null) {
                result += line;
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return result;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }else  if(type.equals("register")) {
        try {
            String password = params[1];
            String name = params[2];
            String email = params[3];

            URL url = new URL(register_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String post_data = URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8")+"&"
                              +URLEncoder.encode("username","UTF-8")+"="+URLEncoder.encode(name,"UTF-8")+"&"
                              +URLEncoder.encode("email","UTF-8")+"="+URLEncoder.encode(email,"UTF-8");
            bufferedWriter.write(post_data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
            String result="";
            String line="";
            while((line = bufferedReader.readLine())!= null) {
                result += line;
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return result;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

@Override
protected void onPreExecute() {
    alertDialog = new AlertDialog.Builder(context).create();
    alertDialog.setTitle("Login Status");
}
@Override
protected void onPostExecute(String result) {
   if(result.equals("Insert Successful")) {

        Toast.makeText(context, "Done!! Please Login", Toast.LENGTH_LONG).show();
        Intent i = new Intent(context, MainActivity.class);
        context.startActivity(i);

    }else if(result.equals("This Email")) {

        Toast.makeText(context, "This Email have an account!!! please Sign Up with another Email", Toast.LENGTH_LONG).show();

    }else if(result.equals("login")){

        Toast.makeText(context, "Welcome ",Toast.LENGTH_LONG).show();
        Intent i = new Intent(context,HomePage.class);
        context.startActivity(i);

    }else{
        Toast.makeText(context, "Email Or Password is Incorrect",Toast.LENGTH_LONG).show();
    }
}
@Override
protected void onProgressUpdate(Void... values) {

    super.onProgressUpdate(values);
}
}

这是Main.java活动

public class MainActivity extends AppCompatActivity{
EditText EmailEt, PasswordEt;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_main);

    EmailEt = (EditText)findViewById(R.id.etEmail);
    PasswordEt = (EditText)findViewById(R.id.etPassword);
}
public void OnLogin(View view) {
    String username = EmailEt.getText().toString();
    String password = PasswordEt.getText().toString();
    if(TextUtils.isEmpty(username)) {
        EmailEt.setError("Please Enter  our Email");
        return;
    }else if(TextUtils.isEmpty(password)) {
        PasswordEt.setError("Please Enter Your Password");
        return;
    }else {
        String type = "login";
        BackgroundWorker backgroundWorker = new BackgroundWorker(this);
        backgroundWorker.execute(type, username, password);
    }
}

public void Register(View view){
    Intent intent = new Intent(MainActivity.this, Signup.class);
    startActivity(intent);
}


}

这是signup.java活动

public class Signup extends AppCompatActivity {
EditText PasswordEt,NameEt,EmailEt;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_signup);
    PasswordEt = (EditText)findViewById(R.id.etPassword);
    NameEt = (EditText)findViewById(R.id.etName);
    EmailEt = (EditText)findViewById(R.id.etEmail);
}
public void OnSubmit(View view) {
    String str_pass = PasswordEt.getText().toString();
    String str_name     = NameEt.getText().toString();
    String str_email    = EmailEt.getText().toString();

    if(TextUtils.isEmpty(str_name)) {
        NameEt.setError("Please Enter Your Name");
        return;
    }else if(TextUtils.isEmpty(str_pass)) {
        PasswordEt.setError("Please Enter Your Password");
        return;
    }  else if(TextUtils.isEmpty(str_email)) {
        EmailEt.setError("Please Enter Your Email");
        return;
    }else if(!isValidEmaillId(EmailEt.getText().toString().trim())){
   EmailEt.setError("Please Enter A valid Email Like  'email@example.com'");
        return;
    }else {
         String type = "register";
         BackgroundWorker backgroundWorker = new BackgroundWorker(this);
         backgroundWorker.execute(type, str_pass, str_name, str_email);
     }
}

public void Return(View view){
    Intent intent = new Intent(Signup.this, MainActivity.class);
    startActivity(intent);
}

private boolean isValidEmaillId(String email){

return Pattern.compile("^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]{1}|[\\w-]  {2,}))@"
            + "((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
            + "[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\."
            + "([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
            + "[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
        + "([a-zA-Z]+[\\w-]+\\.)+[a-zA-Z]{2,4})$").matcher(email).matches();
}

}

2 个答案:

答案 0 :(得分:0)

应用程序适用于仿真器,因为可以从它访问http://10.0.2.2:80/,这是模拟器的主机特殊地址。

如果您希望此应用也在设备上运行,请将地址更新为您机器的IP并确保机器和设备在同一网络上(如果服务也在公共网络上的某个地方托管,则使用域名)

答案 1 :(得分:0)

http://10.0.2.2:80仅适用于您的模拟器。您需要在某个地方托管您的PHP文件才能使用它。