简体   繁体   English

放置和删除方法在 Retrofit 和 rxjava Android 中不起作用

[英]Put & Delete method not working in Retrofit and rxjava Android

I creating Android application with retrofit & rxjava, server in nodejs.我使用 retrofit 和 rxjava 创建 Android 应用程序,服务器在 nodejs 中。 I created post function its working but I created Put function its not working it shows successful but its not affected in mysql help me to solve this problem its save my life我创建了帖子 function 它工作但我创建了 Put function 它不工作它显示成功但它在 mysql 中不受影响帮助我解决这个问题它拯救我的生命

I tested my Api with postman its working.我用 postman 测试了我的 Api 的工作。 Its problem in Android retrofit I don't where its mistake它在 Android retrofit 中的问题我不知道它的错误在哪里

MyApi我的 API

connection.connect(function(err) {
  if (err) throw err
  console.log('You are now connected with mysql database...')
})

var server = app.listen(3000, function () {
  var port = server.address().port
  console.log("Server listening at", port)
});

app.get('/get', function (req, res) {
   connection.query('select * from customer', function (error, results, fields) {
      if (error) throw error;
      res.end(JSON.stringify(results));
    });
});

app.get('/get/:id', function (req, res) {
   connection.query('select * from customer where Id=?', [req.params.id], function (error, results, fields) {
      if (error) throw error;
      res.end(JSON.stringify(results));
    });
});

app.post('/register', function (req, res) {
   var params  = req.body;
   console.log(params);
   connection.query('INSERT INTO customer SET ?', params, function (error, results, fields) {
      if (error) throw error;
      res.end(JSON.stringify(results));
    });
});

app.put('/update/:id', function (req, res) {
   connection.query('UPDATE `customer` SET `Name`=?,`Address`=?,`Country`=?,`Phone`=? where `Id`=?', [req.body.Name,req.body.Address, req.body.Country, req.body.Phone, req.body.Id], function (error, results, fields) {
      if (error) throw error;
      res.end(JSON.stringify(results));
    });
});

app.delete('/delete/:id', function (req, res) {
   console.log(req.body);
   connection.query('DELETE FROM `customer` WHERE `Id`=?', [req.body.Id], function (error, results, fields) {
      if (error) throw error;
      res.end('Record has been deleted!');
    });
});

INodeJS.java INodeJS.java

public interface INodeJS {
    @POST("register")
    @FormUrlEncoded
    Observable<String> insert(@Field("Id") String id,
                                    @Field("Name") String name,
                                    @Field("Address") String address,
                                    @Field("Country") String Country,
                                    @Field("Phone") String Phone);
    @PUT("update/{Id}/")
    @FormUrlEncoded
    Observable<String> update(@Path("Id") String id,
                              @Field("Name") String name,
                              @Field("Address") String address,
                              @Field("Country") String Country,
                              @Field("Phone") String Phone);
}

RetrofitClient.java RetrofitClient.java

public class RetrofitClient {
    private static Retrofit instance;
    public static Retrofit getInstance(OkHttpClient client)
    {
        if(instance == null)
            instance = new Retrofit.Builder()
                    .baseUrl("http://10.0.2.2:3000")
                    .addConverterFactory(ScalarsConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .client(client)
                    .build();
            return instance;
    }
}

MainActivity.java MainActivity.java

INodeJS myApi;
    CompositeDisposable compositeDisposable = new CompositeDisposable();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(loggingInterceptor)
                .build();

        Retrofit retrofit = RetrofitClient.getInstance(okHttpClient);
        myApi = retrofit.create(INodeJS.class);

        edit_id = findViewById(R.id.id);
        edit_name = findViewById(R.id.name);
        edit_address = findViewById(R.id.address);
        edit_country = findViewById(R.id.country);
        edit_phone = findViewById(R.id.phone);
        insert = findViewById(R.id.btn_insert);
        update = findViewById(R.id.btn_update);

        insert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                insertuser(edit_id.getText().toString(),edit_name.getText().toString(),edit_address.getText().toString(),edit_country.getText().toString(),edit_phone.getText().toString());
            }
        });
        update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateuser(edit_id.getText().toString(),edit_name.getText().toString(),edit_address.getText().toString(),edit_country.getText().toString(),edit_phone.getText().toString());
            }
        });
    }
    private void updateuser(String id, String name, String address, String country, String phone)
    {
        compositeDisposable.add(myApi.update(id,name,address,country,phone)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Consumer<String>() {
            @Override
            public void accept(String s) throws Exception {
                Toast.makeText(MainActivity.this,"Data updated",Toast.LENGTH_LONG).show();
            }
        }));
    }
    private void insertuser(String id, String name, String address, String country, String phone) {

        compositeDisposable.add(myApi.insert(id,name,address,country,phone)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) throws Exception {
                        Toast.makeText(MainActivity.this,"Data inserted",Toast.LENGTH_LONG).show();
                        clear_edittext();
                    }
                }));
    }

I am using HttpLoggingInterceptor to all function while update function我在更新 function 时对所有 function 使用 HttpLoggingInterceptor

D/OkHttp: --> PUT http://10.0.2.2:3000/update/100/
D/OkHttp: Content-Type: application/x-www-form-urlencoded
D/OkHttp: Content-Length: 53
D/OkHttp: Name=David&Address=sydney&Country=Australia&Phone=234555
D/OkHttp: --> END PUT (53-byte body)
D/OkHttp: <-- 200 OK http://10.0.2.2:3000/update/100/ (110ms)
D/OkHttp: X-Powered-By: Express
D/OkHttp: Connection: keep-alive
D/OkHttp: Content-Length: 169

Just remove / from the end of your endpoint and do like below.只需从端点末尾删除/并执行以下操作。

Also, set your base URL like this "http://10.0.2.2:3000/"另外,设置你的基础 URL 像这样"http://10.0.2.2:3000/"

    @FormUrlEncoded
    @PUT("update/{Id}") 
    Observable<String> update(@Path("Id") String id,
                              @Field("Name") String name,
                              @Field("Address") String address,
                              @Field("Country") String Country,
                              @Field("Phone") String Phone);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM