I have one java bean class set values in parsing .My requirement to access this class
Globally but give null pointer exception when use its instance static and assign value in that.Code is as:-
private String Responce;
private String Error;
private String Url;
private SIPModle objsip;
private VMModle objvmmodle;
private ArrayList<CustompadModle> objcmodlelist = new ArrayList<CustompadModle>();
private SettingModle objsettingmodle;
private WifiModle objwifimodle;
public String getResponce() {
return Responce;
}
public void setResponce(String responce) {
Responce = responce;
}
public String getError() {
return Error;
}
public void setError(String error) {
Error = error;
}
public ArrayList<CustompadModle> getObjcmodlelist() {
return objcmodlelist;
}
public void setObjcmodlelist(CustompadModle objcmodlelist) {
this.objcmodlelist.add(objcmodlelist);
}
public String getUrl() {
return Url;
}
public void setUrl(String url) {
Url = url;
}
public SIPModle getObjsip() {
return objsip;
}
public void setObjsip(SIPModle objsip) {
this.objsip = objsip;
}
public VMModle getObjvmmodle() {
return objvmmodle;
}
public void setObjvmmodle(VMModle objvmmodle) {
this.objvmmodle = objvmmodle;
}
public SettingModle getObjsettingmodle() {
return objsettingmodle;
}
public void setObjsettingmodle(SettingModle objsettingmodle) {
this.objsettingmodle = objsettingmodle;
}
public WifiModle getObjwifimodle() {
return objwifimodle;
}
public void setObjwifimodle(WifiModle objwifimodle) {
this.objwifimodle = objwifimodle;
}
My requirement is that globle access this bean class globlly.Anyone suggest me
I am getting this object in doinbackground and assign in static object of that class as:
AsyncTask {
ProgressDialog objprogress = new ProgressDialog(
UserSettingConfiguration.this);
ApplicationRequestHandler objhandler = new ApplicationRequestHandler();
#Override
protected void onPreExecute() {
this.objprogress.setMessage("Please Wait While Loading...");
this.objprogress.isShowing();
}
#Override
protected ConfigurationSttingModle doInBackground(String... params) {
objconfigsetting = objhandler.getConfigurationSetting(params[0],
params[1], params[2], params[3]);
return objconfigsetting;
}
#Override
protected void onPostExecute(ConfigurationSttingModle result) {
if (this.objprogress.isShowing()) {
this.objprogress.dismiss();
}
}
}
And use in a class Advance as;-
private static HashMap<String, String> SUMMARIES = new HashMap<String, String>() {
private static final long serialVersionUID = 3055562364235868653L;
{
String server = UserSettingConfiguration.objconfigsetting.getObjsip().getServer();
String displayname1 = UserSettingConfiguration.objconfigsetting.getObjsip().getUser();
String user = UserSettingConfiguration.objconfigsetting.getObjsip().getUser();
String password= UserSettingConfiguration.objconfigsetting.getObjsip().getPassword();
put(FIELD_DISPLAY_NAME,displayname1);// "90901");
put(FIELD_CALLER_ID,displayname1); //"90901");
put(FIELD_SERVER,server);
put(FIELD_USERNAME,user);
put(FIELD_AUTH_ID, "207");
put(FIELD_PASSWORD,password);
put(FIELD_PROXY, null);
}
};
I think that a singleton pattern will match your requirements.
You must add this code:
private static MyJavaBeanClass = null;
public static MyJavaBeanClass getInstance(){
if(null == instance){
instance = new MyJavaBeanClass();
}
return instance;
}
You must change MyJavaBeanClass for the name of your class, and then you can invoke it anywhere like this:
MyJavaBeanClass.getInstance().setError("Testing");
Related
I've seen a few similar questions but they don't seem to answer my problem exactly. I'm pulling a list with Retrofit and I want to export it to a list and create a listview. But I am not getting any return from onResponse. I've also tried returning a list directly with return. Please help.
this is the callback func
listCatcher just holds a list
Ibreeds is interface
public ListCatcher allBreeds(View view){
ArrayList<String> breedList = new ArrayList<>(breeds);
Ibreeds.allBreeds().enqueue(new Callback<Breeds>() {
#Override
public void onResponse(Call<Breeds> call, Response<Breeds> response) {
List<String> breeds = response.body().getMessage();
for (String b: breeds){
breedList.add(b);
}
}
#Override
public void onFailure(Call<Breeds> call, Throwable t) {
Snackbar.make(view,R.string.connectionStatus, 3000 ).show();
}
});
ListCatcher listcatcher = new ListCatcher(breedList);
return listcatcher;
}
public interface BreedsDAOInterface {
#GET("breeds/list")
Call<Breeds> allBreeds();
#GET("breed/{breed}/list")
Call<Breeds> listSubBreed(#Path("breed") String breed);
#GET("breed/{breed}/images")
Call<Breeds> listBreedImages(#Path("breed") String breed);
#GET("breed/{breed}/{subBreed}/images")
Call<Breeds> listSubBreedImages(#Path("breed") String breed, #Path("subBreed") String subBreed);
#GET("breeds/image/random")
Call<Breeds> iFeelLucky();
}
public class ApiUtils {
public static final String BASE_URL = "https://dog.ceo/api/";
public static BreedsDAOInterface getBreedsDaoInterface(){
return RetrofitClient.getClient(BASE_URL).create(BreedsDAOInterface.class);
}
}
public class RetrofitClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(String baseURL){
if (retrofit == null){
retrofit = new Retrofit
.Builder()
.baseUrl(baseURL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
public class Breeds {
#SerializedName("message")
#Expose
private List<String> message;
public List<String> getMessage() {
return message;
}
public void setMessage(List<String> message) {
this.message = message;
}
}
EDIT
I found the solution to the problem:
listCatcher deleted
public class HomeActivity extends AppCompatActivity {
List<String> breedsList = new ArrayList<>();
private BreedsInterface Ibreeds;
private RecyclerViewAdapter RWAdapter;
private ActivityHomeBinding binding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityHomeBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
Ibreeds = ApiUtils.getBreedsDaoInterface();
allBreeds();
}
public void allBreeds(){
Ibreeds.allBreeds().enqueue(new Callback<Answer>() {
#Override
public void onResponse(Call<Answer> call, Response<Answer> response) {
List<String> breedResponceList = response.body().getMessage();
breedsList.clear();
breedsList.addAll(breedResponceList);
initRecyclerView();
}
#Override
public void onFailure(Call<Answer> call, Throwable t) {
throwError();
}
});
}
private void throwError() {
Snackbar.make(binding.getRoot(), R.string.connectionStatus, 3000).show();
}
private void initRecyclerView() {
RWAdapter = new RecyclerViewAdapter(breedsList);
binding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
binding.recyclerView.setAdapter(RWAdapter);
}
}
I added the adapter to the enqueue function via a function
Trying to use test driven development and ran into a NPE that I can't resolve and obviously because of that one of my tests fail.
In a method to fetch items I pass in a limit int and then instantiate a callback.
this is exactly where it falis the listener returns null I think.
[![enter image description here][1]][1]
Test class
package com.techyourchance.testdrivendevelopment.example11;
#RunWith(MockitoJUnitRunner.class)
public class FetchCartItemsUseCaseTest {
public static final int LIMIT = 10;
public static final int PRICE = 5;
public static final String ID = "id";
public static final String TITLE = "title";
public static final String DESCRIPTION = "description";
FetchCartItemsUseCase SUT;
#Mock
FetchCartItemsUseCase.Listener mListnerMock1;
FetchCartItemsUseCase.Listener mListnerMock2;
#Mock
GetCartItemsHttpEndpoint mGetCartItemsHttpEndpointMock;
#Captor
ArgumentCaptor<List<CartItem>> mAcListCartItem;
#Before
public void setup() throws Exception {
SUT = new FetchCartItemsUseCase(mGetCartItemsHttpEndpointMock);
success();
}
private void success() {
doAnswer(new Answer() {
#Override
public Object answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
Callback callback = (Callback) args[1];
callback.onGetCartItemsSucceeded(getCartItemSchemes());
return null;
}
}).when(mGetCartItemsHttpEndpointMock).getCartItems(anyInt(), any(Callback.class));
}
private List<CartItemSchema> getCartItemSchemes() {
List<CartItemSchema> schemas = new ArrayList<>();
schemas.add(new CartItemSchema(ID, TITLE, DESCRIPTION, PRICE));
return schemas;
}
#Test
public void fetchCartItems_correctLimitPassedToEndPoint() throws Exception {
ArgumentCaptor<Integer> acInt = ArgumentCaptor.forClass(Integer.class);
SUT.fetchCartItemsAndNotify(LIMIT);
verify(mGetCartItemsHttpEndpointMock).getCartItems(acInt.capture(), any(GetCartItemsHttpEndpoint.Callback.class));
assertThat(acInt.getValue(), is(LIMIT));
}
#Test
public void fetchCartItems_success_observersNotifiedWithCorrectData() throws Exception {
SUT.registerListener(mListnerMock1);
SUT.registerListener(mListnerMock2);
SUT.fetchCartItemsAndNotify(LIMIT);
verify(mListnerMock1).onCartItemsFetched(mAcListCartItem.capture());
verify(mListnerMock2).onCartItemsFetched(mAcListCartItem.capture());
List<List<CartItem>> captures = mAcListCartItem.getAllValues();
List<CartItem> capture1 = captures.get(0);
List<CartItem> capture2 = captures.get(1);
assertThat(capture1, is(getCartItems()));
assertThat(capture2, is(getCartItems()));
}
private List<CartItem> getCartItems() {
List<CartItem> cartItems = new ArrayList<>();
cartItems.add(new CartItem(ID, TITLE, DESCRIPTION, PRICE));
return cartItems;
}
//correct limit passed to the endpoint
//success - all observers notified with correct data
//success - unsubscribed observers not notified
//general error - observers notified of failure
//network error - observers notified of failure
}
public class FetchCartItemsUseCase {
private final List<Listener> mListeners = new ArrayList<>();
private final GetCartItemsHttpEndpoint mGetCartItemsHttpEndpoint;
public FetchCartItemsUseCase(GetCartItemsHttpEndpoint mGetCartItemsHttpEndpoint) {
this.mGetCartItemsHttpEndpoint = mGetCartItemsHttpEndpoint;
}
public void fetchCartItemsAndNotify(int limit) {
mGetCartItemsHttpEndpoint.getCartItems(limit, new GetCartItemsHttpEndpoint.Callback() {
#Override
public void onGetCartItemsSucceeded(List<CartItemSchema> cartItems) {
for(Listener listener : mListeners) {
listener.onCartItemsFetched(cartItemsFromSchemas(cartItems));
}
}
#Override
public void onGetCartItemsFailed(GetCartItemsHttpEndpoint.FailReason failReason) {
}
}) ;
}
private List<CartItem> cartItemsFromSchemas(List<CartItemSchema> cartItemSchemas) {
List<CartItem> cartItems = new ArrayList<>();
for(CartItemSchema schema : cartItemSchemas) {
cartItems.add(new CartItem(schema.getId(), schema.getTitle(),
schema.getDescription(), schema.getPrice()));
}
return cartItems;
}
public void registerListener(Listener listener) {
mListeners.add(listener);
}
public interface Listener {
Void onCartItemsFetched(List<CartItem> capture);
}
}
[1]: https://i.stack.imgur.com/r6Sea.png
really lost would appreciate any help
public class FetchReputationUseCaseSync {
private GetReputationHttpEndpointSync mGetReputationHttpEndpointSync;
public FetchReputationUseCaseSync(GetReputationHttpEndpointSync getReputationHttpEndpointSync) {
this.mGetReputationHttpEndpointSync = getReputationHttpEndpointSync;
}
public UseCaseResult fetchReputation() {
GetReputationHttpEndpointSync.EndpointResult result;
try{
result = mGetReputationHttpEndpointSync.getReputationSync();
}catch (NetworkErrorException e) {
e.printStackTrace();
return UseCaseResult.FAILURE;
}
switch(result.getStatus()) {
case SUCCESS:
return UseCaseResult.SUCCESS;
case GENERAL_ERROR:
return UseCaseResult.FAILURE;
default:
throw new RuntimeException("invalid status: " + result);
}
}
public enum UseCaseResult{
SUCCESS, FAILURE
}
}
I am trying to map two structures with JMapper but struggle with two encapsulated complex types and how to map them. I want to achive the following:
Source > Destination
Source.sourceString > Destination.destinationString
Source.SourceInternal > Destination.DestinationInternal
Source.SourceInternal.internalString2 > Destination.DestinationInternal.internalString
My classes look as follows:
public class Source {
private String sourceString;
private SourceInternal sourceInternal;
public String getSourceString() {
return sourceString;
}
public void setSourceString(final String sourceString) {
this.sourceString = sourceString;
}
public SourceInternal getSourceInternal() {
return sourceInternal;
}
public void setSourceInternal(final SourceInternal sourceInternal) {
this.sourceInternal = sourceInternal;
}
}
The internal source object
public class SourceInternal {
private String internalString1;
private String internalString2;
public String getInternalString1() {
return internalString1;
}
public void setInternalString1(final String internalString1) {
this.internalString1 = internalString1;
}
public String getInternalString2() {
return internalString2;
}
public void setInternalString2(final String internalString2) {
this.internalString2 = internalString2;
}
}
The destination the source should be mapped to
public class Destination {
private String destinationString;
private DestinationInternal destinationInternal;
public String getDestinationString() {
return destinationString;
}
public void setDestinationString(final String destinationString) {
this.destinationString = destinationString;
}
public DestinationInternal getDestinationInternal() {
return destinationInternal;
}
public void setDestinationInternal(final DestinationInternal destinationInternal) {
this.destinationInternal = destinationInternal;
}
}
The internal destination object.
public class DestinationInternal {
private String internalString;
public String getInternalString() {
return internalString;
}
public void setInternalString(final String internalString) {
this.internalString = internalString;
}
}
How would I achive the described mapping? Is it even possible with JMapper? Thanks.
I was looking into that a similar feature too. Here's how I managed it.
JMapperAPI jMapperAPI = new JMapperAPI()
.add(mappedClass(Destination.class)
.add(attribute("destinationString").value("sourceString"))
.add(attribute("destinationInternal").value("sourceInternal")))
.add(mappedClass(DestinationInternal.class).add(attribute("internalString").value("internalString1").targetClasses(SourceInternal.class)));
Basically the logic is to have a mapping for each nested class.
I'm trying to store a list in the Application class instance as a global variable in one of my Android applications. Below is my Application class code:
public class DefectsApplication extends Application{
private NormalUser normalUser;
private ArrayList<Complaint> complaintList;
public String getTestString() {
return testString;
}
public void setTestString(String testString) {
this.testString = testString;
}
private String testString;
public NormalUser getNormalUser() {
return normalUser;
}
public void setNormalUser(NormalUser normalUser) {
this.normalUser = normalUser;
}
public ArrayList<Complaint> getComplaintList() {
return complaintList;
}
public void setComplaintList(ArrayList<Complaint> m_complaints) {
this.complaintList = complaintList;
}
}
Below is my code which is trying to access the fields from the Application class instance:
DefectsApplication defectsApplication = ((DefectsApplication)getApplicationContext());
defectsApplication.setComplaintList(m_complaints);
defectsApplication.setTestString("urghhhhhhhhh");
ArrayList<Complaint> complaintList = defectsApplication.getComplaintList();
String s = defectsApplication.getTestString();
In the above code, m_complaints is a list of objects. When I try to store a String, it works. But for a list, it doesn't. Please, help me to resolve this issue.
Probably, a typo is taking place:
public void setComplaintList(ArrayList<Complaint> m_complaints) {
this.complaintList = complaintList;
}
You're setting this.complaintList to itself which is initially null. Try
public void setComplaintList(ArrayList<Complaint> m_complaints) {
this.complaintList = m_complaints;
}
I am new to jmockit and trying to execute the following online example.
The #MockClass is not working. My BookStore's getBookTitle() method is calling the function of orginal class instead of the mock class.
BookStore class:
public class BookStore {
public String getBookTitle(String isbn){
return BookStoreService.getBookTitle(isbn);
}
}
BookStoreService class:
public class BookStoreService {
public static String getBookTitle(String isbn){
return "Random";
}
}
Test class:
public class BookStoreTest {
private static Map<String, String> bookMap = new HashMap<String, String>(2);
#BeforeClass
public static void setup() {
System.out.println("in setup()");
bookMap.put("0553293354", "Foundation");
bookMap.put("0836220625", "The Far Side Gallery");
}
#MockClass(realClass = BookStoreService.class)
public static class MockBookstoreService {
#Mock
public static String getBookTitle(String isbn) {
System.out.println("in getBookTitle()");
if (bookMap.containsKey(isbn)) {
return bookMap.get(isbn);
} else {
return null;
}
}
}
#Test
public void testGetBookTitle() throws Exception {
System.out.println("in testGetBookTitle()");
final String isbn = "0553293354";
final String expectedTitle = "Foundation";
BookStore store = new BookStore();
String title = store.getBookTitle(isbn);
System.out.println(title); // This prints "Random" instead of "Foundation"
Assert.assertEquals(title, expectedTitle);
}
}
PS: I am using TestNG
Using the latest stable version of jmockit you could do it like this:
#BeforeClass
public static void setup() {
System.out.println("in setup()");
bookMap.put("0553293354", "Foundation");
bookMap.put("0836220625", "The Far Side Gallery");
new MockUp<BookStoreService>() {
#Mock
public String getBookTitle(String isbn) {
System.out.println("in getBookTitle()");
if (bookMap.containsKey(isbn)) {
return bookMap.get(isbn);
} else {
return null;
}
}
};
}
Remove the obsolete block:
public static class MockBookstoreService{...}