当我点击保存按钮时,我当前正试图将我的微调器的选定位置保存在文本文件中。
目前这就是我所拥有的。微调器工作正常但是当我尝试添加零件以保存微调器位置(saveSettings)时,这就是我的问题所在。
我收到以下错误:
Error:(56, 85) error: incompatible types: String cannot be converted to File
Error:(61, 40) error: method getPosition in class ArrayAdapter<T> cannot be applied to given types;
required: CharSequence
found: no arguments
reason: actual and formal argument lists differ in length
where T is a type-variable:
T extends Object declared in class ArrayAdapter
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.
我认为问题在于我尝试将两种不同的方法结合起来,但是我还在学习,我对于保存选定的微调器位置的正确方法感到困惑。
public class MainActivity extends AppCompatActivity {
Spinner spinner;
ArrayAdapter<CharSequence> adapter;
String SelectedServer;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner) findViewById(R.id.spinner);
adapter = ArrayAdapter.createFromResource(this, R.array.serverUrl, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
SelectedServer = parent.getItemAtPosition(position).toString();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void saveSettings(View view) {
File txtFolder = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/MyFolder/");
if (!txtFolder.exists()) {
txtFolder.mkdir();
}
File file = new File(txtFolder, "setting.txt");
String.valueOf(SelectedServer.getBytes());
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write(SelectedServer.getBytes());
fos.close();
Toast.makeText(getApplicationContext(),"Setting Saved", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
所以我正在寻找帮助来解决这个问题。 有什么建议吗?
答案 0 :(得分:0)
这一行是第一个错误:
File txtFolder = Environment.getExternalStorageDirectory().getAbsolutePath()+"/MyFolder/";
您正在为文件分配string
值。您可能希望将该值放在构造函数new File(String path)
中:
File txtFolder = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/MyFolder/");
第二个错误是:
String SelectedServer = adapter.getPosition().toString();
我会使用String.valueOf(adapter.getPosition());
或隐式转化""+adapter.getPosition();
。
如果情况并非如此,那么您需要检查getPosition
返回的内容(可能是空的)。