0

I'm trying to create a file in a JSONhelper class, that is not an activity.

From what I've read, I can't use the method openFileOutput(String name, Context.MODE_PRIVATE).

I guess that only works when you're creating a file from an activity. But I can't seem to find out how to create a file from a helper class. Here is my class and what I'm trying to accomplish is pretty straight forward.

Please help and thanks in advance.

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;
        }
    }

}
2

2 Answers 2

0

To do that you need a context object which you can get by doing the following:

  1. Set the name attribute for your <application> in the manifest file:
    <application android:name="com.companyname.applicationname">....</application>
  1. Create the class applicationname which extends 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;
        }
    }
    
  2. Call getAppContext() within your helper class to get the context and use it to call openFileOutput:

    FileOutputStream fos = getAppContext().openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
    
Sign up to request clarification or add additional context in comments.

Comments

0

Use this JSON Helper Class

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();
    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.