Vishal Sharma
Vishal Sharma

Reputation: 19

Android studio is not creating object using another class

WeatherDataModel weatherDataModel = new WeatherDataModel.fromJson(response);

I am creating a WeatherDataModel(my second class) object using the method fromJson ( defined in WeatherDataModel class) in my MainActivity using the parameters response.

But when I write above code Android studio can't recognize fromJson, but when I write this:

WeatherDataModel weatherDataModel = new WeatherDataModel();
weatherDataModel.fromJson(response);

It doesn't show any error.

Is there's a difference between these 2 lines?

Upvotes: 0

Views: 342

Answers (2)

Grisgram
Grisgram

Reputation: 3253

Either you missed the brackets for the constructor or you can even get rid of the new keyword by declaring the fromJson method static, which would make even more sense from a point of readability of the code.

If fromJson is not static, it can be called on a living instance at any time, destroying any values already stored in that instance.

So I'd declare that method as

public static WeatherDataModel fromJson(String response) {
    WeatherDataModel wd = new WeatherDataModel();
    // parse your response into wd's fields
    return wd;
}

and from outside your call then looks like

WeatherDataModel model = WeatherDataModel.fromJson(response);

Hope this helps, cheers

Upvotes: 0

Elias Meireles
Elias Meireles

Reputation: 1058

You need an instance of an object before call a method, so you code should be like this.

WeatherDataModel weatherDataModel = new WeatherDataModel().fromJson(response);

Upvotes: 1

Related Questions