public JSONObject getInformation() {
    JSONObject JObject = new JSONObject();
    InputStream is;

    try {
      URL url = new URL(Url);
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setRequestMethod("GET");
      conn.setDoInput(true);
      // Starts the query
      conn.connect();

      // checks for valid response from api
      int response = conn.getResponseCode();
      if (response == 200) {
        is = conn.getInputStream();
        // Convert the InputStream into a string
        String contentAsString = readResponse(is);
        JObject = new JSONObject(contentAsString);

        // Closes the input stream
        is.close();
      }
    } catch (IOException | JSONException e) {
      e.printStackTrace();
    }

    return JObject;
  } // ends jsonobject
    @Override
    protected List<Repository> doInBackground(Void... params) {
      List<Repository> repositories = new ArrayList<>();
      try {
        JSONObject responseObject =
            new ApiClient()
                .addAuthHeader()
                .setUrl(ApiClient.GET_CURRENT_USER_REPOS_URL)
                .asArray()
                .executeGet();

        if (responseObject.optInt(ApiClient.STATUS_CODE) != ApiClient.STATUS_CODE_OK) {
          cancel(true);
          return null;
        }

        JSONArray array = (JSONArray) responseObject.get(ApiClient.LIST_DATA_KEY);

        for (int i = 0; i < array.length(); i++) {
          repositories.add(new Repository(((JSONObject) array.get(i)).getString("name")));
        }

      } catch (IOException | JSONException e) {
        e.printStackTrace();
      }

      return repositories;
    }
  public boolean getEntries(User u, JFrame frame) {
    if (!Methodes.testConnectie()) {
      JFrame[] frames = {frame};
      Methodes.Disconnect(frames, "Connectie verloren, terug naar login scherm");
    }
    boolean check = false;

    DefaultHttpClient client = u.getClient();
    HttpGet getRequest =
        new HttpGet("http://" + Methodes.getIp() + "/webservice/getProjectById/" + id);
    try {
      HttpResponse resp = client.execute(getRequest);
      // Date start, Date end, String description,Project p
      BufferedReader rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
      String output = "";
      boolean oneLoop = true;
      while ((output = rd.readLine()) != null) {
        if (oneLoop) {
          Synchronisatie.setOfflineEntries(this.id, output, this.user.username);
        }
        oneLoop = false;
        System.out.println(output);
        JSONObject jsonObject = new JSONObject(output);
        JSONArray array = jsonObject.optJSONArray("entries");
        for (int i = 0; i < array.length(); i++) {
          JSONObject entry = (JSONObject) array.get(i);
          String description = entry.getString("notities");
          String name = entry.getString("achternaam");
          String firstname = entry.getString("voornaam");

          String begin = entry.getString("begin");
          String eind = entry.getString("eind");

          System.out.println(eind);

          Date start = Timestamp.valueOf(begin);
          Date end;
          if (eind.equals("0000-00-00 00:00:00")) {
            end = null;
          } else {

            end = Timestamp.valueOf(eind);
          }
          int uid = entry.getInt("uid");
          String trid = entry.getString("trid");
          // int rid = entry.getInt("rid");
          if (entries.add(new Entry(start, end, description, u, this.id, trid))) check = true;
          // System.out.println(new Entry(start,end,description,this,new User(uid,firstname,name)));

        }
      }

    } catch (IOException | JSONException e) {
      e.printStackTrace();
    } finally {
      client.getConnectionManager().shutdown();
    }
    return check;
  }
 @Override
 protected List<Schule> doInBackground(Void... arg0) {
   try {
     return BackendConnectParser.getAvailableSchools();
   } catch (IOException | JSONException e) {
     e.printStackTrace();
   }
   return null;
 }
Beispiel #5
0
  public static void main(String[] args) {
    if (args.length < 1) {
      System.out.println("Usage: MixServerRMI [settings file]");
      return;
    }

    try {
      MixServerRMI rmiserv = new MixServerRMI(args[0]);
    } catch (IOException | JSONException | NotBoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Beispiel #6
0
  @Override
  protected Void doInBackground(Void... voids) {

    URL url;
    HttpURLConnection urlConn;

    try {

      JSONObject jsonParam = new JSONObject();
      url =
          new URL(
              "http://192.168.1.179/api/626b39467d5a4f110a85bc2f0843b7/lights/"
                  + lightModel.id.toString()
                  + "/state");

      urlConn = (HttpURLConnection) url.openConnection();
      urlConn.setDoInput(true);
      urlConn.setDoOutput(true);
      urlConn.setUseCaches(false);
      urlConn.setRequestMethod("PUT");
      urlConn.setRequestProperty("Content-Type", "application/json");
      urlConn.setRequestProperty("Accept", "application/json");

      jsonParam.put("on", Boolean.parseBoolean(lightModel.stateOn));
      jsonParam.put("bri", Integer.parseInt(lightModel.stateBrightness));

      if (lightModel.stateSaturation != null && lightModel.stateHue != null) {
        jsonParam.put("sat", Integer.parseInt(lightModel.stateSaturation));
        jsonParam.put("hue", Integer.parseInt(lightModel.stateHue));
      }

      OutputStream os = new BufferedOutputStream(urlConn.getOutputStream());
      os.write(jsonParam.toString().getBytes("UTF-8"));
      os.close();

      BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
      String inputLine;
      StringBuilder response = new StringBuilder();

      while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
      }
      in.close();

    } catch (IOException | JSONException e) {
      e.printStackTrace();
    }

    return null;
  }
  @Override
  protected List<StockViewBean> doInBackground(Context[] params) {
    try {
      // for(StockViewBean viewBean:stocks){
      downloader.getYahooData(stocks);
      // }
      // if (BuildConfig.DEBUG) Log.v(StockActivity.REFACTOR_L;OG_TAG, "First url: " + urls[0]);
      return stocks;
    } catch (IOException | JSONException e) {
      // Log.e("JSON", "DownloadURL IO error.");
      e.printStackTrace();
    }

    return null;
  }
    @Override
    protected JSONObject doInBackground(Bitmap... sub) {

      Bitmap bitmap = sub[0];
      b = bitmap;

      // Creates Byte Array from picture
      URL url;
      try {

        url = new URL("https://imgur-apiv3.p.mashape.com/3/image");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        String data =
            URLEncoder.encode("image", "UTF-8")
                + "="
                + URLEncoder.encode(getImageLink(bitmap), "UTF-8");

        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");
        conn.addRequestProperty("X-Mashape-Key", SecretConstants.getImgurApiKey(c));
        conn.addRequestProperty("Authorization", "Client-ID " + "bef87913eb202e9");
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        conn.connect();
        StringBuilder stb = new StringBuilder();
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data);
        wr.flush();

        // Get the response
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = rd.readLine()) != null) {
          stb.append(line).append("\n");
        }
        wr.close();
        rd.close();
        return new JSONObject(stb.toString());

      } catch (IOException | JSONException e) {
        e.printStackTrace();
      }

      return null;
    }
Beispiel #9
0
  // While chatting with the server
  public void whileChatting() throws IOException {

    try {
      obj.put("message", "");
      jsonObjectString = obj.toString();
      output.writeObject(jsonObjectString);
      output.flush();
    } catch (IOException | JSONException e) {
      e.printStackTrace();
    }

    ableToType(true);

    do {
      try {
        obj = new JSONObject((String) input.readObject());

        /*
         * If the "file" directory in the JSONObject is not empty it means someone just sent a file, so then
         * we'll go ahead and ask the user if they want to download the file.
         */
        if (!obj.getString("file").equals("") && downloadFile) {
          int result =
              JOptionPane.showConfirmDialog(
                  null,
                  obj.getString("sendingUser")
                      + " wants to send you the file: "
                      + obj.getString("fileName")
                      + ".\nAccept?",
                  null,
                  JOptionPane.YES_NO_OPTION);
          if (result == JOptionPane.YES_OPTION) {
            saveFile();
          }
        }

        downloadFile = true;

        showUsersOnline();
        showMessage("\n" + obj.get("message"));
      } catch (ClassNotFoundException classNotFoundException) {
        showMessage("\n Unrecognized class");
      } catch (JSONException e) {
        e.printStackTrace();
      }
    } while (true);
  }
 public SharePreFileManager(Context context, String config) {
   InputStream in = null;
   try {
     in = context.getAssets().open(config, AssetManager.ACCESS_BUFFER);
     res = new JSONObject(FileUtils.read(in));
   } catch (IOException | JSONException e) {
     e.printStackTrace();
   } finally {
     if (in != null) {
       try {
         in.close();
       } catch (IOException e) {
         e.printStackTrace();
       }
     }
   }
 }
  protected JSONObject doInBackground(String... strings) {
    JSONObject jsonObject = null;

    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder().url(URL_JSON).build();

    Response response;
    try {
      response = client.newCall(request).execute();
      if (!response.isSuccessful()) throw new IOException(String.valueOf(response));

      jsonObject = new JSONObject(response.body().string());
    } catch (IOException | JSONException e) {
      e.printStackTrace();
    }
    return jsonObject;
  }
Beispiel #12
0
  @Override
  public void onLoad() {
    instance = this;
    start = (int) System.currentTimeMillis();

    if (!this.getDataFolder().exists()) {
      File dir = this.getDataFolder();
      dir.mkdir();
    }

    try {
      CRYPTIC_JSON =
          new JsonCache(
                  new File(
                      CrypticMain.get().getDataFolder().getAbsolutePath()
                          + References.CRYPTIC_JSON_FILE),
                  new URL(References.CRYPTIC_JSON_URL),
                  15)
              .getJson();
    } catch (IOException | JSONException e) {
      e.printStackTrace();
      try {
        CRYPTIC_JSON = new JSONObject().put("error", e.toString());
      } catch (JSONException e1) {
        e1.printStackTrace();
      }
    }

    try {
      References.MODULE_DIRECTORY =
          References.WORKING_DIRECTORY + CRYPTIC_JSON.getString("module_directory");
    } catch (JSONException e1) {
      e1.printStackTrace();
    }

    try {
      clogger.log(
          Level.INFO,
          CRYPTIC_JSON.getJSONObject("messages").getString("loading"),
          new Object[] {this.getDescription().getName(), this.getDescription().getVersion()});
    } catch (JSONException e) {
      e.printStackTrace();
    }
  }
Beispiel #13
0
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    // Set header Content-type of the HttpResponse
    // Read more here. https://en.wikipedia.org/wiki/List_of_HTTP_header_fields
    response.setContentType("application/json");
    // For accepting cross domain requests
    response.addHeader("Access-Control-Allow-Origin", "*");
    response.addHeader("Access-Control-Allow-Methods", "GET, PUT, POST, OPTIONS, DELETE");
    response.addHeader("Access-Control-Allow-Headers", "Content-Type");

    // get email by get method
    String email = request.getParameter(Signup.EMAIL);
    if (email == null || email.equals("")) {
      response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Field 'email' required");
      return;
    }

    // get password by get method
    String password = request.getParameter(Signup.PASSWORD);

    if (password == null || password.equals("")) {
      response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Field required");
      return;
    }

    try {
      Signup signup = new Signup(email, password);
      // insert a single value in database
      String _id = DB.insertValue(signup);
      // creating a json object and put the id of data inserted into it
      JSONObject jsonResponse = new JSONObject();
      jsonResponse.put(Signup.ID, _id);

      // function to print the id ie return response
      response.getWriter().write(jsonResponse.toString());
    }

    // if input output erroroccurs due to database
    catch (IOException | JSONException e) {
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
      e.printStackTrace();
    }
  }
    @TargetApi(Build.VERSION_CODES.KITKAT)
    @Override
    protected Void doInBackground(Void... params) {

      String hostName = "52.26.125.237";
      Integer portNumber = 4444;
      JSONOutputStream outToServer;
      JSONInputStream inFromServer;

      HashMap<String, String> highScore = new HashMap<>();

      highScore.put("Command", "View High Scores");
      Socket toServer = null;

      try {

        toServer = new Socket(hostName, portNumber);
        outToServer = new JSONOutputStream(toServer.getOutputStream());
        outToServer.writeObject(highScore);

      } catch (IOException | JSONException e) {

        Toast.makeText(
                getApplicationContext(),
                "Couldn't connect to server."
                    + "Please ensure that either Wi-Fi or Data is enabled.",
                Toast.LENGTH_SHORT)
            .show();
      }

      try {
        inFromServer = new JSONInputStream(toServer.getInputStream());
        highScores = (ArrayList<String>) inFromServer.readObject();

      } catch (IOException | JSONException e) {

        e.printStackTrace();
      }

      highScoresList = highScores.toArray(new CharSequence[highScores.size()]);

      return null;
    }
 @Override
 public Object fromBody(TypedInput body, Type type) throws ConversionException {
   InputStream inputStream = null;
   JSONObject jsonObject = null;
   try {
     inputStream = body.in();
     jsonObject = new JSONObject(IOUtils.toString(inputStream, UTF_8));
   } catch (IOException | JSONException e) {
     e.printStackTrace();
   } finally {
     try {
       if (inputStream != null) {
         inputStream.close();
       }
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
   return jsonObject;
 }
  public boolean setUsersInProject(JFrame frame, User u) {
    if (!Methodes.testConnectie()) {
      JFrame[] frames = {frame};
      Methodes.Disconnect(frames, "Connectie verloren, terug naar login scherm");
    }
    boolean check = false;
    this.entries = new ArrayList<Entry>();
    DefaultHttpClient client = u.getClient();
    HttpGet getRequest =
        new HttpGet("http://" + Methodes.getIp() + "/webservice/getUsersInProject/" + id);
    try {
      HttpResponse resp = client.execute(getRequest);
      // uid,uname,voonaam,achternaam,
      BufferedReader rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
      String output = "";
      while ((output = rd.readLine()) != null) {
        System.out.println(output);
        JSONObject object = new JSONObject(output);
        JSONArray array = object.optJSONArray("users");
        for (int i = 0; i < array.length(); i++) {
          JSONObject json = array.getJSONObject(i);
          int uid = json.getInt("uid");
          String username = json.getString("uname");
          String firstname = json.getString("voornaam");
          String name = json.getString("achternaam");
          User usr = new User(uid, firstname, name);
          usr.setUsername(username);
          if (user == null) user = u;
          usr.getRightsFromDB(frame, this.id, user);
          users.add(usr);
          System.out.println(user);
        }
      }

    } catch (IOException | JSONException e) {
      e.printStackTrace();
    } finally {
      client.getConnectionManager().shutdown();
    }
    return check;
  }
    @Override
    protected JSONArray doInBackground(Void... params) {
      HttpClient httpclient = new DefaultHttpClient();
      HttpGet httpget =
          new HttpGet("http://apexbackend.azurewebsites.net/api/advices/patient/" + patientId);

      httpget.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded;charset=UTF-8");
      httpget.setHeader("Authorization", "Bearer " + access_token);

      JSONArray json = new JSONArray();

      // Execute HTTP Get Request
      try {
        HttpResponse response = httpclient.execute(httpget);
        String json_string = EntityUtils.toString(response.getEntity());
        json = new JSONArray(json_string);
        System.out.println(json);
      } catch (IOException | JSONException e) {
        e.printStackTrace();
      }

      return json;
    }
  public boolean getData(JFrame frame, User u) {
    if (!Methodes.testConnectie()) {
      JFrame[] frames = {frame};
      Methodes.Disconnect(frames, "Connectie verloren, terug naar login scherm");
    }
    boolean check = false;
    this.entries = new ArrayList<Entry>();
    DefaultHttpClient client = new DefaultHttpClient();
    Credentials cred = new UsernamePasswordCredentials(u.getUsername(), u.getPassword());
    client.getCredentialsProvider().setCredentials(AuthScope.ANY, cred);
    List<String> authprefs = new ArrayList<String>(1);
    authprefs.add(AuthPolicy.DIGEST);
    client.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authprefs);
    HttpGet getRequest =
        new HttpGet("http://" + Methodes.getIp() + "/webservice/getProjectById/" + id);
    try {
      HttpResponse resp = client.execute(getRequest);
      // Date start, Date end, String description,Project p
      BufferedReader rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
      String output = "";
      while ((output = rd.readLine()) != null) {
        System.out.println(output);
        JSONObject jsonObject = new JSONObject(output);

        this.projectName = jsonObject.getString("projectnaam");
        this.customer = jsonObject.getString("opdrachtgever");
        this.setStartDate(Timestamp.valueOf(jsonObject.getString("begindatum")));
        description = jsonObject.getString("omschrijving");
      }

    } catch (IOException | JSONException e) {
      e.printStackTrace();
    } finally {
      client.getConnectionManager().shutdown();
    }
    return check;
  }
  protected String makeRequest() {
    try {
      // URL
      URL url = new URL(serverUrl + "/set-name");
      HttpURLConnection connection = (HttpURLConnection) url.openConnection();
      connection.setDoOutput(true);
      connection.setRequestMethod("POST");

      // Body
      JSONObject json = new JSONObject();
      json.put("deviceId", deviceId);
      json.put("name", name);

      // Send
      OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
      writer.write(json.toString() + "\n");
      writer.close();

      code = connection.getResponseCode();
      if (code == HttpURLConnection.HTTP_OK) {
        BufferedReader inFromServer =
            new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String body = "", line;
        while ((line = inFromServer.readLine()) != null) {
          body = body + line;
        }

        return body;
      } else {
        Log.d("MapUpdater", "" + connection.getResponseCode());
        return connection.getResponseMessage();
      }
    } catch (IOException | JSONException e) {
      return e.getMessage();
    }
  }
  public static byte[] fetchContent(
      Context context, String language, String page, boolean readOnly, int templateType) {
    Class[] scriptingClasses = {JavaScriptEngine.class, SchemeEngine.class};

    language = language.toLowerCase();

    ArrayList<String> languages = new ArrayList<>();
    languages.add(BootstrapSiteExporter.LANGUAGE_ALL.toLowerCase());

    if (languages.contains(language) == false) languages.add(language.toLowerCase());

    if (page == null || page.trim().length() == 0) {
      try {
        JSONArray declaredMethods = BootstrapSiteExporter.methodsForLanguage(context, language);

        AssetManager am = context.getAssets();

        String template = "embedded_website/docs/scripting_template.html";

        if (readOnly && templateType == BootstrapSiteExporter.TEMPLATE_TYPE_BOOTSTRAP)
          template = "embedded_website/docs/scripting_template_readonly.html";
        else if (templateType == BootstrapSiteExporter.TEMPLATE_TYPE_JEKYLL)
          template = "embedded_website/docs/scripting_template_jekyll.html";

        InputStream in = am.open(template);

        // http://stackoverflow.com/questions/309424/read-convert-an-inputstream-to-a-string
        Scanner s = new Scanner(in).useDelimiter("\\A");

        String content = "";

        if (s.hasNext()) content = s.next();

        content = content.replace("{{ METHOD_DEFINITIONS }}", declaredMethods.toString(2));
        content = content.replace("{{ LANGUAGE }}", language.toLowerCase());

        return content.getBytes(Charset.forName("UTF-8"));
      } catch (IOException | JSONException e) {
        e.printStackTrace();
      }

      return "404 ERROR".getBytes(Charset.forName("UTF-8"));
    } else {
      if (page.startsWith("all_")) language = "all";

      try {
        AssetManager am = context.getAssets();

        String template = "embedded_website/docs/method_template.html";

        if (readOnly && templateType == BootstrapSiteExporter.TEMPLATE_TYPE_BOOTSTRAP)
          template = "embedded_website/docs/method_template_readonly.html";
        else if (templateType == BootstrapSiteExporter.TEMPLATE_TYPE_JEKYLL)
          template = "embedded_website/docs/method_template_jekyll.html";

        InputStream in = am.open(template);

        // http://stackoverflow.com/questions/309424/read-convert-an-inputstream-to-a-string
        Scanner s = new Scanner(in).useDelimiter("\\A");

        String content = "";

        if (s.hasNext()) content = s.next();

        s.close();

        in = am.open("embedded_website/docs/" + language.toLowerCase() + "/" + page);

        s = new Scanner(in).useDelimiter("\\A");

        String pageContent = "";

        if (s.hasNext()) pageContent = s.next();

        s.close();

        for (Class classObj : scriptingClasses) {
          Method[] methods = classObj.getMethods();

          for (Method method : methods) {
            Annotation[] annotations = method.getDeclaredAnnotations();

            for (Annotation annotation : annotations) {
              if (annotation instanceof ScriptingEngineMethod) {
                ScriptingEngineMethod scriptAnnotation = (ScriptingEngineMethod) annotation;

                if (page.equals(scriptAnnotation.assetPath())) {
                  StringBuilder args = new StringBuilder();

                  for (String argument : ((ScriptingEngineMethod) annotation).arguments()) {
                    if (args.length() > 0) args.append(", ");

                    args.append(argument);
                  }

                  content =
                      content.replace(
                          "{{ METHOD_NAME }}", method.getName() + "(" + args.toString() + ")");
                  content =
                      content.replace(
                          "{{ LANGUAGE }}",
                          ((ScriptingEngineMethod) annotation).language().toLowerCase());
                  content = content.replace("{{ PAGE }}", page);
                }
              }
            }
          }
        }

        content = content.replace("{{ METHOD_DOCUMENTATION }}", pageContent);

        return content.getBytes(Charset.forName("UTF-8"));
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    return "404 ERROR".getBytes(Charset.forName("UTF-8"));
  }
Beispiel #21
0
  /**
   * **************************************************************************************************************************************
   * STORE FAVORITES
   * **************************************************************************************************************************************
   */
  private void storeFavorite(View view) {

    int imgPosition = -1;
    for (int i = 0; i < jsonArray.size(); i++) {
      TextView tv = (TextView) view.findViewById(R.id.species_name);
      String name = tv.getText().toString();
      if (jsonArray.get(i).getName().equals(name)) imgPosition = i;
    }

    // ===================================================================
    // Step 1: Get all text views and the image
    // ===================================================================
    TextView speciesName = (TextView) view.findViewById(R.id.species_name);
    TextView scientific = (TextView) view.findViewById(R.id.scientific);
    TextView common = (TextView) view.findViewById(R.id.common);
    Log.d("KENNY", "Image Position: " + String.valueOf(imgPosition));
    Log.d("KENNY", "Photos List size: " + String.valueOf(photosList.size()));
    String favoriteImage = photosList.get(imgPosition);
    TextView individual = (TextView) view.findViewById(R.id.individual);
    TextView aggregate = (TextView) view.findViewById(R.id.aggregate);
    TextView minimum = (TextView) view.findViewById(R.id.minimum);
    TextView season = (TextView) view.findViewById(R.id.season);
    TextView record = (TextView) view.findViewById(R.id.record);

    // ===================================================================
    // Step 2: Store all information in a single json object
    // ===================================================================
    JSONObject favorite = new JSONObject();
    try {
      favorite.put("scientific", scientific.getText().toString());
      favorite.put("common", common.getText().toString());
      favorite.put("image", favoriteImage);
      favorite.put("individual", individual.getText().toString());
      favorite.put("aggregate", aggregate.getText().toString());
      favorite.put("minimum", minimum.getText().toString());
      favorite.put("season", season.getText().toString());
      favorite.put("record", record.getText().toString());
    } catch (JSONException e) {
      Toast.makeText(
              getActivity(),
              "Could not save your favorite fish at this time...",
              Toast.LENGTH_SHORT)
          .show();
    }

    // ===================================================================
    // Step 3: Get the json array and add it, or make a new one if necessary.
    //         Then write it to the new json text.
    // ===================================================================
    JsonStorage json = new JsonStorage(getActivity());
    boolean isOutermostThere = false;
    try {
      String favoriteJson = json.readProfileJSON();
      JSONObject object = new JSONObject(favoriteJson);
      JSONObject outer =
          object.getJSONObject("outermost"); // Get outermost json object (everything)
      isOutermostThere = true; // There is a JSON object already made
      JSONObject favorites = outer.getJSONObject("favorites"); // Get the "favorites" JSONObject
      favorites.put(
          speciesName.getText().toString(), favorite); // Add it to the favorites object list
      outer.put("favorites", favorites); // Overwrite the favorites list with new one
      object.put("outermost", outer); // Add outermost to the JSON object
      json.writeJSON(object); // Populate this in the memory
      Toast.makeText(getActivity(), "You have added a favorite!", Toast.LENGTH_SHORT).show();
    } catch (IOException | JSONException e) {
      // ********* Go here if the array did not already exist ***********//
      JSONObject newFavList = new JSONObject(); // Create new JSONObject
      try {
        newFavList.put(speciesName.getText().toString(), favorite); // Add the first entry
        if (isOutermostThere) { // If there is a JSONObject already made
          String favoriteJson = json.readProfileJSON(); // Load the populated data
          JSONObject object = new JSONObject(favoriteJson); // Get the whole json object
          JSONObject outer = object.getJSONObject("outermost"); // Get outermost object
          outer.put("favorites", newFavList); // Add new favorites array to the profile object
          object.put("outermost", outer);
          json.writeJSON(object); // Write this to the memory
        } else {
          JSONObject favorites = new JSONObject(); // Create new favorites object
          favorites.put("favorites", newFavList); // Add favorites list to favorites JSON object
          JSONObject outer = new JSONObject(); // Create new outermost JSON since it doesnt exist
          outer.put("outermost", favorites); // Store new favorites list into it.
          json.writeJSON(outer);
        }
        Toast.makeText(
                getActivity(), "You have added your first favorite fish!", Toast.LENGTH_SHORT)
            .show();
      } catch (IOException | JSONException e1) {
        Toast.makeText(
                getActivity(),
                "Something went wrong saving.  Please try again later.",
                Toast.LENGTH_SHORT)
            .show();
        e1.printStackTrace();
      }
    }
  }
Beispiel #22
0
  @Override
  public View onCreateView(
      LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    // Get the Species Type: "Shark," "Billfish," etc.
    jsonItem = this.getArguments().getString("type");
    Log.d("KENNY", "String argument = " + jsonItem);

    try {
      JsonStorage jStore = new JsonStorage(getActivity());
      String temp = jStore.loadSpeciesJSON();
      populateItem(temp);
    } catch (IOException | JSONException e) {
      e.printStackTrace();
    }

    final View myInflatedView = inflater.inflate(R.layout.fragment_species, container, false);

    /**
     * ************************************************************************** **************
     * Favorite a fish ********************************************
     * **************************************************************************
     */
    Button favorite = (Button) myInflatedView.findViewById(R.id.favorite);
    favorite.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            storeFavorite(myInflatedView);
          }
        });

    /**
     * ************************************************************************** ***************
     * Log a fish ************************************************
     * **************************************************************************
     */
    Button log = (Button) myInflatedView.findViewById(R.id.log);
    log.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            TextView text = (TextView) myInflatedView.findViewById(R.id.species_name);
            Calendar c = Calendar.getInstance();
            String formattedDate = new SimpleDateFormat("MMM-dd-yyyy").format(c.getTime());

            Intent intent = new Intent(getActivity(), LogActivity.class);
            intent.putExtra("speciesName", text.getText());
            intent.putExtra("currDate", formattedDate);
            intent.putExtra("title", "Log a Fish");
            startActivity(intent);
          }
        });

    // Set the top text (above all the pics) to typeface and to this text
    TextView typeTextView = (TextView) myInflatedView.findViewById(R.id.type);
    StringBuilder typeString = new StringBuilder(); // Create string to capitalize first letters
    String[] typeArray = jsonItem.split("_"); // Split string by underscores
    for (int i = 0; i < typeArray.length; i++) { // Loop through only if multiple words
      String temp = typeArray[i]; // Get the first word
      typeString.append(
          temp.substring(0, 1).toUpperCase()); // Capitalize the first letter and append
      typeString.append(
          temp.substring(
              1, temp.length())); // Append the rest of the word to capitalized first letter
      if (typeArray.length - i > 1)
        typeString.append(" "); // Put a space if there are multiple words.
    }
    typeTextView.setText(typeString.toString());
    Typeface typeTypeFace =
        Typeface.createFromAsset(getActivity().getAssets(), "fonts/Walkway_Bold.ttf");
    typeTextView.setTypeface(typeTypeFace);

    // Loop through each species of the specified type and populate below the top text
    for (int i = 0; i < jsonArray.size(); i++) {

      // Get the linear layout and set the parameters
      LinearLayout ll = (LinearLayout) myInflatedView.findViewById(R.id.species_ll);
      LinearLayout.LayoutParams params =
          new LinearLayout.LayoutParams(
              LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
      params.gravity = Gravity.CENTER;

      // Use this for each image in the list
      final ImageView image = new ImageView(getActivity());
      image.setAdjustViewBounds(true); // Scales it to the screen
      image.setId(i); // Sets each with unique id
      ll.addView(image, params); // Adds the ImageView to screen BEFORE adding image (important)
      Picasso.with(getActivity()) // THEN you add the image from photosList
          .load(photosList.get(i))
          .into(image);

      // Next, set click listener.  It makes a different view appear ABOVE the species images
      image.setOnClickListener(
          new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              populateList(myInflatedView, image);
            }
          });
    }
    return myInflatedView;
  }