我正在尝试在JSONhelper
类中创建一个不是活动的文件。
从我读过的内容来看,我不能使用方法openFileOutput(String name, Context.MODE_PRIVATE)
。
我想这只有在您从活动中创建文件时才有效。但我似乎无法找到如何从助手类创建文件。这是我的课程,我想要完成的是非常直接的。
请提前帮助和谢谢。
import android.content.Context;
import android.os.Environment;
import android.util.Log;
import com.checkinsystems.ez_score.model.Match;
import com.google.gson.Gson;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import static android.content.Context.MODE_PRIVATE;
import static java.security.AccessController.getContext;
public class JSONhelper {
private static final String FILE_NAME = "new_match.json";
private static final String TAG = "JSONHelper";
public static boolean exportToJSON(Context context, List<Match> matches) {
Matches newMatch = new Matches();
newMatch.setMatches(matches);
Gson gson = new Gson();
String jsonString = gson.toJson(newMatch);
Log.i(TAG, "exportToJSON: " + jsonString);
FileOutputStream fileOutputStream = null;
File file = new File(FILE_NAME);
try {
fileOutputStream = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
fileOutputStream.write(jsonString.getBytes());
return true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return false;
}
public static List<Match> importFromJSON(Context context) {
FileReader reader = null;
try {
File file = new File(FILE_NAME);
reader = new FileReader(file);
Gson gson = new Gson();
Matches matches = gson.fromJson(reader, Matches.class);
return matches.getMatches();
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
static class Matches {
List<Match> matches;
public List<Match> getMatches() {
return matches;
}
public void setMatches(List<Match> matches) {
this.matches = matches;
}
}
}
答案 0 :(得分:0)
context
对象,您可以通过执行以下操作获得该对象:name
设置 <application>
属性: <application android:name="com.companyname.applicationname">....</application>
创建类 applicationname
扩展 Application
:
public class applicationname extends Application {
private static Context context;
public void onCreate() {
super.onCreate();
applicationname.context = getApplicationContext();
}
public static Context getAppContext() {
return applicationname.context;
}
}
在您的帮助程序类中调用 getAppContext()
以获取上下文并使用它来调用 openFileOutput
:强>
FileOutputStream fos = getAppContext().openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
答案 1 :(得分:0)
使用此JSON帮助器类
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class JSONHelper extends AsyncTask<Void, Void, String> {
Context context;
String myUrl;
ProgressDialog progressDialog;
OnAsyncLoader onAsyncLoader;
HashMap<String, String> hashMap;
JSONObject hashMapWithJson;
boolean isProgressVisible;
public JSONHelper(Context context, String url, HashMap<String, String> hashMap, OnAsyncLoader onAsynckLoader, boolean isProgressVisible) {
this.context = context;
myUrl = url;
this.onAsyncLoader = onAsynckLoader;
this.hashMap = hashMap;
this.isProgressVisible = isProgressVisible;
}
public JSONHelper(Context context, String url, HashMap<String, String> hashMap, OnAsyncLoader onAsynckLoader, boolean isProgressVisible, JSONObject jsonObj) {
this.context = context;
myUrl = url;
this.onAsyncLoader = onAsynckLoader;
this.hashMap = hashMap;
this.isProgressVisible = isProgressVisible;
this.hashMapWithJson = jsonObj;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
if (isProgressVisible) {
progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Please wait a moment");
progressDialog.show();
}
}
@Override
protected String doInBackground(Void... params) {
String result = "";
try {
URL url = new URL(myUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
if (hashMap != null) {
httpURLConnection.setReadTimeout(20000);
httpURLConnection.setConnectTimeout(20000);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
OutputStream os = httpURLConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(hashMap));
writer.flush();
writer.close();
os.close();
}
if (hashMapWithJson != null) {
httpURLConnection.setReadTimeout(20000);
httpURLConnection.setConnectTimeout(20000);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestProperty("Content-Type", "application/json");
httpURLConnection.setRequestProperty("Accept", "application/json");
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
wr.writeBytes(hashMapWithJson.toString());
/*OutputStream os = httpURLConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(hashMapWithJson.toString());*/
// writer.write(getPostDataString(hashMap));
wr.flush();
wr.close();
// os.close();
}
if (httpURLConnection.getResponseCode() == 200) {
InputStreamReader inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
}
httpURLConnection.disconnect();
} catch (MalformedURLException e) {
Log.e("result", "Error = " + e.toString());
e.printStackTrace();
} catch (IOException e) {
Log.e("result", "Error = " + e.toString());
e.printStackTrace();
}
return result;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (isProgressVisible) {
progressDialog.dismiss();
}
try {
onAsyncLoader.OnResult(s);
} catch (JSONException e) {
e.printStackTrace();
}
}
String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
Log.d("url", result.toString());
return result.toString();
}
}