简体   繁体   English

JAVA静态方法调用非静态方法

[英]Call non-static method in Static method JAVA

EDITED:编辑:

The real purpose of that is to have one activity and on class who fetch data and render it to the activity.这样做的真正目的是让一个活动和班级获取数据并将其呈现给活动。

The problem is I have dropdown menu.问题是我有下拉菜单。 When I clicked on an item of the menu it change my url but it does not load or fetch my data to the activity but when i clicked again it works but with the paramaters selected just before and if I clicked again it still works but still with the previous elements selected.当我点击菜单中的一个项目时,它会更改我的 url,但它不会加载或获取我的数据到活动中,但是当我再次点击它时,它可以工作,但是之前选择了参数,如果我再次点击它仍然可以工作,但仍然使用先前选择的元素。

My "teacher" said I have to call build into my callback method.我的“老师”说我必须在我的回调方法中调用 build 。 But it doesen't work at all.但它根本不起作用。 And I still didn't find any solution :/.我仍然没有找到任何解决方案:/。

As you recommended I changed everything for non-static method正如你所建议的,我改变了非静态方法的所有内容

I thought why not saving an history of the dropdown, compare the current value with the saved value and if it's diffrent it means it was changed so reload the app to make new fetch and displyed new data.我想为什么不保存下拉列表的历史记录,将当前值与保存的值进行比较,如果它不同,则意味着它已更改,因此重新加载应用程序以进行新的获取并显示新的数据。

But I got :但我得到了:

Here my all code这是我的所有代码

PhotosActivity照片活动

public class PhotosActivity extends AppCompatActivity {

    // Local variable
    private OkHttpClient httpClient;
    private ImageButton home_btn;
    private ImageButton favorites_btn;
    private ImageButton search_btn;
    private ImageButton profil_btn;
    // Constante variable
    private static final String TAG = "PhotoActivity";
    private static final String clientId = "bb0c749c6403fd2";

    // Private shared variable
    private static  List<Photo> mPhotos;
    private static JSONArray mItems;
    private static String mAccessToken;
    private static String userID;
    static Activity activity;

    // Shared variable
    private static String selectedItem;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photos);
        this.home_btn = findViewById(R.id.home_button);
        this.favorites_btn = findViewById(R.id.favorites_button);
        this.search_btn = findViewById(R.id.search_button);
        this.profil_btn = findViewById(R.id.profil_button);

        final HttpHandler httpHandler = new HttpHandler();
        httpHandler.fetchData();
        build();

        activity = this;

        Spinner spinner=(Spinner)findViewById(R.id.spinner);
        String[] filters=getResources().getStringArray(R.array.filters);
        ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,R.layout.spinner,R.id.text, filters);
        spinner.setAdapter(adapter);


        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
        {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
            {
                selectedItem = parent.getItemAtPosition(position).toString();
//                httpHandler.fetchData();
//                build();
            }
            public void onNothingSelected(AdapterView<?> parent)
            {
                Log.d("TAG", "Error");
            }
        });

        home_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent next_activity = new Intent(getApplicationContext(), PhotosActivity.class);
                finish();
                startActivity(next_activity);
            }
        });
        favorites_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent next_activity = new Intent(getApplicationContext(), FavoriteActivity.class);
                finish();

                startActivity(next_activity);
            }
        });
        search_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent next_activity = new Intent(getApplicationContext(), SearchActivity.class);
                finish();
                startActivity(next_activity);
            }
        });
        profil_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent next_activity = new Intent(getApplicationContext(), ProfileActivity.class);
                finish();
                startActivity(next_activity);
            }
        });
    }

    public void Filters() {
        String hSection;
        String hSort;
        String hShowV;

        hSection = HttpHandler.section ;
        hSort = HttpHandler.sort;
        hShowV = HttpHandler.showV;
        Intent next_activity = new Intent(getApplicationContext(), FavoriteActivity.class);

        if(selectedItem != null) {
            if (selectedItem.equals("Most Viral")) {
                HttpHandler.sort = "viral/";
                HttpHandler.section = "hot/";
                if ( (!HttpHandler.sort.equals(hSort))  || (!HttpHandler.section.equals(hSection))) {
                    Log.d("TAG", "most: "+HttpHandler.section);
                    Log.d("TAG", "H most: "+hSection);
//                    activity.recreate();
//                    onRestart();
                    finish();
                    startActivity(next_activity);
                }
            } else if (selectedItem.equals("Newest")) {
                HttpHandler.section = "top/";
                HttpHandler.sort = "time/";
                if ( (!HttpHandler.sort.equals(hSort))  || (!HttpHandler.section.equals(hSection))) {
                    Log.d("TAG", "new: "+HttpHandler.section);
                    Log.d("TAG", "H new: "+hSection);
                    finish();
                    startActivity(next_activity);
//                    activity.recreate();
//                    onRestart();
                }
            } else if (selectedItem.equals("Rising")) {
                HttpHandler.section = "user/";
                HttpHandler.sort = "rising/";
                HttpHandler.showV = "?showViral=false";
                if ( (!HttpHandler.sort.equals(hSort))  || (!HttpHandler.section.equals(hSection))) {
                    Log.d("TAG", "rising: "+HttpHandler.section);
                    Log.d("TAG", "H rising: "+hSection);
//                    onRestart();
//                    activity.recreate();
                    finish();
                    startActivity(next_activity);
                }
            } else {
                Log.d(TAG, "Might be a problem");
            }
        } else {
                activity.recreate();
        }
    }
    public void build () {
        try {
            for(int i = 0; i < mItems.length(); i++) {
                JSONObject item = mItems.getJSONObject(i);
                Photo photo = new Photo();
                if(item.getBoolean("is_album")) {
                    photo.id = item.getString("cover");
                } else {
                    photo.id = item.getString("id");
                }
                photo.title = item.getString("title");
                mPhotos.add(photo);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        render(mPhotos);
                    }
                });
            }

        } catch (Exception e) {
            Log.e("JSONerr" , "Something went wrong.");
        }
    }

    private static class PhotoVH extends RecyclerView.ViewHolder {
        ImageView photo;
        TextView title;

        public PhotoVH(View itemView) {
            super(itemView);
        }
    }

    private void render(final List<Photo> photos) {
        RecyclerView rv = (RecyclerView)findViewById(R.id.rv_of_photos);
        rv.setLayoutManager(new LinearLayoutManager(this));

        RecyclerView.Adapter<PhotoVH> adapter = new RecyclerView.Adapter<PhotoVH>() {
            @NonNull
            @Override
            public PhotoVH onCreateViewHolder(ViewGroup parent, int viewType) {
                PhotoVH vh = new PhotoVH(getLayoutInflater().inflate(R.layout.item, null));
                vh.photo = (ImageView) vh.itemView.findViewById(R.id.photo);
                vh.title = (TextView) vh.itemView.findViewById(R.id.title);
                return vh;
            }

            @Override
            public void onBindViewHolder(PhotoVH holder, int position) {
                Picasso.with(PhotosActivity.this).load("https://i.imgur.com/" +
                        photos.get(position).id + ".jpg").into(holder.photo);
                holder.title.setText(photos.get(position).title);
            }

            @Override
            public int getItemCount() {
                return photos.size();
            }
        };

        rv.setAdapter(adapter);
    }

    public static void getUserID(String UserID) {
        Log.d("TAG", UserID);
        userID = UserID;
    }

    public void callBackPhoto( List<Photo> photos, JSONArray items)
    {
         mPhotos = photos;
         mItems = items;
//         build();
    }

}

HttpHandler HttpHandler

public class HttpHandler {
    private static final String TAG = "HttpHandler";
    private static String clientId = "bb0c749c6403fd2";
    private static OkHttpClient httpClient;
    private static String mAccessToken;

    // URL BUILDER VARIABLES
    public static String section = "hot/";
    public static String sort = "viral/";
    public static String page;
    public static String showV;
    public static String mUrl;

    public void fetchData() {
        httpClient = new OkHttpClient.Builder().build();
        photosActivity.Filters();
        mUrl = "https://api.imgur.com/3/gallery/" + section + sort;
//        Log.d("TAG", "Sort: " + sort + ": URl is" + mUrl);
        Request request = new Request.Builder()
                .url(mUrl + "0.json" + showV)
                .addHeader("Authorization", "Client-ID " + clientId)
                .header("User-Agent", "epicture")
                .build();
        httpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "An error has occurred " + e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    JSONObject data = new JSONObject(response.body().string());
                    JSONArray items = data.getJSONArray("data");
                    final List<Photo> photos = new ArrayList<Photo>();
                    photosActivity.callBackPhoto(photos, items);
                } catch (Exception e) {
                    Log.e("JSONerr", "Something went wrong.");
                }
            }
        });
    }

    public static void getLoginData(String accessToken) {
        mAccessToken = accessToken;
    }
}

It doesn't look like making sense to declare callBackPhoto as a static method.callBackPhoto声明为static方法似乎没有意义。 If you have put static keyword accidentally in its declaration, simply remove it to solve your problem ie replace如果您在其声明中意外地放置了static关键字,只需将其删除即可解决您的问题,即替换

public static void callBackPhoto( List<Photo> photos, JSONArray items)

with

public void callBackPhoto( List<Photo> photos, JSONArray items)

Note that there is no way to call a non-static method from a static one directly (ie without calling it on an object/instance).请注意,有没有办法来调用从一个非静态方法static直接一(即无需调用它的对象/实例)。 Thus, if for any reason, you can't remove static keyword from the declaration of callBackPhoto , you are left with only two options:因此,如果出于任何原因,您无法从callBackPhoto的声明中删除static关键字, callBackPhoto剩下两个选项:

  1. Declare build too as staticbuild也声明为static

  2. Call build on an object/instance eg new PhotosActivity().build()在对象/实例上调用build ,例如new PhotosActivity().build()

    Though any of these two options will solve your problem, I don't think this is how you intend to design your class.尽管这两个选项中的任何一个都可以解决您的问题,但我认为这不是您打算设计课程的方式。

In java, a static method belongs to EVERY object of the class that defines it.在java中,静态方法属于定义它的类的每个对象。 Therefore, you can call it from the parent class without creating an object like so:因此,您可以从父类调用它,而无需像这样创建对象:

ParentClass.myMethod;

However, this is not the case the case with instance (non-static) methods.但是,实例(非静态)方法的情况并非如此。 To call this type of method, you need to define it in a class, create an object from that class, and then call it from that object, like this:要调用这种类型的方法,您需要在一个类中定义它,从该类创建一个对象,然后从该对象调用它,如下所示:

//inside ParentClass definition
public void myMethod(){bla bla;}
//In some other class
ParentClass obj = new ParentClass;
obj.myMethod;

Suppose you have code calling a static member of a class without creating an instance of that class.假设您有代码调用类的静态成员,而没有创建该类的实例。 If that method contained a non-static method, there would be no object in memory to call it on.如果该方法包含非静态方法,则内存中将没有可调用它的对象。 This is why it isn't possible.这就是不可能的原因。

Static静止的

The static methods are alive all the time.静态方法一直存在。 They live from the class is loaded.它们从类被加载住。 They don't need objects to live.他们不需要对象来生存。 I think of them as not really belonging to the class, but the class is just a nice way to organize those methods (the same for variables).我认为它们并不真正属于类,但类只是组织这些方法的好方法(变量也是如此)。 The methods could be put in any other class definition and it would still work.这些方法可以放在任何其他类定义中,它仍然可以工作。 But organizing them in classes where they will be used make it easy to prevent access from other parts of the program, like other objects or other static methods.但是将它们组织在将使用它们的类中可以很容易地防止从程序的其他部分访问,比如其他对象或其他静态方法。 They are called class methods or class variables .它们被称为类方法类变量

Instance实例

The non-static "stuff" does not live unless there is an object.除非有对象,否则非静态“东西”不会存在。 That's why you cannot call below methodOne or methodTwo from the static methods.这就是为什么你不能调用下面methodOnemethodTwo从静态方法。 You have to create an object first.您必须先创建一个对象。 They are called instance methods or instance variables , because you need an instance of an object to call them.它们被称为实例方法实例变量,因为您需要一个对象的实例来调用它们。

Error错误

error: non-static method <methodname> cannot be referenced from a static context basically means "There's no object" error: non-static method <methodname> cannot be referenced from a static context基本上意味着“没有对象”

Example例子

public class StackOverflowTest {
  public static void main(String[] args) {  // this is just another static method
//    methodOne();                            // error. There's no object

    StackOverflowTest test = new StackOverflowTest(); 
    test.methodOne();                       // method called on object.
  }

  // methods live outside objects
  static void staticMethodOne() {
    System.out.println("staticMethodOne");
    staticMethodTwo();                      // no object required.
  }
  static void staticMethodTwo() { 
    System.out.println("staticMethodTwo");
//    methodTwo();                            // error. There's no object
  }

  // methods that only live inside objects
  void methodOne() {                        // method can only be invoked if there's an object.
    System.out.println("methodOne");
    methodTwo();                            // no problem. Already inside the object.
  }
  void methodTwo() {
    System.out.println("methodTwo");
    staticMethodTwo();                      // no problem. Objects can access static methods.
  }
}

Your case你的情况

So you either have to create a PhotosActivity object inside your build() , or you have to make callBackPhoto a static method.因此,您要么必须在build()创建一个PhotosActivity对象,要么必须使callBackPhoto成为static方法。 I can't see what your render does, but it's the same principle.我看不到你的render是做什么的,但原理是一样的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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