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;
}
}
Related
Please I don't understand the error.java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY at line 1 column 28 path $.message retrofit android studio Please I need your help
package com.sensei.linkrestaurant;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.material.navigation.NavigationView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.firebase.auth.FirebaseAuth;
import com.sensei.linkrestaurant.Adapter.MyRestaurantAdapter;
import com.sensei.linkrestaurant.Adapter.RestaurantSliderAdapter;
import com.sensei.linkrestaurant.Common.Common;
import com.sensei.linkrestaurant.Model.EventBus.RestaurantLoadEvent;
import com.sensei.linkrestaurant.Model.Restaurant;
import com.sensei.linkrestaurant.Retrofit.ILinkRestaurantAPI;
import com.sensei.linkrestaurant.Retrofit.RetrofitClient;
import com.sensei.linkrestaurant.Service.PicassoImageLoadingService;
import com.sensei.linkrestaurant.databinding.ActivityHomeBinding;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import butterknife.BindView;
import butterknife.ButterKnife;
import dmax.dialog.SpotsDialog;
import io.paperdb.Paper;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers;
import ss.com.bannerslider.Slider;
public class HomeActivity extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener{
private static final String TAG = "HomeActivity";
private AppBarConfiguration mAppBarConfiguration;
private ActivityHomeBinding binding;
TextView txt_user_name, txt_user_phone;
#BindView(R.id.banner_slider)
Slider banner_slider;
#BindView(R.id.recycler_restaurant)
RecyclerView recyclerView;
private ILinkRestaurantAPI iLinkRestaurantAPI;
private final CompositeDisposable compositeDisposable = new CompositeDisposable();
private AlertDialog dialog;
#Override
protected void onDestroy() {
compositeDisposable.clear();
super.onDestroy();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityHomeBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
setSupportActionBar(binding.appBarHome.toolbar);
DrawerLayout drawer = binding.drawerLayout;
NavigationView navigationView = binding.navView;
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow)
.setOpenableLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this,
R.id.nav_host_fragment_content_link_main2);
NavigationUI.setupActionBarWithNavController(this, navController,
mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
View headerView = navigationView.getHeaderView(0);
txt_user_name = headerView.findViewById(R.id.txt_user_name);
txt_user_phone = headerView.findViewById(R.id.txt_user_phone);
txt_user_name.setText(Common.currentUser.getName());
txt_user_phone.setText(Common.currentUser.getUserPhone());
navigationView.setNavigationItemSelectedListener(this);
init();
initView();
loadRestaurant();
}
private void init() {
dialog = new SpotsDialog.Builder().setContext(this).setCancelable(false).build();
iLinkRestaurantAPI = RetrofitClient
.getInstance(Common.API_RESTAURANT_ENDPOINT).create(ILinkRestaurantAPI.class);
Slider.init(new PicassoImageLoadingService());
}
private void initView() {
ButterKnife.bind(this);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.addItemDecoration(new DividerItemDecoration(this,
layoutManager.getOrientation()));
}
private void loadRestaurant() {
dialog.show();
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", Common.buildJWT(Common.API_KEY));
compositeDisposable.add(
iLinkRestaurantAPI.getRestaurant(headers)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(restaurantModel -> {
//Event bus to send local even to set adapter and slider
EventBus.getDefault().post(new RestaurantLoadEvent(true,
restaurantModel.getResult()));
dialog.dismiss();
},
throwable ->{
dialog.dismiss();
EventBus.getDefault().post(new RestaurantLoadEvent(false,
throwable.getMessage()));
Toast.makeText(this, "[GET RESTAURANT]"+throwable.getMessage(),
Toast.LENGTH_SHORT).show();
})
);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this,
R.id.nav_host_fragment_content_link_main2);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_log_out){
signOut();
} else if (id == R.id.nav_nearby){
startActivity(new Intent(HomeActivity.this, NearbyRestaurantActivity.class));
} else if(id == R.id.order_history){
startActivity(new Intent(HomeActivity.this, ViewOrderActivity.class));
} else if(id == R.id.update_information){
startActivity(new Intent(HomeActivity.this, UpdateInfoActivity.class));
}else if (id == R.id.nav_fav){
startActivity(new Intent(HomeActivity.this, FavoriteActivity.class));
}
return true;
}
private void signOut() {
AlertDialog confirmExit = new AlertDialog.Builder(this)
.setTitle("Sign Out")
.setMessage("Do you really want to Sign Out")
.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Common.currentUser = null;
Common.currentRestaurant = null;
FirebaseAuth.getInstance().signOut();
Intent intent = new Intent(HomeActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
}).create();
confirmExit.show();
}
//Register Event Bus
#Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
#Override
public void onStop() {
EventBus.getDefault().unregister(this);
super.onStop();
}
//Listen Event Bus
#Subscribe(threadMode = ThreadMode.MAIN)
public void processRestaurantLoadEvent(RestaurantLoadEvent event) {
if (event.isSuccess()){
displayBanner(event.getRestaurantList());
displayRestaurant(event.getRestaurantList());
}else{
Toast.makeText(this, "[RESTAURANT LOAD]" + event.getMessage(),
Toast.LENGTH_LONG).show();
}
dialog.dismiss();
}
private void displayRestaurant(List<Restaurant> restaurantList) {
MyRestaurantAdapter adapter = new MyRestaurantAdapter(this, restaurantList);
recyclerView.setAdapter(adapter);
}
private void displayBanner(List<Restaurant> restaurantList) {
banner_slider.setAdapter(new RestaurantSliderAdapter(restaurantList));
}
}
This is the Handles the loadEvent
package com.sensei.linkrestaurant.Model.EventBus;
import com.sensei.linkrestaurant.Model.Restaurant;
import java.util.List;
public class RestaurantLoadEvent {
private boolean success;
private String message;
private List<Restaurant> restaurantList;
public RestaurantLoadEvent() {
}
public RestaurantLoadEvent(boolean success, String message) {
this.success = success;
this.message = message;
}
public RestaurantLoadEvent(boolean success, List<Restaurant> restaurantList) {
this.success = success;
this.restaurantList = restaurantList;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<Restaurant> getRestaurantList() {
return restaurantList;
}
public void setRestaurantList(List<Restaurant> restaurantList) {
this.restaurantList = restaurantList;
}
}
This is the Restaurant Class
package com.sensei.linkrestaurant.Model;
public class Restaurant {
//Remember all variable names has to be exactly as Json property return from API
//That will help Gson to parse it correctly
private int id;
private String name;
private String address;
private String phone;
private Float lat;
private Float lng;
private int userOwner;
private String image;
private String paymentUrl;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Float getLat() {
return lat;
}
public void setLat(Float lat) {
this.lat = lat;
}
public Float getLng() {
return lng;
}
public void setLng(Float lng) {
this.lng = lng;
}
public int getUserOwner() {
return userOwner;
}
public void setUserOwner(int userOwner) {
this.userOwner = userOwner;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getPaymentUrl() {
return paymentUrl;
}
public void setPaymentUrl(String paymentUrl) {
this.paymentUrl = paymentUrl;
}
}
This is the Retrofit client for the ILinkRestaurantAPI
#GET("restaurant")
Observable<RestaurantModel> getRestaurant(#HeaderMap Map<String, String> headers);
This is the Restaurant model
package com.sensei.linkrestaurant.Model;
import java.util.List;
public class RestaurantModel {
private boolean success;
private String message;
private List<Restaurant> result;
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<Restaurant> getResult() {
return result;
}
public void setResult(List<Restaurant> result) {
this.result = result;
}
}
I think you must change Observable to Observable<RestaurantModel[]>
or in anather place you have strign but API give array, check API response and compare with your model (use for example tool Postman)
try and give response if help
[EDIT]
try private String message[];
[EDIT2]
in API message it's not String it's Array of object
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.
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!
I want to receive the value of the variable Id from the listItem clicked and to pass it in the other activity.But I am not receiving anything in the variable.
Here is the attached code :
MainActivity.java
package com.example.hp.citysearchapp;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.view.menu.ExpandedMenuView;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private List<City> cityList = new ArrayList<City>();
private ListView listView;
private static String url;
ImageView searchIcon;
String idGet;
String edittextSearch;
TextInputLayout searchLayout;
EditText search;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.city_listView);
searchLayout=(TextInputLayout)findViewById(R.id.input_layout_search);
search=(EditText)findViewById(R.id.input_search);
searchIcon=(ImageView)findViewById(R.id.imageView);
adapter = new CustomListAdapter(this,cityList);
searchIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
edittextSearch=search.getText().toString();
Log.d("hello2", search.getText().toString());
adapter.notifyDataSetChanged();
url = "http://test.maheshwari.org/services/testwebservice.asmx/SuggestCity?tryValue="+edittextSearch;
parsingMethod();
}
});
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this,CityDetailsActivity.class);
City city = cityList.get(position);
idGet=city.getId();
Log.d("dfjdkfj", idGet); //Not receiving anything ,here is the problem
intent.putExtra("gettingId",idGet);
startActivity(intent);
}
});
}
private void parsingMethod() {
Log.d("hello", url);
pDialog = new ProgressDialog(this);
// Showing progress dialog
pDialog.setMessage("Loading...");
pDialog.show();
// Creating volley request obj
JsonArrayRequest cityReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
hidePDialog();
// Parsing json
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = null;
try {
obj = jsonArray.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
City city = new City();
try {
city.setId(obj.getString("Id"));
city.setTitle(obj.getString("Title"));
city.setDescription(obj.getString("Description"));
city.setExv1(obj.getString("ExtraValue1"));
Log.d("hello",obj.getString("ExtraValue1"));
city.setExv2(obj.getString("ExtraValue2"));
city.setExv3(obj.getString("ExtraValue3"));
city.setExv4(obj.getString("ExtraValue4"));
city.setExv5(obj.getString("ExtraValue5"));
city.setExv6(obj.getString("ExtraValue6"));
city.setExv7(obj.getString("ExtraValue7"));
city.setExv8(obj.getString("ExtraValue8"));
city.setExv9(obj.getString("ExtraValue9"));
cityList.add(city);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse (VolleyError error){
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(cityReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
City.java
package com.example.hp.citysearchapp;
/**
* Created by hp on 22-03-2016.
*/
public class City {
String title,description,exv1,exv3,exv6,id,exv2,exv4,exv5,exv9,exv7,exv8;
public City(String title, String description, String id, String exv1, String exv3, String exv6,
String exv2, String exv4 , String exv5 , String exv7 , String exv8 , String exv9) {
this.title = title;
this.description=description;
this.id=id;
this.exv1=exv1;
this.exv2=exv2;
this.exv3=exv3;
this.exv4=exv4;
this.exv5=exv5;
this.exv6=exv6;
this.exv7=exv7;
this.exv8=exv8;
this.exv9=exv9;
}
public City() {
}
public String getId() {
return id;
}
public String getExv2() {
return exv2;
}
public String getExv4() {
return exv4;
}
public String getExv5() {
return exv5;
}
public String getExv7() {
return exv7;
}
public String getExv8() {
return exv8;
}
public String getExv9() {
return exv9;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public String getExv1() {
return exv1;
}
public String getExv3() {
return exv3;
}
public String getExv6() {
return exv6;
}
public void setId(String id) {
this.id = id;
}
public void setExv2(String exv2) {
this.exv2 = exv2;
}
public void setExv4(String exv4) {
this.exv4 = exv4;
}
public void setExv5(String exv5) {
this.exv5 = exv5;
}
public void setExv7(String exv7) {
this.exv7 = exv7;
}
public void setExv8(String exv8) {
this.exv8 = exv8;
}
public void setExv9(String exv9) {
this.exv9 = exv9;
}
public void setTitle(String title) {
this.title = title;
}
public void setDescription(String description) {
this.description = description;
}
public void setExv1(String exv1) {
this.exv1 = exv1;
}
public void setExv3(String exv3) {
this.exv3 = exv3;
}
public void setExv6(String exv6) {
this.exv6 = exv6;
}
}
Please modify your code a bit to achieve this --
You already have --
City city = cityList.get(position);
Now add this line to get Id from the ListItem clicked --
String Id = city.getExv3(); //Use one of your actual Getter methods accordingly.
Hope this helps!
Since I'm using a CustomAdapter for my list , I have to use the following code :
TextView textView = (TextView)view.findViewById(R.id.id); /*(R.id.id) is the id of the textview */
String gettingID=textView.getText().toString();
I need to pass an arraylist which contains object with a string and arraylist. I am unable to pass the arraylist to other activity. In the Activity1 the list contains value that I have verified.
DepositBn:
package support;
import android.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
public class DepositBn implements Parcelable {
private String limit;
#SerializedName("period")
private ArrayList<Rate> rateList;
protected DepositBn(Parcel in) {
limit = in.readString();
}
public String getLimit() {
return limit;
}
public void setLimit(String limit) {
this.limit = limit;
}
public ArrayList<Rate> getRateList() {
return rateList;
}
public void setRateList(ArrayList<Rate> rateList) {
this.rateList = rateList;
}
public class Rate {
private String rate;
public String getRate() {
return rate;
}
public void setRate(String rate) {
this.rate = rate;
}
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(limit);
}
public static final Creator<DepositBn> CREATOR = new Creator<DepositBn>() {
#Override
public DepositBn createFromParcel(Parcel in) {
return new DepositBn(in);
}
#Override
public DepositBn[] newArray(int size) {
return new DepositBn[size];
}
};
}
In the Activity1:
#Override
protected void onPostExecute(ArrayList<DepositBn> result) {
super.onPostExecute(result);
System.out.println("result = " + result);
for (DepositBn depositBn : result) {
System.out.println("----" + depositBn.getLimit());
}
try {
Intent intent = new Intent(DepositRates.this, GenericRateDisplay.class);
Resources res = DepositRates.this.getResources();
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("depositBnArrayList",result);
bundle.putString("pageName", res.getString(R.string.domesticRates));
intent.putExtras(bundle);
startActivity(intent);
} catch (Exception ex) {
ex.printStackTrace();
}
}
In Activity2:
package in.co.sbm.sbmvirtual;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import support.DepositBn;
public class GenericRateDisplay extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_generic_rate_display);
Bundle b = this.getIntent().getExtras();
ArrayList<DepositBn> depositBnArrayList = b.getParcelableArrayList("depositBnArrayList");
//String pageName = b.getString("pageName");
ArrayList<String> rateList = new ArrayList();
for (DepositBn depositBn : depositBnArrayList) {
for(DepositBn.Rate rate : depositBn.getRateList()){
rateList.add(rate.toString());
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(GenericRateDisplay.this,
android.R.layout.simple_list_item_1, rateList);
ListView listView = (ListView) findViewById(R.id.genericListView);
listView.setAdapter(adapter);
}
}
I have fixed it. I have used inner class as well which I did not serialize hence I was unable to use putSerializable. I have serialized both the outer and inner class and used intent.putSerializable.