Android: Issues in making a REST call

2019-04-16 17:10发布

I have developed a REST API using Java, implementing Jersey. Now I am trying to connect my android application with it.

Below code is related to my REST API.

PatientJSONService

import bean.PatientBean;
import bean.UserBean;
import db.PatientImpl;
import db.PatientInterface;
import db.UserImpl;
import db.UserInterface;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/patient")
public class PatientJSONService 
{
    @POST
    @Path("/insertPatient")
    @Consumes(MediaType.APPLICATION_JSON)
    public String insertPatient(PatientBean bean)
    {
        System.out.println("Printed");
        PatientInterface patientInterface = new PatientImpl();
        String insertUser = patientInterface.insertPatient(bean);
        return insertUser;
    }

    @GET
    @Path("/getAllPatients")
    @Produces(MediaType.APPLICATION_JSON)       
    public List<PatientBean> getAllPatients()
    {
        PatientInterface patinetInterface=new PatientImpl();
        List<PatientBean> allPatients = patinetInterface.getAllPatients();

        return allPatients;
    }

    @POST
    @Path("/getPatientById/{id}")
    @Produces(MediaType.APPLICATION_JSON)       
    public PatientBean getPatientByFlareId(@PathParam("id")String flareId)
    {
        PatientInterface patinetInterface=new PatientImpl();
        PatientBean patientById = patinetInterface.getPatientById(id);
        return patientById;
    }

}

PatientBean

public class PatientBean {

    private int idPatient;
    private String id;

    public int getIdPatient() {
        return idPatient;
    }

    public void setIdPatient(int idPatient) {
        this.idPatient = idPatient;
    }

    public String getID() {
        return flareID;
    }

    public void setID(String id) {
        this.id = id;
    }

}

PatientImpl- (database class)

public class PatientImpl implements PatientInterface {

    @Override
    public String insertPatient(PatientBean patientBean) 
    {
        String sql = "INSERT INTO patient (id) values(?)";
        String result="";

        Connection con = null;
        PreparedStatement ps = null;

        try
        {
            con = DBMaster.getInstance().getConnection();
            con.setAutoCommit(false);
            ps = con.prepareStatement(sql.toLowerCase());

            ps.setString(1,patientBean.getID());

            ps.executeUpdate();
            con.commit();
            result = Common.SUCCESS;
        }
        catch(Exception e)
        {
            try
            {
                con.rollback();
                e.printStackTrace();
                result = Common.ROLLBACK;
            } 
            catch (SQLException ex)
            {
                ex.printStackTrace();
                result = Common.ROLLBACK_FAILED;
            }
        }
        finally
        {
            try
            {
                ps.close();
                con.close();
            } catch (SQLException ex)
            {
                ex.printStackTrace();
            }
        }

        System.out.println(result);
        return result;   
    }
}

Now you have a proper and a clear understanding of how my REST API looks like. Let's see how I programmed my Android application to access this API. In here I am actually using retrofit 2 - http://square.github.io/retrofit/

MainActivity

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;

import bean.Common;
import bean.PatientBean;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {

    public static final String URL = "http://x.x.x.x:8080/TestRest/rest/";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        restCall();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private void restCall()
    {

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        YourEndpoints request = retrofit.create(YourEndpoints.class);

        PatientBean patientBean= new PatientBean ();
        patientBean.setId(SLKRT0065);

        Call<ResponseBody> yourResult = request.insertPatient(patientBean);
        yourResult.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

                try {
                    Log.d("MainActivity", "RESPONSE: " + response.body().string());
                }
                catch(Exception e)
                {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                try {
                    t.printStackTrace();
                    Log.d("MainActivity", "RESPONSE: "+"FAILED");
                }
                catch(Exception e)
                {
                    e.printStackTrace();
                }
            }

        });
    }
}

From the above class, have a look at the method restCall() where the REST call is happening.

YourEndpoints

public interface YourEndpoints {

    @POST("patient/insertPatient")
    Call<ResponseBody> insertPatient(@Body PatientBean patientBean);
}

I don't know what I have done wrong, but it simply didn't work. When I run this code, I get a NULLPOINTERException in here Log.d("MainActivity", "RESPONSE: " + response.body().string()); which means the response is probably null/ If I remove that part the code runs fine, but I see nothing in the database.

How can I solve this issue?

0条回答
登录 后发表回答