I have some JSON below.
{
"Table": [
{
"CMBL009001": "010001",
"NMBL009002": 0,
"CMBL009003": "",
"CMBL009004": "",
"CMBL009005": "",
"CMBL009006": "",
"NMBL009007": 0,
"BMBL009008": 0,
"NMBL009009": 0,
"CMBL009010": "ADMIN",
"CMBL009011": "",
"NMBL009012": 2,
"NMBL009013": 1
}
]
}
this is my model:
package com.example.showmyjsonapplicationuser;
import com.google.gson.annotations.SerializedName;
public class User {
#SerializedName("BMBL009008")
private Long mBMBL009008;
#SerializedName("CMBL009001")
private String mCMBL009001;
#SerializedName("CMBL009003")
private String mCMBL009003;
#SerializedName("CMBL009004")
private String mCMBL009004;
#SerializedName("CMBL009005")
private String mCMBL009005;
#SerializedName("CMBL009006")
private String mCMBL009006;
#SerializedName("CMBL009010")
private String mCMBL009010;
#SerializedName("CMBL009011")
private String mCMBL009011;
#SerializedName("NMBL009002")
private Long mNMBL009002;
#SerializedName("NMBL009007")
private Long mNMBL009007;
#SerializedName("NMBL009009")
private Long mNMBL009009;
#SerializedName("NMBL009012")
private Long mNMBL009012;
#SerializedName("NMBL009013")
private Long mNMBL009013;
public Long getBMBL009008() {
return mBMBL009008;
}
public void setBMBL009008(Long bMBL009008) {
mBMBL009008 = bMBL009008;
}
public String getCMBL009001() {
return mCMBL009001;
}
public void setCMBL009001(String cMBL009001) {
mCMBL009001 = cMBL009001;
}
public String getCMBL009003() {
return mCMBL009003;
}
public void setCMBL009003(String cMBL009003) {
mCMBL009003 = cMBL009003;
}
public String getCMBL009004() {
return mCMBL009004;
}
public void setCMBL009004(String cMBL009004) {
mCMBL009004 = cMBL009004;
}
public String getCMBL009005() {
return mCMBL009005;
}
public void setCMBL009005(String cMBL009005) {
mCMBL009005 = cMBL009005;
}
public String getCMBL009006() {
return mCMBL009006;
}
public void setCMBL009006(String cMBL009006) {
mCMBL009006 = cMBL009006;
}
public String getCMBL009010() {
return mCMBL009010;
}
public void setCMBL009010(String cMBL009010) {
mCMBL009010 = cMBL009010;
}
public String getCMBL009011() {
return mCMBL009011;
}
public void setCMBL009011(String cMBL009011) {
mCMBL009011 = cMBL009011;
}
public Long getNMBL009002() {
return mNMBL009002;
}
public void setNMBL009002(Long nMBL009002) {
mNMBL009002 = nMBL009002;
}
public Long getNMBL009007() {
return mNMBL009007;
}
public void setNMBL009007(Long nMBL009007) {
mNMBL009007 = nMBL009007;
}
public Long getNMBL009009() {
return mNMBL009009;
}
public void setNMBL009009(Long nMBL009009) {
mNMBL009009 = nMBL009009;
}
public Long getNMBL009012() {
return mNMBL009012;
}
public void setNMBL009012(Long nMBL009012) {
mNMBL009012 = nMBL009012;
}
public Long getNMBL009013() {
return mNMBL009013;
}
public void setNMBL009013(Long nMBL009013) {
mNMBL009013 = nMBL009013;
}
}
this is my retrofit class:
package com.example.showmyjsonapplicationuser;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
public class RetrofitSingleton {
private static Retrofit retrofit;
public static Retrofit getInstance() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl("http://192.168.200.10:6139/api/")
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
private RetrofitSingleton() {
}
}
this is provider class:
package com.example.showmyjsonapplicationuser.providers;
import com.example.showmyjsonapplicationuser.ApiService;
import com.example.showmyjsonapplicationuser.RetrofitSingleton;
public class ApiServiceProvider {
private static ApiService apiService;
public static ApiService provideApiService() {
if (apiService == null) {
apiService = RetrofitSingleton.getInstance().create(ApiService.class);
}
return apiService;
}
}
this is jsonUserResponse:
package com.example.showmyjsonapplicationuser;
public class JSONUserResponse {
private User[] Table;
public User[] getTable(){
return Table;
}
}
this is apiService:
package com.example.showmyjsonapplicationuser;
import retrofit2.Call;
import retrofit2.http.GET;
public interface ApiService {
#GET("values?url=<NewDataSet><Table><ver>1_02.01.06</ver><proc>003TOTALSELECT</proc><P1>ADMIN</P1><P2>123456</P2><P3>MBLTYPEVISIT1</P3></Table></NewDataSet>")
Call<JSONUserResponse> getUsersJSON();
}
this is mainViewModel:
`package com.example.showmyjsonapplicationuser;
import com.example.showmyjsonapplicationuser.providers.ApiServiceProvider;
import retrofit2.Call;
public class MainViewModel {
private ApiService apiService = ApiServiceProvider.provideApiService();
Call<JSONUserResponse> callUser = apiService.getUsersJSON();
}
this in main activity:
package com.example.showmyjsonapplicationuser;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivity extends AppCompatActivity {
private MainViewModel viewModel = new MainViewModel();
private ArrayList<User> data = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewModel.callUser.enqueue(new Callback<JSONUserResponse>() {
#Override
public void onResponse(Call<JSONUserResponse> call, Response<JSONUserResponse> response) {
JSONUserResponse jsonUserResponse = response.body();
assert jsonUserResponse != null;
data = new ArrayList<>(Arrays.asList(jsonUserResponse.getTable()));
Toast.makeText(MainActivity.this, "اطلاعات با موفقیت دریافت شد", Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(Call<JSONUserResponse> call, Throwable t) {
Log.d("Error", t.getMessage());
}
});
}
}
the problem is that the response is null.
You need to create two model classes , one will be like below
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Table {
#SerializedName("CMBL009001")
#Expose
private String cMBL009001;
#SerializedName("NMBL009002")
#Expose
private Integer nMBL009002;
#SerializedName("CMBL009003")
#Expose
private String cMBL009003;
#SerializedName("CMBL009004")
#Expose
private String cMBL009004;
#SerializedName("CMBL009005")
#Expose
private String cMBL009005;
#SerializedName("CMBL009006")
#Expose
private String cMBL009006;
#SerializedName("NMBL009007")
//getters and setters
}
Another will be
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class TestModel {
#SerializedName("Table")
#Expose
private List<Table> table = null;
public List<Table> getTable() {
return table;
}
public void setTable(List<Table> table) {
this.table = table;
}
}
And then you can use the TestModel in your call.
Related
i have some problem with room database i guess.
I created an entity class:
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;
import android.os.Parcel;
import android.os.Parcelable;
#Entity
public class Supplier implements Parcelable {
#PrimaryKey(autoGenerate = true)
private Long id;
private String mastro;
private String partitario;
private String description;
// region Construction
public Supplier() {
super();
}
// region Public getters and setters
protected Supplier(Parcel in) {
if (in.readByte() == 0) {
id = null;
} else {
id = in.readLong();
}
mastro = in.readString();
partitario = in.readString();
description = in.readString();
}
public static final Creator<Supplier> CREATOR = new Creator<Supplier>() {
#Override
public Supplier createFromParcel(Parcel in) {
return new Supplier(in);
}
#Override
public Supplier[] newArray(int size) {
return new Supplier[size];
}
};
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getMastro() {
return mastro;
}
public void setMastro(String mastro) {
this.mastro = mastro;
}
public String getPartitario() {
return partitario;
}
public void setPartitario(String partitario) {
this.partitario = partitario;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
if (id == null) {
dest.writeByte((byte) 0);
} else {
dest.writeByte((byte) 1);
dest.writeLong(id);
}
dest.writeString(mastro);
dest.writeString(partitario);
dest.writeString(description);
}
// endregion
}
Then i create a Dao class with simple queries:
#Dao
public interface SupplierDao {
#Query("SELECT * FROM Supplier WHERE id = :id")
Supplier getById(Long id);
#Insert
Long insert(Supplier supplier);
#Insert
Long insert(List<Supplier> suppliers);
#Update
void update(Supplier supplier);
#Delete
void delete(Supplier supplier);
#Query("DELETE FROM Supplier")
void deleteAll();
}
And this is the class when i create database:
package com.poltronesofa.plt.storage;
import android.arch.persistence.room.Database;
import android.arch.persistence.room.Room;
import android.arch.persistence.room.RoomDatabase;
import android.arch.persistence.room.TypeConverter;
import android.arch.persistence.room.TypeConverters;
import android.content.Context;
import com.poltronesofa.plt.storage.dao.AnomalyDao;
import com.poltronesofa.plt.storage.dao.ContractorDao;
import com.poltronesofa.plt.storage.dao.LoadingPlanDao;
import com.poltronesofa.plt.storage.dao.ProductDao;
import com.poltronesofa.plt.storage.dao.SupplierDao;
import com.poltronesofa.plt.storage.dao.UsersDao;
import com.poltronesofa.plt.storage.model.Anomaly;
import com.poltronesofa.plt.storage.model.Contractor;
import com.poltronesofa.plt.storage.model.LoadingPlan;
import com.poltronesofa.plt.storage.model.Product;
import com.poltronesofa.plt.storage.model.Supplier;
import com.poltronesofa.plt.storage.model.User;
import java.util.Date;
/**
* #author arinaldi
*/
#Database(entities = {User.class, LoadingPlan.class, Contractor.class, Product.class, Anomaly.class, Supplier.class}, version = PLTDatabase.DB_VERSION, exportSchema = false)
#TypeConverters({PLTDatabase.Converters.class})
public abstract class PLTDatabase
extends RoomDatabase {
static final String DB_NAME = "plt_db";
static final int DB_VERSION = 1;
private static PLTDatabase INSTANCE = null;
public static void init(Context context) {
if (INSTANCE != null) {
INSTANCE.close();
}
INSTANCE = Room.databaseBuilder(context, PLTDatabase.class, DB_NAME)
.allowMainThreadQueries()
.build();
}
public static PLTDatabase get() {
if (INSTANCE == null) {
throw new RuntimeException("DATABASE not initialized");
}
return INSTANCE;
}
public void clear() {
users().deleteAll();
loadingPlans().deleteAll();
contractors().deleteAll();
products().deleteAll();
anomalies().deleteAll();
//suppliers().deleteAll();
}
public abstract UsersDao users();
public abstract LoadingPlanDao loadingPlans();
public abstract ContractorDao contractors();
public abstract ProductDao products();
public abstract AnomalyDao anomalies();
public abstract SupplierDao suppliers();
public static class Converters {
#TypeConverter
public Date fromTimeStamp(Long timestamp) {
return timestamp == null ? null : new Date(timestamp);
}
#TypeConverter
public Long toTimeStamp(Date date) {
return date == null ? null : date.getTime();
}
}
}
When I compile I get errors related to the databinding and I can not go back to the real error because it's not specified:
C:/Documents/Android Studio/PLT
app/build/generated/data_binding_base_class_source_out/devDebug/dataBindingGenBaseClassesDevDebug/out
com/poltronesofa/plt/databinding/ActivityHomeBinding.java
error: cannot find symbol class DataBindingComponent
error: cannot find symbol class DataBindingComponent
error: cannot find symbol class DataBindingComponent
error: cannot find symbol class DataBindingComponent
com/poltronesofa/plt/databinding/ViewToolbarBinding.java
com/poltronesofa/plt/databinding/FragmentWelcomeBinding.java
com/poltronesofa/plt/databinding/ListItemLoadingPlanBinding.java
com/poltronesofa/plt/databinding/FragmentLoadingPlansBinding.java
com/poltronesofa/plt/databinding/ActivityLoginBinding.java
com/poltronesofa/plt/databinding/ActivityCheckTissueBinding.java
com/poltronesofa/plt/databinding/ActivitySuppliersBinding.java
com/poltronesofa/plt/databinding/ListItemSupplierBinding.java
com/poltronesofa/plt/databinding/ActivityContractorsBinding.java
com/poltronesofa/plt/databinding/ListItemContractorBinding.java
com/poltronesofa/plt/databinding/ActivityLoadingPlanBinding.java
com/poltronesofa/plt/databinding/ActivityProductDetailBinding.java
com/poltronesofa/plt/databinding/ActivityProductsBinding.java
com/poltronesofa/plt/databinding/ListItemProductBinding.java
com/poltronesofa/plt/databinding/ActivitySettingsBinding.java
com/poltronesofa/plt/databinding/ActivitySplashBinding.java
com/poltronesofa/plt/databinding/FragmentProductBinding.java
com/poltronesofa/plt/databinding/ListItemArticleBinding.java
app/src/main/java
com/poltronesofa/plt/storage/dao/SupplierDao.java
error: Method returns long but it should return one of the following: `void, long[], java.lang.Long[], java.util.List<java.lang.Long>`. If you want to return the list of row ids from the query, your insertion method can receive only 1 parameter.
How can i solve this?
I'm trying to pass an ArrayList filled in the getPartidos() method with volley to another activity through the btnClick_Normal(View v) method, but whenever I press any button the uses the method I get an error saying miListaPartidos is empty (this).
The URL is online and working properly. Why could this be happening and how much of the code is wrong?
This is my Activity
import android.content.Intent;
import android.os.Parcelable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Act1_1 extends AppCompatActivity {
public String urlPartidos="https://.."; /*hid the url, it's working properly*/
public ArrayList<Partido> miListaPartidos=new ArrayList<>();
public Button btns1;
public Button btns2;
public Button btns3;
public Button btns4;
public Button btns5;
public Button btns6;
public Button btns7;
public Button btns8;
public Button btnE;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_act1_1);
btns1=findViewById(R.id.btns1);
btns2=findViewById(R.id.btns2);
btns3=findViewById(R.id.btns3);
btns4=findViewById(R.id.btns4);
btns5=findViewById(R.id.btns5);
btns6=findViewById(R.id.btns6);
btns7=findViewById(R.id.btns7);
btns8=findViewById(R.id.btns8);
btnE=findViewById(R.id.btnE);
getPartidos();
}
public void btnClick_Normal(View v){
Intent intent=new Intent(getApplicationContext(),Act1_1_1.class);
int id1=(Integer.parseInt((String)v.getTag()));
ArrayList<Partido> listaEq=new ArrayList<>();
for(int i=(((id1-1)*6)); i<=(id1*6)-1;i++ ) {
listaEq.add(miListaPartidos.get(i));
}
intent.putExtra("listaEq", listaEq);
startActivity(intent);
}
public void btnClick_Especial(View v){
Intent intent=new Intent(getApplicationContext(),Act1_1_2.class);
ArrayList<Partido> listaEq=new ArrayList<>();
for(int i=48; i<=63;i++ ) {
listaEq.add(miListaPartidos.get(i));
}
intent.putExtra("listaEq2", listaEq);
startActivity(intent);
}
public void getPartidos(){
RequestQueue requestQueue= Volley.newRequestQueue(this);
JsonObjectRequest jSonObjectRequest=new JsonObjectRequest(Request.Method.GET,urlPartidos, null, new Response.Listener<JSONObject>(){
public void onResponse(JSONObject response){
try{
JSONArray jsonArrayPartidos=response.getJSONArray("results");
if(jsonArrayPartidos.length()>0) {
for (int i = 0; i < jsonArrayPartidos.length(); i++) {
JSONObject jsonPartido = jsonArrayPartidos.getJSONObject(i);
final int id = jsonPartido.getInt("id");
final String detalles = jsonPartido.getString("details");
final String equipo1 = jsonPartido.getString("team1");
final String equipo2 = jsonPartido.getString("team2");
final int goles1 = jsonPartido.getInt("goals1");
final int goles2 = jsonPartido.getInt("goals2");
final Partido nuevoPartido = new Partido(id, detalles, equipo1, equipo2, goles1, goles2);
miListaPartidos.add(nuevoPartido);
}
}
}
catch(JSONException je){ }
}
}, new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
}
}
);
requestQueue.add(jSonObjectRequest);
}
}
And this is my Partido class
public class Partido {
private int id;
private String detalles;
private String equipo1;
private String equipo2;
private int goles1;
private int goles2;
public Partido(int id, String detalles, String equipo1, String equipo2, int goles1, int goles2){
this.id=id;
this.detalles=detalles;
this.equipo1=equipo1;
this.equipo2=equipo2;
this.goles1=goles1;
this.goles2=goles2;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDetalles() {
return detalles;
}
public void setDetalles(String detalles) {
this.detalles = detalles;
}
public String getEquipo1() {
return equipo1;
}
public void setEquipo1(String equipo1) {
this.equipo1 = equipo1;
}
public String getEquipo2() {
return equipo2;
}
public void setEquipo2(String equipo2) {
this.equipo2 = equipo2;
}
public int getGoles1() {
return goles1;
}
public void setGoles1(int goles1) {
this.goles1 = goles1;
}
public int getGoles2() {
return goles2;
}
public void setGoles2(int goles2) {
this.goles2 = goles2;
}
}
If your list is empty, then there may be a problem with the Json itself. Some times they have some extra characters, So
try to validate the your Json using JsonLint or Code beautify
In your catch Json exception block, try to print the stack trace and grab the message
catch(JSONException je){
je.printStackTrace();
Log.d("ERR",je.getMessage()) ;
}
Please implement Serializable in Partido class
public class Partido implements Serializable {
private int id;
private String detalles;
private String equipo1;
private String equipo2;
private int goles1;
private int goles2;
public Partido(int id, String detalles, String equipo1, String equipo2, int goles1, int goles2){
this.id=id;
this.detalles=detalles;
this.equipo1=equipo1;
this.equipo2=equipo2;
this.goles1=goles1;
this.goles2=goles2;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDetalles() {
return detalles;
}
public void setDetalles(String detalles) {
this.detalles = detalles;
}
public String getEquipo1() {
return equipo1;
}
public void setEquipo1(String equipo1) {
this.equipo1 = equipo1;
}
public String getEquipo2() {
return equipo2;
}
public void setEquipo2(String equipo2) {
this.equipo2 = equipo2;
}
public int getGoles1() {
return goles1;
}
public void setGoles1(int goles1) {
this.goles1 = goles1;
}
public int getGoles2() {
return goles2;
}
public void setGoles2(int goles2) {
this.goles2 = goles2;
}
}
This is code to receive data in Act1_1_2
misPartidos = (ArrayList<Partido>) getIntent().getSerializableExtra("listaEq2");
Hope this will be help you!
Even though every thing is working properly and registration is happening. Retrofit on Response don't get called but onFailure gets called. Call.isexecutted returns true.
I am showing the model class and registrationFragment where the error occured. This is taking a lot time. So thanks in advance for help
RegistrationFragment.java
package com.example.milan.hospital;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* A simple {#link Fragment} subclass.
*/
public class RegistrationFragment extends Fragment {
private EditText Name,UserName, UserPassword;
private Button BnRegister;
public RegistrationFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_registration, container, false);
Name = view.findViewById(R.id.txt_name);
UserName = view.findViewById(R.id.txt_user_name);
UserPassword = view.findViewById(R.id.txt_password);
BnRegister = view.findViewById(R.id.bn_register);
BnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
performRegistration();
}
});
return view;
}
public void performRegistration()
{
String name = Name.getText().toString();
String username = UserName.getText().toString();
String password = UserPassword.getText().toString();
Call<User> call = MainActivity.apiInterface.performRegistration(name,username,password);
call.enqueue(new Callback<User>() {
#Override
public void onResponse(Call<User> call, Response<User> response) {
if(response.body().getResponse().equals("ok"))
{
MainActivity.prefConfig.displayToast("Registration success...");
}
else if(response.body().getResponse().equals("exist"))
{
MainActivity.prefConfig.displayToast("User already exist....");
}
else if(response.body().getResponse().equals("error"))
{
MainActivity.prefConfig.displayToast("Something went wrong...");
}
}
#Override
public void onFailure(Call<User> call, Throwable t) {
}
});
Name.setText("");
UserPassword.setText("");
UserName.setText("");
}
}
User.java
package com.example.milan.hospital;
import com.google.gson.annotations.SerializedName;
public class User {
#SerializedName("response")
private String Response;
#SerializedName("name")
private String Name;
public String getResponse() {
return Response;
}
public String getName() {
return Name;
}
}
MainActivity.java
package com.example.milan.hospital;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity implements LoginFragment.OnLoginFormActivityListener{
public static PrefConfig prefConfig;
public static ApiInterface apiInterface;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prefConfig = new PrefConfig(this);
apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
if(findViewById(R.id.fragment_container) != null)
{
if(savedInstanceState != null)
{
return;
}
if(prefConfig.readLoginStatus())
{
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container,new WelcomeFragment()).commit();
}
else
{
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container,new LoginFragment()).commit();
}
}
}
#Override
public void performRegister() {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new RegistrationFragment()).addToBackStack(null).commit();
}
#Override
public void performLogin(String name) {
}
}
ApiInterface.java
package com.example.milan.hospital;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;
public interface ApiInterface
{
#GET("register.php")
Call<User> performRegistration(#Query("name") String Name,#Query("user_name") String UserName,#Query("user_password") String UserPassword);
#GET("login.php")
Call<User> performUserLogin(#Query("user_name") String UserName,#Query("user_password") String UserPassword);
}
I think performRegistration() in ApiInterface.java should have an annotation of #POST rather than #GET since registration is the act of posting data rather than getting. Give it a try once.
change the ApiClient to this. As there was a well known problem of retrofit while reading json. to resolve we have initialize gson object ourself
public class ApiClient
{
public static final String BASE_URL = "http://10.0.3.2/loginapp/";
public static Retrofit retrofit = null;
public static Retrofit getApiClient()
{
Gson gson = new GsonBuilder()
.setLenient()
.create();
if(retrofit == null)
{
retrofit = new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create(gson)).build();
}
return retrofit;
}
}
I want to load question and answer in expandable listview from json using retrofit library. I dont know how to do this. Find me a solution.
Here is the two model class i am using.
public class QuestionResult {
boolean IsSuccess;
List<QuestionsModel> question;
public boolean isSuccess() {
return IsSuccess;
}
public List<QuestionsModel> getQuestion() {
return question;
}
}
And
public class QuestionsModel {
private int q_id;
private int category_id;
private String question;
private String answer;
public int getQ_id() {
return q_id;
}
public int getCategory_id() {
return category_id;
}
public String getQuestion() {
return question;
}
public String getAnswer() {
return answer;
}
}
Here is my Activity
public class QuestionBank extends AppCompatActivity {
#InjectView(R.id.ques_type_spinner)
Spinner courseSpinner;
#InjectView(R.id.home_btn_qbank)
Button homeButton;
#InjectView(R.id.no_questions)
TextView textView;
#InjectView(R.id.ques_ans_listview)
ExpandableListView listView;
List<String> courseNames;
ArrayAdapter<String> courseAdapter;
ExpandableListAdapter listAdapter;
List<QuestionResult> resultList;
ProgressDialog progress;
int selectedPosition;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question_bank);
ButterKnife.inject(this);
StatusBarTheme.setStatusBarColor(this);
showCourseCategory();
homeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
courseSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedPosition = courseSpinner.getSelectedItemPosition() + 1;
Log.d("cat_id ", " " + selectedPosition);
loadQuestions(selectedPosition);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
private void loadQuestions(final int selectedPosition) {
ApiInterface apiInterface = ApiClient.getClient(this).create(ApiInterface.class);
Call<QuestionResult> call = apiInterface.loadQuesAndAnswers(selectedPosition);
call.enqueue(new Callback<QuestionResult>() {
#Override
public void onResponse(Call<QuestionResult> call, Response<QuestionResult> response) {
List<QuestionsModel> questionsModelList = response.body().getQuestion();
if (questionsModelList != null) {
listAdapter = new ExpandListAdapter(QuestionBank.this, questionsModelList, selectedPosition);
listView.setAdapter(listAdapter);
} else {
listView.setVisibility(View.GONE);
textView.setVisibility(View.VISIBLE);
}
}
#Override
public void onFailure(Call<QuestionResult> call, Throwable t) {
}
});
}
private void showCourseCategory() {
ApiInterface apiInterface = ApiClient.getClient(this).create(ApiInterface.class);
Call<CategoryResult> call = apiInterface.loadCourseTitle();
progress = new ProgressDialog(QuestionBank.this);
progress.setMessage("Loading.. Please wait");
progress.show();
call.enqueue(new Callback<CategoryResult>() {
#Override
public void onResponse(Call<CategoryResult> call, Response<CategoryResult> response) {
if (progress.isShowing()) {
progress.dismiss();
}
if (response.body().isSuccess() && response.body().getCategory() != null) {
response.body().getCategory();
courseNames = new ArrayList<>();
for (CourseType courseType : response.body().getCategory()) {
courseNames.add(courseType.getCategory_title());
}
loadSpinner(courseNames);
}
}
#Override
public void onFailure(Call<CategoryResult> call, Throwable t) {
}
});
}
private void loadSpinner(List<String> educationTypeList) {
courseAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, educationTypeList);
courseAdapter.setDropDownViewResource(android.R.layout.simple_list_item_checked);
courseSpinner.setAdapter(courseAdapter);
}
}
Here is the complete code. Change it for your purposes. If anything will happen you can write comment i will answer.
Application.class
public class Application extends Application{
private static Application instance;
private I_Requests iWebEndpoint;
#Override
public void onCreate() {
super.onCreate();
instance = this;
}
public static Application i() {
return instance;
}
public I_Requests w() {
if(this.iWebEndpoint == null){
initRetrofit();
}
return iWebEndpoint;
}
private void initRetrofit(){
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient
.Builder()
.addInterceptor(interceptor)
.readTimeout(1, TimeUnit.MINUTES)
.writeTimeout(1, TimeUnit.MINUTES)
.connectTimeout(1, TimeUnit.MINUTES)
.build();
client.readTimeoutMillis();
this.iWebEndpoint = new Retrofit.Builder()
.baseUrl(I_Requests.address)
.client(client)
.addConverterFactory(JacksonConverterFactory.create())
.build()
.create(I_Requests.class);
}
}
JacksonConverterFactory.class
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.ObjectWriter;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;
/**
* A {#linkplain Converter.Factory converter} which uses Jackson.
* <p>
* Because Jackson is so flexible in the types it supports, this converter assumes that it can
* handle all types. If you are mixing JSON serialization with something else (such as protocol
* buffers), you must {#linkplain Retrofit.Builder#addConverterFactory(Converter.Factory) add this
* instance} last to allow the other converters a chance to see their types.
*/
public final class JacksonConverterFactory extends Converter.Factory {
/** Create an instance using a default {#link ObjectMapper} instance for conversion. */
public static JacksonConverterFactory create() {
return create(new ObjectMapper());
}
/** Create an instance using {#code mapper} for conversion. */
public static JacksonConverterFactory create(ObjectMapper mapper) {
return new JacksonConverterFactory(mapper);
}
private final ObjectMapper mapper;
private JacksonConverterFactory(ObjectMapper mapper) {
if (mapper == null) throw new NullPointerException("mapper == null");
this.mapper = mapper;
}
#Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
Retrofit retrofit) {
JavaType javaType = mapper.getTypeFactory().constructType(type);
ObjectReader reader = mapper.reader(javaType);
return new JacksonResponseBodyConverter<>(reader);
}
#Override
public Converter<?, RequestBody> requestBodyConverter(Type type,
Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
JavaType javaType = mapper.getTypeFactory().constructType(type);
ObjectWriter writer = mapper.writerWithType(javaType);
return new JacksonRequestBodyConverter<>(writer);
}
}
JacksonRequestBodyConverter.class
import com.fasterxml.jackson.databind.ObjectWriter;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Converter;
final class JacksonRequestBodyConverter<T> implements Converter<T, RequestBody> {
private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8");
private final ObjectWriter adapter;
JacksonRequestBodyConverter(ObjectWriter adapter) {
this.adapter = adapter;
}
#Override public RequestBody convert(T value) throws IOException {
byte[] bytes = adapter.writeValueAsBytes(value);
return RequestBody.create(MEDIA_TYPE, bytes);
}
}
JacksonResponseBodyConverter.class
import com.fasterxml.jackson.databind.ObjectReader;
import java.io.IOException;
import okhttp3.ResponseBody;
import retrofit2.Converter;
final class JacksonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
private final ObjectReader adapter;
JacksonResponseBodyConverter(ObjectReader adapter) {
this.adapter = adapter;
}
#Override public T convert(ResponseBody value) throws IOException {
try {
return adapter.readValue(value.charStream());
} finally {
value.close();
}
}
}
I_Request.interface
import java.util.ArrayList;
import manqaro.com.projectz.ServerSide.Response.TestData;
import manqaro.com.projectz.ServerSide.Response.TestResponse;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
public interface I_Requests {
//PUT HERE YOUR SERVER MAIN ADDRES
String address = "http://goto.xcodes.club";
//SAMPLE EXAMPLE OF POST TYPE , YOU SHOULD CHANGE EVERYTHING YOU WANT.
//IN THIS EXAMPLE YOU WILL GET JSON DATA WHICH WILL BE CONVERTED TO JAVA OBJECT.
#FormUrlEncoded
//Here YOU HAVE TO GIVE ADDRESS TO SPECIFIC CALL
#GET("/api/v1/objects/")
Call<TestResponse<ArrayList<TestData>>> login(
);
#FormUrlEncoded
#POST("/api/v1/objects/")
Call<TestResponse<ArrayList<TestData>>> register(
);
}
TestResponse.class
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Created by ArsenSench on 11/9/2016.
*/
public class TestResponse<T> {
#JsonProperty("status")
public int status;
#JsonProperty("message")
public String message;
#JsonProperty("data")
public T data;
}
TestData.class
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Created by ArsenSench on 11/9/2016.
*/
public class TestData extends {
#JsonProperty("id")
public int id;
#JsonProperty("name")
public String name;
#JsonProperty("description")
public String description;
#JsonProperty("avatar")
public String avatar;
#JsonProperty("rate")
public int rate;
}
ServerCalls.class
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
import java.util.ArrayList;
import manqaro.com.projectz.ServerSide.Application.Tickle_Application;
import manqaro.com.projectz.ServerSide.Response.TestData;
import manqaro.com.projectz.ServerSide.Response.TestResponse;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* Created by ArsenSench on 11/9/2016.
*/
public class ServerCalls {
Context context;
public ServerCalls(Context context){
this.context = context;
}
public void testCallBack(){
Tickle_Application.i().w().login().enqueue(new Callback<TestResponse<ArrayList<TestData>>>() {
#Override
public void onResponse(Call<TestResponse<ArrayList<TestData>>> call, Response<TestResponse<ArrayList<TestData>>> response) {
if(response.code()==200){
if(response.body().status==200){
Toast.makeText(context, response.body().data.get(0).name, Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(context, "No Name", Toast.LENGTH_SHORT).show();
}
}
else{
Toast.makeText(context, "No Connection", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<TestResponse<ArrayList<TestData>>> call, Throwable t) {
Toast.makeText(context, t.getCause().getMessage(), Toast.LENGTH_SHORT).show();
Log.e("jex", "onFailure: " + t.getCause().getMessage() );
}
});
}
}
TestActivity.activity
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import manqaro.com.projectz.R;
import manqaro.com.projectz.ServerSide.Main.ServerCalls;
public class TestActivity extends AppCompatActivity {
ServerCalls sc = new ServerCalls(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
}
public void clickThatShit(View view){
sc.testCallBack();
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="your.package.name">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name=".Application"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:largeHeap="true"
android:supportsRtl="true"
android:theme="#style/AppTheme"
tools:replace="android:icon">
<activity
android:name=".TestActivity">
</activity>
</application>
</manifest>
build.gradle(module app)
Include these dependencies in yourdependencies
compile 'com.squareup.retrofit2:retrofit:2.0.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.2.0'
compile 'com.fasterxml.jackson.core:jackson-databind:2.7.3'
compile 'com.fasterxml.jackson.core:jackson-annotations:2.7.3'
Include this lines in your android{} block
packagingOptions {
exclude 'META-INF/LICENSE'
exclude 'META-INF/NOTICE'
}
I am using kinvey as my backend where I have a collection and would like to fetch data using appData.get. I have tried using the code below but it doesnt work. Could someone please tell me whats wrong with it.
package com.example.kinvey;
import com.kinvey.android.AsyncAppData;
import com.kinvey.android.callback.KinveyListCallback;
import com.kinvey.java.core.KinveyClientCallback;
import android.app.Activity;
import android.content.Entity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
public class ActionData extends Activity{
//protected static final String TAG = "LOG:";
public static final String TAG = "ActionData";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
return super.onCreateOptionsMenu(menu);
}
public void onLoadClick(View view) {
AsyncAppData<Entity> myevents = MainActivity.mKinveyClient.appData("events",Entity.class);
myevents.get(new KinveyListCallback<Entity>() {
#Override
public void onSuccess(Entity[] result) {
Log.v(TAG, "received "+ result.length + " events");
}
#Override
public void onFailure(Throwable error) {
Log.e(TAG, "failed to fetch all", error);
}
});
}
And this is my Entity class.
package com.example.kinvey;
import com.google.api.client.json.GenericJson;
import com.google.api.client.util.Key;
import com.kinvey.java.model.KinveyMetaData;
public class Entity extends GenericJson{
#Key("_id")
private String id;
#Key("_class")
private String _class;
#Key("author")
private String author;
#Key("relatedObj")
private String relatedObj;
#Key("relatedObjName")
private String relatedObjName;
#Key("type")
private String type;
#Key("_kmd")
private KinveyMetaData meta;
#Key("_acl")
private KinveyMetaData.AccessControlList acl;
public Entity(){}
public String getActionId() {
return id;
}
public void setActionId(String id) {
this.id = id;
}
public String getclass() {
return _class;
}
public void setclass(String _class) {
this._class = _class;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getRelatedObj() {
return relatedObj;
}
public void setRelatedObj(String relatedObj) {
this.relatedObj = relatedObj;
}
public String getRelatedObjName() {
return relatedObjName;
}
public void setRelatedObjName(String relatedObjName) {
this.relatedObjName = relatedObjName;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}