私は OOP と Android の初心者です。小さな問題に直面していて、とてもイライラしています。永続ストレージを使用するアプリを作成しています。最初に、保存された設定にアクセスするコードをすべて MainActivity に混ぜて作成し、それが機能したので、そのコードを別のクラス ファイルに移動したいと考えました。問題は、何らかの理由で別のクラス ファイルでは機能しないことです。試行錯誤した結果、MainActivity クラス内に内部クラスを作成できることがわかりました。そのように機能します。内部クラスとして作成すれば、アクティビティを拡張するために内部クラスを作成する必要がないという事実に関連していると思います(再び)。永続ストレージ処理用の外部クラスを作成するとき、そのクラスでアクティビティを拡張する必要がありましたが、それが問題だと思いますが、よくわかりません。なぜこれが起こっているのかを説明して、正しいアプローチを提案してもらえますか? 以下に、機能するコード スニペットを含めますが、私の目標は、別のクラス ファイルにクラス PermanentStorageHelper を作成できるようにすることです。前もって感謝します!
public class MainActivity extends Activity {
public static MainActivity _mainActivity;
private TextView textView1;
// OnCreate
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Persistent preferences
PermanentStorageHelper ps = new PermanentStorageHelper();
// UI Initialization
textView1 = (TextView) findViewById(R.id.textView1);
String uId = ps.getuId();
UiHelper.displayOnTextView(this, R.id.textView1, uId);
}
// =============================================
// This is the class I'm talking about, I'm unable to move this to
// a separated class (.java) file.
// It seems to be related to the fact that, if making this a separated
// class file, I need to extend Activity again and that is what
// seems to be the problem
// =============================================
public class PermanentStorageHelper /*extends Activity*/{
// CONSTANTS
public static final String USERUNIQUEID="userUniqueID"; // Saved setting 1
public static final String FILENAME="mtcPreferences"; // Filename for persisting storage file
// Fields
public SharedPreferences shp; // SharedPreferences field (1)
public String uId;
public PermanentStorageHelper(){
// Preferences initialization (2)
shp = getSharedPreferences(FILENAME, MODE_PRIVATE);
// Read Preferences (3)
uId = shp.getString(USERUNIQUEID, null);
}
// Getters and Setters
public String getuId() {
return uId;
}
public void setuId(String uId) {
this.uId = uId;
}
}