简体   繁体   中英

Can't access methods in another class from my MainActivity

I'm developping an Android application. Simple stuff. Only one view. i'm using two packages, tho. Helpers and the main one. I created this class "produto" to make itens, so i can create an ArrayList and just hardcode some exemples in it for a project. However Android Studio (i'm using 3.0) doesn't let me call the setters for the elements of the arraylist.

here is a part of my MainActivity.java

package com.example.khovis.mqtt;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.GridLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.util.ArrayList;

import helpers.MQTThelper;
import helpers.Produto;

public class MainActivity extends AppCompatActivity {
    MQTThelper mqttHelper;
    GridLayout myLayout = null;
    TextView dataReceived;
    ArrayList<Produto> lista = new ArrayList<Produto>();

    Produto coisa = new Produto("teste", 300 );

    lista.add(coisa);
    ...

and here is my class Produto

    package helpers;

/**
 * Created by khovis on 26-11-2017.
 */

public class Produto {

    private double price;

    private String name;

    public Produto(String nome, float v) {
        setPrice(v);
        setName(nome);
    }


    public double getPrice() {
        return price;
    }


    public String getName() {
        return name;
    }


    public void setPrice(double price) {
        this.price = price;
    }


    public void setName(String name) {
        this.name = name;
    }

}

The way it is Right now it says the object coisa is a class (which clearly isn't). and it's an unknown class.

If I change 'coisa' for 'new Produto()' is says it cannot resolve the symbol 'add'

I've used java before (last year), but i have never seen weird stuff like this.

Does anyone know how to solve this? I just want to add the object 'coisa' to the arrayList

Thanks for the attention

My guess is you are trying to add "coisa" outside a method. Maybe do this step in the onCreate() method or so. Another way could be adding it directly into your ArrayList like this...

ArrayList<Produto> lista = new ArrayList<Produto>() {{
    add(new Produto("teste", 300));
}};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM