0
我試圖創建一個全局類。我想爲我的所有活動都有一個全局變量。創建全球課堂。錯誤:android.app.application不能轉換爲com
我的類:
package com.example.app;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import android.app.Application;
public class Records extends Application{
private int N_livelli=30;
private int[] record = new int[N_livelli];
private String path = getApplicationContext().getFilesDir().getPath() + "/Records.txt";
public void LetturaFile()
{
File f = new File(path);
if(f.exists())
{
try
{
FileReader fileLeggi = new FileReader(path);
BufferedReader lettore = new BufferedReader(fileLeggi);
String rigaLetta;
int n=0;
while((rigaLetta=lettore.readLine())!=null)
{
record[n]=Integer.valueOf(rigaLetta);
n++;
}
lettore.close();
fileLeggi.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
try
{
for(int i=0;i<N_livelli;i++) record[i]=0;
f.createNewFile();
FileWriter fileScrivi = new FileWriter(path);
fileScrivi.write("");
for(int i=0;i<N_livelli;i++) fileScrivi.append(record[i]+"\n");
fileScrivi.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public int getRecord(int livello)
{
return record[livello-1];
}
}
我在MainActivity中的OnCreate代碼:
[...]
Records records = (Records) getApplicationContext();
records.LetturaFile();
[..]
我的AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.app"
android:versionCode="3"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="9"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
[...]
</activity>
<activity
android:name=".SecondActivity"
[...]
</activity>
</application>
<application
android:name=".Records">
</application>
</manifest>
Eclipse的錯誤:android.app.application不能cast to com.example.app.Records
請幫幫我。謝謝。
我會用一個特別的偏好持有該變量在sharedPreference http://developer.android.com/reference/android/content/SharedPreferences.html – danny117 2014-10-01 21:22:58