-1

我相信我有一个简单的问题......但对于我作为初学者来说,我再也看不到它了。

在一个类中,我想从另一个类中获取一些 var。

第一类:

package com.blabla;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
public class SMSReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    //get shared preferences

    GetSettings test1 = new RingSettings();
    String theSMStext = test1.getSMStext();
    Boolean theActivateSMS = test1.getActivateSMS();    
}
}

第 2 类:

package com.blabla;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
public class GetSettings {

/**
 * @param args
 */
private String SMStext;
private Boolean ActivateSMS;


public static void RingSettings(Context context) {
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);

    String SMStext = sp.getString("SMStext", "0");
    Boolean ActivateSMS = sp.getBoolean("ActivateSMS", false);
}

public String getSMStext(){
    return SMStext;
}

public Boolean getActivateSMS(){
    return ActivateSMS;
}
}

Eclipse 在 Class1 中为我提供“RingSettings 无法解析为类型”=> 在 GetSettings test1 = new RingSettings();

我做错了什么?!

4

2 回答 2

2

You definitly have a few things to fix here.

  • RingSettings as defined in GetSettings returns type void not a GetSettings object.
  • RingSettings is defined to take a context as an argument.
  • RingSettings is defined as a method of a GetSettings object and should be called with GetSettings.RingSettings(context)
  • assuming you are trying to create a GetSettings object... GetSettings should have a constructor

These are just a few to get started. I don't mean to be rude here but you should be playing with some simpler examples to better learn the basics of Java. That being said, if you fix the above problems and repost your code someone should be able to get you closer to what your trying to accomplish.

Check out this info on the new keyword: (to get you started)

The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the object constructor.

Good luck

于 2012-05-20T08:00:23.520 回答
1

最简单的解决方案是实现一个辅助类:

public class GlobalVars extends Application {

    private static String value2;


    public static String getValue() {
        return value2;
    }

    public static void setValue(String value) {
        value2 = value;
    }
}

在 A 类中,将值设置为GlobalVars.setValue("something");

在 B 类中,获取值为String your_value = GlobalVars.getValue();

于 2012-05-20T08:27:26.373 回答