AsyncTaskで共有設定を取得しようとしていますが、取得できません。
ここでコンテキストを使用するにはどうすればよいですか?
package com.example.wettkampftimerbt;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.URL;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
public class network extends AsyncTask<URL, String, String> {
private final String PREFS_NAME = "prefs", W1 = "w1", W2="w2", W3="w3", W4="w4",
W5="w5", W6="w6", W7="w7", SENDBEG="sendbeg", SENDEND="sendend";
int w1, w2, w3, w4, w5, w6, w7, sendend, sendbeg;
protected String doInBackground(URL... params) {
int c2, c3, c4, c5, c6;
int w0 = 00;
try {
w1 = sendbeg;
c2 = w2;
c3 = w3;
c4 = w4;
c5 = w5;
c6 = w6;
w7 = sendend;
Socket ss = new Socket("192.168.3.100", 4455);
System.out.println(ss);
boolean stopData = true;
System.out.println("lane1 stop send");
DataOutputStream dos = new DataOutputStream(
ss.getOutputStream());
while (stopData) {
dos.writeByte(w0);
dos.writeByte(w1);
dos.writeByte(c2);
dos.writeByte(c3);
dos.writeByte(c4);
dos.writeByte(c5);
dos.writeByte(c6);
dos.writeByte(w7);
stopData=false;
}
} catch (IOException e) {
System.out.println("IO error" + e);
e.printStackTrace();
}
return "Done";
}
public void onPreExecute(){
Context context = network.this;
SharedPreferences prefs = context.getSharedPreferences("PREFS_NAME");
doInBackground();
}
public void getPrefs (Context context){
w1= Integer.valueOf(context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).getString(W1, "00"));
w2= Integer.valueOf(context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).getString(W2, "00"));
w3= Integer.valueOf(context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).getString(W3, "00"));
w4= Integer.valueOf(context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).getString(W4, "00"));
w5= Integer.valueOf(context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).getString(W5, "00"));
w6= Integer.valueOf(context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).getString(W6, "00"));
w7= Integer.valueOf(context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).getString(W7, "00"));
sendbeg= Integer.valueOf(context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).getString(SENDBEG, "00"));
sendend= Integer.valueOf(context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).getString(SENDEND, "00"));
}
}
これはスニペットです。私の問題は次のとおりです。StartでのnullPointerException(?によって引き起こされるgetPrefs(null);
)を除いて、エラーはありません。誰かが私を助けることができますか?
私はすでに多くのコンテキストの説明とアクセスしたAndroid開発者サイトを読みましたが、コンテキストとは何か、そしてそれが正確に何をするのかがわかりません。
編集:速い答えをありがとう、しかしそれはまだ働きません。ここにアクティビティ全体を入れました。サンプルを1つ提供してくれましたが、エラーが発生しました。それは私次第ですか、それともEclipseは私を嫌っていますか?
EDIT2:doInBackgroundは自分で開始しないため、自分で呼び出します。
EDIT3:今は回避され、動作します^^メインアクティビティからgetPrefsを直接呼び出してから、getPrefsからネットワークを呼び出しています...これまでのところ問題ありませんが、このNetworkOnMainThreadExceptionエラーが発生しています。今何をする?