예제 #1
0
  /**
   * Method to fetch Task data from appropriate API
   *
   * @param index Position of the Feed in List
   * @param url The url of the API
   */
  private void fetchTaskData(final int index, String url) {
    JsonObjectRequest jsonObjectRequest =
        new JsonObjectRequest(
            url,
            null,
            new Response.Listener<JSONObject>() {
              @Override
              public void onResponse(JSONObject response) {
                try {
                  String taskName = response.getString("name");
                  String taskDescription = response.getString("description");
                  String taskState = response.getString("state");
                  String modifiedTitle = "";

                  Cursor cursor =
                      getContentResolver()
                          .query(
                              Contract.FeedEntry.CONTENT_URI,
                              FEED_COLUMNS,
                              Contract.FeedEntry._ID + "=" + index,
                              null,
                              null);
                  if (cursor != null && cursor.moveToFirst()) {
                    modifiedTitle =
                        cursor
                            .getString(COL_FEED_TITLE)
                            .replace("{taskName}", '"' + taskName + '"');
                  }

                  ContentValues contentValues = new ContentValues();
                  contentValues.put(Contract.FeedEntry._ID, index);
                  contentValues.put(Contract.FeedEntry.COLUMN_FEED_TITLE, modifiedTitle);
                  contentValues.put(Contract.FeedEntry.COLUMN_FEED_TASK_NAME, taskName);
                  contentValues.put(
                      Contract.FeedEntry.COLUMN_FEED_TASK_DESCRIPTION, taskDescription);
                  contentValues.put(Contract.FeedEntry.COLUMN_FEED_TASK_STATE, taskState);

                  getContentResolver()
                      .update(
                          Contract.FeedEntry.CONTENT_URI,
                          contentValues,
                          Contract.FeedEntry._ID + " = ?",
                          new String[] {Integer.toString(index)});

                } catch (JSONException e) {
                  showToast("Error in working with JSON: " + e.getMessage());
                }
              }
            },
            new Response.ErrorListener() {
              @Override
              public void onErrorResponse(VolleyError error) {
                showToast("VolleyError: " + error.getMessage());
              }
            });

    // Add request to the queue
    AppController.getInstance().getRequestQueue().add(jsonObjectRequest);
  }
예제 #2
0
  /**
   * Method to fetch Profile data from appropriate API
   *
   * @param index Position of the Feed in List
   * @param url The url of the API
   */
  private void fetchProfileData(final int index, String url) {
    JsonObjectRequest jsonObjectRequest =
        new JsonObjectRequest(
            url,
            null,
            new Response.Listener<JSONObject>() {
              @Override
              public void onResponse(JSONObject response) {
                try {
                  String firstName = response.getString("first_name");
                  String avatarUrl = response.getString("avatar_mini_url");
                  String modifiedTitle = "";

                  Cursor cursor =
                      getContentResolver()
                          .query(
                              Contract.FeedEntry.CONTENT_URI,
                              FEED_COLUMNS,
                              Contract.FeedEntry._ID + "=" + index,
                              null,
                              null);
                  if (cursor != null && cursor.moveToFirst()) {
                    modifiedTitle =
                        cursor
                            .getString(COL_FEED_TITLE)
                            .replace("{profileName}", '"' + firstName + '"');
                  }

                  ContentValues contentValues = new ContentValues();
                  contentValues.put(Contract.FeedEntry._ID, index);
                  contentValues.put(Contract.FeedEntry.COLUMN_FEED_TITLE, modifiedTitle);
                  contentValues.put(Contract.FeedEntry.COLUMN_FEED_AUTHOR, firstName);
                  contentValues.put(
                      Contract.FeedEntry.COLUMN_FEED_AUTHOR_PROFILE,
                      "https://stage.airtasker.com/android-code-test" + avatarUrl);

                  getContentResolver()
                      .update(
                          Contract.FeedEntry.CONTENT_URI,
                          contentValues,
                          Contract.FeedEntry._ID + " = ?",
                          new String[] {Integer.toString(index)});

                } catch (JSONException e) {
                  showToast("Error in working with JSON: " + e.getMessage());
                }
              }
            },
            new Response.ErrorListener() {
              @Override
              public void onErrorResponse(VolleyError error) {
                showToast("VolleyError: " + error.getMessage());
              }
            });

    // Add request to the queue
    AppController.getInstance().getRequestQueue().add(jsonObjectRequest);
  }
예제 #3
0
  // Gets the Events
  public void getEvents() {
    String tag_string_req = "req_events";

    StringRequest strReq =
        new StringRequest(
            Request.Method.POST,
            URL,
            new Response.Listener<String>() {

              @Override
              public void onResponse(String response) {

                hideDialog();

                try {
                  JSONObject jObj = new JSONObject(response);
                  boolean error = jObj.getBoolean("error");

                  if (!error) {
                    layout.removeAllViews();
                    events = new ArrayList<JSONObject>();

                    int counter = 0;
                    while (jObj.has(Integer.toString(counter))) {
                      events.add(jObj.getJSONObject(Integer.toString(counter)));
                      counter++;
                    }
                    drawEvents();
                  } else {
                    String error_msg = jObj.getString("error_msg");
                    // Toast.makeText(getBaseContext(),error_msg, Toast.LENGTH_LONG).show();
                  }
                } catch (JSONException e) {
                  e.printStackTrace();
                }
              }
            },
            new Response.ErrorListener() {

              @Override
              public void onErrorResponse(VolleyError error) {
                hideDialog();
                // Toast.makeText(getApplicationContext(),"Something went wrong",
                // Toast.LENGTH_LONG).show();
              }
            }) {

          @Override
          protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put("tag", "get");
            params.put("uid", uid);

            return params;
          }
        };
    AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
  }
예제 #4
0
  // Gets the country code of the user so the app can add Country Codes to the Phone numbers in the
  // users contacts.
  public void getCountry() {
    String tag_string_req = "req_country";
    if (first) {
      pDialog.setMessage("Getting your contacts...");
      showDialog();
    }

    StringRequest strReq =
        new StringRequest(
            Request.Method.POST,
            CONTACTS_URL,
            new Response.Listener<String>() {

              @Override
              public void onResponse(String response) {

                try {
                  JSONObject jObj = new JSONObject(response);
                  boolean error = jObj.getBoolean("error");
                  if (!error) {
                    JSONObject details = jObj.getJSONObject("result");
                    country = details.getString("country");
                    ownphone = details.getString("phone");
                    getContacts();
                  } else {
                    country = null;
                    ownphone = null;
                  }
                } catch (JSONException e) {

                }
              }
            },
            new Response.ErrorListener() {

              @Override
              public void onErrorResponse(VolleyError error) {
                // Toast.makeText(getApplicationContext(),"something went wrong",
                // Toast.LENGTH_LONG).show();
              }
            }) {

          @Override
          protected Map<String, String> getParams() {
            // Posting params to register url
            Map<String, String> params = new HashMap<String, String>();
            params.put("tag", "check");
            params.put("uid", uid);
            return params;
          }
        };

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
  }
  public static void createUser(String name, String email, Context c, final VolleyRes res) {
    String tag_json_obj = "json_obj_req";

    String url = "http://api.androidhive.info/volley/person_object.json";

    final ProgressDialog pDialog = new ProgressDialog(c);
    pDialog.setMessage("Loading...");
    pDialog.show();

    JsonObjectRequest jsonObjReq =
        new JsonObjectRequest(
            Request.Method.POST,
            url,
            null,
            new Response.Listener<JSONObject>() {

              @Override
              public void onResponse(JSONObject response) {
                Log.d(TAG, response.toString());
                pDialog.hide();
                res.onSuccessResponse();
              }
            },
            new Response.ErrorListener() {

              @Override
              public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                pDialog.hide();
                res.onFailureResponse();
              }
            }) {

          @Override
          protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put("name", "Androidhive");
            params.put("email", "*****@*****.**");
            params.put("password", "password123");

            return params;
          }
        };

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
  }
예제 #6
0
  // Checks whether a contact is in the details database or not.
  public void checkContact(final String phone, final String name) {
    String tag_string_req = "req_phoneno";

    StringRequest strReq =
        new StringRequest(
            Request.Method.POST,
            CONTACTS_URL,
            new Response.Listener<String>() {

              @Override
              public void onResponse(String response) {

                try {
                  JSONObject jObj = new JSONObject(response);
                  boolean error = jObj.getBoolean("error");
                  if (!error) {
                    String uid = jObj.getJSONObject("uid").getString("UID");
                    Log.d("added:", name);
                    user_db.addContact(uid, name, phone);
                  }
                } catch (JSONException e) {

                }
              }
            },
            new Response.ErrorListener() {

              @Override
              public void onErrorResponse(VolleyError error) {
                // Toast.makeText(getApplicationContext(),"something went wrong",
                // Toast.LENGTH_LONG).show();
              }
            }) {

          @Override
          protected Map<String, String> getParams() {
            // Posting params to register url
            Map<String, String> params = new HashMap<String, String>();
            params.put("tag", "get");
            params.put("phone", phone);
            return params;
          }
        };

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
  }
예제 #7
0
  /** Checks whether the users UID is in the details DB. If not, starts the PhoneActivity. */
  public void firstLogin() {
    String tag_string_req = "req_phone";
    StringRequest strReq =
        new StringRequest(
            Request.Method.POST,
            CONTACTS_URL,
            new Response.Listener<String>() {

              @Override
              public void onResponse(String response) {

                try {
                  JSONObject jObj = new JSONObject(response);
                  boolean error = jObj.getBoolean("error");
                  Log.d("test", Boolean.toString(error));
                  if (error) {
                    Intent intent = new Intent(MainActivity.this, PhoneActivity.class);
                    startActivity(intent);
                    finish();
                  }
                } catch (JSONException e) {
                  e.printStackTrace();
                }
              }
            },
            new Response.ErrorListener() {

              @Override
              public void onErrorResponse(VolleyError error) {
                // Toast.makeText(getApplicationContext(),error.toString(),
                // Toast.LENGTH_LONG).show();
              }
            }) {

          @Override
          protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put("tag", "check");
            params.put("uid", uid);

            return params;
          }
        };
    AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
  }
예제 #8
0
  public static void getAllData(String msg, Context c) {
    final Context context = c;

    final String message = msg;
    AppCommon.showDialog("Loading....", c);
    String url = AppCommon.getURL() + "allControlsData/0/0";
    Log.i("atag", url);
    final JsonObjectRequest jsonObjReq =
        new JsonObjectRequest(
            Request.Method.GET,
            url,
            new JSONObject(),
            new Response.Listener<JSONObject>() {
              @Override
              public void onResponse(JSONObject response) {

                try {

                  Log.i("atag", response.toString());

                  int loopLength =
                      (response.getJSONArray("allControlsDataResult").getJSONObject(0)).length();
                  ControllData strData = new ControllData();
                  DatabaseHandler db = new DatabaseHandler(context);

                  if (message.equals("upd")) {
                    db.deleteControllData();
                  }
                  for (int i = 0; i < loopLength; i++) {
                    if (i == 0) {
                      strData.setDataName("AREADATA");
                      strData.setDataValue(
                          response
                              .getJSONArray("allControlsDataResult")
                              .getJSONObject(0)
                              .getJSONArray("AREADATA")
                              .toString());
                    } else if (i == 1) {
                      strData.setDataName("WORDDATA");
                      strData.setDataValue(
                          response
                              .getJSONArray("allControlsDataResult")
                              .getJSONObject(0)
                              .getJSONArray("WORDDATA")
                              .toString());
                    } else if (i == 2) {
                      strData.setDataName("CATAGORYDATA");
                      strData.setDataValue(
                          response
                              .getJSONArray("allControlsDataResult")
                              .getJSONObject(0)
                              .getJSONArray("CATAGORYDATA")
                              .toString());
                      //                                }else if(i==3){
                      //                                    strData.setDataName("TYPEDATA");
                      //
                      // strData.setDataValue(response.getJSONArray("allControlsDataResult").getJSONObject(0).getJSONArray("TYPEDATA").toString());
                    } else if (i == 3) {
                      strData.setDataName("STATUS");
                      strData.setDataValue(
                          response
                              .getJSONArray("allControlsDataResult")
                              .getJSONObject(0)
                              .getJSONArray("STATUS")
                              .toString());
                    }
                    db.addControllData(strData);
                  }
                } catch (JSONException e) {
                  e.printStackTrace();
                }

                AppCommon.hideDialog();

                if (message.equals("FB") || message.equals("ACT")) {
                  Intent actvI = new Intent(context, NewDashboardActivity.class);
                  actvI.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                  // ActivityCompat.finishAffinity(LoginActivity.class);
                  context.startActivity(actvI);
                } else if (message.equals("Skip")) {
                  Intent actvI = new Intent(context, NewDashboardActivity.class);
                  context.startActivity(actvI);
                } else if (message.equals("upd")) {
                  AppCommon.showAlert("Message", "Application data updated successfully.", context);
                } else {
                  Intent actvI = new Intent(context, UserRegistrationActivity.class);
                  actvI.putExtra("mobNo", message);
                  context.startActivity(actvI);
                }
              }
            },
            new Response.ErrorListener() {
              @Override
              public void onErrorResponse(VolleyError error) {
                AppCommon.hideDialog();
                Snackbar snackbar =
                    Snackbar.make(
                        ((Activity) context).findViewById(android.R.id.content),
                        CommonDialogs.SERVER_ERROR,
                        Snackbar.LENGTH_LONG);
                ColoredSnackbar.confirm(snackbar).show();
              }
            });
    jsonObjReq.setRetryPolicy(
        new DefaultRetryPolicy(30000, -1, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
  }
예제 #9
0
  /** Method to fetch Feed data from appropriate API */
  private void fetchFeedData() {
    JsonArrayRequest request =
        new JsonArrayRequest(
            FEED_API_URL,
            new Response.Listener<JSONArray>() {
              @Override
              public void onResponse(JSONArray response) {
                try {
                  Cursor cursor =
                      getContentResolver()
                          .query(Contract.FeedEntry.CONTENT_URI, FEED_COLUMNS, null, null, null);
                  if (cursor == null || cursor.getCount() == response.length()) {
                    return;
                  }

                  ContentValues rows[] = new ContentValues[response.length()];
                  for (int i = 0; i < response.length(); i++) {
                    int idx = i + 1;
                    JSONObject obj = response.getJSONObject(i);

                    String feedTitle = obj.getString("text");
                    String feedTime = obj.getString("created_at");
                    String feedEvent = obj.getString("event");

                    SimpleDateFormat format =
                        new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH);
                    String formattedTime = "";
                    try {
                      Date date = format.parse(feedTime);
                      SimpleDateFormat sdf = new SimpleDateFormat("EEE h:mma", Locale.ENGLISH);
                      formattedTime = sdf.format(date);
                    } catch (ParseException e) {
                      e.printStackTrace();
                    }

                    ContentValues subcategoryValues = new ContentValues();
                    subcategoryValues.put(Contract.FeedEntry._ID, idx);
                    subcategoryValues.put(Contract.FeedEntry.COLUMN_FEED_TITLE, feedTitle);
                    subcategoryValues.put(Contract.FeedEntry.COLUMN_FEED_TIME, formattedTime);
                    subcategoryValues.put(Contract.FeedEntry.COLUMN_FEED_EVENT, feedEvent);

                    int taskId = obj.getInt("task_id");
                    String taskUrl = TASK_API_URL.replace("{taskId}", Integer.toString(taskId));
                    fetchTaskData(idx, taskUrl);

                    int profileId = obj.getInt("profile_id");
                    String profileUrl =
                        PROFILE_API_URL.replace("{profileId}", Integer.toString(profileId));
                    fetchProfileData(idx, profileUrl);

                    rows[i] = subcategoryValues;
                  }
                  getContentResolver().bulkInsert(Contract.FeedEntry.CONTENT_URI, rows);
                } catch (JSONException e) {
                  showToast("Error in working with JSON: " + e.getMessage());
                }
              }
            },
            new Response.ErrorListener() {
              @Override
              public void onErrorResponse(VolleyError error) {
                showToast("VolleyError: " + error.getMessage());
              }
            });

    // Add request to the queue
    AppController.getInstance().getRequestQueue().add(request);
  }
예제 #10
0
  private void loginPostRequest(String email, String password) {

    data = new JSONObject();

    try {
      data.put("UserName", email);
      data.put("Password", password);

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

    String url = "http://altynorda.kz/SGAccountAPI/Login";

    JsonObjectRequest jsonObjectRequest =
        new JsonObjectRequest(
            Request.Method.POST,
            url,
            data,
            new Response.Listener<JSONObject>() {
              @Override
              public void onResponse(JSONObject response) {

                try {
                  //                            msg = response.getString("errors");
                  //                            Toast.makeText(getApplicationContext(), msg,
                  // Toast.LENGTH_LONG).show();

                  if (response.getBoolean("success")) {

                    // getting the token and saving in SharedPrefs
                    token = response.getString("token");

                    //                                SharedPreferences loginPref =
                    // getSharedPreferences(BaseActivity.APP_PREFERENCES, MODE_PRIVATE);

                    SharedPreferences.Editor editor = loginPrefs.edit();
                    editor.putString(BaseActivity.GAME_PREFERENCES_TOKEN, token);
                    editor.commit();

                    Toast.makeText(
                            getApplicationContext(), "Авторизация успешна", Toast.LENGTH_LONG)
                        .show();
                    progressView.stop();
                    startActivity(new Intent(LoginActivity.this, MainActivity.class));

                  } else {

                    if (!response.getString("errors").isEmpty()) {
                      String errors = response.getString("errors");
                      Toast.makeText(getApplicationContext(), errors, Toast.LENGTH_SHORT).show();
                      progressView.stop();
                    }
                    // user needs to confirm the phone number
                    if (response.getString("redirect").equals("PhoneConfirmation")) {
                      progressView.stop();
                      startActivity(
                          new Intent(LoginActivity.this, PhoneConfirmationActivity.class));
                    }
                  }
                } catch (JSONException e) {
                  e.printStackTrace();
                }
              }
            },
            new Response.ErrorListener() {
              @Override
              public void onErrorResponse(VolleyError error) {

                //                        NetworkResponse response = error.networkResponse;

                String errors = error.getMessage();
                Toast.makeText(getApplicationContext(), errors, Toast.LENGTH_LONG).show();
                progressView.stop();
              }
            }) {
          /** Passing some request headers */
          @Override
          public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json; charset=utf-8");
            return headers;
          }
        };
    AppController.getInstance().addToRequestQueue(jsonObjectRequest);
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    k = 0;
    setContentView(R.layout.activity_main);
    progressBar = (ProgressBar) findViewById(R.id.progresbar);
    progressBar.setVisibility(View.VISIBLE);
    // -----------------------------------------
    // nothing!!
    ObservableScrollView scrollview = (ObservableScrollView) findViewById(R.id.scrollview);
    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.next);
    fab.attachToScrollView(scrollview);
    ll = (LinearLayout) findViewById(R.id.ll2);

    quizname = getIntent().getStringExtra("quizname");
    url = getIntent().getStringExtra("URI");
    totalq = getIntent().getStringExtra("totalq");

    // ------------------------------------------

    toolbar = (Toolbar) findViewById(R.id.app_bar);
    toolbar.setTitleTextColor(getResources().getColor(R.color.white));
    setSupportActionBar(toolbar);
    ActionBar actionBar = getSupportActionBar();
    actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.teal)));
    actionBar.setTitle("ORGANIC CHEMISTRY ");
    toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_back_white));
    toolbar.setNavigationOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            onBackPressed(); // PB in Gap-by default given//do something
          }
        });
    // --------------------------------------------

    /*  ActionBar bar = getActionBar();
    bar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.actionbar_background)));*/

    // -------------------------------------------------------------

    imageLoader = AppController.getInstance().getImageLoader();

    timer = (TextView) findViewById(R.id.timer);
    cor = (TextView) findViewById(R.id.tcorrect);
    inc = (TextView) findViewById(R.id.incorrect);
    tot = (TextView) findViewById(R.id.tot);

    Typeface myTypeface = Typeface.createFromAsset(getAssets(), "fonts/pie.ttf");
    /* cor.setTypeface(myTypeface);
    inc.setTypeface(myTypeface);
    tot.setTypeface(myTypeface);*/

    t1 = (RadioButton) findViewById(R.id.t1);
    t2 = (RadioButton) findViewById(R.id.t2);
    t3 = (RadioButton) findViewById(R.id.t3);
    t4 = (RadioButton) findViewById(R.id.t4);
    question = (TextView) findViewById(R.id.question);

    v1 = (ImageView) findViewById(R.id.v1);
    v2 = (ImageView) findViewById(R.id.v2);
    v3 = (ImageView) findViewById(R.id.v3);
    v4 = (ImageView) findViewById(R.id.v4);
    questionimage = (ImageView) findViewById(R.id.questionimage);
    questionimage2 = (ImageView) findViewById(R.id.questionimage2);
    questionimage3 = (ImageView) findViewById(R.id.questionimage3);
    questionimage4 = (ImageView) findViewById(R.id.questionimage4);

    qiarr = new ImageView[] {questionimage, questionimage2, questionimage3, questionimage4};

    next = (FloatingActionButton) findViewById(R.id.next);
    next.setOnClickListener(this);

    t1.setOnCheckedChangeListener(this);
    t2.setOnCheckedChangeListener(this);
    t3.setOnCheckedChangeListener(this);
    t4.setOnCheckedChangeListener(this);

    AlertDialog.Builder builder1;

    // AlertDialog.Builder builder;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
      builder1 =
          new AlertDialog.Builder(
              this, android.R.style.Theme_Material_Light_Dialog_Alert); // theme problem
    } else {
      builder1 = new AlertDialog.Builder(this);
    }
    builder1.setTitle("Test Information");
    builder1.setMessage(
        "This test would have "
            + totalq
            + " questions and you would get 1 minute for each question. All the best! ;)");
    builder1.setCancelable(true); // change
    builder1.setNeutralButton(
        android.R.string.ok,
        new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int id) {
            dialog.cancel();
            getdata();
          }
        });
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
      builder1.setOnDismissListener(
          new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
              getdata();
              Log.d("ondismiss", "dismissed");
            }
          });
    }
    AlertDialog alert11 = builder1.create();
    alert11.show();
  }
  public void getdata() {
    JsonArrayRequest req =
        new JsonArrayRequest(
            url,
            new Response.Listener<JSONArray>() {
              @Override
              public void onResponse(JSONArray response) {
                Log.d(TAG, response.toString());

                jsonArray = response;
                displayData(k);
                length = jsonArray.length();
              }
            },
            new Response.ErrorListener() {
              @Override
              public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                if (AppStatus.getInstance(getBaseContext()).isOnline()) {

                  // Toast t = Toast.makeText(getBaseContext(),"You are online!!!!",8000).show();
                  // while im connected to the internet but my app isn't responding

                  /*new Thread(new Runnable() {
                          @Override
                          public void run() {


                              --timeout;
                              Log.d("timeout_count",Integer.toString(timeout));
                              if(timeout <=0)
                              {
                                  getdata();
                              }
                              else
                              {
                                  Snackbar.make(ll, "Connection too slow!", Snackbar.LENGTH_LONG)
                                          .setAction("Refreshed", null)
                                          .setActionTextColor(getResources().getColor(R.color.lightblue))//imp
                                          .setDuration(3000).show();
                              }

                          }
                      });



                  } else {

                      Snackbar.make(ll, "Please check your internet connection!", Snackbar.LENGTH_LONG)
                              .setAction("Refreshed", null)
                              .setActionTextColor(getResources().getColor(R.color.lightblue))//imp
                              .setDuration(3000).show();
                      Log.v("Home", "############################You are not online!!!!");
                      progressBar.setVisibility(View.INVISIBLE);
                  }*/

                }

                VolleyLog.d(TAG, "Error: " + error.getMessage());
                Snackbar.make(ll, "Please check your internet connection", Snackbar.LENGTH_LONG)
                    .setAction("Refreshed", null)
                    .setActionTextColor(getResources().getColor(R.color.lightblue)) // imp
                    .setDuration(3000)
                    .show();
                progressBar.setVisibility(View.INVISIBLE);
              }
            });

    // -----------------------------prevent double posting here(double request) double countdown
    // timer updation---------------------------------------

    req.setRetryPolicy(
        new DefaultRetryPolicy(
            500000,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    AppController.getInstance().addToRequestQueue(req, "feeds");
  }
예제 #13
0
  // Draws the Events
  private void drawEvents() {

    int counter = 0;
    layout.removeAllViews();
    for (JSONObject j : events) {
      try {
        final String eid = j.getString("eid");
        final String name = j.getString("name");
        final int icon = j.getInt("icon");
        final int creator = j.getInt("creator");
        String update = j.getString("updated");
        final String temp = j.getString("datetime");
        String month = temp.substring(5, 7);
        String day = temp.substring(8, 10);
        String date = day + '-' + month;

        RelativeLayout.LayoutParams lp_icon = new RelativeLayout.LayoutParams(height, height);
        RelativeLayout.LayoutParams lp_button = new RelativeLayout.LayoutParams(width, height);
        RelativeLayout.LayoutParams lp_date = new RelativeLayout.LayoutParams(dateWidth, height);
        RelativeLayout.LayoutParams lp_div = new RelativeLayout.LayoutParams(width, divHeight);

        /**
         * Adds the icon: to limit the use of data we store the images in a local database, and in
         * an online database. Whenever someone uploads a new icon a new random icon_ID gets
         * generated when the icon_ID in your local DB doesn't equal the one in the online database,
         * the one in the online DB gets downloaded and the offline DB gets updated with this EID
         * and image.
         */
        lp_icon.setMargins(0, (height + divHeight) * counter, 0, 0);
        final ImageButton img = new ImageButton(this);
        if (icon == 0) {
          img.setImageResource(R.drawable.group);
          img.setPadding(12, 12, 12, 12);
          user_db.deleteBlob(eid);
        } else {
          if (icon == user_db.getVersion(eid)) {
            byte[] image = user_db.getBlob(eid);
            img.setImageBitmap(BitmapFactory.decodeByteArray(image, 0, image.length));
            img.setPadding(7, 7, 7, 7);
          } else {
            String tag_icon = "req_icon";
            StringRequest stringRequest =
                new StringRequest(
                    Request.Method.POST,
                    URL_ICON,
                    new Response.Listener<String>() {

                      @Override
                      public void onResponse(String response) {
                        try {
                          JSONObject jObj = new JSONObject(response);
                          boolean error = jObj.getBoolean("error");

                          if (!error) {
                            byte[] blob = Base64.decode(jObj.getString("blob"), Base64.DEFAULT);
                            if (user_db.getVersion(eid) == 0) {
                              user_db.addBLOB(eid, icon, blob);
                            } else {
                              user_db.updateBlob(eid, icon, blob);
                            }
                            img.setImageBitmap(BitmapFactory.decodeByteArray(blob, 0, blob.length));
                            img.setPadding(7, 7, 7, 7);
                          }
                        } catch (JSONException e) {
                          e.printStackTrace();
                        }
                      }
                    },
                    new Response.ErrorListener() {

                      @Override
                      public void onErrorResponse(VolleyError error) {}
                    }) {

                  @Override
                  protected Map<String, String> getParams() {
                    Map<String, String> params = new HashMap<String, String>();
                    params.put("tag", "get");
                    params.put("eid", eid);
                    return params;
                  }
                };
            AppController.getInstance().addToRequestQueue(stringRequest, tag_icon);
          }
        }
        img.setLayoutParams(lp_icon);
        img.setBackground(null);
        img.setScaleType(ImageView.ScaleType.FIT_CENTER);
        layout.addView(img);

        // Add the button
        lp_button.setMargins(height, (height + divHeight) * counter, height, 0);
        TextView button = new TextView(this);
        button.setText(name);
        button.setTypeface(express);
        button.setTextSize(getResources().getDimension(R.dimen.button_text));
        button.setTextColor(getResources().getColor(R.color.black));
        button.setGravity(Gravity.CENTER_VERTICAL);
        button.setLayoutParams(lp_button);
        layout.addView(button);
        button.setOnClickListener(
            new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, EventActivity.class);
                Bundle b = new Bundle();
                b.putString("eid", eid);
                b.putString("name", name);
                b.putInt("icon", icon);
                b.putInt("creator", creator);
                b.putString("date", temp);
                intent.putExtras(b);
                startActivity(intent);
              }
            });

        // Add the Date
        if (!month.equals("00") && !day.equals("00")) {
          lp_date.setMargins(0, (height + divHeight) * counter, 0, 0);
          lp_date.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
          TextView datetime = new TextView(this);
          datetime.setText(date);
          datetime.setGravity(Gravity.CENTER);
          datetime.setLayoutParams(lp_date);
          layout.addView(datetime);
        }

        // Add the Divider
        lp_div.setMargins(height, (height + divHeight) * counter + height, 20, 0);
        ImageView div = new ImageView(this);
        div.setImageResource(R.drawable.divider);
        div.setLayoutParams(lp_div);
        layout.addView(div);

        counter++;
      } catch (JSONException ex) {

      }
    }
  }
  public void getMasterList() {
    PDialog.show(getActivity());
    StringRequest request =
        new StringRequest(
            Request.Method.POST,
            getResources().getString(R.string.url_motherland) + "customers_monthly_report.php?",
            new Response.Listener<String>() {
              @Override
              public void onResponse(String response) {
                PDialog.hide();
                Log.v("response", response);
                try {
                  JSONObject jobj = new JSONObject(response);
                  String order_report = jobj.getString("orders");
                  String order_inprogress = jobj.getString("inprogress");
                  String order_completed = jobj.getString("completed");

                  JSONArray ar = new JSONArray(order_report);
                  JSONArray ar_inprogress = new JSONArray(order_inprogress);
                  JSONArray ar_completed = new JSONArray(order_completed);
                  JSONObject obj = ar.getJSONObject(0);
                  JSONObject obj_inprogress = ar_inprogress.getJSONObject(0);
                  JSONObject obj_completed = ar_completed.getJSONObject(0);

                  monthlyOrders.add(obj.getString("jan"));
                  monthlyOrders.add(obj.getString("feb"));
                  monthlyOrders.add(obj.getString("mar"));
                  monthlyOrders.add(obj.getString("Apr"));
                  monthlyOrders.add(obj.getString("May"));
                  monthlyOrders.add(obj.getString("Jun"));
                  monthlyOrders.add(obj.getString("July"));
                  monthlyOrders.add(obj.getString("Aug"));
                  monthlyOrders.add(obj.getString("Sep"));
                  monthlyOrders.add(obj.getString("Oct"));
                  monthlyOrders.add(obj.getString("Nov"));
                  monthlyOrders.add(obj.getString("December"));

                  orders_inprogress.add(obj_inprogress.getString("jan"));
                  orders_inprogress.add(obj_inprogress.getString("feb"));
                  orders_inprogress.add(obj_inprogress.getString("mar"));
                  orders_inprogress.add(obj_inprogress.getString("Apr"));
                  orders_inprogress.add(obj_inprogress.getString("May"));
                  orders_inprogress.add(obj_inprogress.getString("Jun"));
                  orders_inprogress.add(obj_inprogress.getString("July"));
                  orders_inprogress.add(obj_inprogress.getString("Aug"));
                  orders_inprogress.add(obj_inprogress.getString("Sep"));
                  orders_inprogress.add(obj_inprogress.getString("Oct"));
                  orders_inprogress.add(obj_inprogress.getString("Nov"));
                  orders_inprogress.add(obj_inprogress.getString("December"));

                  orders_completed.add(obj_completed.getString("jan"));
                  orders_completed.add(obj_completed.getString("feb"));
                  orders_completed.add(obj_completed.getString("mar"));
                  orders_completed.add(obj_completed.getString("Apr"));
                  orders_completed.add(obj_completed.getString("May"));
                  orders_completed.add(obj_completed.getString("Jun"));
                  orders_completed.add(obj_completed.getString("July"));
                  orders_completed.add(obj_completed.getString("Aug"));
                  orders_completed.add(obj_completed.getString("Sep"));
                  orders_completed.add(obj_completed.getString("Oct"));
                  orders_completed.add(obj_completed.getString("Nov"));
                  orders_completed.add(obj_completed.getString("December"));

                  Log.v("size", monthlyOrders.size() + "");
                  //                            Log.v("line_r")

                  BuildTable(12, 3);

                } catch (Exception e) {
                  e.printStackTrace();
                }
              }
            },
            new Response.ErrorListener() {

              @Override
              public void onErrorResponse(VolleyError arg0) {
                PDialog.hide();
                Toast.makeText(
                        getActivity(),
                        getResources().getString(R.string.no_internet_access),
                        Toast.LENGTH_LONG)
                    .show();
              }
            }) {

          @Override
          protected Map<String, String> getParams() {

            Map<String, String> params = new HashMap<>();
            params.put("email", StaticVariables.database.get(0).getEmail());
            params.put("password", StaticVariables.database.get(0).getPassword());
            params.put("id", StaticVariables.database.get(0).getId());
            return params;
          }
        };
    AppController.getInstance().addToRequestQueue(request, "data_receive");
  }
  private void syncSongsWithServer(final ArrayList<Song> songListArray) throws JSONException {
    /** Function to sync device music information to server */

    // Tag used to cancel the request
    String tag_string_req = "req_syncmusic";

    Map<String, JSONObject> postParam = new HashMap<String, JSONObject>();
    for (int i = 0; i < songListArray.size(); i++) {
      JSONObject innerObject = new JSONObject();
      innerObject.put("fileTitle", songListArray.get(i).getTitle());
      innerObject.put("fileArtist", songListArray.get(i).getArtist());
      innerObject.put("fileAlbum", songListArray.get(i).getAlbum());
      innerObject.put("fileChecksum", songListArray.get(i).getChecksum());
      postParam.put(String.valueOf(i), innerObject);
    }

    JsonObjectRequest jsonObjReq =
        new JsonObjectRequest(
            Request.Method.POST,
            AppConfig.URL_SYNCMUSIC,
            new JSONObject(postParam),
            new Response.Listener<JSONObject>() {
              @Override
              public void onResponse(JSONObject response) {
                //                        general.log("MOJA MUZYKA", "Sync to database OK:
                // "+response.toString());
                try {
                  boolean error = response.getBoolean("error");

                  if (!error) {
                    String reponseMessage = response.getString("message");
                    general.log("PLAYER", "Sync to database OK: " + reponseMessage);

                  } else {
                    // Error occurred, get error message
                    // message
                    String errorMsg = response.getString("message");
                    general.log("PLAYER", "Sync to database ERROR: " + errorMsg);
                  }
                } catch (JSONException e) {
                  e.printStackTrace();
                }
              }
            },
            new Response.ErrorListener() {

              @Override
              public void onErrorResponse(VolleyError error) {
                general.log("MOJA MUZYKA", "Sync to database ERROR: " + error.getMessage());
              }
            }) {

          /** Passing some request headers */
          @Override
          public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("AUTHORIZATION", getResources().getString(R.string.soundieApiKey));
            headers.put("Content-Type", "application/json; charset=utf-8");
            return headers;
          }
        };

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(jsonObjReq, tag_string_req);
  }