问:
An app with Retrofit 2 crashes while posting data to Mysql
I'm developing an android application which need to posting and getting data to mysql db with php. Right now i am trying to sign up a user to application. I have created 2 php classes Connection and insertUser. With Postman i can successfully insert data to database. But when i try on the physical phone, it crashes. My code builds without error and till i press SignUp button it works fine. I can not see where i am making mistake. Please help.

I have added my dependencies.

```<code>    compile 'com.squareup.retrofit2:retrofit:2.3.0'
    compile 'com.squareup.retrofit2:converter-gson:2.3.0'
    compile 'com.squareup.okhttp:okhttp:2.0.0'
</code>```

Connection.php for connecting my localhost XAMPP Phpmyadmin.

```<code><?php

    class Connection{
        function getConnection(){
            $host       = "localhost";
            $username   = "root";
            $password   = "root";
            $dbname     = "activityplanner_db";
            try{
                $conn    = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
                $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                return $conn;
            }catch (PDOException $e){
                echo "ERROR CONNECTIONF : " . $e->getMessage();
            }
        }
    }

    ?>
</code>```

insertUser.php for inserting user info to database.

```<code><?php

require_once('Connection.php');
class insertUser{
    function startInsertUser(){
        $connection = new Connection();
        $conn = $connection->getConnection();
        //array for json response
        $response = array();
        $Lastname = $_POST['LastName'];
        $Firstname = $_POST['FirstName'];
        $Email = $_POST['User_Email'];
        $Mobilephone = $_POST['MobilePhone'];
        $Ssn = $_POST['SSN'];
        $Password = $_POST['User_Password'];
        $City = $_POST['User_City'];
        $JobTittle = $_POST['User_Job'];
        $BirthDate = $_POST['User_BirthDate'];
        $Gender = $_POST['Gender'];

        if($Lastname == '' || $Firstname == '' || $Email == '' || $Mobilephone == '' || $Ssn == '' || $Password == '' || $City == '' || $JobTittle == '' ||
        $BirthDate == ''){
        echo 'All fields required';
    }
        try{
            if(isset($Email) && isset($Ssn)){
                $sqlInsert = "INSERT INTO user (LastName, FirstName, User_Email, MobilePhone, SSN, User_Password,
                 User_City, User_Job, User_BirthDate, Gender) VALUES ('$Lastname', '$Firstname', '$Email', '$Mobilephone', '$Ssn', '$Password',
                    '$City','$JobTittle', '$BirthDate', '$Gender')";
                $conn->exec($sqlInsert);
            }
        }catch (PDOException $e){
            echo "Error while inserting ".$e->getMessage();
        }
        //cek is the row was inserted or not
        if($sqlInsert){
            //success inserted
            $response["success"] = 1;
            $response["message"] = "User successful inserted!";
            echo json_encode($response);
        }else{
            //failed inserted
            $response["success"] = 0;
            $response["message"] = "Failed while insert data";
            echo json_encode($response);
        }
    }
}
$insert = new insertUser();
$insert->startInsertUser();;
?>
</code>```

LoggingInterceptors.java to see the output of the process displaying data. If there is an error, this class file know what the causes of the error. T

```<code>public class LoggingInterceptors implements Interceptor{

    @Override
    public Response intercept(Chain chain) throws IOException{
        Request request = chain.request();
        long t1 = System.nanoTime();
        String requestLog = String.format("Sending request %s on %s%n%s",
                request.url(), chain.connection(), request.headers());

        if (request.method().compareToIgnoreCase("post") == 0){
            requestLog = "\n" + requestLog + "\n" + bodyToString(request);
        }

        Log.d("TAG", "request" + "\n" + requestLog);
        Response response = chain.proceed(request);

        long t2 = System.nanoTime();
        String responseLog = String.format("Received response for %s in %.1fms%n%s",
                response.request().url(), (t2 - t1) / 1e6d, response.headers());

        String bodyString = response.body().string();
        Log.d("TAG", "response" + "\n" + responseLog + "\n" + bodyString);

        return response.newBuilder()
                .body(ResponseBody.create(response.body().contentType(), bodyString))
                .build();
    }

    public static String bodyToString(final Request request){
        try{
            final Request copy = request.newBuilder().build();
            final Buffer buffer = new Buffer();
            copy.body().writeTo(buffer);

            return buffer.readUtf8();
        }catch (final IOException e){
            return "did not work";
        }
    }
}
</code>```

My URLs.java Api Client for Retrofit Client.

```<code>public class URLs {

    public static final String URL = "http://192.168.43.172/activityplanner_php/";
</code>```

//this my ipv4 ip when i connect my pc to my phone's hotspot.
        public static Retrofit retrofit = null;

```<code>    public static Retrofit getClient(){
        if (retrofit==null){
            OkHttpClient client = new OkHttpClient.Builder()
                    .addInterceptor(new LoggingInterceptors())
                    .build();
            retrofit = new Retrofit.Builder()
                    .baseUrl(URL)
                    .client(client)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }

}
</code>```

And my RegisterApi interface

```<code>public interface RegisterAPI {

    @FormUrlEncoded
    @POST("/activityplanner_php/insertUser.php")
    Call<User> insertUser(@Field("LastName") String LastName, @Field("FirstName") String FirstName,
                          @Field("User_Email") String User_Email, @Field("MobilePhone") long MobilePhone,
                          @Field("SSN") String SSN, @Field("User_Password") String User_Password,
                          @Field("User_City") String User_City, @Field("User_Job") String User_Job,
                          @Field("User_BirthDate") Date User_BirthDate, @Field("Gender") String Gender);
}
</code>```

My user response model.

```<code>public class User {

    @SerializedName("success")
    private int status;
    @SerializedName("message")
    private String message;

    public User(int status, String message) {
        this.status = status;
        this.message = message;
    }

    public User() {
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}
</code>```

And my SignUpActivity .

```<code>public class SignUpActivity extends AppCompatActivity {

    EditText etLastName, etFirstName, etEmail, etMobilePhone, etSsn, etPassword, etCity, etJob, etBirthDate;
    RadioGroup rgGender;
    Spinner spUserType;
    ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_up);

        Button btnSignUp = (Button) findViewById(R.id.bSignUp);
        etBirthDate = (EditText) findViewById(R.id.etBirthDate);
        etLastName = (EditText) findViewById(R.id.etLastName);
        etFirstName = (EditText) findViewById(R.id.etName);
        etEmail = (EditText) findViewById(R.id.etEmail);
        etMobilePhone = (EditText) findViewById(R.id.etPhone);
        etSsn = (EditText) findViewById(R.id.etSSN);
        etPassword = (EditText) findViewById(R.id.etPassword);
        etCity = (EditText) findViewById(R.id.etCity);
        etJob = (EditText) findViewById(R.id.etJob);
        rgGender = (RadioGroup) findViewById(R.id.rgGender);
        spUserType = (Spinner) findViewById(R.id.spUserRole);

        btnSignUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                insertUser();
            }
        });

    }
    /*public void GoToLoginActivity(View v) {
        insertUser();
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
    }*/

    private void insertUser(){
        progressDialog.show();

        String firstName = etFirstName.getText().toString();
        String lastName = etLastName.getText().toString();
        String u_Email = etEmail.getText().toString();

        int radioButtonId = rgGender.getCheckedRadioButtonId();
        View radioButton = rgGender.findViewById(radioButtonId);
        int idx = rgGender.indexOfChild(radioButton);
        RadioButton rbGender = (RadioButton)rgGender.getChildAt(idx);

        String gender = rbGender.getText().toString();
        Long mobilePhone =Long.parseLong(etMobilePhone.getText().toString());
        String ssn = etSsn.getText().toString();
        String u_City = etCity.getText().toString();
        Date birthDate =Date.valueOf(etBirthDate.getText().toString());
        String u_Job = etJob.getText().toString();
        String password = etPassword.getText().toString();

        insertData(firstName,lastName,u_Email,gender,mobilePhone,ssn,u_City,birthDate,u_Job,password);
    }
        private void insertData(String firstName, String lastName, String u_Email, String gender,
                Long mobilePhone, String ssn, String u_City, Date birthDate, String u_Job, String password){

            RegisterAPI registerAPI = URLs.getClient().create(RegisterAPI.class);
            Call<User> call = registerAPI.insertUser(firstName, lastName, u_Email, mobilePhone, ssn, password,
                    u_City, u_Job, birthDate, gender);
            call.enqueue(new Callback<User>() {
                @Override
                public void onResponse(Call<User> call, Response<User> response) {
                    User user =response.body();

                    if(user.getStatus()==1){
                        Toast.makeText(SignUpActivity.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                        progressDialog.dismiss();
                    }else{
                        Toast.makeText(SignUpActivity.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                        progressDialog.dismiss();
                    }
                }

                @Override
                public void onFailure(Call<User> call, Throwable t) {
                    Toast.makeText(SignUpActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
                    progressDialog.dismiss();
                }
            });
        }

}
</code>```

My activity_sign_up.xml layout.

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:background="@color/OpeningBackground"
    android:layout_height="match_parent">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="55dp"
        android:background="@color/toolbar"
        android:minHeight="?attr/actionBarSize"
        android:theme="@android:style/Widget"
        tools:layout_editor_absoluteY="1dp" />

    <ScrollView
        style="@android:style/Widget.DeviceDefault.Light.ScrollView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="52dp"
        android:clipToPadding="true"
        android:fillViewport="true"
        android:scrollbarStyle="insideOverlay"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:minHeight="200dp">

            <EditText
                android:id="@+id/etBirthDate"
                style="@android:style/Widget.Material.Light.EditText"
                android:layout_width="364dp"
                android:layout_height="wrap_content"
                android:layout_marginTop="16dp"
                android:ems="10"
                android:layout_marginStart="8dp"
                android:hint="@string/birthDate"
                android:inputType="date"
                android:textColor="#ffffff"
                android:textColorHint="#ffffff"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/etJob" />

            <EditText
                android:id="@+id/etPassword"
                style="@android:style/Widget.Material.Light.EditText"
                android:layout_width="364dp"
                android:layout_marginStart="8dp"
                android:layout_height="45dp"
                android:layout_marginTop="16dp"
                android:ems="10"
                android:hint="@string/password"
                android:inputType="numberPassword"
                android:textAppearance="@android:style/Widget.Material.Light.EditText"
                android:textColor="#ffffff"
                android:textColorHint="#ffffff"
                android:textSize="16sp"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/etSSN" />

            <EditText
                android:id="@+id/etPhone"
                style="@android:style/Widget.Material.Light.EditText"
                android:layout_width="364dp"
                android:layout_marginStart="8dp"
                android:layout_height="wrap_content"
                android:layout_marginTop="16dp"
                android:ems="10"
                android:hint="@string/phone"
                android:inputType="phone"
                android:textColor="#ffffff"
                android:textColorHint="#ffffff"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/etEmail" />

            <EditText
                android:id="@+id/etName"
                style="@android:style/Widget.Material.Light.EditText"
                android:layout_width="179dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="200dp"
                android:layout_marginTop="16dp"
                android:ems="10"
                android:hint="@string/Name"
                android:inputType="textPersonName"
                android:singleLine="true"
                android:textColor="#ffffff"
                android:textColorHint="#ffffff"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

            <EditText
                android:id="@+id/etLastName"
                style="@android:style/Widget.Material.Light.EditText"
                android:layout_width="182dp"
                android:layout_height="wrap_content"
                android:layout_marginTop="16dp"
                android:ems="10"
                android:layout_marginStart="8dp"
                android:hint="@string/lName"
                android:inputType="textPersonName"
                android:singleLine="true"
                android:textColor="#ffffff"
                android:textColorHint="#ffffff"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

            <EditText
                android:id="@+id/etEmail"
                android:layout_width="364dp"
                android:layout_height="wrap_content"
                android:layout_marginStart="8dp"
                android:ems="10"
                android:hint="@string/email"
                android:inputType="textEmailAddress"
                android:textColor="#ffffff"
                android:textColorHint="#ffffff"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/etLastName" />

            <EditText
                android:id="@+id/etSSN"
                style="@android:style/Widget.Material.Light.EditText"
                android:layout_width="364dp"
                android:layout_height="wrap_content"
                android:layout_marginStart="8dp"
                android:layout_marginTop="16dp"
                android:ems="10"
                android:hint="@string/ssn"
                android:inputType="number"
                android:textColor="#ffffff"
                android:textColorHint="#ffffff"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/etPhone" />

            <EditText
                android:id="@+id/etCity"
                style="@android:style/Widget.Material.Light.EditText"
                android:layout_width="364dp"
                android:layout_height="wrap_content"
                android:layout_marginStart="8dp"
                android:layout_marginTop="16dp"
                android:ems="10"
                android:hint="@string/city"
                android:inputType="textPersonName"
                android:textColor="#ffffff"
                android:textColorHint="#ffffff"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/etPassword" />

            <EditText
                android:id="@+id/etJob"
                style="@android:style/Widget.Material.Light.EditText"
                android:layout_width="364dp"
                android:layout_height="wrap_content"
                android:layout_marginStart="8dp"
                android:layout_marginTop="16dp"
                android:ems="10"
                android:hint="@string/Job"
                android:inputType="textPersonName"
                android:textColor="#ffffff"
                android:textColorHint="#ffffff"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/etCity" />

            <Spinner
                android:id="@+id/spUserRole"
                style="@android:style/Widget.Material.Light.TextView.SpinnerItem"
                android:layout_width="364dp"
                android:layout_height="51dp"
                android:layout_marginBottom="175dp"
                android:layout_marginStart="8dp"
                android:entries="@array/user_role"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintHorizontal_bias="1.0"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/tUser_Role_Hint"
                app:layout_constraintVertical_bias="0.0" />

            <TextView
                android:id="@+id/tUser_Role_Hint"
                android:layout_width="364dp"
                android:layout_height="41dp"
                android:layout_marginTop="16dp"
                android:layout_marginStart="8dp"
                android:text="@string/user_role_hint"
                android:textAppearance="@style/TextAppearance.AppCompat.Widget.PopupMenu.Large"
                android:textColor="#ffffff"
                android:textSize="18sp"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/etBirthDate" />

            <Button
                android:id="@+id/bSignUp"
                style="@android:style/Widget.Material.Light.Button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="48dp"
                android:layout_marginEnd="32dp"
                android:backgroundTint="@color/OpeningBackground"
                android:text="@string/btnSignUp"
                android:textColor="@android:color/background_light"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent" />

            <TextView
                android:id="@+id/textView"
                android:layout_width="92dp"
                android:layout_height="27dp"
                android:layout_marginStart="24dp"
                android:layout_marginTop="32dp"
                android:text="@string/gender"
                android:textColor="@color/buttoncolor"
                android:textSize="20sp"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/spUserRole" />

            <RadioGroup
                android:id="@+id/rgGender"
                android:layout_width="177dp"
                android:layout_height="91dp"
                android:layout_marginStart="20dp"
                android:layout_marginTop="12dp"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/textView">

                <RadioButton
                    android:id="@+id/rbMan"
                    style="@android:style/Widget.DeviceDefault.Light.CompoundButton.RadioButton"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:buttonTint="@color/buttoncolor"
                    android:text="Erkek"
                    android:textColor="#ffffff"
                    tools:layout_editor_absoluteX="16dp"
                    tools:layout_editor_absoluteY="676dp" />

                <RadioButton
                    android:id="@+id/rbWoman"
                    style="@android:style/Widget.DeviceDefault.Light.CompoundButton.RadioButton"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:buttonTint="@color/buttoncolor"
                    android:text="Kadın"
                    android:textColor="#ffffff"
                    tools:layout_editor_absoluteX="130dp"
                    tools:layout_editor_absoluteY="676dp" />
            </RadioGroup>

        </android.support.constraint.ConstraintLayout>
    </ScrollView>

</android.support.design.widget.CoordinatorLayout>
</code>```

答:
I don't see you initializing the progress dialog here. I guess this is the error you didn't initialize the progress dialog before calling show()

```<code>ProgressDialog progressDialog;

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_up);
        progressDialog = new ProgressDialog(this);
        ...............

}
</code>```

Body:
I'm developing an android application which need to posting and getting data to mysql db with php. Right now i am trying to sign up a user to application. I have created 2 php classes Connection and insertUser. With Postman i can successfully insert data to database. But when i try on the physical phone, it crashes. My code builds without error and till i press SignUp button it works fine. I can not see where i am making mistake. Please help.

I have added my dependencies.

    compile 'com.squareup.retrofit2:retrofit:2.3.0'
    compile 'com.squareup.retrofit2:converter-gson:2.3.0'
    compile 'com.squareup.okhttp:okhttp:2.0.0'

Connection.php for connecting my localhost XAMPP Phpmyadmin.

<?php

    class Connection{
        function getConnection(){
            $host       = "localhost";
            $username   = "root";
            $password   = "root";
            $dbname     = "activityplanner_db";
            try{
                $conn    = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
                $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                return $conn;
            }catch (PDOException $e){
                echo "ERROR CONNECTIONF : " . $e->getMessage();
            }
        }
    }

    ?>

insertUser.php for inserting user info to database.

<?php

require_once('Connection.php');
class insertUser{
    function startInsertUser(){
        $connection = new Connection();
        $conn = $connection->getConnection();
        //array for json response
        $response = array();
        $Lastname = $_POST['LastName'];
        $Firstname = $_POST['FirstName'];
        $Email = $_POST['User_Email'];
        $Mobilephone = $_POST['MobilePhone'];
        $Ssn = $_POST['SSN'];
        $Password = $_POST['User_Password'];
        $City = $_POST['User_City'];
        $JobTittle = $_POST['User_Job'];
        $BirthDate = $_POST['User_BirthDate'];
        $Gender = $_POST['Gender'];

        if($Lastname == '' || $Firstname == '' || $Email == '' || $Mobilephone == '' || $Ssn == '' || $Password == '' || $City == '' || $JobTittle == '' ||
        $BirthDate == ''){
        echo 'All fields required';
    }
        try{
            if(isset($Email) && isset($Ssn)){
                $sqlInsert = "INSERT INTO user (LastName, FirstName, User_Email, MobilePhone, SSN, User_Password,
                 User_City, User_Job, User_BirthDate, Gender) VALUES ('$Lastname', '$Firstname', '$Email', '$Mobilephone', '$Ssn', '$Password',
                    '$City','$JobTittle', '$BirthDate', '$Gender')";
                $conn->exec($sqlInsert);
            }
        }catch (PDOException $e){
            echo "Error while inserting ".$e->getMessage();
        }
        //cek is the row was inserted or not
        if($sqlInsert){
            //success inserted
            $response["success"] = 1;
            $response["message"] = "User successful inserted!";
            echo json_encode($response);
        }else{
            //failed inserted
            $response["success"] = 0;
            $response["message"] = "Failed while insert data";
            echo json_encode($response);
        }
    }
}
$insert = new insertUser();
$insert->startInsertUser();;
?>

LoggingInterceptors.java to see the output of the process displaying data. If there is an error, this class file know what the causes of the error. T

public class LoggingInterceptors implements Interceptor{

    @Override
    public Response intercept(Chain chain) throws IOException{
        Request request = chain.request();
        long t1 = System.nanoTime();
        String requestLog = String.format("Sending request %s on %s%n%s",
                request.url(), chain.connection(), request.headers());

        if (request.method().compareToIgnoreCase("post") == 0){
            requestLog = "\n" + requestLog + "\n" + bodyToString(request);
        }

        Log.d("TAG", "request" + "\n" + requestLog);
        Response response = chain.proceed(request);

        long t2 = System.nanoTime();
        String responseLog = String.format("Received response for %s in %.1fms%n%s",
                response.request().url(), (t2 - t1) / 1e6d, response.headers());

        String bodyString = response.body().string();
        Log.d("TAG", "response" + "\n" + responseLog + "\n" + bodyString);

        return response.newBuilder()
                .body(ResponseBody.create(response.body().contentType(), bodyString))
                .build();
    }

    public static String bodyToString(final Request request){
        try{
            final Request copy = request.newBuilder().build();
            final Buffer buffer = new Buffer();
            copy.body().writeTo(buffer);

            return buffer.readUtf8();
        }catch (final IOException e){
            return "did not work";
        }
    }
}

My URLs.java Api Client for Retrofit Client.

public class URLs {

    public static final String URL = "http://192.168.43.172/activityplanner_php/";

//this my ipv4 ip when i connect my pc to my phone's hotspot.
        public static Retrofit retrofit = null;

    public static Retrofit getClient(){
        if (retrofit==null){
            OkHttpClient client = new OkHttpClient.Builder()
                    .addInterceptor(new LoggingInterceptors())
                    .build();
            retrofit = new Retrofit.Builder()
                    .baseUrl(URL)
                    .client(client)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }

}

And my RegisterApi interface

public interface RegisterAPI {

    @FormUrlEncoded
    @POST("/activityplanner_php/insertUser.php")
    Call<User> insertUser(@Field("LastName") String LastName, @Field("FirstName") String FirstName,
                          @Field("User_Email") String User_Email, @Field("MobilePhone") long MobilePhone,
                          @Field("SSN") String SSN, @Field("User_Password") String User_Password,
                          @Field("User_City") String User_City, @Field("User_Job") String User_Job,
                          @Field("User_BirthDate") Date User_BirthDate, @Field("Gender") String Gender);
}

My user response model.

public class User {

    @SerializedName("success")
    private int status;
    @SerializedName("message")
    private String message;

    public User(int status, String message) {
        this.status = status;
        this.message = message;
    }

    public User() {
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

And my SignUpActivity .

public class SignUpActivity extends AppCompatActivity {

    EditText etLastName, etFirstName, etEmail, etMobilePhone, etSsn, etPassword, etCity, etJob, etBirthDate;
    RadioGroup rgGender;
    Spinner spUserType;
    ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_up);

        Button btnSignUp = (Button) findViewById(R.id.bSignUp);
        etBirthDate = (EditText) findViewById(R.id.etBirthDate);
        etLastName = (EditText) findViewById(R.id.etLastName);
        etFirstName = (EditText) findViewById(R.id.etName);
        etEmail = (EditText) findViewById(R.id.etEmail);
        etMobilePhone = (EditText) findViewById(R.id.etPhone);
        etSsn = (EditText) findViewById(R.id.etSSN);
        etPassword = (EditText) findViewById(R.id.etPassword);
        etCity = (EditText) findViewById(R.id.etCity);
        etJob = (EditText) findViewById(R.id.etJob);
        rgGender = (RadioGroup) findViewById(R.id.rgGender);
        spUserType = (Spinner) findViewById(R.id.spUserRole);

        btnSignUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                insertUser();
            }
        });

    }
    /*public void GoToLoginActivity(View v) {
        insertUser();
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
    }*/

    private void insertUser(){
        progressDialog.show();

        String firstName = etFirstName.getText().toString();
        String lastName = etLastName.getText().toString();
        String u_Email = etEmail.getText().toString();

        int radioButtonId = rgGender.getCheckedRadioButtonId();
        View radioButton = rgGender.findViewById(radioButtonId);
        int idx = rgGender.indexOfChild(radioButton);
        RadioButton rbGender = (RadioButton)rgGender.getChildAt(idx);

        String gender = rbGender.getText().toString();
        Long mobilePhone =Long.parseLong(etMobilePhone.getText().toString());
        String ssn = etSsn.getText().toString();
        String u_City = etCity.getText().toString();
        Date birthDate =Date.valueOf(etBirthDate.getText().toString());
        String u_Job = etJob.getText().toString();
        String password = etPassword.getText().toString();

        insertData(firstName,lastName,u_Email,gender,mobilePhone,ssn,u_City,birthDate,u_Job,password);
    }
        private void insertData(String firstName, String lastName, String u_Email, String gender,
                Long mobilePhone, String ssn, String u_City, Date birthDate, String u_Job, String password){

            RegisterAPI registerAPI = URLs.getClient().create(RegisterAPI.class);
            Call<User> call = registerAPI.insertUser(firstName, lastName, u_Email, mobilePhone, ssn, password,
                    u_City, u_Job, birthDate, gender);
            call.enqueue(new Callback<User>() {
                @Override
                public void onResponse(Call<User> call, Response<User> response) {
                    User user =response.body();

                    if(user.getStatus()==1){
                        Toast.makeText(SignUpActivity.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                        progressDialog.dismiss();
                    }else{
                        Toast.makeText(SignUpActivity.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                        progressDialog.dismiss();
                    }
                }

                @Override
                public void onFailure(Call<User> call, Throwable t) {
                    Toast.makeText(SignUpActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
                    progressDialog.dismiss();
                }
            });
        }

}

My activity_sign_up.xml layout.

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:background="@color/OpeningBackground"
    android:layout_height="match_parent">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="55dp"
        android:background="@color/toolbar"
        android:minHeight="?attr/actionBarSize"
        android:theme="@android:style/Widget"
        tools:layout_editor_absoluteY="1dp" />

    <ScrollView
        style="@android:style/Widget.DeviceDefault.Light.ScrollView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="52dp"
        android:clipToPadding="true"
        android:fillViewport="true"
        android:scrollbarStyle="insideOverlay"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:minHeight="200dp">

            <EditText
                android:id="@+id/etBirthDate"
                style="@android:style/Widget.Material.Light.EditText"
                android:layout_width="364dp"
                android:layout_height="wrap_content"
                android:layout_marginTop="16dp"
                android:ems="10"
                android:layout_marginStart="8dp"
                android:hint="@string/birthDate"
                android:inputType="date"
                android:textColor="#ffffff"
                android:textColorHint="#ffffff"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/etJob" />

            <EditText
                android:id="@+id/etPassword"
                style="@android:style/Widget.Material.Light.EditText"
                android:layout_width="364dp"
                android:layout_marginStart="8dp"
                android:layout_height="45dp"
                android:layout_marginTop="16dp"
                android:ems="10"
                android:hint="@string/password"
                android:inputType="numberPassword"
                android:textAppearance="@android:style/Widget.Material.Light.EditText"
                android:textColor="#ffffff"
                android:textColorHint="#ffffff"
                android:textSize="16sp"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/etSSN" />

            <EditText
                android:id="@+id/etPhone"
                style="@android:style/Widget.Material.Light.EditText"
                android:layout_width="364dp"
                android:layout_marginStart="8dp"
                android:layout_height="wrap_content"
                android:layout_marginTop="16dp"
                android:ems="10"
                android:hint="@string/phone"
                android:inputType="phone"
                android:textColor="#ffffff"
                android:textColorHint="#ffffff"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/etEmail" />

            <EditText
                android:id="@+id/etName"
                style="@android:style/Widget.Material.Light.EditText"
                android:layout_width="179dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="200dp"
                android:layout_marginTop="16dp"
                android:ems="10"
                android:hint="@string/Name"
                android:inputType="textPersonName"
                android:singleLine="true"
                android:textColor="#ffffff"
                android:textColorHint="#ffffff"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

            <EditText
                android:id="@+id/etLastName"
                style="@android:style/Widget.Material.Light.EditText"
                android:layout_width="182dp"
                android:layout_height="wrap_content"
                android:layout_marginTop="16dp"
                android:ems="10"
                android:layout_marginStart="8dp"
                android:hint="@string/lName"
                android:inputType="textPersonName"
                android:singleLine="true"
                android:textColor="#ffffff"
                android:textColorHint="#ffffff"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

            <EditText
                android:id="@+id/etEmail"
                android:layout_width="364dp"
                android:layout_height="wrap_content"
                android:layout_marginStart="8dp"
                android:ems="10"
                android:hint="@string/email"
                android:inputType="textEmailAddress"
                android:textColor="#ffffff"
                android:textColorHint="#ffffff"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/etLastName" />

            <EditText
                android:id="@+id/etSSN"
                style="@android:style/Widget.Material.Light.EditText"
                android:layout_width="364dp"
                android:layout_height="wrap_content"
                android:layout_marginStart="8dp"
                android:layout_marginTop="16dp"
                android:ems="10"
                android:hint="@string/ssn"
                android:inputType="number"
                android:textColor="#ffffff"
                android:textColorHint="#ffffff"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/etPhone" />

            <EditText
                android:id="@+id/etCity"
                style="@android:style/Widget.Material.Light.EditText"
                android:layout_width="364dp"
                android:layout_height="wrap_content"
                android:layout_marginStart="8dp"
                android:layout_marginTop="16dp"
                android:ems="10"
                android:hint="@string/city"
                android:inputType="textPersonName"
                android:textColor="#ffffff"
                android:textColorHint="#ffffff"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/etPassword" />

            <EditText
                android:id="@+id/etJob"
                style="@android:style/Widget.Material.Light.EditText"
                android:layout_width="364dp"
                android:layout_height="wrap_content"
                android:layout_marginStart="8dp"
                android:layout_marginTop="16dp"
                android:ems="10"
                android:hint="@string/Job"
                android:inputType="textPersonName"
                android:textColor="#ffffff"
                android:textColorHint="#ffffff"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/etCity" />

            <Spinner
                android:id="@+id/spUserRole"
                style="@android:style/Widget.Material.Light.TextView.SpinnerItem"
                android:layout_width="364dp"
                android:layout_height="51dp"
                android:layout_marginBottom="175dp"
                android:layout_marginStart="8dp"
                android:entries="@array/user_role"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintHorizontal_bias="1.0"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/tUser_Role_Hint"
                app:layout_constraintVertical_bias="0.0" />

            <TextView
                android:id="@+id/tUser_Role_Hint"
                android:layout_width="364dp"
                android:layout_height="41dp"
                android:layout_marginTop="16dp"
                android:layout_marginStart="8dp"
                android:text="@string/user_role_hint"
                android:textAppearance="@style/TextAppearance.AppCompat.Widget.PopupMenu.Large"
                android:textColor="#ffffff"
                android:textSize="18sp"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/etBirthDate" />

            <Button
                android:id="@+id/bSignUp"
                style="@android:style/Widget.Material.Light.Button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="48dp"
                android:layout_marginEnd="32dp"
                android:backgroundTint="@color/OpeningBackground"
                android:text="@string/btnSignUp"
                android:textColor="@android:color/background_light"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent" />

            <TextView
                android:id="@+id/textView"
                android:layout_width="92dp"
                android:layout_height="27dp"
                android:layout_marginStart="24dp"
                android:layout_marginTop="32dp"
                android:text="@string/gender"
                android:textColor="@color/buttoncolor"
                android:textSize="20sp"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/spUserRole" />

            <RadioGroup
                android:id="@+id/rgGender"
                android:layout_width="177dp"
                android:layout_height="91dp"
                android:layout_marginStart="20dp"
                android:layout_marginTop="12dp"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/textView">

                <RadioButton
                    android:id="@+id/rbMan"
                    style="@android:style/Widget.DeviceDefault.Light.CompoundButton.RadioButton"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:buttonTint="@color/buttoncolor"
                    android:text="Erkek"
                    android:textColor="#ffffff"
                    tools:layout_editor_absoluteX="16dp"
                    tools:layout_editor_absoluteY="676dp" />

                <RadioButton
                    android:id="@+id/rbWoman"
                    style="@android:style/Widget.DeviceDefault.Light.CompoundButton.RadioButton"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:buttonTint="@color/buttoncolor"
                    android:text="Kadın"
                    android:textColor="#ffffff"
                    tools:layout_editor_absoluteX="130dp"
                    tools:layout_editor_absoluteY="676dp" />
            </RadioGroup>

        </android.support.constraint.ConstraintLayout>
    </ScrollView>

</android.support.design.widget.CoordinatorLayout>

Body:
I don't see you initializing the progress dialog here. I guess this is the error you didn't initialize the progress dialog before calling show()

ProgressDialog progressDialog;

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_up);
        progressDialog = new ProgressDialog(this);
        ...............

}


来源: stackexchange

问:
Printing a Class
Hi I'm trying to print 4 band members details using a class, however I'm only able to print one, ill give samples to give you an understanding below, this is my whole code

```<code>class Person:
    def __init__(self, _firstname, _surname, d, m, y):
        self._firstname = _firstname
        self._surname = _surname
        self.d = d
        self.m = m
        self.y = y

    def __repr__(self):
        return '{} {} \n{} {} {}'.format(john._firstname, john._surname, john.d, john.m, john.y)
        return '{} {} \n{} {} {}'.format(paul._firstname, paul._surname,     paul.d, paul.m, paul.y)
        return '{} {} \n{} {} {}'.format(george._firstname,     george._surname, george.d, george.m, george.y)
        return '{} {} \n{} {} {}'.format(ringo._firstname, ringo._surname,     ringo.d, ringo.m, ringo.y)

john = Person('John','Lennon','8th','October','1940')
paul = Person('Paul','McCartney','18th','June','1942')
george = Person('George','Harrison','25th','February','1943')
ringo = Person('Ringo','Starr','7th','July','1940')

john._firstname = 'John'
john._surname = 'Lennon'
john.d = '8th'
john.m = 'October'
john.y = '1940'

paul._firstname = 'Paul'
paul._surname = 'McCartney'
paul._d = '18th'
paul._m = 'June'
paul._y = '1942'

george._firstname = 'George'
george._surname = 'Harrison'
george._d = '25th'
george._m = 'February'
george._y = '1943'

ringo._firstname = 'Ringo'
ringo._surname = 'Starr'
ringo._d = '7th'
ringo._m = 'July'
ringo._y = '1940'

print('{} {} \n{} {} {}'.format(john._firstname, john._surname, john.d, john.m, john.y))
print('{} {} \n{} {} {}'.format(paul._firstname, paul._surname, paul.d,     paul.m, paul.y))
print('{} {} \n{} {} {}'.format(george._firstname, george._surname,         george.d, george.m, george.y))
print('{} {} \n{} {} {}'.format(ringo._firstname, ringo._surname,     ringo.d,     ringo.m, ringo.y))
</code>```

I receive, the correct output, which is this:

```<code>John Lennon
8th October 1940
Paul McCartney
18th June 1942
George Harrison
25th February 1943
Ringo Starr
7th July 1940
</code>```

I want to be able to type:

```<code>print(john)
print(george)
print(paul)
print(ringo)
</code>```

To get the same output, however when i type this and remove the bottom 4 print lines, i get this

```<code>John Lennon
8th October 1940
John Lennon
8th October 1940
John Lennon
8th October 1940
John Lennon
8th October 1940
</code>```

My understanding up until now is that the __repr__(self) can only read one line of code, which would be john, but that's where my knowledge stops.

ANY help is more than appreciated! if you need more info please ask, I'm quite new to this as I'm in my first year at university so I appreciate your patience and help!:)

答:
Your __repr__ talks about class instances like john. It needs to be written to cater for any instance of Person.

```<code>def __repr__(self):
    return '{} {} \n{} {} {}'.format(self._firstname, self._surname, self.d, self.m, self.y)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Printing a Class

Body:
Hi I'm trying to print 4 band members details using a class, however I'm only able to print one, ill give samples to give you an understanding below, this is my whole code

class Person:
    def __init__(self, _firstname, _surname, d, m, y):
        self._firstname = _firstname
        self._surname = _surname
        self.d = d
        self.m = m
        self.y = y

    def __repr__(self):
        return '{} {} \n{} {} {}'.format(john._firstname, john._surname, john.d, john.m, john.y)
        return '{} {} \n{} {} {}'.format(paul._firstname, paul._surname,     paul.d, paul.m, paul.y)
        return '{} {} \n{} {} {}'.format(george._firstname,     george._surname, george.d, george.m, george.y)
        return '{} {} \n{} {} {}'.format(ringo._firstname, ringo._surname,     ringo.d, ringo.m, ringo.y)

john = Person('John','Lennon','8th','October','1940')
paul = Person('Paul','McCartney','18th','June','1942')
george = Person('George','Harrison','25th','February','1943')
ringo = Person('Ringo','Starr','7th','July','1940')

john._firstname = 'John'
john._surname = 'Lennon'
john.d = '8th'
john.m = 'October'
john.y = '1940'

paul._firstname = 'Paul'
paul._surname = 'McCartney'
paul._d = '18th'
paul._m = 'June'
paul._y = '1942'

george._firstname = 'George'
george._surname = 'Harrison'
george._d = '25th'
george._m = 'February'
george._y = '1943'

ringo._firstname = 'Ringo'
ringo._surname = 'Starr'
ringo._d = '7th'
ringo._m = 'July'
ringo._y = '1940'

print('{} {} \n{} {} {}'.format(john._firstname, john._surname, john.d, john.m, john.y))
print('{} {} \n{} {} {}'.format(paul._firstname, paul._surname, paul.d,     paul.m, paul.y))
print('{} {} \n{} {} {}'.format(george._firstname, george._surname,         george.d, george.m, george.y))
print('{} {} \n{} {} {}'.format(ringo._firstname, ringo._surname,     ringo.d,     ringo.m, ringo.y))

I receive, the correct output, which is this:

John Lennon
8th October 1940
Paul McCartney
18th June 1942
George Harrison
25th February 1943
Ringo Starr
7th July 1940

I want to be able to type:

print(john)
print(george)
print(paul)
print(ringo)

To get the same output, however when i type this and remove the bottom 4 print lines, i get this

John Lennon
8th October 1940
John Lennon
8th October 1940
John Lennon
8th October 1940
John Lennon
8th October 1940

My understanding up until now is that the __repr__(self) can only read one line of code, which would be john, but that's where my knowledge stops.

ANY help is more than appreciated! if you need more info please ask, I'm quite new to this as I'm in my first year at university so I appreciate your patience and help!:)

Body:
Your __repr__ talks about class instances like john. It needs to be written to cater for any instance of Person.

def __repr__(self):
    return '{} {} \n{} {} {}'.format(self._firstname, self._surname, self.d, self.m, self.y)


问:
How to update a response through LimeSurvey's Remote Control (JSON)
I'm trying to modify a single response through Remote Control using request promise native with a Node Server, so far all API calls have been successful, unfortunately "update_response" has not.
this is what I've got:

```<code>var options = {
    uri: "http://localhost/admin/remotecontrol",
    method: "POST",
    body: {
      method:'update_response',
      params:[sessionkey,surveyid,{ id: 5, token: "aValidToken", aValidColumnName: "a perfectly normal string" }],
      id:1
    },
    json: true
};

request(options).then((body) => {
    console.log(body.result);
}).catch((err) => {
    res.send(err);
});
</code>```

The LimeSurvey API docummentation is not quite clear as to what structure the third parameter should have (https://api.limesurvey.org/classes/remotecontrol_handle.html#method_update_response), funnily enough if I only pass { id: 5, token: "aValidToken" } it does work (outputs "true"), with a key value pair though I'm getting:

```<code>Error: Invalid Column names supplied: aValidColumnName
</code>```

Has anyone had success with this?

答:
The column names are the question or sub-question IDs - https://manual.limesurvey.org/SGQA_identifier/en

I would think that the third parameter is an array of question/sub-question IDs and answers.

```<code>{'123':'A1', '124':'A3', '128':'Some text input...'}
</code>```

Body:
I'm trying to modify a single response through Remote Control using request promise native with a Node Server, so far all API calls have been successful, unfortunately "update_response" has not.
this is what I've got:

var options = {
    uri: "http://localhost/admin/remotecontrol",
    method: "POST",
    body: {
      method:'update_response',
      params:[sessionkey,surveyid,{ id: 5, token: "aValidToken", aValidColumnName: "a perfectly normal string" }],
      id:1
    },
    json: true
};

request(options).then((body) => {
    console.log(body.result);
}).catch((err) => {
    res.send(err);
});

The LimeSurvey API docummentation is not quite clear as to what structure the third parameter should have (https://api.limesurvey.org/classes/remotecontrol_handle.html#method_update_response), funnily enough if I only pass { id: 5, token: "aValidToken" } it does work (outputs "true"), with a key value pair though I'm getting:

Error: Invalid Column names supplied: aValidColumnName

Has anyone had success with this?

Body:
The column names are the question or sub-question IDs - https://manual.limesurvey.org/SGQA_identifier/en

I would think that the third parameter is an array of question/sub-question IDs and answers.

{'123':'A1', '124':'A3', '128':'Some text input...'}


问:
Spring return null when transaction rollback
can you tell me how can I run transaction only for some block of code? I have service functions with @Transactional, and from them I call repository functions where I execute queries. But when query failed, it also failed service function because transaction must be ended. So how could I return null value when repository function failed? I need catch null value when failed, and continue some logic. My Code:

```<code>public class SomeService{

    @Autowired
    SomeRepository repo;

    @Transactional
    public int getSomeValue(){

        MyObj obj = repo.getLastItem(); // this failed because not items in table, so I need here null
        if (obj != null) {
            //some calculations
            return [calculatedValue]
        } else {
            return 1
        }

    }
}
</code>```

EDIT
I'll tried @davidxxx 's answer and I got this error :

Transaction was marked for rollback only; cannot commit; nested exception is javax.persistence.PersistenceException: org.hibernate.TransactionException: Transaction was marked for rollback only; cannot commit

答:
You could include the code that may throw the exception in a try/catch statement and specify that you don't want rollback for this specific exception:

```<code>public static final int DEFAULT_VALUE_WHEN_GET_LAST_ITEM_FAILED = 1;
...
@Transactional(rollbackFor = ExpectedException.class)
public int getSomeValue(){

    try {
      MyObj obj = repo.getLastItem(); // this failed because not items in table, so I need here null
      if (obj != null) {
          return calculatedValue();
        }
    }
    catch(ExpectedException e){
       //TODO exception logging
    }

    return DEFAULT_VALUE_WHEN_LAST_ITEM_FAILED;

}
</code>```

Body:
can you tell me how can I run transaction only for some block of code? I have service functions with @Transactional, and from them I call repository functions where I execute queries. But when query failed, it also failed service function because transaction must be ended. So how could I return null value when repository function failed? I need catch null value when failed, and continue some logic. My Code:

public class SomeService{

    @Autowired
    SomeRepository repo;

    @Transactional
    public int getSomeValue(){

        MyObj obj = repo.getLastItem(); // this failed because not items in table, so I need here null
        if (obj != null) {
            //some calculations
            return [calculatedValue]
        } else {
            return 1
        }

    }
}

EDIT
I'll tried @davidxxx 's answer and I got this error :

Transaction was marked for rollback only; cannot commit; nested exception is javax.persistence.PersistenceException: org.hibernate.TransactionException: Transaction was marked for rollback only; cannot commit

Body:
You could include the code that may throw the exception in a try/catch statement and specify that you don't want rollback for this specific exception:

public static final int DEFAULT_VALUE_WHEN_GET_LAST_ITEM_FAILED = 1;
...
@Transactional(rollbackFor = ExpectedException.class)
public int getSomeValue(){

    try {
      MyObj obj = repo.getLastItem(); // this failed because not items in table, so I need here null
      if (obj != null) {
          return calculatedValue();
        }
    }
    catch(ExpectedException e){
       //TODO exception logging
    }

    return DEFAULT_VALUE_WHEN_LAST_ITEM_FAILED;

}


问:
Focus on input and remove focus using Jquery
I'm tying to check if the input has focus to add color to the back ground However when I remove the mouse and focus on another input it doesn't remove the focus anymore
it actually stays with the focus! how can I remove the backgound from the first one!

```<code>Fullname: <input type="text" name="name"><br>
Email: <input type="text" name="email">
</code>```

How can I check that the class test exists

I'm tying the following if statement by not working for some reason. it may be something wrong with my code that I can't spot for some reason!

```<code>$(document).ready(function(){
    $("input").focus(function(){
        $(this).css("background-color", "#f4fcef");
    });
});
</code>```

I would approcialte it if you can test this for me or let me know what's going wrong on the above code!?

答:
you can check that if class exist on focus then do some action same on focus out.</p>

```<code> $(document).ready(function(){
$("input").focus(function(){
    if($(this).hasClass("yourclassName")){
     $(this).css("background-color", "#f4fcef");
    }

}).focusout(function(){
   if($(this).hasClass("yourclassName")){
     $(this).css("background-color", "#f4fcef");//some other color.
    }
});

});
</code>```

Body:
I'm tying to check if the input has focus to add color to the back ground However when I remove the mouse and focus on another input it doesn't remove the focus anymore
it actually stays with the focus! how can I remove the backgound from the first one!

Fullname: <input type="text" name="name">

Email: <input type="text" name="email">

How can I check that the class test exists

I'm tying the following if statement by not working for some reason. it may be something wrong with my code that I can't spot for some reason!

$(document).ready(function(){
    $("input").focus(function(){
        $(this).css("background-color", "#f4fcef");
    });
});

I would approcialte it if you can test this for me or let me know what's going wrong on the above code!?

Body:
you can check that if class exist on focus then do some action same on focus out.

 $(document).ready(function(){
$("input").focus(function(){
    if($(this).hasClass("yourclassName")){
     $(this).css("background-color", "#f4fcef");
    }

}).focusout(function(){
   if($(this).hasClass("yourclassName")){
     $(this).css("background-color", "#f4fcef");//some other color.
    }
});

});


问:
Strict schema validation for Cerberus
I'm using Cerberus version 1.1.

The Cerberus required validation rule appears to default to False, with the result being that an empty document is perfectly valid.

```<code>>>> schema = {
    'spam': {'type': 'string'}
}

>>> v = Validator()
>>> v.validate({}, schema)
True
</code>```

But I have a very lengthy schema document which needs to be strictly enforced.  Is there a way to default to 'required': True for the entire schema, such that every defined field is required?

As it stands, I seem to have to paste 'required': True into every field definition, which seems needlessly redundant.

答:
Sure, you can use simple Python idioms to design your schema:</p>

```<code>schema = {
    'spam': {'type': 'string'},
    …
}
for field in schema:
    schema[field].update({'required': True})
</code>```

Title: Strict schema validation for Cerberus

Body:
I'm using Cerberus version 1.1.

The Cerberus required validation rule appears to default to False, with the result being that an empty document is perfectly valid.

>>> schema = {
    'spam': {'type': 'string'}
}

>>> v = Validator()
>>> v.validate({}, schema)
True

But I have a very lengthy schema document which needs to be strictly enforced.  Is there a way to default to 'required': True for the entire schema, such that every defined field is required?

As it stands, I seem to have to paste 'required': True into every field definition, which seems needlessly redundant.

Body:
Sure, you can use simple Python idioms to design your schema:

schema = {
    'spam': {'type': 'string'},
    …
}
for field in schema:
    schema[field].update({'required': True})


问:
Shell script to count no of character,word,line in a file
```<code>#!/bin/bash

clear
character=0
word=0
line=`echo -e "\n"`
space=`echo -e " "`

if [ $# -eq 0 ]
then
    echo "You haven't entered any line"
elif [ $# -eq 1 ]
then
    filename=$1
    while read -n1 newline
    do
        if [ '$newline' == '$line' ]
        then
            ((line++))
        elif [ '$newline' == '$space' ]
        then
            ((word++))
        else
            ((character++))
        fi
    done < $filename
    echo "No of line =$line"
    echo "No of word =$word"
    echo "No of character =$character"
fi
</code>```

答:
Are you aware of what single quotes do? It prevents any escaping, or string substitution from occurring. In other words, it denotes raw string (you can't even put a single quote inside a single quote!).

You should change to double quotes if you want variable expansion inside:

if [ "$newline" == "$line" ]
#    ^        ^    ^     ^
```


问:
Scrapy csv file has uniform empty rows?
here is the spider:

```<code>import scrapy
from danmurphys.items import DanmurphysItem

class MySpider(scrapy.Spider):
    name = 'danmurphys'
    allowed_domains = ['danmurphys.com.au']
    start_urls = ['https://www.danmurphys.com.au/dm/navigation/navigation_results_gallery.jsp?params=fh_location%3D%2F%2Fcatalog01%2Fen_AU%2Fcategories%3C%7Bcatalog01_2534374302084767_2534374302027742%7D%26fh_view_size%3D120%26fh_sort%3D-sales_value_30_days%26fh_modification%3D&resetnav=false&storeExclusivePage=false']

    def parse(self, response):
        urls = response.xpath('//h2/a/@href').extract()
        for url in urls:
            request = scrapy.Request(url , callback=self.parse_page)
            yield request

    def parse_page(self , response):
        item = DanmurphysItem()
        item['brand'] = response.xpath('//span[@itemprop="brand"]/text()').extract_first().strip()
        item['name'] = response.xpath('//span[@itemprop="name"]/text()').extract_first().strip()
        item['url'] = response.url
        return item
</code>```

and here is the items :

```<code>import scrapy
class DanmurphysItem(scrapy.Item):
    brand = scrapy.Field()
    name = scrapy.Field()
    url = scrapy.Field()
</code>```

when I run the spider with this command :

```<code>scrapy crawl danmurphys -o output.csv
</code>```

the output is like this :

答:
I solved it via the pipelines.py file:

i suspect not ideal but I have found a work around to this problem. In the pipelines.py file I have added more code that essentially reads the csv file with the blank lines to a list, and so removes the blank lines and then writes that cleaned list to a new file.

the code I added is:

```<code>with open('%s_items.csv' % spider.name, 'r') as f:
  reader = csv.reader(f)
  original_list = list(reader)
  cleaned_list = list(filter(None,original_list))

with open('%s_items_cleaned.csv' % spider.name, 'w', newline='') as output_file:
    wr = csv.writer(output_file, dialect='excel')
    for data in cleaned_list:
      wr.writerow(data)
</code>```

Therefore, details of the entire pipelines.py file is Scrapy python csv output has blank lines between each row

Title: Scrapy csv file has uniform empty rows?

Body:
here is the spider:

import scrapy
from danmurphys.items import DanmurphysItem

class MySpider(scrapy.Spider):
    name = 'danmurphys'
    allowed_domains = ['danmurphys.com.au']
    start_urls = ['https://www.danmurphys.com.au/dm/navigation/navigation_results_gallery.jsp?params=fh_location%3D%2F%2Fcatalog01%2Fen_AU%2Fcategories%3C%7Bcatalog01_2534374302084767_2534374302027742%7D%26fh_view_size%3D120%26fh_sort%3D-sales_value_30_days%26fh_modification%3D&resetnav=false&storeExclusivePage=false']

    def parse(self, response):
        urls = response.xpath('//h2/a/@href').extract()
        for url in urls:
            request = scrapy.Request(url , callback=self.parse_page)
            yield request

    def parse_page(self , response):
        item = DanmurphysItem()
        item['brand'] = response.xpath('//span[@itemprop="brand"]/text()').extract_first().strip()
        item['name'] = response.xpath('//span[@itemprop="name"]/text()').extract_first().strip()
        item['url'] = response.url
        return item

and here is the items :

import scrapy
class DanmurphysItem(scrapy.Item):
    brand = scrapy.Field()
    name = scrapy.Field()
    url = scrapy.Field()

when I run the spider with this command :

scrapy crawl danmurphys -o output.csv

the output is like this :

Body:
I solved it via the pipelines.py file:

i suspect not ideal but I have found a work around to this problem. In the pipelines.py file I have added more code that essentially reads the csv file with the blank lines to a list, and so removes the blank lines and then writes that cleaned list to a new file.

the code I added is:

with open('%s_items.csv' % spider.name, 'r') as f:
  reader = csv.reader(f)
  original_list = list(reader)
  cleaned_list = list(filter(None,original_list))

with open('%s_items_cleaned.csv' % spider.name, 'w', newline='') as output_file:
    wr = csv.writer(output_file, dialect='excel')
    for data in cleaned_list:
      wr.writerow(data)

Therefore, details of the entire pipelines.py file is Scrapy python csv output has blank lines between each row


问:
C: difference between 'struct Table *const' and 'const struct Table *'?
I created a struct like this:

```<code>typedef struct Table {
    #some members
  } Table;

typedef struct Table *TableP; // pointer to Table
</code>```

And I want to use it in the following function (given to me)

```<code>int insert(const TableP table, const void *key, DataP object)
</code>```

but Clion highlights table in the function, and gives the warning: "'table' declared with a const-qualified typedef type; results in the type being 'struct Table * const' instead of 'const struct Table *'"

I am not quite sure what this means. I tried changing my table struct to const but it doesn't change the warning.

答:
Difference Betweem struct Table * const and const struct  Table*?

struct Table * const means  const pointer to struct Table.

const struct  Table* means  pointer to a struct Table which is constant.

In the first case the pointer is constant but the struct Table is not. you can modify the table's attributes. But you can't change the pointer to point to different table.

Second case the pointer is non-constant. You can make it point to any struct table but if you try to modify the attribute of the initially pointed table it will throw error.

What did you do and why the error?

You have used typedef struct Table *TableP;. Now const TableP doesn't mean const struct Table*. It simply means const pointer to a struct TableP or struct TableP* const. That's what compiler said to you.

The solution would be to use struct Table *const table directly into the code when you are writing the function. This is what you want - here this means table is a constant pointer to a struct Table. Also this is much more readable and easy to use.

Extra points

This is why it's not a good idea to hide pointer behind typedef - it hampers readability and you run into some weird cases like this.

Note: The best way is to simply typedef the struct and pointer to it should be used directly.

```<code>typedef struct {
   ....
}Table;

void someFunc(Table *t);
</code>```

Body:
I created a struct like this:

typedef struct Table {
    #some members
  } Table;

typedef struct Table *TableP; // pointer to Table

And I want to use it in the following function (given to me)

int insert(const TableP table, const void *key, DataP object)

but Clion highlights table in the function, and gives the warning: "'table' declared with a const-qualified typedef type; results in the type being 'struct Table * const' instead of 'const struct Table *'"

I am not quite sure what this means. I tried changing my table struct to const but it doesn't change the warning.

Body:
Difference Betweem struct Table * const and const struct  Table*?

struct Table * const means  const pointer to struct Table.

const struct  Table* means  pointer to a struct Table which is constant.

In the first case the pointer is constant but the struct Table is not. you can modify the table's attributes. But you can't change the pointer to point to different table.

Second case the pointer is non-constant. You can make it point to any struct table but if you try to modify the attribute of the initially pointed table it will throw error.

What did you do and why the error?

You have used typedef struct Table *TableP;. Now const TableP doesn't mean const struct Table*. It simply means const pointer to a struct TableP or struct TableP* const. That's what compiler said to you.

The solution would be to use struct Table *const table directly into the code when you are writing the function. This is what you want - here this means table is a constant pointer to a struct Table. Also this is much more readable and easy to use.

Extra points

This is why it's not a good idea to hide pointer behind typedef - it hampers readability and you run into some weird cases like this.

Note: The best way is to simply typedef the struct and pointer to it should be used directly.

typedef struct {
   ....
}Table;

void someFunc(Table *t);


问:
How to solve failed to find build tools revision 26.0.2?
I'm trying to Install Build Tools 26.0.2 and sync project

```<code>Failed to find build tools revision 26.0.2
</code>```

I clicked "Install Build Tools 26.0.2 and sync project" but still failed ...
Downloaded it from the external link .. but I don't know where I put it.
So, What should I do? and THANKS

image1
image2

答:
i have same problem , my activity_main can't open because gradle project sync failed and i click "Install Build Tools 26.0.2 and sync project" and still failed

First , turn off kernel (file->seting->plugin->search kotlin then uncheck)
Then your android studio will reopen automaticly

After this i click again  "Install Build Tools 26.0.2 and sync project" and now it's works

If you wanna put from external link u can open :
C:\Users\?\AppData\Local\Android\sdk\build-tools

image

Body:
I'm trying to Install Build Tools 26.0.2 and sync project

Failed to find build tools revision 26.0.2

I clicked "Install Build Tools 26.0.2 and sync project" but still failed ...
Downloaded it from the external link .. but I don't know where I put it.
So, What should I do? and THANKS

image1
image2


问:
CDI (Weld) / Seam 3 Persistence module / Glassfish 3 - Unexplainable exception when starting server
I am using Weld, Jboss' implementation of CDI.  JPA/Hibernate for persistence.  For something different I am giving it a crack on Glassfish 3 which I have not used before.  I am using Maven for dependency management.

As CDI doesn't have transaction management included out of the box, I decided to use the Seam 3 Persistence module instead of rolling my own.  Now, I am well aware that this is only in Alpha at the moment so maybe I am asking for trouble. I'm hoping someone else has seen this and can either help me fix it or at least let me know why I'm getting the problems that I am.

So, before adding the persistence module, everything builds and runs fine.  I can open the homepage of the app fine.  However, when I add the Seam 3 persistence module to my pom.xml, the application throws an exception when starting up.  The only difference between working and not working is the one dependency I am adding to the pom.xml

The dependency I am adding to my pom.xml is:

```<code><dependency>
  <groupId>org.jboss.seam.persistence</groupId>
  <artifactId>seam-persistence-impl</artifactId>
  <version>3.0.0.Alpha1</version>
</dependency>
</code>```

I added this dependency based on the instructions at http://seamframework.org/Seam3/PersistenceModule .  I'm aware that when clicking on the documentation from this page it mentions a couple of other dependencies but I get the same problem when adding them as well.  This is the dependency that I have narrowed the problem down to.

So, after adding the dependency above and starting the server I get the following on startup:

```<code>INFO: Launching GlassFish on Felix platform
Welcome to Felix
================
INFO: Perform lazy SSL initialization for the listener 'http-listener-2'
INFO: Grizzly Framework 1.9.18-o started in: 113ms listening on port 8080
INFO: Grizzly Framework 1.9.18-o started in: 33ms listening on port 4848
INFO: Grizzly Framework 1.9.18-o started in: 76ms listening on port 8181
INFO: Starting Grizzly Framework 1.9.18-o - Thu Oct 28 23:06:04 BST 2010
INFO: Grizzly Framework 1.9.18-o started in: 10ms listening on port 3700
INFO: Starting Grizzly Framework 1.9.18-o - Thu Oct 28 23:06:04 BST 2010
INFO: Grizzly Framework 1.9.18-o started in: 7ms listening on port 7676
INFO: The Admin Console is already installed, but not yet loaded.
INFO: GlassFish Server Open Source Edition 3.0.1 (22) startup time : Felix(4429ms) startup services(1530ms) total(5959ms)
INFO: Hibernate Validator bean-validator-3.0-JBoss-4.0.2
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
INFO: Grizzly Framework 1.9.18-o started in: 16ms listening on port 8080
INFO: Binding RMI port to *:8686
INFO: JMXStartupService: Started JMXConnector, JMXService URL = service:jmx:rmi://192.168.1.73:8686/jndi/rmi://192.168.1.73:8686/jmxrmi
INFO: Using com.sun.enterprise.transaction.jts.JavaEETransactionManagerJTSDelegate as the delegate
INFO: [Thread[GlassFish Kernel Main Thread,5,main]] started
INFO: {felix.fileinstall.poll (ms) = 5000, felix.fileinstall.dir = /Applications/NetBeans/glassfish-3.0.1/glassfish/domains/domain1/autodeploy/bundles, felix.fileinstall.debug = 1, felix.fileinstall.bundles.new.start = true, felix.fileinstall.tmpdir = /var/folders/Q0/Q00qqJF1Gi8VesnYN54iM++++TI/-Tmp-/fileinstall-2957414086269585283, felix.fileinstall.filter = null}
INFO: {felix.fileinstall.poll (ms) = 5000, felix.fileinstall.dir = /Applications/NetBeans/glassfish-3.0.1/glassfish/modules/autostart, felix.fileinstall.debug = 1, felix.fileinstall.bundles.new.start = true, felix.fileinstall.tmpdir = /var/folders/Q0/Q00qqJF1Gi8VesnYN54iM++++TI/-Tmp-/fileinstall--8933010182761076907, felix.fileinstall.filter = null}
INFO: Started bundle: file:/Applications/NetBeans/glassfish-3.0.1/glassfish/modules/autostart/org.apache.felix.scr.jar
INFO: Started bundle: file:/Applications/NetBeans/glassfish-3.0.1/glassfish/modules/autostart/osgi-web-container.jar
INFO: SEC1002: Security Manager is OFF.
INFO: Security startup service called
INFO: SEC1143: Loading policy provider com.sun.enterprise.security.provider.PolicyWrapper.
INFO: Realm admin-realm of classtype com.sun.enterprise.security.auth.realm.file.FileRealm successfully created.
INFO: Realm file of classtype com.sun.enterprise.security.auth.realm.file.FileRealm successfully created.
INFO: Realm certificate of classtype com.sun.enterprise.security.auth.realm.certificate.CertificateRealm successfully created.
INFO: Security service(s) started successfully....
INFO: Created HTTP listener http-listener-1 on port 8080
INFO: Created HTTP listener http-listener-2 on port 8181
INFO: Created HTTP listener admin-listener on port 4848
INFO: Created virtual server server
INFO: Created virtual server __asadmin
INFO: Virtual server server loaded system default web module
INFO: Updating configuration from org.apache.felix.fileinstall-autodeploy-bundles.cfg
INFO: Installed /Applications/NetBeans/glassfish-3.0.1/glassfish/modules/autostart/org.apache.felix.fileinstall-autodeploy-bundles.cfg
INFO: {felix.fileinstall.poll (ms) = 5000, felix.fileinstall.dir = /Applications/NetBeans/glassfish-3.0.1/glassfish/domains/domain1/autodeploy/bundles, felix.fileinstall.debug = 1, felix.fileinstall.bundles.new.start = true, felix.fileinstall.tmpdir = /var/folders/Q0/Q00qqJF1Gi8VesnYN54iM++++TI/-Tmp-/fileinstall-9012588867170808207, felix.fileinstall.filter = null}
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
INFO: Portable JNDI names for EJB EjbSynchronizations : [java:global/com.coffeesnobs_web_war_1.0-SNAPSHOT/EjbSynchronizations, java:global/com.coffeesnobs_web_war_1.0-SNAPSHOT/EjbSynchronizations!org.jboss.seam.persistence.transaction.LocalEjbSynchronizations]
INFO: WELD-000900 1.0.1 (SP3)
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
SEVERE: Exception while loading the app
org.glassfish.deployment.common.DeploymentException: Exception #0 :null
        at org.glassfish.weld.WeldDeployer.event(WeldDeployer.java:167)
        at org.glassfish.kernel.event.EventsImpl.send(EventsImpl.java:125)
        at org.glassfish.internal.data.ApplicationInfo.load(ApplicationInfo.java:224)
        at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:338)
        at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:183)
        at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:272)
        at com.sun.enterprise.v3.admin.CommandRunnerImpl$1.execute(CommandRunnerImpl.java:305)
        at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:320)
        at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1176)
        at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$900(CommandRunnerImpl.java:83)
        at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1235)
        at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1224)
        at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:365)
        at com.sun.enterprise.v3.admin.AdminAdapter.service(AdminAdapter.java:204)
        at com.sun.grizzly.tcp.http11.GrizzlyAdapter.service(GrizzlyAdapter.java:166)
        at com.sun.enterprise.v3.server.HK2Dispatcher.dispath(HK2Dispatcher.java:100)
        at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:245)
        at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:791)
        at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:693)
        at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:954)
        at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:170)
        at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:135)
        at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:102)
        at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:88)
        at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:76)
        at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:53)
        at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:57)
        at com.sun.grizzly.ContextTask.run(ContextTask.java:69)
        at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:330)
        at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:309)
        at java.lang.Thread.run(Thread.java:680)
Caused by: org.jboss.weld.exceptions.DefinitionException: Exception #0 :null
        at org.jboss.weld.bootstrap.events.AbstractDefinitionContainerEvent.fire(AbstractDefinitionContainerEvent.java:45)
        at org.jboss.weld.bootstrap.events.ProcessAnnotatedTypeImpl.fire(ProcessAnnotatedTypeImpl.java:44)
        at org.jboss.weld.bootstrap.BeanDeployer.addClass(BeanDeployer.java:61)
        at org.jboss.weld.bootstrap.BeanDeployer.addClasses(BeanDeployer.java:88)
        at org.jboss.weld.bootstrap.BeanDeployment.deployBeans(BeanDeployment.java:134)
        at org.jboss.weld.bootstrap.WeldBootstrap.deployBeans(WeldBootstrap.java:377)
        at org.glassfish.weld.WeldDeployer.event(WeldDeployer.java:165)
        ... 30 more

INFO: Perform lazy SSL initialization for the listener 'http-listener-2'
INFO: Created HTTP listener http-listener-2 on port 8181
INFO: Grizzly Framework 1.9.18-o started in: 14ms listening on port 8181
</code>```

As you can see, there really isn't much to go on.

Have you seen this exception before?  Do you have any idea what is causing it?  And finally, do you know how to fix it?

答: It turns out it was a bug with the versions and combination of technologies we were using.  We are now using the final version of Jboss 6 and the beta version of the Seam Persistence Module and all seems to be working ok.</p>

ContentLicense: CC BY-SA 4.0

Body:
I am using Weld, Jboss' implementation of CDI.  JPA/Hibernate for persistence.  For something different I am giving it a crack on Glassfish 3 which I have not used before.  I am using Maven for dependency management.

As CDI doesn't have transaction management included out of the box, I decided to use the Seam 3 Persistence module instead of rolling my own.  Now, I am well aware that this is only in Alpha at the moment so maybe I am asking for trouble. I'm hoping someone else has seen this and can either help me fix it or at least let me know why I'm getting the problems that I am.

So, before adding the persistence module, everything builds and runs fine.  I can open the homepage of the app fine.  However, when I add the Seam 3 persistence module to my pom.xml, the application throws an exception when starting up.  The only difference between working and not working is the one dependency I am adding to the pom.xml

The dependency I am adding to my pom.xml is:

<dependency>
  <groupId>org.jboss.seam.persistence</groupId>
  <artifactId>seam-persistence-impl</artifactId>
  <version>3.0.0.Alpha1</version>
</dependency>

I added this dependency based on the instructions at http://seamframework.org/Seam3/PersistenceModule .  I'm aware that when clicking on the documentation from this page it mentions a couple of other dependencies but I get the same problem when adding them as well.  This is the dependency that I have narrowed the problem down to.

So, after adding the dependency above and starting the server I get the following on startup:

INFO: Launching GlassFish on Felix platform
Welcome to Felix
================
INFO: Perform lazy SSL initialization for the listener 'http-listener-2'
INFO: Grizzly Framework 1.9.18-o started in: 113ms listening on port 8080
INFO: Grizzly Framework 1.9.18-o started in: 33ms listening on port 4848
INFO: Grizzly Framework 1.9.18-o started in: 76ms listening on port 8181
INFO: Starting Grizzly Framework 1.9.18-o - Thu Oct 28 23:06:04 BST 2010
INFO: Grizzly Framework 1.9.18-o started in: 10ms listening on port 3700
INFO: Starting Grizzly Framework 1.9.18-o - Thu Oct 28 23:06:04 BST 2010
INFO: Grizzly Framework 1.9.18-o started in: 7ms listening on port 7676
INFO: The Admin Console is already installed, but not yet loaded.
INFO: GlassFish Server Open Source Edition 3.0.1 (22) startup time : Felix(4429ms) startup services(1530ms) total(5959ms)
INFO: Hibernate Validator bean-validator-3.0-JBoss-4.0.2
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
INFO: Grizzly Framework 1.9.18-o started in: 16ms listening on port 8080
INFO: Binding RMI port to *:8686
INFO: JMXStartupService: Started JMXConnector, JMXService URL = service:jmx:rmi://192.168.1.73:8686/jndi/rmi://192.168.1.73:8686/jmxrmi
INFO: Using com.sun.enterprise.transaction.jts.JavaEETransactionManagerJTSDelegate as the delegate
INFO: [Thread[GlassFish Kernel Main Thread,5,main]] started
INFO: {felix.fileinstall.poll (ms) = 5000, felix.fileinstall.dir = /Applications/NetBeans/glassfish-3.0.1/glassfish/domains/domain1/autodeploy/bundles, felix.fileinstall.debug = 1, felix.fileinstall.bundles.new.start = true, felix.fileinstall.tmpdir = /var/folders/Q0/Q00qqJF1Gi8VesnYN54iM++++TI/-Tmp-/fileinstall-2957414086269585283, felix.fileinstall.filter = null}
INFO: {felix.fileinstall.poll (ms) = 5000, felix.fileinstall.dir = /Applications/NetBeans/glassfish-3.0.1/glassfish/modules/autostart, felix.fileinstall.debug = 1, felix.fileinstall.bundles.new.start = true, felix.fileinstall.tmpdir = /var/folders/Q0/Q00qqJF1Gi8VesnYN54iM++++TI/-Tmp-/fileinstall--8933010182761076907, felix.fileinstall.filter = null}
INFO: Started bundle: file:/Applications/NetBeans/glassfish-3.0.1/glassfish/modules/autostart/org.apache.felix.scr.jar
INFO: Started bundle: file:/Applications/NetBeans/glassfish-3.0.1/glassfish/modules/autostart/osgi-web-container.jar
INFO: SEC1002: Security Manager is OFF.
INFO: Security startup service called
INFO: SEC1143: Loading policy provider com.sun.enterprise.security.provider.PolicyWrapper.
INFO: Realm admin-realm of classtype com.sun.enterprise.security.auth.realm.file.FileRealm successfully created.
INFO: Realm file of classtype com.sun.enterprise.security.auth.realm.file.FileRealm successfully created.
INFO: Realm certificate of classtype com.sun.enterprise.security.auth.realm.certificate.CertificateRealm successfully created.
INFO: Security service(s) started successfully....
INFO: Created HTTP listener http-listener-1 on port 8080
INFO: Created HTTP listener http-listener-2 on port 8181
INFO: Created HTTP listener admin-listener on port 4848
INFO: Created virtual server server
INFO: Created virtual server __asadmin
INFO: Virtual server server loaded system default web module
INFO: Updating configuration from org.apache.felix.fileinstall-autodeploy-bundles.cfg
INFO: Installed /Applications/NetBeans/glassfish-3.0.1/glassfish/modules/autostart/org.apache.felix.fileinstall-autodeploy-bundles.cfg
INFO: {felix.fileinstall.poll (ms) = 5000, felix.fileinstall.dir = /Applications/NetBeans/glassfish-3.0.1/glassfish/domains/domain1/autodeploy/bundles, felix.fileinstall.debug = 1, felix.fileinstall.bundles.new.start = true, felix.fileinstall.tmpdir = /var/folders/Q0/Q00qqJF1Gi8VesnYN54iM++++TI/-Tmp-/fileinstall-9012588867170808207, felix.fileinstall.filter = null}
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
INFO: Portable JNDI names for EJB EjbSynchronizations : [java:global/com.coffeesnobs_web_war_1.0-SNAPSHOT/EjbSynchronizations, java:global/com.coffeesnobs_web_war_1.0-SNAPSHOT/EjbSynchronizations!org.jboss.seam.persistence.transaction.LocalEjbSynchronizations]
INFO: WELD-000900 1.0.1 (SP3)
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
SEVERE: Exception while loading the app
org.glassfish.deployment.common.DeploymentException: Exception #0 :null
        at org.glassfish.weld.WeldDeployer.event(WeldDeployer.java:167)
        at org.glassfish.kernel.event.EventsImpl.send(EventsImpl.java:125)
        at org.glassfish.internal.data.ApplicationInfo.load(ApplicationInfo.java:224)
        at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:338)
        at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:183)
        at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:272)
        at com.sun.enterprise.v3.admin.CommandRunnerImpl$1.execute(CommandRunnerImpl.java:305)
        at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:320)
        at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1176)
        at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$900(CommandRunnerImpl.java:83)
        at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1235)
        at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1224)
        at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:365)
        at com.sun.enterprise.v3.admin.AdminAdapter.service(AdminAdapter.java:204)
        at com.sun.grizzly.tcp.http11.GrizzlyAdapter.service(GrizzlyAdapter.java:166)
        at com.sun.enterprise.v3.server.HK2Dispatcher.dispath(HK2Dispatcher.java:100)
        at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:245)
        at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:791)
        at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:693)
        at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:954)
        at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:170)
        at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:135)
        at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:102)
        at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:88)
        at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:76)
        at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:53)
        at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:57)
        at com.sun.grizzly.ContextTask.run(ContextTask.java:69)
        at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:330)
        at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:309)
        at java.lang.Thread.run(Thread.java:680)
Caused by: org.jboss.weld.exceptions.DefinitionException: Exception #0 :null
        at org.jboss.weld.bootstrap.events.AbstractDefinitionContainerEvent.fire(AbstractDefinitionContainerEvent.java:45)
        at org.jboss.weld.bootstrap.events.ProcessAnnotatedTypeImpl.fire(ProcessAnnotatedTypeImpl.java:44)
        at org.jboss.weld.bootstrap.BeanDeployer.addClass(BeanDeployer.java:61)
        at org.jboss.weld.bootstrap.BeanDeployer.addClasses(BeanDeployer.java:88)
        at org.jboss.weld.bootstrap.BeanDeployment.deployBeans(BeanDeployment.java:134)
        at org.jboss.weld.bootstrap.WeldBootstrap.deployBeans(WeldBootstrap.java:377)
        at org.glassfish.weld.WeldDeployer.event(WeldDeployer.java:165)
        ... 30 more

INFO: Perform lazy SSL initialization for the listener 'http-listener-2'
INFO: Created HTTP listener http-listener-2 on port 8181
INFO: Grizzly Framework 1.9.18-o started in: 14ms listening on port 8181

As you can see, there really isn't much to go on.

Have you seen this exception before?  Do you have any idea what is causing it?  And finally, do you know how to fix it?

ContentLicense: CC BY-SA 2.5