I am writing an android app that uses a bundle to pass data between activities. I made an Answers.java class to get the data from the bundle. When I try to get the data I receive an error Illegal Self-Reference. I get the error on
Answers a = a.getQuestion1_1();
Here is my activity code
package www.iup.edu.iupcrimsurvey;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Thank_You_MainActivity extends AppCompatActivity {
Answers a = a.getQuestion1_1();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_thank__you__main);
// Sets an onClickListener to the button and calls the launchNextScreenActivity() method
final Button btn = (Button) findViewById(R.id.Next_Screen15);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
launchNextScreenActivity();
}
});
// Sets an onClickListener to the button and calls the launchNextScreenActivity() method
final Button btn2 = (Button) findViewById(R.id.Close);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
launchFinishActivity();
}
});
}
// Switches to the StartScreen_Activity screen
private void launchNextScreenActivity() {
Intent intent = new Intent(this, StartScreen_MainActivity.class);
startActivity(intent);
}
// Closes the app
private void launchFinishActivity() {
}
}
My Answers.java file
package www.iup.edu.iupcrimsurvey;
public class Answers {
private int question1_1 = StartScreen_MainActivity.MyAppsBundle.getInt("Demographics_question1");
private String question1_2 = StartScreen_MainActivity.MyAppsBundle.getString("Demographics_question2");
private String question1_3 = StartScreen_MainActivity.MyAppsBundle.getString("Demographics_question3");
private String question1_4 = StartScreen_MainActivity.MyAppsBundle.getString("Demographics_question4");
private String question1_5 = StartScreen_MainActivity.MyAppsBundle.getString("Demographics_question5");
private String question1_6 = StartScreen_MainActivity.MyAppsBundle.getString("Demographics_question6");
private String question1_7= StartScreen_MainActivity.MyAppsBundle.getString("Demographics_question7");
private String question2_1 = StartScreen_MainActivity.MyAppsBundle.getString("housing_question1");
private int question2_2 = StartScreen_MainActivity.MyAppsBundle.getInt("housing_question2");
private String question2_3 = StartScreen_MainActivity.MyAppsBundle.getString("housing_question3");
private String question2_4 = StartScreen_MainActivity.MyAppsBundle.getString("housing_question4");
private String question3_1 = StartScreen_MainActivity.MyAppsBundle.getString("Sexuality_question1");
private String question3_2 = StartScreen_MainActivity.MyAppsBundle.getString("Sexuality_question2");
private String question3_3 = StartScreen_MainActivity.MyAppsBundle.getString("Sexuality_question3");
private String question3_4 = StartScreen_MainActivity.MyAppsBundle.getString("Sexuality_question4");
private String question3_5 = StartScreen_MainActivity.MyAppsBundle.getString("Sexuality_question5");
private String question4_1 = StartScreen_MainActivity.MyAppsBundle.getString("Alcohol_question1");
private String question4_2 = StartScreen_MainActivity.MyAppsBundle.getString("Alcohol_question2");
private String question4_3 = StartScreen_MainActivity.MyAppsBundle.getString("Alcohol_question3");
private String question4_4 = StartScreen_MainActivity.MyAppsBundle.getString("Alcohol_question4");
private String question4_5 = StartScreen_MainActivity.MyAppsBundle.getString("Alcohol_question5");
private String question5_1 = StartScreen_MainActivity.MyAppsBundle.getString("Travel_question1");
private String question5_2 = StartScreen_MainActivity.MyAppsBundle.getString("Travel_question2");
private String question5_3 = StartScreen_MainActivity.MyAppsBundle.getString("Travel_question3");
private String question5_4 = StartScreen_MainActivity.MyAppsBundle.getString("Travel_question4");
private String question5_5 = StartScreen_MainActivity.MyAppsBundle.getString("Travel_question5");
private String question6_1 = StartScreen_MainActivity.MyAppsBundle.getString("Work_question1");
private String question6_2 = StartScreen_MainActivity.MyAppsBundle.getString("Work_question2");
private String question6_3 = StartScreen_MainActivity.MyAppsBundle.getString("Work_question3");
private String question6_4 = StartScreen_MainActivity.MyAppsBundle.getString("Work_question4");
private String question6_5 = StartScreen_MainActivity.MyAppsBundle.getString("Work_question5");
private String question7_1 = StartScreen_MainActivity.MyAppsBundle.getString("Crime_question1");
private String question8_1 = StartScreen_MainActivity.MyAppsBundle.getString("Crime_Committed_question1");
private String question8_2 = StartScreen_MainActivity.MyAppsBundle.getString("Crime_Committed_question2");
private String question10_1 = StartScreen_MainActivity.MyAppsBundle.getString("Incident_question1");
private String question10_2 = StartScreen_MainActivity.MyAppsBundle.getString("Incident_question2");
private String question10_3 = StartScreen_MainActivity.MyAppsBundle.getString("Incident_question3");
private String question10_4 = StartScreen_MainActivity.MyAppsBundle.getString("Incident_question4");
private String question10_5 = StartScreen_MainActivity.MyAppsBundle.getString("Incident_question5");
private String question10_6 = StartScreen_MainActivity.MyAppsBundle.getString("Incident_question6");
private String question10_7 = StartScreen_MainActivity.MyAppsBundle.getString("Incident_question7");
private String question10_8 = StartScreen_MainActivity.MyAppsBundle.getString("Incident_question8");
private String question10_9 = StartScreen_MainActivity.MyAppsBundle.getString("Incident_question9");
private String question10_10 = StartScreen_MainActivity.MyAppsBundle.getString("Incident_question10");
public int getQuestion1_1() {
return question1_1;
}
public void setQuestion1_1(int question1_1) {
this.question1_1 = question1_1;
}
public String getQuestion1_2() {
return question1_2;
}
public void setQuestion1_2(String question1_2) {
this.question1_2 = question1_2;
}
public String getQuestion1_3() {
return question1_3;
}
public void setQuestion1_3(String question1_3) {
this.question1_3 = question1_3;
}
public String getQuestion1_4() {
return question1_4;
}
public void setQuestion1_4(String question1_4) {
this.question1_4 = question1_4;
}
public String getQuestion1_5() {
return question1_5;
}
public void setQuestion1_5(String question1_5) {
this.question1_5 = question1_5;
}
public String getQuestion1_6() {
return question1_6;
}
public void setQuestion1_6(String question1_6) {
this.question1_6 = question1_6;
}
public String getQuestion1_7() {
return question1_7;
}
public void setQuestion1_7(String question1_7) {
this.question1_7 = question1_7;
}
public String getQuestion2_1() {
return question2_1;
}
public void setQuestion2_1(String question2_1) {
this.question2_1 = question2_1;
}
public int getQuestion2_2() {
return question2_2;
}
public void setQuestion2_2(int question2_2) {
this.question2_2 = question2_2;
}
public String getQuestion2_3() {
return question2_3;
}
public void setQuestion2_3(String question2_3) {
this.question2_3 = question2_3;
}
public String getQuestion2_4() {
return question2_4;
}
public void setQuestion2_4(String question2_4) {
this.question2_4 = question2_4;
}
public String getQuestion3_1() {
return question3_1;
}
public void setQuestion3_1(String question3_1) {
this.question3_1 = question3_1;
}
public String getQuestion3_2() {
return question3_2;
}
public void setQuestion3_2(String question3_2) {
this.question3_2 = question3_2;
}
public String getQuestion3_3() {
return question3_3;
}
public void setQuestion3_3(String question3_3) {
this.question3_3 = question3_3;
}
public String getQuestion3_4() {
return question3_4;
}
public void setQuestion3_4(String question3_4) {
this.question3_4 = question3_4;
}
public String getQuestion3_5() {
return question3_5;
}
public void setQuestion3_5(String question3_5) {
this.question3_5 = question3_5;
}
public String getQuestion4_1() {
return question4_1;
}
public void setQuestion4_1(String question4_1) {
this.question4_1 = question4_1;
}
public String getQuestion4_2() {
return question4_2;
}
public void setQuestion4_2(String question4_2) {
this.question4_2 = question4_2;
}
public String getQuestion4_3() {
return question4_3;
}
public void setQuestion4_3(String question4_3) {
this.question4_3 = question4_3;
}
public String getQuestion4_4() {
return question4_4;
}
public void setQuestion4_4(String question4_4) {
this.question4_4 = question4_4;
}
public String getQuestion4_5() {
return question4_5;
}
public void setQuestion4_5(String question4_5) {
this.question4_5 = question4_5;
}
public String getQuestion5_1() {
return question5_1;
}
public void setQuestion5_1(String question5_1) {
this.question5_1 = question5_1;
}
public String getQuestion5_2() {
return question5_2;
}
public void setQuestion5_2(String question5_2) {
this.question5_2 = question5_2;
}
public String getQuestion5_3() {
return question5_3;
}
public void setQuestion5_3(String question5_3) {
this.question5_3 = question5_3;
}
public String getQuestion5_4() {
return question5_4;
}
public void setQuestion5_4(String question5_4) {
this.question5_4 = question5_4;
}
public String getQuestion5_5() {
return question5_5;
}
public void setQuestion5_5(String question5_5) {
this.question5_5 = question5_5;
}
public String getQuestion6_1() {
return question6_1;
}
public void setQuestion6_1(String question6_1) {
this.question6_1 = question6_1;
}
public String getQuestion6_2() {
return question6_2;
}
public void setQuestion6_2(String question6_2) {
this.question6_2 = question6_2;
}
public String getQuestion6_3() {
return question6_3;
}
public void setQuestion6_3(String question6_3) {
this.question6_3 = question6_3;
}
public String getQuestion6_4() {
return question6_4;
}
public void setQuestion6_4(String question6_4) {
this.question6_4 = question6_4;
}
public String getQuestion6_5() {
return question6_5;
}
public void setQuestion6_5(String question6_5) {
this.question6_5 = question6_5;
}
public String getQuestion7_1() {
return question7_1;
}
public void setQuestion7_1(String question7_1) {
this.question7_1 = question7_1;
}
public String getQuestion8_1() {
return question8_1;
}
public void setQuestion8_1(String question8_1) {
this.question8_1 = question8_1;
}
public String getQuestion8_2() {
return question8_2;
}
public void setQuestion8_2(String question8_2) {
this.question8_2 = question8_2;
}
public String getQuestion10_1() {
return question10_1;
}
public void setQuestion10_1(String question10_1) {
this.question10_1 = question10_1;
}
public String getQuestion10_2() {
return question10_2;
}
public void setQuestion10_2(String question10_2) {
this.question10_2 = question10_2;
}
public String getQuestion10_3() {
return question10_3;
}
public void setQuestion10_3(String question10_3) {
this.question10_3 = question10_3;
}
public String getQuestion10_4() {
return question10_4;
}
public void setQuestion10_4(String question10_4) {
this.question10_4 = question10_4;
}
public String getQuestion10_5() {
return question10_5;
}
public void setQuestion10_5(String question10_5) {
this.question10_5 = question10_5;
}
public String getQuestion10_6() {
return question10_6;
}
public void setQuestion10_6(String question10_6) {
this.question10_6 = question10_6;
}
public String getQuestion10_7() {
return question10_7;
}
public void setQuestion10_7(String question10_7) {
this.question10_7 = question10_7;
}
public String getQuestion10_8() {
return question10_8;
}
public void setQuestion10_8(String question10_8) {
this.question10_8 = question10_8;
}
public String getQuestion10_9() {
return question10_9;
}
public void setQuestion10_9(String question10_9) {
this.question10_9 = question10_9;
}
public String getQuestion10_10() {
return question10_10;
}
public void setQuestion10_10(String question10_10) {
this.question10_10 = question10_10;
}
public String getQuestion11_1() {
return question11_1;
}
public void setQuestion11_1(String question11_1) {
this.question11_1 = question11_1;
}
public String getQuestion11_2() {
return question11_2;
}
public void setQuestion11_2(String question11_2) {
this.question11_2 = question11_2;
}
public String getQuestion11_3() {
return question11_3;
}
public void setQuestion11_3(String question11_3) {
this.question11_3 = question11_3;
}
public String getQuestion11_4() {
return question11_4;
}
public void setQuestion11_4(String question11_4) {
this.question11_4 = question11_4;
}
public String getQuestion11_5() {
return question11_5;
}
public void setQuestion11_5(String question11_5) {
this.question11_5 = question11_5;
}
public String getQuestion11_6() {
return question11_6;
}
public void setQuestion11_6(String question11_6) {
this.question11_6 = question11_6;
}
public String getQuestion11_7() {
return question11_7;
}
public void setQuestion11_7(String question11_7) {
this.question11_7 = question11_7;
}
public String getQuestion11_8() {
return question11_8;
}
public void setQuestion11_8(String question11_8) {
this.question11_8 = question11_8;
}
public String getQuestion11_9() {
return question11_9;
}
public void setQuestion11_9(String question11_9) {
this.question11_9 = question11_9;
}
public String getQuestion11_10() {
return question11_10;
}
public void setQuestion11_10(String question11_10) {
this.question11_10 = question11_10;
}
private String question11_1 = StartScreen_MainActivity.MyAppsBundle.getString("Relationship_question1");
private String question11_2 = StartScreen_MainActivity.MyAppsBundle.getString("Relationship_question2");
private String question11_3 = StartScreen_MainActivity.MyAppsBundle.getString("Relationship_question3");
private String question11_4 = StartScreen_MainActivity.MyAppsBundle.getString("Relationship_question4");
private String question11_5 = StartScreen_MainActivity.MyAppsBundle.getString("Relationship_question5");
private String question11_6 = StartScreen_MainActivity.MyAppsBundle.getString("Relationship_question6");
private String question11_7 = StartScreen_MainActivity.MyAppsBundle.getString("Relationship_question7");
private String question11_8 = StartScreen_MainActivity.MyAppsBundle.getString("Relationship_question8");
private String question11_9 = StartScreen_MainActivity.MyAppsBundle.getString("Relationship_question9");
private String question11_10 = StartScreen_MainActivity.MyAppsBundle.getString("Relationship_question10");
}
The way you are trying to call is wrong.
Please follow this:
Create the Object of the Answer class
> public class Thank_You_MainActivity extends AppCompatActivity {
Answer a;//Create an object
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_thank__you__main);
a = new Ans();//define it
String aa = a.getGetQuestion1_1(); then use it anywhere
Hope this will help you
Related
I have tough problem with my project. Its hard to explain. I have two different model but, I should compare these two model. Should I make a new model for this two models?
Here is Cart.java. There is Voyage.java as a Model. This class differentiate if type_voyage not equals each other. I have another model named Bus.java. I should compare if it equals together with model.
Cart.java
boolean cartContainsDifferentTypeVoyage(final String type_voyage) {
ArrayList<Voyage> list = Lists.newArrayList(Collections2.filter(voyages, new Predicate<Voyage>() {
#Override
public boolean apply(Voyage voyage) {
return !voyage.getType_voyage().equals(type_voyage);
}
}));
return list.size() > 0 ? true : false;
}
Bus.java
public class Bus {
private static Bus instance;
private String BROADCAST_TAG = "com.bss.hepsi.bus";
public int hotel_counter = 5;
public int car_counter = 5;
private String logo_link;
private String voyage_code;
private String from_port;
private String from_port_label;
private String from_city;
private String to_port;
private String to_port_label;
private String to_city;
private String company_name;
private boolean has_transfer;
private String telephone_number;
Calendar departureTime = Calendar.getInstance();
private Calendar arrivalTime = Calendar.getInstance();
long departure_time;
long arrival_time;
float price;
ArrayList<Leg> legs = new ArrayList<>();
public ArrayList<BusPassenger> busPasengers = new ArrayList<>();
int direction = MyConstants.DIRECTION_GOING;
private String type_bus;
private boolean has_return;
private Calendar selected_date;
private String goingDate;
private String returnDate;
private Context context;
public boolean in_Cart = false;
public String type;
private String passengerNumber;
boolean isExpanded;
boolean isShowProgress;
public Bus() {
}
public static synchronized Bus getInstance() {
if (instance == null) {
instance = new Bus();
}
instance.setPassengerNumber(ResultActivity.passengerNumber);
instance.setFrom_city(ResultActivity.fromCity);
instance.setTo_city(ResultActivity.toCity);
instance.setGoingDate(ResultActivity.strGoingDate);
instance.setReturnDate(ResultActivity.strReturnDate);
instance.setHas_return(ResultActivity.hasReturn);
return instance;
}
public String getPassengerNumber() {
return passengerNumber;
}
public void setPassengerNumber(String passengerNumber) {
this.passengerNumber = passengerNumber;
}
public boolean isExpanded() {
return this.isExpanded;
}
public void setExpanded(boolean expanded) {
this.isExpanded = expanded;
}
public boolean isShowProgress() {
return this.isShowProgress;
}
public void setShowProgress(boolean showProgress) {
this.isShowProgress = showProgress;
}
public static synchronized void clearInstance() {
instance = null;
}
public String getCompany_name() {
return company_name;
}
public void setCompany_name(String company_name) {
this.company_name = company_name;
}
public String getFrom_port() {
return from_port;
}
public void setFrom_port(String from_port) {
this.from_port = from_port;
}
public String getTo_port() {
return to_port;
}
public void setTo_port(String to_port) {
this.to_port = to_port;
}
public Calendar getSelected_date() {
return selected_date;
}
public void setSelected_date(Calendar selected_date) {
this.selected_date = selected_date;
}
public String getFrom_city() {
return from_city;
}
public void setFrom_city(String from_city) {
this.from_city = from_city;
}
public String getTo_city() {
return to_city;
}
public void setTo_city(String to_city) {
this.to_city = to_city;
}
public String getLogo_link() {
return logo_link;
}
public void setLogo_link(String logo_link) {
this.logo_link = logo_link;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public String getTelephone_number() {
return telephone_number;
}
public void setTelephone_number(String telephone_number) {
this.telephone_number = telephone_number;
}
public String getVoyage_code() {
return voyage_code;
}
public void setVoyage_code(String voyage_code) {
this.voyage_code = voyage_code;
}
public String getFrom_port_label() {
return from_port_label;
}
public void setFrom_port_label(String from_port_label) {
this.from_port_label = from_port_label;
}
public String getTo_port_label() {
return to_port_label;
}
public void setTo_port_label(String to_port_label) {
this.to_port_label = to_port_label;
}
public Boolean getHas_transfer() {
return has_transfer;
}
public void setHas_transfer(Boolean has_transfer) {
this.has_transfer = has_transfer;
}
public Calendar getDepartureTime() {
return departureTime;
}
public void setDepartureTime(long departure_time_in_milliseconds) {
this.departureTime.setTimeInMillis(departure_time_in_milliseconds);
}
public Calendar getArrivalTime() {
return arrivalTime;
}
public void setArrivalTime(long return_time_in_milliseconds) {
this.arrivalTime.setTimeInMillis(return_time_in_milliseconds);
}
public int getDirection() {
return direction;
}
public void setDirection(int direction) {
this.direction = direction;
}
public String getGoingDate() {
return goingDate;
}
public void setGoingDate(String goingDate) {
this.goingDate = goingDate;
}
public String getReturnDate() {
return returnDate;
}
public void setReturnDate(String returnDate) {
this.returnDate = returnDate;
}
public boolean getHas_return() {
return has_return;
}
public void setHas_return(boolean has_return) {
this.has_return = has_return;
}
public ArrayList<Leg> getLegs() {
return legs;
}
public void setLegs(ArrayList<Leg> legs) {
this.legs = legs;
}
public long getDeparture_time() {
return departure_time;
}
public void setDeparture_time(long departure_time) {
this.departure_time = departure_time;
}
public long getArrival_time() {
return arrival_time;
}
public void setArrival_time(long arrival_time) {
this.arrival_time = arrival_time;
}
public String getType_bus() {
return type_bus;
}
public void setType_voyage(String type_bus) {
this.type_bus = type_bus;
}
private void sendRequest(final String owner, final Map<String, String> header) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, MyConstants.URL + owner,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject object = new JSONObject(response);
if (object.getString(MyConstants.SERVICE_STATUS).equals(MyConstants.SERVICE_RESPONSE_STATUS_NOTAVAILABLE)) {
sendVoyagesErrorBroadcast(owner, MyConstants.ERROR_NOTAVAILABLE);
} else if (object.getString(MyConstants.SERVICE_STATUS).equals(MyConstants.SERVICE_RESPONSE_STATUS_SUCCESS)) {
JSONArray result = object.getJSONArray(MyConstants.SERVICE_RESULT);
if (result.length()>0) {
JSONArray resultGoing = result.getJSONObject(0).getJSONArray("going");
sendVoyagesArrayBroadcast(owner + MyConstants.DIRECTION_GOING, resultGoing);
}
if (has_return) {
if (result.length() > 1) {
JSONArray resultReturn = result.getJSONObject(1).getJSONArray("round");
if (resultReturn.length()<1){
busReturnIsEmpty();}
else{
busReturnIsNotEmpty();
}
sendVoyagesArrayBroadcast(owner + MyConstants.DIRECTION_RETURN, resultReturn);
}
}
} else if (object.getString(MyConstants.SERVICE_STATUS).equals(MyConstants.SERVICE_RESPONSE_STATUS_FAILURE)) {
sendVoyagesErrorBroadcast(owner, MyConstants.ERROR_SERVER);
}
} catch (JSONException e) {
}
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
sendVoyagesErrorBroadcast(owner, getErrorType(error));
}
}) {
#Override
public Map<String, String> getHeaders() {
return header;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(600 * 1000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MySingleton.getInstance(context).addToRequestQueue(stringRequest);
}
private void sendVoyagesArrayBroadcast(String target, JSONArray resultArray) {
Intent intent = new Intent();
intent.setAction(BROADCAST_TAG + target);
intent.putExtra("data", resultArray.toString());
context.sendBroadcast(intent);
}
public static Bus setJsonToClass(JSONObject jsonObject, int direction, String owner) {
Bus bus = new Gson().fromJson(String.valueOf(jsonObject), Bus.class);
bus.setDirection(direction);
bus.setType_voyage(owner);
bus.setDepartureTime(bus.departure_time);
bus.setArrivalTime(bus.arrival_time);
for (Leg leg :
bus.legs) {
leg.setDepartureTime(leg.departure_time);
leg.setArrivalTime(leg.arrival_time);
}
bus.type = owner;
return bus;
}
Voyage.java
public class Voyage {
private static Voyage instance;
//private static String url="http://78.186.57.167:3000/";
//private static String url="http://10.0.0.27:1337/";
/////public static final String BROADCAST_TAG = "com.bss.hepsi.voyage"; ///bunu kaldırdım static oldugu için
private String BROADCAST_TAG = "com.bss.hepsi.voyage"; ///onun yerine bunu koydum
//private static String url="http://185.122.203.104:3002/";
// private static String url="http://10.0.0.25:1337/";
public int checkCart; // Result activity'de veri gelip gelmediğini kontrol edip kullanıcıyı uyarmak için
public int hotel_counter = 5;
public int car_counter = 5;
private String logo_link;
private String voyage_code;
private String from_port;
private String from_port_label;
private String from_city;
private String to_port;
private String to_port_label;
private String to_city;
private String company_name;
private boolean has_transfer;
private String telephone_number;
Calendar departureTime = Calendar.getInstance();
private Calendar arrivalTime = Calendar.getInstance();
long departure_time;
long arrival_time;
float price;
ArrayList<Leg> legs = new ArrayList<>();
public ArrayList<FlightPassenger> flightPassengers = new ArrayList<>();
int direction = MyConstants.DIRECTION_GOING;
private String type_voyage;
private boolean has_return;
private Calendar selected_date;
private String goingDate;
private String returnDate;
private Context context;
public boolean in_Cart = false;
public String type;
private String passengerNumber;
public Voyage() {
}
public static synchronized Voyage getInstance() {
if (instance == null) {
instance = new Voyage();
}
instance.setPassengerNumber(ResultActivity.passengerNumber);
instance.setFrom_city(ResultActivity.fromCity);
instance.setTo_city(ResultActivity.toCity);
instance.setGoingDate(ResultActivity.strGoingDate);
instance.setReturnDate(ResultActivity.strReturnDate);
instance.setHas_return(ResultActivity.hasReturn);
return instance;
}
public String getPassengerNumber() {
return passengerNumber;
}
public void setPassengerNumber(String passengerNumber) {
this.passengerNumber = passengerNumber;
}
public static synchronized void clearInstance() {
instance = null;
}
public String getCompany_name() {
return company_name;
}
public void setCompany_name(String company_name) {
this.company_name = company_name;
}
public String getFrom_port() {
return from_port;
}
public void setFrom_port(String from_port) {
this.from_port = from_port;
}
public String getTo_port() {
return to_port;
}
public void setTo_port(String to_port) {
this.to_port = to_port;
}
/*public static String getUrl() {
return url;
}*/
public Calendar getSelected_date() {
return selected_date;
}
public void setSelected_date(Calendar selected_date) {
this.selected_date = selected_date;
}
public String getFrom_city() {
return from_city;
}
public void setFrom_city(String from_city) {
this.from_city = from_city;
}
public String getTo_city() {
return to_city;
}
public void setTo_city(String to_city) {
this.to_city = to_city;
}
public String getLogo_link() {
return logo_link;
}
public void setLogo_link(String logo_link) {
this.logo_link = logo_link;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public String getTelephone_number() {
return telephone_number;
}
public void setTelephone_number(String telephone_number) {
this.telephone_number = telephone_number;
}
public String getVoyage_code() {
return voyage_code;
}
public void setVoyage_code(String voyage_code) {
this.voyage_code = voyage_code;
}
public String getFrom_port_label() {
return from_port_label;
}
public void setFrom_port_label(String from_port_label) {
this.from_port_label = from_port_label;
}
public String getTo_port_label() {
return to_port_label;
}
public void setTo_port_label(String to_port_label) {
this.to_port_label = to_port_label;
}
public Boolean getHas_transfer() {
return has_transfer;
}
public void setHas_transfer(Boolean has_transfer) {
this.has_transfer = has_transfer;
}
public Calendar getDepartureTime() {
return departureTime;
}
public void setDepartureTime(long departure_time_in_milliseconds) {
this.departureTime.setTimeInMillis(departure_time_in_milliseconds);
}
public Calendar getArrivalTime() {
return arrivalTime;
}
public void setArrivalTime(long return_time_in_milliseconds) {
this.arrivalTime.setTimeInMillis(return_time_in_milliseconds);
}
public int getDirection() {
return direction;
}
public void setDirection(int direction) {
this.direction = direction;
}
public String getGoingDate() {
return goingDate;
}
public void setGoingDate(String goingDate) {
this.goingDate = goingDate;
}
public String getReturnDate() {
return returnDate;
}
public void setReturnDate(String returnDate) {
this.returnDate = returnDate;
}
public boolean getHas_return() {
return has_return;
}
public void setHas_return(boolean has_return) {
this.has_return = has_return;
}
public ArrayList<Leg> getLegs() {
return legs;
}
public void setLegs(ArrayList<Leg> legs) {
this.legs = legs;
}
public long getDeparture_time() {
return departure_time;
}
public void setDeparture_time(long departure_time) {
this.departure_time = departure_time;
}
public long getArrival_time() {
return arrival_time;
}
public void setArrival_time(long arrival_time) {
this.arrival_time = arrival_time;
}
public String getType_voyage() {
return type_voyage;
}
public void setType_voyage(String type_voyage) {
this.type_voyage = type_voyage;
}
public void searchFlightVoyages(Context context) {
this.context = context;
cancelRequest("flight/search", context);
Map<String, String> header = prepareVoyageSearchHeaderForFlight();
sendRequest("flight/search", header);
}
public void searchTrainVoyages(Context context) {
this.context = context;
cancelRequest("train/search", context);
Map<String, String> header = prepareVoyageSearchHeader();
sendRequest("train/search", header);
}
public void searchBoatVoyages(Context context) {
this.context = context;
cancelRequest("seaway/boat/search", context);
Map<String, String> header = prepareVoyageSearchHeader();
sendRequest("seaway/boat/search", header);
}
public void searchFerryVoyages(Context context) {
this.context = context;
cancelRequest("seaway/ferry/search", context);
Map<String, String> header = prepareVoyageSearchHeader();
sendRequest("seaway/ferry/search", header);
}
private void sendRequest(final String owner, final Map<String, String> header) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, MyConstants.URL + owner,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("AAAA" + owner, response);
try {
JSONObject object = new JSONObject(response);
if (object.getString(MyConstants.SERVICE_STATUS).equals(MyConstants.SERVICE_RESPONSE_STATUS_NOTAVAILABLE)) {
// servisten gelen cevap not_available ise
//// owner
sendVoyagesErrorBroadcast(owner, MyConstants.ERROR_NOTAVAILABLE);
} else if (object.getString(MyConstants.SERVICE_STATUS).equals(MyConstants.SERVICE_RESPONSE_STATUS_SUCCESS)) {
// servisten gösterilebilecek bir sonuç geldiyse
JSONArray result = object.getJSONArray(MyConstants.SERVICE_RESULT);
if (result.length()>0) {
// checkCart=0;
// sendCheckCart();
JSONArray resultGoing = result.getJSONObject(0).getJSONArray("going");
sendVoyagesArrayBroadcast(owner + MyConstants.DIRECTION_GOING, resultGoing);
}
if (has_return) {
if (result.length() > 1) {
JSONArray resultReturn = result.getJSONObject(1).getJSONArray("round");
sendVoyagesArrayBroadcast(owner + MyConstants.DIRECTION_RETURN, resultReturn);
}
}
} else if (object.getString(MyConstants.SERVICE_STATUS).equals(MyConstants.SERVICE_RESPONSE_STATUS_FAILURE)) {
sendVoyagesErrorBroadcast(owner, MyConstants.ERROR_SERVER);
}
} catch (JSONException e) {
Log.e("search" + owner + "VoyagesErr1", e.toString());
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("AAAA" + owner, String.valueOf(error.getCause()));
sendVoyagesErrorBroadcast(owner, getErrorType(error));
}
}) {
#Override
public Map<String, String> getHeaders() {
return header;
}
};
stringRequest.setTag(owner);
stringRequest.setRetryPolicy(new DefaultRetryPolicy(60 * 1000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MySingleton.getInstance(context).addToRequestQueue(stringRequest);
}
public static Voyage setJsonToClass(JSONObject jsonObject, int direction, String owner) {
//Log.e("jsonobj", String.valueOf(jsonObject));
Voyage voyage = new Gson().fromJson(String.valueOf(jsonObject), Voyage.class);
voyage.setDirection(direction);
voyage.setType_voyage(owner);
voyage.setDepartureTime(voyage.departure_time);
voyage.setArrivalTime(voyage.arrival_time);
for (Leg leg :
voyage.legs) {
leg.setDepartureTime(leg.departure_time);
leg.setArrivalTime(leg.arrival_time);
}
voyage.type = owner;
return voyage;
}
When you remove all the code from your question that is superfluous, it makes the problem more obvious.
First I simplified your comparison method:
Cart.java
boolean cartContainsDifferentTypeVoyage(final String type_voyage) {
for(Voyage voyage : voyages) {
if(!type_voyage.equals(voyage.getType_voyage()) {
return true;
}
}
}
Then created an interface
interface Voyage {
String getType_voyage();
}
Bus.java
public class Bus implements Voyage {
...
private String type_voyage;
#Override
public String getType_voyage() {
return type_voyage;
}
...
}
And changed Voyage.java to Ferry.java
public class Ferry implements Voyage {
...
private String type_voyage;
...
#Override
public String getType_voyage() {
return type_voyage;
}
...
}
You may want to look at creating some more classes so that your 'model' classes are not doing to much / have so many responsibilities.
Interface:
public interface BabService {
#GET("bab.php")
Call<Respon> tampil(#Query("imam") String imam);
}
Respon:
public class Respon {
private String value;
private List<BabResult> resultBab;
public String getValue() {
return value;
}
public List<BabResult> getResultBab() { return resultBab; }
}
Result:
public class BabResult {
private String id_bab;
private String id_kitab;
private String bab;
public String getId_bab() { return id_bab; }
public String getId_kitab() {
return id_kitab;
}
public String getBab() {
return bab;
}
}
Adapter:
public class BabAdapter extends RecyclerView.Adapter<BabAdapter.ViewHolder>
{
private Context context;
private List<BabResult> results;
private String idBab, judulBab;
private int no;
public BabAdapter(Context context, List<BabResult> results) {
this.context = context;
this.results = results;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_bab, parent, false);
ViewHolder holder = new ViewHolder(v);
return holder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
if(position % 2 != 0){
holder.vBab.setBackgroundResource(R.color.ijo);
}else{
holder.vBab.setBackgroundResource(R.color.oren);
}
no = position + 1;
BabResult result = results.get(position);
idBab = result.getId_bab();
judulBab = result.getBab();
holder.tvNo.setText(no);
holder.tvBab.setText(judulBab);
}
#Override
public int getItemCount() {
if(results == null){
return 4;
}
return results.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private View vBab;
private TextView tvBab, tvNo;
public ViewHolder(View itemView) {
super(itemView);
vBab = (View) itemView.findViewById(R.id.v_bab);
tvNo = (TextView) itemView.findViewById(R.id.tv_no);
tvBab = (TextView) itemView.findViewById(R.id.tv_bab);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(context, HadisList.class);
i.putExtra("id", idBab);
i.putExtra("bab", judulBab);
i.putExtra("no", no);
context.startActivity(i);
}
});
}
}
}
Activity:
public class MenuBab extends AppCompatActivity {
public static final String URL = "http://mi3bpolinema.000webhostapp.com/";
private List<BabResult> results = new ArrayList<>();
private BabAdapter babAdapter;
private ProgressBar pbLoading;
private RecyclerView rvBab;
private TextView tvImam;
private String imam, namaImam;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_bab);
if(getSupportActionBar() != null){
getSupportActionBar().hide();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
Intent intent = getIntent();
if(intent != null){
if(intent.getStringExtra("imam") != null){
imam = intent.getStringExtra("imam");
namaImam = intent.getStringExtra("nama");
}
}
pbLoading = (ProgressBar) findViewById(R.id.pb_loading);
rvBab = (RecyclerView) findViewById(R.id.rv_bab);
tvImam = (TextView) findViewById(R.id.tv_imam);
tvImam.setText(namaImam);
babAdapter = new BabAdapter(this, results);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
rvBab.setLayoutManager(mLayoutManager);
rvBab.setItemAnimator(new DefaultItemAnimator());
rvBab.setAdapter(babAdapter);
loadDataBab();
}
#Override
protected void onResume() {
super.onResume();
loadDataBab();
}
private void loadDataBab() {
Retrofit retrofit = new Retrofit
.Builder()
.baseUrl(URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
BabService api = retrofit.create(BabService.class);
Call<Respon> call = api.tampil(imam);
call.enqueue(new Callback<Respon>() {
#Override
public void onResponse(Call<Respon> call, Response<Respon> response) {
String value = response.body().getValue();
pbLoading.setVisibility(View.GONE);
if (value.equals("1")) {
results = response.body().getResultBab();
babAdapter = new BabAdapter(MenuBab.this, results);
rvBab.setAdapter(babAdapter);
}
}
#Override
public void onFailure(Call<Respon> call, Throwable t) {
}
});
}
}
On retrofit get result null, but when I run in website get result like this:
{"value":1,"result":[{"id_bab":"4","id_kitab":"1","bab":"Wudhu"},
{"id_bab":"8","id_kitab":"1","bab":"Shalat"},
{"id_bab":"15","id_kitab":"1","bab":"Puasa"}]}
using this link.
You need to use Model class in this way
now you can get API Result
Response Model Class
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.util.ArrayList;
public class Response implements Serializable{
#SerializedName("value")
private String value;
#SerializedName("result")
private ArrayList<BabResult> resultBab;
public String getValue() {
return value;
}
public ArrayList<BabResult> getResultBab() {
return resultBab;
}
public void setValue(String value) {
this.value = value;
}
public void setResultBab(ArrayList<BabResult> resultBab) {
this.resultBab = resultBab;
}
public class BabResult {
#SerializedName("id_bab")
private String id_bab;
#SerializedName("id_kitab")
private String id_kitab;
#SerializedName("bab")
private String bab;
public String getId_bab() {
return id_bab;
}
public void setId_bab(String id_bab) {
this.id_bab = id_bab;
}
public String getId_kitab() {
return id_kitab;
}
public void setId_kitab(String id_kitab) {
this.id_kitab = id_kitab;
}
public String getBab() {
return bab;
}
public void setBab(String bab) {
this.bab = bab;
}
}
}
Respon class
public class Respon
{
private ArrayList<Result> result;
private String value;
public ArrayList<Result> getResult ()
{
return result;
}
public void setResult ( ArrayList<Result> result)
{
this.result = result;
}
public String getValue ()
{
return value;
}
public void setValue (String value)
{
this.value = value;
}
#Override
public String toString()
{
return "ClassPojo [result = "+result+", value = "+value+"]";
}
public class Result
{
private String id_kitab;
private String bab;
private String id_bab;
public String getId_kitab ()
{
return id_kitab;
}
public void setId_kitab (String id_kitab)
{
this.id_kitab = id_kitab;
}
public String getBab ()
{
return bab;
}
public void setBab (String bab)
{
this.bab = bab;
}
public String getId_bab ()
{
return id_bab;
}
public void setId_bab (String id_bab)
{
this.id_bab = id_bab;
}
#Override
public String toString()
{
return "ClassPojo [id_kitab = "+id_kitab+", bab = "+bab+", id_bab =
"+id_bab+"]";
}
}
}
Check this way data null or not and add arraylist
private void loadDataBab() {
Retrofit retrofit = new Retrofit
.Builder()
.baseUrl(URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
BabService api = retrofit.create(BabService.class);
Call<Respon> call = api.tampil(imam);
call.enqueue(new Callback<Respon>() {
#Override
public void onResponse(Call<Respon> call, Response<Respon> response) {
if (response.isSuccessful())
if (response.body() != null)
pbLoading.setVisibility(View.GONE);
if (response.body().getValue().equalsIgnoreCase("1")) {
results.addAll(response.body().getResult());
babAdapter = new BabAdapter(MenuBab.this, results);
rvBab.setAdapter(babAdapter);
}
}
#Override
public void onFailure(Call<Respon> call, Throwable t) {
}
});
}
Pass the array in your Respon class like this ..
public class Respon {
private String value;
private BabResult [] result;
public String getValue() {
return value;
}
public BabResult [] getResultBab() { return result; }
}
and in your loadDataBab method ..
private List<BabResult> results = new ArrayList<>();
private void loadDataBab() {
Retrofit retrofit = new Retrofit
.Builder()
.baseUrl(URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
RequestInterface api = retrofit.create(RequestInterface.class);
Call<Respon> call = api.tampil("1");
call.enqueue(new Callback<Respon>() {
#Override
public void onResponse(Call<Respon> call, Response<Respon> response) {
String value = response.body().getValue();
if (value.equals("1")) {
results = new ArrayList<>(Arrays.asList(response.body().getResultBab()));
}
}
#Override
public void onFailure(Call<Respon> call, Throwable t) {
}
});
}
I change Respon to :
public class Respon {
private String value;
private List<BabResult> result;
public String getValue() { return value; }
public List<BabResult> getResult() { return result; }
}
and it works. Thx :))
Please i need help , i am new to android so i need help . i need to receive data from JSON and i watched a loot of tutorials and i cant find my answer . I need to receive data from JSON link . once i do it i get a loot of errors and also the compilator gives me a lot of errors . Here is my code :
my custom adapter called CustomItemAdapter.java
package com.example.madrit.okhttp_gson_view;
import android.content.Context;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class CustomItemAdapter extends ArrayAdapter <model_item> {
public CustomItemAdapter(Context context , List<model_item> mymodel)
{
super(context , 0 , mymodel);
}
#Nullable
#Override
public model_item getItem(int position) {
return super.getItem(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
model_item model = getItem(position);
if (convertView==null){
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_shop_list, parent, false);
}
TextView title = (TextView) convertView.findViewById(R.id.item_onthelist_title);
TextView price = (TextView) convertView.findViewById(R.id.item_onthelist_price);
TextView description = (TextView) convertView.findViewById(R.id.item_onthelist_description);
title.setText(model.getName());
price.setText(Double.toString(model.getPrice()));
description.setText(model.getMeta_description());
return convertView;
}
}
my model item model_item.java
package com.example.madrit.okhttp_gson_view;
import com.google.gson.annotations.SerializedName;
import java.util.List;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class model_item {
private String id_product;
private String id_supplier;
private String id_manufacturer;
private String id_category_default;
private String id_shop_default;
private String id_tax_rules_group;
private String on_sale;
private String online_only;
private String ean13;
private String upc;
private String ecotax;
private int quantity;
private String minimal_quantity;
private double price;
private String wholesale_price;
private String unity;
private String unit_price_ratio;
private String additional_shipping_cost;
private String reference;
private String supplier_reference;
private String location;
private String width;
private String height;
private String depth;
private String weight;
private String out_of_stock;
private String quantity_discount;
private String customizable;
private String uploadable_files;
private String text_fields;
private String active;
private String redirect_type;
private String id_product_redirected;
private String available_for_order;
private String available_date;
private String condition;
private String show_price;
private String indexed;
private String visibility;
private String cache_is_pack;
private String cache_has_attachments;
private String is_virtual;
private String cache_default_attribute;
private String date_add;
private String date_upd;
private String advanced_stock_management;
private String pack_stock_type;
private String id_shop;
private int id_product_attribute;
private String product_attribute_minimal_quantity;
private String description;
private String description_short;
private String available_now;
private String available_later;
private String link_rewrite;
private String meta_description;
private String meta_keywords;
private String meta_title;
private String name;
private String id_image;
private String legend;
private String manufacturer_name;
private String category_default;
#SerializedName("new")
private String newX;
private String orderprice;
private int allow_oosp;
private String category;
private String link;
private int attribute_price;
private double price_tax_exc;
private double price_without_reduction;
private int reduction;
private boolean specific_prices;
private int quantity_all_versions;
private int virtual;
private int pack;
private int nopackprice;
private boolean customization_required;
private int rate;
private String tax_name;
private String image_url;
private List<?> features;
private List<?> attachments;
private List<?> packItems;
public String getId_product() {
return id_product;
}
public void setId_product(String id_product) {
this.id_product = id_product;
}
public String getId_supplier() {
return id_supplier;
}
public void setId_supplier(String id_supplier) {
this.id_supplier = id_supplier;
}
public String getId_manufacturer() {
return id_manufacturer;
}
public void setId_manufacturer(String id_manufacturer) {
this.id_manufacturer = id_manufacturer;
}
public String getId_category_default() {
return id_category_default;
}
public void setId_category_default(String id_category_default) {
this.id_category_default = id_category_default;
}
public String getId_shop_default() {
return id_shop_default;
}
public void setId_shop_default(String id_shop_default) {
this.id_shop_default = id_shop_default;
}
public String getId_tax_rules_group() {
return id_tax_rules_group;
}
public void setId_tax_rules_group(String id_tax_rules_group) {
this.id_tax_rules_group = id_tax_rules_group;
}
public String getOn_sale() {
return on_sale;
}
public void setOn_sale(String on_sale) {
this.on_sale = on_sale;
}
public String getOnline_only() {
return online_only;
}
public void setOnline_only(String online_only) {
this.online_only = online_only;
}
public String getEan13() {
return ean13;
}
public void setEan13(String ean13) {
this.ean13 = ean13;
}
public String getUpc() {
return upc;
}
public void setUpc(String upc) {
this.upc = upc;
}
public String getEcotax() {
return ecotax;
}
public void setEcotax(String ecotax) {
this.ecotax = ecotax;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public String getMinimal_quantity() {
return minimal_quantity;
}
public void setMinimal_quantity(String minimal_quantity) {
this.minimal_quantity = minimal_quantity;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getWholesale_price() {
return wholesale_price;
}
public void setWholesale_price(String wholesale_price) {
this.wholesale_price = wholesale_price;
}
public String getUnity() {
return unity;
}
public void setUnity(String unity) {
this.unity = unity;
}
public String getUnit_price_ratio() {
return unit_price_ratio;
}
public void setUnit_price_ratio(String unit_price_ratio) {
this.unit_price_ratio = unit_price_ratio;
}
public String getAdditional_shipping_cost() {
return additional_shipping_cost;
}
public void setAdditional_shipping_cost(String additional_shipping_cost) {
this.additional_shipping_cost = additional_shipping_cost;
}
public String getReference() {
return reference;
}
public void setReference(String reference) {
this.reference = reference;
}
public String getSupplier_reference() {
return supplier_reference;
}
public void setSupplier_reference(String supplier_reference) {
this.supplier_reference = supplier_reference;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getWidth() {
return width;
}
public void setWidth(String width) {
this.width = width;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public String getDepth() {
return depth;
}
public void setDepth(String depth) {
this.depth = depth;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public String getOut_of_stock() {
return out_of_stock;
}
public void setOut_of_stock(String out_of_stock) {
this.out_of_stock = out_of_stock;
}
public String getQuantity_discount() {
return quantity_discount;
}
public void setQuantity_discount(String quantity_discount) {
this.quantity_discount = quantity_discount;
}
public String getCustomizable() {
return customizable;
}
public void setCustomizable(String customizable) {
this.customizable = customizable;
}
public String getUploadable_files() {
return uploadable_files;
}
public void setUploadable_files(String uploadable_files) {
this.uploadable_files = uploadable_files;
}
public String getText_fields() {
return text_fields;
}
public void setText_fields(String text_fields) {
this.text_fields = text_fields;
}
public String getActive() {
return active;
}
public void setActive(String active) {
this.active = active;
}
public String getRedirect_type() {
return redirect_type;
}
public void setRedirect_type(String redirect_type) {
this.redirect_type = redirect_type;
}
public String getId_product_redirected() {
return id_product_redirected;
}
public void setId_product_redirected(String id_product_redirected) {
this.id_product_redirected = id_product_redirected;
}
public String getAvailable_for_order() {
return available_for_order;
}
public void setAvailable_for_order(String available_for_order) {
this.available_for_order = available_for_order;
}
public String getAvailable_date() {
return available_date;
}
public void setAvailable_date(String available_date) {
this.available_date = available_date;
}
public String getCondition() {
return condition;
}
public void setCondition(String condition) {
this.condition = condition;
}
public String getShow_price() {
return show_price;
}
public void setShow_price(String show_price) {
this.show_price = show_price;
}
public String getIndexed() {
return indexed;
}
public void setIndexed(String indexed) {
this.indexed = indexed;
}
public String getVisibility() {
return visibility;
}
public void setVisibility(String visibility) {
this.visibility = visibility;
}
public String getCache_is_pack() {
return cache_is_pack;
}
public void setCache_is_pack(String cache_is_pack) {
this.cache_is_pack = cache_is_pack;
}
public String getCache_has_attachments() {
return cache_has_attachments;
}
public void setCache_has_attachments(String cache_has_attachments) {
this.cache_has_attachments = cache_has_attachments;
}
public String getIs_virtual() {
return is_virtual;
}
public void setIs_virtual(String is_virtual) {
this.is_virtual = is_virtual;
}
public String getCache_default_attribute() {
return cache_default_attribute;
}
public void setCache_default_attribute(String cache_default_attribute) {
this.cache_default_attribute = cache_default_attribute;
}
public String getDate_add() {
return date_add;
}
public void setDate_add(String date_add) {
this.date_add = date_add;
}
public String getDate_upd() {
return date_upd;
}
public void setDate_upd(String date_upd) {
this.date_upd = date_upd;
}
public String getAdvanced_stock_management() {
return advanced_stock_management;
}
public void setAdvanced_stock_management(String advanced_stock_management) {
this.advanced_stock_management = advanced_stock_management;
}
public String getPack_stock_type() {
return pack_stock_type;
}
public void setPack_stock_type(String pack_stock_type) {
this.pack_stock_type = pack_stock_type;
}
public String getId_shop() {
return id_shop;
}
public void setId_shop(String id_shop) {
this.id_shop = id_shop;
}
public int getId_product_attribute() {
return id_product_attribute;
}
public void setId_product_attribute(int id_product_attribute) {
this.id_product_attribute = id_product_attribute;
}
public String getProduct_attribute_minimal_quantity() {
return product_attribute_minimal_quantity;
}
public void setProduct_attribute_minimal_quantity(String product_attribute_minimal_quantity) {
this.product_attribute_minimal_quantity = product_attribute_minimal_quantity;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDescription_short() {
return description_short;
}
public void setDescription_short(String description_short) {
this.description_short = description_short;
}
public String getAvailable_now() {
return available_now;
}
public void setAvailable_now(String available_now) {
this.available_now = available_now;
}
public String getAvailable_later() {
return available_later;
}
public void setAvailable_later(String available_later) {
this.available_later = available_later;
}
public String getLink_rewrite() {
return link_rewrite;
}
public void setLink_rewrite(String link_rewrite) {
this.link_rewrite = link_rewrite;
}
public String getMeta_description() {
return meta_description;
}
public void setMeta_description(String meta_description) {
this.meta_description = meta_description;
}
public String getMeta_keywords() {
return meta_keywords;
}
public void setMeta_keywords(String meta_keywords) {
this.meta_keywords = meta_keywords;
}
public String getMeta_title() {
return meta_title;
}
public void setMeta_title(String meta_title) {
this.meta_title = meta_title;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId_image() {
return id_image;
}
public void setId_image(String id_image) {
this.id_image = id_image;
}
public String getLegend() {
return legend;
}
public void setLegend(String legend) {
this.legend = legend;
}
public String getManufacturer_name() {
return manufacturer_name;
}
public void setManufacturer_name(String manufacturer_name) {
this.manufacturer_name = manufacturer_name;
}
public String getCategory_default() {
return category_default;
}
public void setCategory_default(String category_default) {
this.category_default = category_default;
}
public String getNewX() {
return newX;
}
public void setNewX(String newX) {
this.newX = newX;
}
public String getOrderprice() {
return orderprice;
}
public void setOrderprice(String orderprice) {
this.orderprice = orderprice;
}
public int getAllow_oosp() {
return allow_oosp;
}
public void setAllow_oosp(int allow_oosp) {
this.allow_oosp = allow_oosp;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public int getAttribute_price() {
return attribute_price;
}
public void setAttribute_price(int attribute_price) {
this.attribute_price = attribute_price;
}
public double getPrice_tax_exc() {
return price_tax_exc;
}
public void setPrice_tax_exc(double price_tax_exc) {
this.price_tax_exc = price_tax_exc;
}
public double getPrice_without_reduction() {
return price_without_reduction;
}
public void setPrice_without_reduction(double price_without_reduction) {
this.price_without_reduction = price_without_reduction;
}
public int getReduction() {
return reduction;
}
public void setReduction(int reduction) {
this.reduction = reduction;
}
public boolean isSpecific_prices() {
return specific_prices;
}
public void setSpecific_prices(boolean specific_prices) {
this.specific_prices = specific_prices;
}
public int getQuantity_all_versions() {
return quantity_all_versions;
}
public void setQuantity_all_versions(int quantity_all_versions) {
this.quantity_all_versions = quantity_all_versions;
}
public int getVirtual() {
return virtual;
}
public void setVirtual(int virtual) {
this.virtual = virtual;
}
public int getPack() {
return pack;
}
public void setPack(int pack) {
this.pack = pack;
}
public int getNopackprice() {
return nopackprice;
}
public void setNopackprice(int nopackprice) {
this.nopackprice = nopackprice;
}
public boolean isCustomization_required() {
return customization_required;
}
public void setCustomization_required(boolean customization_required) {
this.customization_required = customization_required;
}
public int getRate() {
return rate;
}
public void setRate(int rate) {
this.rate = rate;
}
public String getTax_name() {
return tax_name;
}
public void setTax_name(String tax_name) {
this.tax_name = tax_name;
}
public String getImage_url() {
return image_url;
}
public void setImage_url(String image_url) {
this.image_url = image_url;
}
public List<?> getFeatures() {
return features;
}
public void setFeatures(List<?> features) {
this.features = features;
}
public List<?> getAttachments() {
return attachments;
}
public void setAttachments(List<?> attachments) {
this.attachments = attachments;
}
public List<?> getPackItems() {
return packItems;
}
public void setPackItems(List<?> packItems) {
this.packItems = packItems;
}
}
list_main_item.java ( the main activity ) :
package com.example.madrit.okhttp_gson_view;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class list_main_item extends AppCompatActivity {
private ListView listview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listview = (ListView) findViewById(R.id.item_shop_list_view);
String url = "http://77.242.25.43:8080/girogama/modules/api/mApi/v1/categories.php?action=get_products&id_category=6&page=1&products_per_page=15";
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
}
#Override
public void onResponse(Call call, Response response) throws IOException {
String json = response.body().string();
Gson gson = new Gson();
model_item[] model = gson.fromJson(json , model_item[].class);
List<model_item> list = Arrays.asList(model);
final ListAdapter myadapter = new CustomItemAdapter(list_main_item.this,list);
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
listview.setAdapter(myadapter);
Log.i("Item_shop_activity"," te dhenat e response");
}
});
}
});
setContentView(R.layout.activity_list__main_item);
}
}
my main xml file activity_list_main_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_item_shop"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.madrit.okhttp_gson_view.list_main_item">
<ListView
android:id="#+id/item_shop_list_view"
android:layout_width="wrap_content"
android:layout_height="match_parent">
</ListView>
</RelativeLayout>
the error
the error it gaved me
Please i need help , even if i have done any other stupid error with data parsing !!
Call setContentView(R.layout.activity_list__main_item); right after super.onCreate(savedInstanceState); or before assigning/accessing any views.
In the below android activity, trying to display data in a view pager and it is working as expected.
But in loadItemsForSuppliers method, when i am adding SupplierAndItemList object to it's arraylist, value returned from getInventoriesByItemDetails method is not updating properly rather takes last value always.
Can some body assist me what's wrong here ?
public class ScreenSlidePagerActivity extends BaseActivity {
private ViewPager mPager;
private PagerAdapter mPagerAdapter;
private Dealer dealerObject;
private ArrayList<ItemDetail> itemDetails;
private List<Dealer> supplierList;
private ArrayList<SupplierAndItemList> supplierAndItemLists = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen_slide);
dealerObject = getIntent().getParcelableExtra(UiConstants.DEALER_OBJECT);
itemDetails = getIntent().getParcelableArrayListExtra("itemDetails");
supplierList = dealerObject.getParentSalesPoints(this,dealerObject.getServerId());
loadItemsForSuppliers();
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager(),supplierAndItemLists);
mPager.setAdapter(mPagerAdapter);
}
private void loadItemsForSuppliers() {
for (Dealer dealer : supplierList) {
ArrayList<ItemDetail> inventories = new ArrayList<>();
SupplierAndItemList supplierAndItem = new SupplierAndItemList();
supplierAndItem.setDealerName(dealer.getDealerName());
supplierAndItem.setSelectedItemList(getInventoriesByItemDetails(dealer, inventories));
supplierAndItemLists.add(supplierAndItem);
}
}
private ArrayList<ItemDetail> getInventoriesByItemDetails(Dealer dealer, ArrayList<ItemDetail> inventories) {
for (ItemDetail id : itemDetails) {
DealerInventory dealerInventory = new DealerInventory();
dealerInventory = dealerInventory.getLastModifiedInventory(this, id.getItemId(), dealer.getId());
if (dealerInventory != null) {
if (dealerInventory.getQuantity() >= 0) {
id.setParentSalesPointLastStock(String.valueOf(dealerInventory.getQuantity()));
id.setParentSalesPointLastStockTakingDate(dealerInventory.getStockTakingDate());
}
} else {
id.setParentSalesPointLastStock(UiConstants.NA);
id.setParentSalesPointLastStockTakingDate(UiConstants.NA);
}
inventories.add(id);
}
return inventories;
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
private final ArrayList<SupplierAndItemList> supplierAndItemList;
public ScreenSlidePagerAdapter(FragmentManager fm, ArrayList<SupplierAndItemList> supplierAndItemList) {
super(fm);
this.supplierAndItemList = supplierAndItemList;
}
#Override
public Fragment getItem(int position) {
SupplierAndItemList supplierAndItems = supplierAndItemList.get(position);
ScreenSlidePageFragment f = new ScreenSlidePageFragment();
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("supplierAndItems",supplierAndItems.getSelectedItemList());
bundle.putString("supplierName",supplierAndItems.getDealerName());
f.setArguments(bundle);
return f;
}
#Override
public int getCount() {
return supplierAndItemList.size();
}
}
}
SupplierAndItemList class
public class SupplierAndItemList implements Parcelable {
public String dealerName;
public ArrayList<ItemDetail> selectedItemList;
public SupplierAndItemList() {
selectedItemList = new ArrayList<>();
}
public String getDealerName() {
return dealerName;
}
public void setDealerName(String dealerName) {
this.dealerName = dealerName;
}
public ArrayList<ItemDetail> getSelectedItemList() {
return selectedItemList;
}
public void setSelectedItemList(ArrayList<ItemDetail> itemList) {
this.selectedItemList = itemList;
}
protected SupplierAndItemList(Parcel in) {
dealerName = in.readString();
selectedItemList = in.readArrayList(ItemDetail.class.getClassLoader());
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(dealerName);
dest.writeList(selectedItemList);
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<SupplierAndItemList> CREATOR = new Parcelable.Creator<SupplierAndItemList>() {
#Override
public SupplierAndItemList createFromParcel(Parcel in) {
return new SupplierAndItemList(in);
}
#Override
public SupplierAndItemList[] newArray(int size) {
return new SupplierAndItemList[size];
}
};
}
ItemDetail class
public class ItemDetail implements Parcelable {
public int itemId;
public String itemName;
public String salesPointLastStock;
public String salesPointLastStockTakingDate;
public String parentSalesPointLastStock;
public String parentSalesPointLastStockTakingDate;
public IDStockInput idStockInput;
public IDReturnInput idReturnInput;
public IDOrderInput idOrderInput;
public boolean isSelected;
public boolean isSelected() {
return isSelected;
}
public void setIsSelected(boolean isUpdated) {
this.isSelected = isUpdated;
}
public String getParentSalesPointLastStockTakingDate() {
return parentSalesPointLastStockTakingDate;
}
public void setParentSalesPointLastStockTakingDate(String parentSalesPointLastStockTakingDate) {
this.parentSalesPointLastStockTakingDate = parentSalesPointLastStockTakingDate;
}
public String getParentSalesPointLastStock() {
return parentSalesPointLastStock;
}
public void setParentSalesPointLastStock(String parentSalesPointLastStock) {
this.parentSalesPointLastStock = parentSalesPointLastStock;
}
#NonNull
public int getItemId() {
return itemId;
}
public void setItemId(int itemId) {
this.itemId = itemId;
}
#NonNull
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
#NonNull
public String getSalesPointLastStock() {
return salesPointLastStock;
}
public void setSalesPointLastStock(String salesPointLastStock) {
this.salesPointLastStock = salesPointLastStock;
}
#NonNull
public String getSalesPointLastStockTakingDate() {
return salesPointLastStockTakingDate;
}
public void setSalesPointLastStockTakingDate(String salesPointLastStockTakingDate) {
this.salesPointLastStockTakingDate = salesPointLastStockTakingDate;
}
public IDStockInput getIdStockInput() {
return idStockInput;
}
public void setIdStockInput(IDStockInput idStockInput) {
this.idStockInput = idStockInput;
}
public IDReturnInput getIdReturnInput() {
return idReturnInput;
}
public void setIdReturnInput(IDReturnInput idReturnInput) {
this.idReturnInput = idReturnInput;
}
public IDOrderInput getIdOrderInput() {
return idOrderInput;
}
public void setIdOrderInput(IDOrderInput idOrderInput) {
this.idOrderInput = idOrderInput;
}
public ItemDetail() {
idStockInput = new IDStockInput();
idReturnInput = new IDReturnInput();
idOrderInput = new IDOrderInput();
}
protected ItemDetail(Parcel in) {
itemId = in.readInt();
itemName = in.readString();
salesPointLastStock = in.readString();
salesPointLastStockTakingDate = in.readString();
parentSalesPointLastStock = in.readString();
parentSalesPointLastStockTakingDate = in.readString();
isSelected =in.readInt()==1;
idStockInput = (IDStockInput) in.readValue(IDStockInput.class.getClassLoader());
idReturnInput = (IDReturnInput) in.readValue(IDReturnInput.class.getClassLoader());
idOrderInput = (IDOrderInput) in.readValue(IDOrderInput.class.getClassLoader());
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(itemId);
dest.writeString(itemName);
dest.writeString(salesPointLastStock);
dest.writeString(salesPointLastStockTakingDate);
dest.writeString(parentSalesPointLastStock);
dest.writeString(parentSalesPointLastStockTakingDate);
dest.writeInt(isSelected ? 1 : 0);
dest.writeValue(idStockInput);
dest.writeValue(idReturnInput);
dest.writeValue(idOrderInput);
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<ItemDetail> CREATOR = new Parcelable.Creator<ItemDetail>() {
#Override
public ItemDetail createFromParcel(Parcel in) {
return new ItemDetail(in);
}
#Override
public ItemDetail[] newArray(int size) {
return new ItemDetail[size];
}
};
}
I have go through your method I have found some assigning value issue
private void loadItemsForSuppliers() {
for (Dealer dealer : supplierList) {
ArrayList<ItemDetail> inventories = new ArrayList<>();
SupplierAndItemList supplierAndItem = new SupplierAndItemList();
supplierAndItem.setDealerName(dealer.getDealerName());
supplierAndItem.setSelectedItemList(getInventoriesByItemDetails(dealer, inventories));
supplierAndItemLists.add(supplierAndItem);
}
}
private ArrayList<ItemDetail> getInventoriesByItemDetails(Dealer dealer, ArrayList<ItemDetail> inventories) {
for (ItemDetail id : itemDetails) {
DealerInventory dealerInventory = new DealerInventory();
dealerInventory = dealerInventory.getLastModifiedInventory(this, id.getItemId(), dealer.getId());
if (dealerInventory != null) {
if (dealerInventory.getQuantity() >= 0) {
id.setParentSalesPointLastStock(String.valueOf(dealerInventory.getQuantity()));
id.setParentSalesPointLastStockTakingDate(dealerInventory.getStockTakingDate());
}
} else {
id.setParentSalesPointLastStock(UiConstants.NA);
id.setParentSalesPointLastStockTakingDate(UiConstants.NA);
}
inventories.add(id); // do this
}
return inventories; // you are not assigning value anywhere;
}
You are not assigning value to the inventories in getInventoriesByItemDetails. I think you should add item through inventories.add(id);
Check it , Hope this help
Set
mPager.setOffscreenPageLimit(1);
I am trying to pass Parcelable object from the A activity to B activity via intent:
Intent intent = new Intent (A.this, B.class);
intent.putExtra ("post", mypost); // where post implements Parcelable`
In B Activity I got the post object in this way:
Post myPost = getIntent().getParcelableExtra("post");
In B activity myPost object fields are mixed, e.g. I have postText and postDate fields in Post model, the values of this fields in B activity are mixed.
Why this can happen? My model class look likes the following:
public class Post implements Parcelable, Serializable {
private static final long serialVersionUID = 2L;
#SerializedName("author")
private User author;
#SerializedName("comments_count")
private String commentsCount;
#SerializedName("image")
private String imageToPost;
#SerializedName("parent_key")
private String parentKey;
#SerializedName("created_date")
private String postDate;
#SerializedName("id")
private String postId;
#SerializedName("text")
private String postText;
#SerializedName("title")
private String postTitle;
#SerializedName("shared_post_id")
private String sharedPostId;
#SerializedName("url")
private String urlToPost;
#SerializedName("video")
private String videoToPost;
public Post() {
}
public Post(Parcel in) {
author = (User) in.readValue(getClass().getClassLoader());
commentsCount = in.readString();
imageToPost = in.readString();
parentKey = in.readString();
postDate = in.readString();
postId = in.readString();
postText = in.readString();
postTitle = in.readString();
sharedPostId = in.readString();
urlToPost = in.readString();
videoToPost = in.readString();
}
public static final Creator<Post> CREATOR = new Creator<Post>() {
#Override
public Post createFromParcel(Parcel in) {
return new Post(in);
}
#Override
public Post[] newArray(int size) {
return new Post[size];
}
};
public User getAuthor() {
return author;
}
public void setAuthor(User author) {
this.author = author;
}
public String getPostDate() {
return postDate;
}
public void setPostDate(String postDate) {
this.postDate = postDate;
}
public String getPostTitle() {
return postTitle;
}
public void setPostTitle(String postTitle) {
this.postTitle = postTitle;
}
public String getPostText() {
return postText;
}
public void setPostText(String postText) {
this.postText = postText;
}
public String getPostId() {
return postId;
}
public void setPostId(String postId) {
this.postId = postId;
}
public String getUrlToPost() {
return urlToPost;
}
public void setUrlToPost(String urlToPost) {
this.urlToPost = urlToPost;
}
public String getImageToPost() {
return imageToPost;
}
public void setImageToPost(String imageToPost) {
this.imageToPost = imageToPost;
}
public String getVideoToPost() {
return videoToPost;
}
public void setVideoToPost(String videoToPost) {
this.videoToPost = videoToPost;
}
public String getParentKey() {
return parentKey;
}
public void setParentKey(String parentKey) {
this.parentKey = parentKey;
}
public String getCommentsCount() {
return commentsCount;
}
public void setCommentsCount(String commentsCount) {
this.commentsCount = commentsCount;
}
public String getSharedPostId() {
return sharedPostId;
}
public void setSharedPostId(String sharedPostId) {
this.sharedPostId = sharedPostId;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(author);
dest.writeString(commentsCount);
dest.writeString(imageToPost);
dest.writeString(parentKey);
dest.writeString(postDate);
dest.writeString(postId);
dest.writeString(postText);
dest.writeString(postTitle);
dest.writeString(sharedPostId);
dest.writeString(urlToPost);
dest.writeString(videoToPost);
}
}
Add describeContents and writeToParcel.
Examples:
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(email);
dest.writeString(pass);
dest.writeFloat(amountPaid);
dest.writeString(url);
dest.writeInt(age);
}