I have my GlobalClass extends Application class. I want to bind the global object data to spinner. Here is my GlobalClass
public class GlobalClass extends Application {
private List<ProjectType> projectTypes;
public List<ProjectType> getProjectTypes() {
return projectTypes;
}
public void setProjectTypes(List<ProjectType> projectTypes) {
this.projectTypes = projectTypes;
}
}
Pojo class
public class ProjectType implements Serializable {
private Integer projectTypeId;
private String typeName;
private Integer peckOrder;
//getter and setter here
And I get the response from the server using volley and parse using GSON and set the response to GlobalClass
here the code
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, getString(R.string.TEST_projectTypeURL), null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
final GlobalClass globalVariable = (GlobalClass) getApplicationContext();
Gson gson = new Gson();
List<ProjectType> projectTypes = gson.fromJson(String.valueOf(response),List.class);
globalVariable.setProjectTypes(projectTypes);
}
}
And finally in another activity class iam using spinner to bind the data from the GlobalClass object
globalVariable = (GlobalClass) getApplicationContext();
List<String> projectTypeList = new ArrayList<>();
ArrayList<ProjectType> projectTypesCollection = new ArrayList<ProjectType>(globalVariable.getProjectTypes());
for (ProjectType projectType: projectTypesCollection) {
projectTypeList.add(projectType.getTypeName());
}
prjtTypeSpinner = (Spinner)findViewById(R.id.spn_prjt_type);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item,projectTypeList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
prjtTypeSpinner.setAdapter(dataAdapter);
While trying the above code I am getting an error "com.google.gson.internal.LinkedTreeMap cannot be cast to the pojo.ProjectType class"
here the object return value,
[{projectTypeId=3.0, typeName=ALS, peckOrder=220.0}, {projectTypeId=2.0, typeName=ALB, peckOrder=210.0}, {projectTypeId=1.0, typeName=CL, peckOrder=200.0}, {projectTypeId=7.0, typeName=ACG, peckOrder=40.0}, {projectTypeId=6.0, typeName=ACS, peckOrder=30.0}, {projectTypeId=5.0, typeName=ACB, peckOrder=20.0}, {projectTypeId=4.0, typeName=CC, peckOrder=10.0}]
I want the typeName in spinner. Thanks in advance.
I finally solve this problem,
Arrays.asList(gson.fromJson(response, ProjectType[].class))
when I try the code my error get resolved, this code work well
I think you have problem with this codes
List<ProjectType> projectTypes = gson.fromJson(String.valueOf(response),List.class);
you need to change to:
List<ProjectType> projectTypes = gson.fromJson(new Gson().toJson(response),new TypeToken<List<ProjectType>>() {
}.getType());
Related
I would like to display movie titles from themoviedb.org. But the applications is not displaying anything in the ListView. Here is my code:
try{
JsonObjectRequest request = new JSonObjectRequest(Request.Method.Get,url,null,new Response.Listener<JSONObject>(){
#Override
public void onResponse(JSONObject response){
try{
JSONArray titlesArray =response.getJSONArray("results");
for(int i=0;i<titlesArray.length();i++){`
JSONObject inner = titlesArray.getJSONObject(i);
String id=inner.getString("id");
String title =inner.getString("title");
String c= id+title;
arrayListMovies=new ArrayListMovies<>();
arrayListMovies.add(c);
}
RequestQueue requestQueue=Volley.newRequestQueue(this);
requestQueue.add(request);
And I am setting the arrayadapter to movieList ListView outside of the Volley function
moviesList = findViewById(R.id.listViewForMovies);
ArrayAdapter<String> adapter =new ArrayAdapter<String>(getApplicationContext(),android.R.layout.android_simple_list_item1,arrayListMovies);
moviesList.setAdapter(adapter);
Thanks.
I would not recommend make REST API calls the way you are doing, this is prone to errors, I recommend you to check about retrofit:
https://square.github.io/retrofit/
You have various problems with your code:
You are creating the adapter and assigning data before the call to the API completes.
You are creating the string list on every iteration of your titlesArray
You are not notifying the adapter that the list have changed.
Dont use a try block inside your response, because if there is errors with your code, it will be useful that the app crashes in order to get notified about this errors.
public class Test extends AppCompatActivity {
private ArrayAdapter<String> myAdapter;
private ArrayList<String> arrayListMovies = new ArrayList<>();
#Override
public void onCreate(#Nullable Bundle savedInstanceState, #Nullable PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
this.myAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.android_simple_list_item1, arrayListMovies);
this.makeRequest();
}
public void makeRequest() {
try {
JsonObjectRequest request = new JSonObjectRequest(Request.Method.Get, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONArray titlesArray = response.getJSONArray("results");
arrayListMovies = new ArrayList<>();
for (int i = 0; i < titlesArray.length(); i++) {
JSONObject inner = titlesArray.getJSONObject(i);
String id = inner.getString("id");
String title = inner.getString("title");
String c = id + title;
arrayListMovies.add(c);
}
myAdapter.notifyDataSetChanged();
RequestQueue requestQueue = Volley.newRequestQueue(this);
}
}
}
}
}
Note some things: I have moved the adapter and arrayListMovies declarations to the top of the class.
I initialize the adapter before making the api call.
In the response of the network call I create the arrayListMovies ONCE.
At the end i call myAdapter.notifyDataSetChanged(); to refresh the adapter data.
I have a fragment that calls a helper class in order to make a jsonRequest with Volley.
Upon response, the helper class creates a custom object, but in order to set it up, it needs to check some values stored in Shared Preferences.
The problem is that I can't access getSharedPreferences inside the helper class.
public class MyDataHandler {
ArrayList<MyItem> itemsArrayList = new ArrayList<>();
public List<MyItem> getAll(Boolean completed, String current, final MyAsyncResponse callBack) {
String url = "https://my.api/" + current;
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
Request.Method.GET,
url,
null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
MyItem myItem = new MyItem();
if (!completed) {
SharedPreferences sharedPreferences = getSharedPreferences("MyApp", MODE_PRIVATE); // this doesn't work
if (sharedPreferences.getBoolean("someKey", false)) {
// set properties in MyItem
}
}
itemsArrayList.add(myItem);
} catch (JSONException e) {
e.printStackTrace();
}
}
if (null != callBack) callBack.processFinished(itemsArrayList);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
AppController.getInstance().addToRequestQueue(jsonArrayRequest);
return itemsArrayList;
}
How can I access Shared Preferences if this class isn't attached to any particular activity?
I assume that you are instantiating MyDataBaseHandler as "getAll" is a non static function
create a constructor and a member variable like this :-
MyDataBaseHandler{
Context context;
public MyDataHandler(Context context){ //pass your activity here
this.context=context;
}
// write rest of your code
}
now you can use this context member variable and access your shared perefrence using context.getSharedPreference("MyApp", Context.MODE_PRIVATE).
In my application, I want to bind Json response to a target class using Volley library, But am not able to do that.
My Code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerComponentDownload(GalleryParser.class, Const.api.URL_GALLERY);
}//on create
private void makeJsonObjectRequest(final Class<? extends BaseModel> className, String urlJsonArry) {
JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.GET,urlJsonArry,null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//start gallery activity
}
} , new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
}
private void registerComponentDownload(Class<? extends BaseModel> aClass, String url) {
makeJsonObjectRequest(aClass,Const.buildUrl(url));
}
}
Is it possible to get response in class? Or am trying in wrong direction.
Please suggest me.
Thank you.
I think you can refer to this using volley with gson library to make a Gson request
https://developer.android.com/training/volley/request-custom.html
Add Gson Library in you lib folder .
this is class formate
public class TestData {
public int success;
public String message;
public TestDatail data;
public class TestDatail
{
public int is_friend;
public int is_following;
}
}
Gson gs=new Gson();
return gs.fromJson(your Volley Library Response,TestData.class);
Method 1:Using Bundle object-->
In my case i'm passing an array from Activity A to Activity B something like this:
public void onResponse(JSONObject response)
{
ArrayList<Images> imagesArrayList = new ArrayList<Images>();
try{
if(response.has("images"))
{
JSONArray imagesList = response.getJSONArray("images");
Intent i = newIntent(ActivityA.this,ActivityB.class);
i.putExtra("jsonArray",imagesList.toString());
startActivity(i);
}
}catch(JSONException e){}
}
And in Activity B's onCreate method check for the that passed bundle something like this:
Intent i = getIntent();
if (i.hasExtra("jsonArray"))
{
String jsonArray = i.getStringExtra("jsonArray");
try {
JSONArray array = new JSONArray(jsonArray);
// do whatever you need with this array
} catch (JSONException e) {
e.printStackTrace();
}
}
Method 2: Using pojo/getters & setter
Create a pojo
Extract the required data once you receive the response using volley.
set it using setters of pojo.
start gallery activity.
get the data using getters of pojo.
I have a MainActivity in which i am getting data from server and i want to set the data using setters and getter. I am using setter function to set the value in Mainactivity. the data is accessed properly if i use it MainActivity. i have another java class AlarmReceiver. I want to access the value which is set in the MainActiviy. But i am not getting any value here in Another class.
Here is my MainActivity
JSONArray arr = new JSONArray(strServerResponse);
JSONObject jsonObj = arr.getJSONObject(0);
String DataStatus = jsonObj.getString("status");
System.out.println(DataStatus);
if (DataStatus.equalsIgnoreCase("true")) {
JSONArray arr1 = new JSONArray(strServerResponse);
JSONObject jsonObj1 = arr.getJSONObject(0);
pojo = new Pojo();
empid = jsonObj1.optString("empid");
pojo.setId(empid);
And this is AlarmReceiver
#Override
public void onReceive(Context context, Intent intent) {
gps = new GPSTracker(context);
Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show();
File root = Environment.getExternalStorageDirectory();
gpxfile = new File(root, "mydata.csv");
startService();
}
private void startService() {
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
strDate = sdf.format(c.getTime());
pojo=new Pojo();
String id=pojo.getId();
And these are setter getters
public class Pojo {
public static String empid11;
public void setId(String empid) {
this.empid11 = empid;
Log.e("empidd setter",""+empid);
}
public String getId() {
Log.e("empidd getter",""+empid11);
return empid11;
}
}
But I am getting null value in the AlarmReceiver. Ho to get this value?
Your pojo is a new Pojo. You need to pass the same object to which the Id was saved.
Pojo pojo =new Pojo(); //global declaration
setting value to pojo
empid = jsonObj1.optString("empid");
pojo.setId(empid);
and in your startService() method,remove new Instance of Pojo,i.e remove new Pojo();
private void startService() {
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
strDate = sdf.format(c.getTime());
String id=pojo.getId();
You can create your getter setter like this :
public void setMethod (String string)
{
this.string= string;
}
// getting the ArrayList value
public static String getMethod()
{
return string;
}
You can use your getmethod name by using yourclassname.getMethod().
I m not sure how and when you AlarmReceiver is getting executed. So for a solution you can make the pojo instance in MainActivity public static i.e.
public static Pojo pojo = null;
Initialize this instance as you are currently doing :-
pojo = new Pojo();
empid = jsonObj1.optString("empid");
pojo.setId(empid);
Inside your AlarmReceiver startService() method you can use this as
if (MainActivity.pojo != null){
String id=pojo.getId();
}
Remove all local instances/variables of POJO class inside AlarmReceiver class.
Though this approach is not advisable.
To find a proper solution, I suggest you to take a closer look on the differences between an object, instance and classes in Java.
some recommended links are:
Source1
Source2
Additionally you can check out static classes and singletons.
I am trying to deserialize this JSON array into my android project.
[{"Name":"Ban","Price":1},{"Name":"Banana","Price":1},{"Name":"chicken","Price":14},{"Name":"pizza","Price":16},{"Name":"slice","Price":1}]
I have made this webservice in Asp.net.
The code I am using to deserialize it is below
public void onClick(View v)
{
String url="http://192.168.15.2/MyAndroid/InputCaller.aspx"; //do not use localhost
String response=callWebService(url);
List<Items> mObjectList = new ArrayList<Items>() ;
ItemsList list = null;
Gson gson = new Gson();
list = gson.fromJson(response, ItemsList.class);
// list = getItemsList(response);
Intent myIntent = new Intent(v.getContext(), Cart.class);
startActivity(myIntent);
}
public final ItemsList getItemsList (String jsonString)
{
ItemsList il = null;
Gson gson = new Gson();
il = gson.fromJson(jsonString, ItemsList.class);
return il;
}
public class ItemsList
{
private List<ItemsContainer> items = new ArrayList<ItemsContainer>();
public List<ItemsContainer> getItemsContainerList()
{
return items;
}
}
class ItemsContainer
{
Items items;
public Items getItem()
{
return items;
}
}
public class Items
{
String Name;
int Price;
}
It is not working and when I try to debug it I get this message on list = gson.fromJson(response, ItemsList.class);
Gson.class Source not found.
This is my first deserialisation program and I would really appreciate if anybody help me with it. Thank you,
Don't make things complicated by using further parent classes (as container) for Items class. Simply de-serialize all the items into a List object using Gson as below:
List<Items> listItems = (List<Items>) gson.fromJson(response,
new TypeToken<List<Items>>(){}.getType());
now you've got all the Items in a List object: listItems