retrofit Json problem

0

Czesc,
pisze sobie apke na androida i zgadnijcie co... nie dziala. Czytalem na stackoverflow ale nie ogarniam. Jak ktos wie o co chodzi prosze o pomoc.

API

<?php 
require_once "conn.php";
if($conn)
{
    $login= $_POST['login'];
    $password= $_POST['password'];

$pg_qry="INSERT INTO register (login,password) VALUES ('$login', '$password')";

$result=pg_query($conn,$pg_qry);


pg_close();

}
?>
implementation 'com.google.code.gson:gson:2.8.0'
    implementation 'com.squareup.retrofit2:retrofit:2.3.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.3.0'

main activity

package com.example.ad.retrofittest;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class MainActivity extends AppCompatActivity {

   EditText log,pass;
   Button przycisk;
   TextView mResponseTv;
   private APIService mAPIService;

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

       log = (EditText) findViewById(R.id.loginetid);
       pass = (EditText) findViewById(R.id.passwordetid);
       mResponseTv = (TextView) findViewById(R.id.napisid);
       Button submitBtn = (Button) findViewById(R.id.button);
       mAPIService = ApiUtils.getAPIService();

       submitBtn.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               String login = log.getText().toString().trim();
               String password = pass.getText().toString().trim();
               if(!TextUtils.isEmpty(login) && !TextUtils.isEmpty(password)) {
                   sendPost(login, password);
               }
           }
       });

   }




   public void sendPost(String login, String password) {
       mAPIService.savePost(login, password, 2).enqueue(new Callback<Post>() {


           @Override
           public void onResponse(Call<Post> call, Response<Post> response) {

               if(response.isSuccessful()) {
                   showResponse(response.body().toString());
                   Log.i("wyslane", "post submitted to API." + response.body().toString());

               }
           }

           @Override
           public void onFailure(Call<Post> call, Throwable t) {
               Log.e("blad", "Unable to submit post to API."+t);
           }
       });
   }



   public void showResponse(String response) {
       if(mResponseTv.getVisibility() == View.GONE) {
           mResponseTv.setVisibility(View.VISIBLE);
       }
       mResponseTv.setText(response);
   }

   }

Post

package com.example.ad.retrofittest;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

/**
* Created by ad on 2018-01-16.
*/

public class Post {

   @SerializedName("login")
   @Expose
   private String login;

   @SerializedName("password")
   @Expose
   private String password;


   @SerializedName("id")
   @Expose
   private Integer id;

   public String getLogin() {
       return login;
   }

   public void setLogin(String login) {
       this.login = login;
   }

   public String getPassword() {
       return password;
   }

   public void setPassword(String password) {
       this.password = password;
   }


   public Integer getId() {
       return id;
   }

   public void setId(Integer id) {
       this.id = id;
   }

   @Override
   public String toString() {
       return "Post{" +
               "login='" + login + '\'' +
               ", password='" + password + '\'' +
               ", id=" + id +
               '}';
   }


}

APIService

package com.example.ad.retrofittest;

import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;

/**
* Created by ad on 2018-01-16.
*/

public interface APIService {


   @GET("login.php")
   Call<Post> getUserInfo();

   @POST("register.php")
   @FormUrlEncoded
   Call<Post> savePost(@Field("login") String login,
                             @Field("password") String password,
                             @Field("id") long id);
}

ApiUtils

package com.example.ad.retrofittest;

/**
* Created by ad on 2018-01-27.
*/

public class ApiUtils {

   private ApiUtils() {}

   public static final String BASE_URL = "https://adrian.kubahaha.tk/retrofittest/";

   public static APIService getAPIService() {

       return RetrofitClient.getClient(BASE_URL).create(APIService.class);
   }
}

I teraz mamy 2 warianty:

1)RetrofitClient

package com.example.ad.retrofittest;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
* Created by ad on 2018-01-16.
*/

public class RetrofitClient {

   private static Retrofit retrofit = null;

   public static Retrofit getClient(String baseUrl) {
       if (retrofit==null) {
     
           retrofit = new Retrofit.Builder()
                   .baseUrl(baseUrl)
                   .addConverterFactory(GsonConverterFactory.create())
                   .build();
       }
       return retrofit;
   }
}

w tym przypadku wywala blad

.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $

2)RetrofitClient

package com.example.ad.retrofittest;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by ad on 2018-01-16.
 */

public class RetrofitClient {

    private static Retrofit retrofit = null;

    public static Retrofit getClient(String baseUrl) {
        if (retrofit==null) {
            Gson gson = new GsonBuilder()
                    .setLenient()
                    .create();
            retrofit = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .build();
        }
        return retrofit;
    }
}

wywala blad

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $ retrofit
1

Poczytałem chwilę ten kod i hmm... czy PHP nie wali jakimiś błędami, zamiast JSON-a?

0

Czesc, miales racje. Chodzilo o to ze w bazie mialem 3 kolumny, a uzupelnialem tylko 2 i wywalalo blad. Dzieki wielkie!

0

Jeszcze jedno pytanie. Jestem w stanie pobrac dane z bazy w formie listview albo recyclerview, ale chcialbym to zrobic w prostszej formie to znaczy wybrac tylko 1 String z bazy danych i wyswietlic go w textview powiedzmy ze z tabeli login wybieram nazwe uzytkownika o id=3. Wiem ze musze uzyc metody getName klasy Contact, ale nie wiem jak to w poprawny sposob zrobic. Troche nie ogarniam jak pewne rzeczy sie ze soba komunikuja.

Zrobilem cos takiego:

public void getData(){

        mAPIService.getUserInfo().enqueue(new Callback<Post>() {
            @Override
            public void onResponse(Call<Post> call, Response<Post> response) {
                showResponse(response.body().toString());
                Log.i("zrobione", "dziala" + response.body().toString());
            }

            @Override
            public void onFailure(Call<Post> call, Throwable t) {
                Log.e("blad", "error."+t);

            }
        });
    }

ale oczywiscie nie dziala, bo nie uzylem metody getName, tylko gdzie ja wplesc jak to ogarnac.

API

<?php 
require_once "conn.php";


$pg_qry="SELECT login FROM register WHERE id=62";
$result=pg_query($conn,$pg_qry);


pg_close();


?>

dodam tylko, ze apka mi sie crashuje w momencie wykonania tej metody. Jak bedzie trzeba to podam log z logcata.

1 użytkowników online, w tym zalogowanych: 0, gości: 1