getting null value when using getter function in another java class - android

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.

Related

ArrayList cannot be set to model class

I am new to android.I have a JSONArray containing images and other attributes.I am trying to set it into the model class.
MenuContent singleItem = new MenuContent();
singleItem.setContent(mContentJsonObject.getString(AppConstants.APIKeys.CONTENT));
singleItem.setContentId(mContentJsonObject.getString(AppConstants.APIKeys.PARAGRAPH_ID));
singleItem.setChapterId(mContentJsonObject.getString(AppConstants.APIKeys.CHAPTER_ID));
singleItem.setClassId(getSharedPreference(AppConstants.APIKeys.CLASS_ID));
singleItem.setLanguageId(getSharedPreference(AppConstants.APIKeys.LANGUAGE_ID));
JSONArray mGalleryimages = mContentJsonObject.getJSONArray(AppConstants.APIKeys.PARAGRAPH_GALLERY_IMAGES);
for (int k = 0; k < mGalleryimages.length(); k++) {
JSONObject mGallerycontent=mGalleryimages.getJSONObject(k);
ImageGallery imageGallery = new ImageGallery();
imageGallery.setImageId(String.valueOf(k));
imageGallery.setImagePath(mGallerycontent.getString(AppConstants.APIKeys.PARAGRAPH_GALLERY_CONTENT));
array_image.add(imageGallery);
}
singleItem.setImageGallery(array_image);
singleItem.save();
mParagraphsList.add(singleItem);
The problem is I can set all attributes except galleryimages array to the model class.But setImageGallery only is not working.I am getting null there when debugging it.This is MenuContent model class snippet
ArrayList <ImageGallery> imageGallery;
public ArrayList<ImageGallery> getImageGallery() {
return imageGallery;
}
public void setImageGallery(ArrayList<ImageGallery> imageGallery) {
this.imageGallery = imageGallery;
}
ImageGallery model class snippet
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
public String getImagePath() {
return imagePath;
}
Can anyone tell me whats the problem?Any help is appreciated.
This code can be converted to 2 lines with well known Google Gson Library
Have a glance at this.
Type listType = new TypeToken<List<MenuContent>>() {}.getType();
List<MenuContent> yourList = new Gson().fromJson(yourJson, listType);
You dont have to write a long code with parsing with keys.

how to adapt the data from global object to spinner

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());

Parcelable how to use the 'KEY' value when receiving all the information?

I'm making an Android application and I would like to send an ArrayList to the next Activity, but I don't know how to do this with Parcelable.
For example: I got an int named as ID and a String named as Names. I use JSON for getting all informations from PHP and MySQL.
In the for-loop I add all those Names and ID to a class. But then I don't know how to write all these Names and ID into a bundle.putParcelableArrayList(KEY, ArrayList...);, because I don't know how to do this with the KEY value. Do I need to give the KEY value numbers or is there automatically one KEY?
class alleDeelnemers implements Parcelable {
int id;
String name;
/* GETTER AND SETTER */
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeString(volgnummer);
}
public alleDeelnemers(Parcel in) {
volgnummer = in.readString();
id = in.readInt();
}
// Creator
public static final Parcelable.Creator CREATOR
= new Parcelable.Creator() {
public alleDeelnemers createFromParcel(Parcel in) {
return new alleDeelnemers(in);
}
public alleDeelnemers[] newArray(int size) {
return new alleDeelnemers[size];
}
};
}
Receiving data:
ArrayList<alleDeelnemers> deelnemers = new ArrayList<>();
for(int i=0; i < jArrayDeelnemer.length(); i++)
{
JSONObject json_data = jArrayDeelnemer.getJSONObject(i);
//class alleDeelnemers
deelnemer = new alleDeelnemers();
//ID
int ID = json_data.getInt("ID");
deelnemer.setId(ID);
//alle deelnemers
String name = json_data.getString("name ");
deelnemer.setName(name );
//toevoegen in de class
deelnemers.add(deelnemer);
}
error this line: deelnemer = new alleDeelnemers(); need to build a constructor.
The key is any name you would use to reference your ArrayList. Further in the started activity, you will use this key to retrieve the ArrayList. For example, in the initial activity, do
bundle.putParcelableArrayList("MY_ARRAY_LIST", deelnemers);
and then in the started activity, to retrieve it later
Bundle b = getIntent().getExtras();
ArrayList<alleDeelnemers> list = b.getParcelableArrayList("MY_ARRAY_LIST");
Note that the KEY used here is "MY_ARRAY_LIST". It is a better practice to use xml string constants or an interface for storing constant KEYS.
1.First create your alleDeelnemers class as Parcelable using plug-in
2 Sender Activity
Intent intent = new Intent(this, YourActivity.class);
intent.putExtra("mData", myArrayList);
3 Receiver Activity
myArrayList = getIntent().getParcelableExtra("mData")

Time is being changed when passing the intent extra to the Service class

I am trying to pass JSON string to the Service class but I noticed the time is being changed there(in the onHandelIntent method) and I am always getting an old timeStamp. I have cleaned my project but nothing changed.
This part is being called from onLocationChanged method in the inner class "MyLocationListener" in the MainActivity:
public void onLocationChanged(Location location) {
if (location != null) {
double pLong = location.getLongitude();
double pLat = location.getLatitude();
SimpleDateFormat sdf = new SimpleDateFormat(
"dd.MM.yyyy HH:mm:ss", java.util.Locale.getDefault());
String formatted = sdf.format(location.getTime());
// If I pass the data like this it works but I have to add a constructor
// for the class and work with Thread as well as AsyncTask.
// String jSONString = convertToJSON(pLong, pLat, formatted);
// PostData sender = new PostData(jSONString);
// sender.timer();
String jSONString = convertToJSON(pLong, pLat, formatted);
Intent intent3 = new Intent(MainActivity.this, PostData.class);
intent3.putExtra("json_data", jSONString);
// Here I am getting the right timeStamp.
startService(intent3);
}
convertToJSON method:
private String convertToJSON(double pLong, double pLat, String formatted) {
//envelop the data in JSON format.
Data d = new Data(pLat, pLong, formatted,route_number);
Gson gson = new GsonBuilder().registerTypeAdapter(Data.class, new DataSerializer()).create();
String a = gson.toJson(d);
return a;
}
PostData class:
public class PostData extends IntentService {
public PostData() {
super("some");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
#Override
protected void onHandleIntent(Intent intent) {
String jSONString = intent.getStringExtra("json_data"); //here I am always getting this time "18:37:49"
}
}
The passed JSON string in the onHandelIntent():
{
"latitude":47.86907815,
"longitude":13.66554789,
"formatted":"23.04.2015 18:37:49",
"route":4
}

How to save Object (includes Array) in Preferences?

How to save Object in Preferences which looks like this:
public class ToDoList {
public String name;
public String date;
public ArrayList<Product> products = new ArrayList<Product>();
public boolean isChecked;
}
and then loads its values?
You could do it with serialization. Serialization of an object is a short unique String format of an object that can be serialized. Particularly almost every object can be serialized in java except from the View object. You won't have any problem in your case.
How to do it:
You should make class ToDoList implement Serializable and all classes that are used inside your object, ex Product. String, boolean ArrayList are serializable so you don't have to do anything.
When implementing serialization in an object you have to supply a serial version UID which would be then used to serialize.
So ToDoList would be something like:
public class ToDoList implelements Serializable {
private static final long serialVersionUID = //generate random by eclipse
.....
public ArrayList<Product> products = new ArrayList<Product>();
}
and Product:
public class Product implelements Serializable {
private static final long serialVersionUID = //generate random by eclipse
.....
}
then include this static helper class:
public class ObjectSerializeDeserialize {
public static String ObjectSerialization(Object obj)
{
ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
try
{
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArray);
objectOutputStream.writeObject(obj);
objectOutputStream.close();
}
catch (Exception e) {
e.printStackTrace();
return "";
}
return new String(Base64.encode(byteArray.toByteArray(), 0));
}
public static Object ObjectDeserialization(String str)
{
byte[] byteArray = Base64.decode(str,0);
Object o;
try
{
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(byteArray));
o = ois.readObject();
ois.close();
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
return o;
}
}
and simply use the following code:
String todolistSer = ObjectSerializeDeserialize.ObjectSerialization(todolistObj);
the above line of code will return an empty String if something goes wrong and will print the detailed message in the log cat.
Then simply save the todolistSer as a String in preferences and reclaim your object like this:
ToDoList todolistObj = (ToDoList) ObjectSerializeDeserialize.ObjectDeserialization(todolistString);
suppress any warnings that are issued by the above method and you are done!
P.S. you can use the above solution whenever you have complicated structures that can not be saved as raw variables and you still don't want to use a database
Preferences are simple key ,value pairs. In your case better use SQLite.

Categories

Resources