Esempio n. 1
0
 public RequestQueue getRequestQueue() {
   if (mRequestQueue == null) {
     mRequestQueue = Volley.newRequestQueue(this);
     mRequestQueue.start();
   }
   return mRequestQueue;
 }
Esempio n. 2
0
  /**
   * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it.
   *
   * @param context A {@link android.content.Context} to use for creating the cache dir.
   * @param stack An {@link HttpStack} to use for the network, or null for default.
   * @return A started {@link RequestQueue} instance.
   */
  public static RequestQueue newRequestQueue(Context context, HttpStack stack) {
    File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);

    String userAgent = "volley/0";
    try {
      String packageName = context.getPackageName();
      PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
      userAgent = packageName + "/" + info.versionCode;
    } catch (NameNotFoundException e) {
    }

    if (stack == null) {
      if (Build.VERSION.SDK_INT >= 9) {
        stack = new HurlStack();
      } else {
        // Prior to Gingerbread, HttpUrlConnection was unreliable.
        // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
        stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
      }
    }

    Network network = new BasicNetwork(stack);

    final DiskBasedCache cache = new DiskBasedCache(cacheDir);
    RequestQueue queue = new RequestQueue(cache, network);
    queue.start();

    return queue;
  }
  /**
   * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it.
   *
   * @param context A {@link Context} to use for creating the cache dir.
   * @param stack An {@link HttpStack} to use for the network, or null for default.
   * @return A started {@link RequestQueue} instance.
   */
  public synchronized void init(Context context, HttpStack stack) {
    File cacheDir = null;
    String status = Environment.getExternalStorageState();
    if (status.equals(Environment.MEDIA_MOUNTED) && context.getExternalCacheDir().exists())
      cacheDir = new File(context.getExternalCacheDir(), DEFAULT_CACHE_DIR);
    else cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);
    String userAgent = "com.sohu.focus";
    try {
      String packageName = context.getPackageName();
      PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
      userAgent = packageName + "Android/v_" + info.versionCode + ",build/" + Build.VERSION.RELEASE;
    } catch (NameNotFoundException e) {
    }

    if (stack == null) {
      if (Build.VERSION.SDK_INT >= 9) {
        stack = new HurlStack();
      } else {
        stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
      }
    }
    diskCache = new DiskBasedCache(cacheDir);
    Network network = new BasicNetwork(stack);
    queue = new RequestQueue(diskCache, network);
    queue.start();

    int memoryCacheSize = (int) (Runtime.getRuntime().maxMemory() / 8);
    memoryCache = new LruMemoryCache(memoryCacheSize);
    imageLoader = new ImageLoader(queue, memoryCache);
  }
Esempio n. 4
0
 public RequestQueue getRequestQueue() {
   if (mRequestQueue == null) {
     mRequestQueue = Volley.newRequestQueue(getActivity());
     mRequestQueue.start();
   }
   return mRequestQueue;
 }
 /**
  * @param listener
  * @param tag
  */
 public DefaultFeatureManager(final Listener listener, final String tag) {
   mContext = AroundMeApplication.getContext();
   mListener = listener;
   mModuleTag = tag;
   TAG = getClass().getSimpleName();
   mQueue = Volley.newRequestQueue(AroundMeApplication.getContext());
   mImageLoader = new ImageLoader(mQueue, new LruBitmapCache());
   mQueue.start();
 }
Esempio n. 6
0
 public RequestQueue getRequestQueue() {
   if (requestQueue == null) {
     Cache cache = new DiskBasedCache(context.getCacheDir(), CACHE_SIZE);
     Network network = new BasicNetwork(new HurlStack());
     requestQueue = new RequestQueue(cache, network);
     requestQueue.start();
   }
   return requestQueue;
 }
 public RequestQueue getRequestQueue() {
   if (mRequestQueue == null) {
     Cache cache = new DiskBasedCache(mCtx.getCacheDir(), 10 * 1024 * 1024);
     Network network = new BasicNetwork(new HurlStack());
     mRequestQueue = new RequestQueue(cache, network);
     // Don't forget to start the volley request queue
     mRequestQueue.start();
   }
   return mRequestQueue;
 }
Esempio n. 8
0
  public RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
      //  mRequestQueue = Volley.newRequestQueue(getApplicationContext());
      Network network = new BasicNetwork(new OkHttpStack());
      mRequestQueue =
          new RequestQueue(new DiskBasedCache(new File(getCacheDir(), "volley")), network);
      mRequestQueue.start();
    }

    return mRequestQueue;
  }
Esempio n. 9
0
 /**
  * 使用单例模式取得RequestQueue 对象
  *
  * @return
  */
 public static RequestQueue getInstance() {
   if (requestQueue == null) {
     synchronized (VolleyUtil.class) {
       if (requestQueue == null) {
         requestQueue = Volley.newRequestQueue(UtilApplication.application);
         requestQueue.start();
       }
     }
   }
   return requestQueue;
 }
Esempio n. 10
0
  private static RequestQueue newRequestQueue(Context context) {
    Proxy proxy = NetUtil.getProxy();
    File cacheDir =
        new File(DirectoryManager.getDirectory(DirectoryManager.DIR.CACHE), DEFAULT_CACHE_DIR);

    String userAgent = "CGTong/0";
    try {
      String packageName = context.getPackageName();
      PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
      userAgent = packageName + "/" + info.versionCode;
    } catch (PackageManager.NameNotFoundException e) {
      return null;
    }
    if (Build.VERSION.SDK_INT >= 9) {
      stack = new HurlStack(proxy);
    } else {
      // Prior to Gingerbread, HttpUrlConnection was unreliable.
      // See:
      // http://android-developers.blogspot.com/2011/09/androids-http-clients.html
      AndroidHttpClient client = AndroidHttpClient.newInstance(userAgent);
      if (proxy != null) {
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
      }
      stack = new HttpClientStack(client);
    }
    Network network = new BasicNetwork(stack);

    final DiskBasedCache diskCache = new DiskBasedCache(cacheDir);
    // 监听目录的变化,切换cache目录
    DirectoryManager.addSdCardListener(
        new DirectoryManager.SdcardStatusListener() {
          @Override
          public void onChange(SDCARD_STATUS status) {
            new Thread(
                    new Runnable() {
                      @Override
                      public void run() {
                        diskCache.switchCache(
                            new File(
                                DirectoryManager.getDirectory(DirectoryManager.DIR.CACHE),
                                DEFAULT_CACHE_DIR));
                      }
                    })
                .start();
          }
        });

    RequestQueue queue = new RequestQueue(diskCache, network);
    // RequestQueue queue = Volley.newRequestQueue(context);
    queue.start();
    return queue;
  }
Esempio n. 11
0
  /**
   * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it. You
   * may set a maximum size of the disk cache in bytes. 创建一个默认的请求队列,可以设置一个最大字节的硬盘缓存
   * 分析这个方法可以看到:RequestQueue、HttpStack、Network、Cache都可以由我们自定义来构建请求队列,可扩展性非常强
   * 这里涉及到HttpClient和HttpURLConnection的选择: 在 Froyo(2.2) 之前,HttpURLConnection 有个重大 Bug,调用 close()
   * 函数会影响连接池,导致连接复用失效,所以在 Froyo 之前使用 HttpURLConnection 需要关闭 keepAlive Gingerbread(2.3)
   * HttpURLConnection 默认开启了 gzip 压缩,提高了 HTTPS 的性能,Ice Cream Sandwich(4.0) HttpURLConnection
   * 支持了请求结果缓存
   *
   * @param context A {@link Context} to use for creating the cache dir.
   * @param stack An {@link HttpStack} to use for the network, or null for default.
   * @param maxDiskCacheBytes the maximum size of the disk cache, in bytes. Use -1 for default size.
   * @return A started {@link RequestQueue} instance.
   */
  public static RequestQueue newRequestQueue(
      Context context, HttpStack stack, int maxDiskCacheBytes) {
    // 缓存文件
    File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);
    // 下面的代码是设置请求头User-Agent 字段,设置形式为packageName/versionCode,这一块是针对HttpClient的,HttpURLConnection
    // 默认是有 User-Agent 的
    // 这里注意在2.1后一种可以获取系统默认的User-Agent,另一种就是在自定义的Request中重写getHeaders方法设置User-Agent
    // uerAgent: 标识请求者的一些信息,如什么浏览器类型和版本、操作系统,使用语言等信息
    String userAgent = "volley/0";
    try {
      String packageName = context.getPackageName();
      PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
      userAgent = packageName + "/" + info.versionCode;
    } catch (NameNotFoundException e) {
    }
    // 得到一个HttpStack,然后通过它构造一个代表网络的具体实现:BasicNetwork
    if (stack == null) {
      if (Build.VERSION.SDK_INT >= 9) {
        stack = new HurlStack();
      } else {
        // Prior to Gingerbread, HttpUrlConnection was unreliable.
        // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
        // AndroidHttpClient在android5.0以后已经被移除了,所以只考虑使用HttpURLConnection对应的HurlStack
        // TODO 当然这里可以采用HttpClient来替代AndroidHttpClient  需要添加apache的httpclient的jar包
        /*HttpClient httpClient = new DefaultHttpClient();
        httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, userAgent);*/
        // TODO With httpcomponents 4.3 you should use the client builder to set the user agent
        HttpClient httpClient = HttpClients.custom().setUserAgent(userAgent).build();
        stack = new HttpClientStack(httpClient);
        //                stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
      }
    }
    Network network = new BasicNetwork(stack);

    // 构造一个代表缓存的基于Disk的具体实现DiskBasedCache,然后将网络对象和缓存对象传入构建一个RequestQueue,启动这个RequestQueue
    RequestQueue queue;
    if (maxDiskCacheBytes <= -1) {
      // No maximum size specified 没有指定最大硬盘缓存大小
      queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
    } else {
      // Disk cache size specified 指定硬盘缓存尺寸
      queue = new RequestQueue(new DiskBasedCache(cacheDir, maxDiskCacheBytes), network);
    }
    // 创建队列完成后,启动该队列
    queue.start();

    return queue;
  }
Esempio n. 12
0
  private static RequestQueue newRequestQueue(Context context, ImageCacheParams imageCacheParams) {

    Network network =
        new BasicNetwork(
            Utils.hasHoneycomb()
                ? new HurlStack()
                : new HttpClientStack(
                    AndroidHttpClient.newInstance(NetUtils.getUserAgent(context))));

    Cache cache;
    if (null != imageCacheParams) {
      cache = new DiskLruBasedCache(imageCacheParams);
    } else {
      cache = new DiskLruBasedCache(Utils.getDiskCacheDir(context, CACHE_DIR));
    }
    RequestQueue queue = new RequestQueue(cache, network);
    queue.start();
    return queue;
  }
 private void requestVolley() {
   // Volley でリクエスト
   String url = "http://www.google.com/uds/GnewsSearch?q=Obama&v=1.0";
   mQueue.add(
       new JsonObjectRequest(
           Method.GET,
           url,
           null,
           new Listener<JSONObject>() {
             @Override
             public void onResponse(JSONObject response) {
               long time = System.currentTimeMillis() - requestStartTime;
               Log.d(TAG, "Volley Request finished : " + time);
             }
           },
           null));
   requestStartTime = System.currentTimeMillis();
   mQueue.start();
 }
Esempio n. 14
0
  public static RequestQueue newRequestQueue(Context context) {

    if (InstanceNetwork == null) {
      InstanceNetwork = new OkNetwork(getDefaultHttpStack());
    }

    if (InstanceCache == null) {
      File cache = context.getExternalCacheDir();
      if (cache == null) {
        cache = context.getCacheDir();
      }
      File cacheDir = new File(cache, DEFAULT_CACHE_DIR);
      InstanceCache = new DiskBasedCache(cacheDir);
    }

    RequestQueue queue = new RequestQueue(InstanceCache, InstanceNetwork);
    queue.start();

    return queue;
  }
Esempio n. 15
0
  /**
   * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it. You
   * may set a maximum size of the disk cache in bytes.
   *
   * @param context A {@link Context} to use for creating the cache dir.
   * @param stack An {@link HttpStack} to use for the network, or null for default.
   * @param maxDiskCacheBytes the maximum size of the disk cache, in bytes. Use -1 for default size.
   * @return A started {@link RequestQueue} instance.
   */
  public static RequestQueue newRequestQueue(
      Context context, HttpStack stack, int maxDiskCacheBytes) {
    File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);

    String userAgent = "volley/0";
    try {
      String packageName = context.getPackageName();
      PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
      userAgent = packageName + "/" + info.versionCode;
    } catch (NameNotFoundException e) {
    }

    if (stack == null) {
      if (Build.VERSION.SDK_INT >= 9) {
        // old way: stack = new HurlStack();
        // http://square.github.io/okhttp/
        stack = new HurlStack(null, null, new OkUrlFactory(new OkHttpClient()));
      } else {
        // Prior to Gingerbread, HttpUrlConnection was unreliable.
        // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
        stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
      }
    }

    Network network = new BasicNetwork(stack);

    RequestQueue queue;
    if (maxDiskCacheBytes <= -1) {
      // No maximum size specified
      queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
    } else {
      // Disk cache size specified
      queue = new RequestQueue(new DiskBasedCache(cacheDir, maxDiskCacheBytes), network);
    }

    queue.start();

    return queue;
  }
Esempio n. 16
0
  private String jSonreadAPIWeather(Context context) {

    RequestQueue requestQueue = Volley.newRequestQueue(context);

    JsonObjectRequest request =
        new JsonObjectRequest(
            Request.Method.GET,
            "http://api.openweathermap.org/data/2.5/weather?q=Medellin&APPID=482579f45f1dc55ae8bd36deafedc58b",
            "",
            new Response.Listener<JSONObject>() {
              @Override
              public void onResponse(JSONObject response) {
                // Log.d("VOLLEY", response.toString());
                try {
                  JSONObject coord = response.getJSONObject("coord");
                  Log.d("VOLLEY", "Coord. :");
                  String lon = coord.getString("lon");
                  Log.d("VOLLEY", "Lon. " + lon);
                  String lat = coord.getString("lat");
                  Log.d("VOLLEY", "lat. " + lat);
                  String name = response.getString("name");
                  Log.d("VOLLEY", "Name " + name);
                } catch (Exception e) {
                  Log.d("VOLLEY", "Error " + e.getMessage());
                }
              }
            },
            new Response.ErrorListener() {
              @Override
              public void onErrorResponse(VolleyError error) {
                Log.d("VOLLEYERROR", error.toString());
              }
            });
    requestQueue.add(request);
    requestQueue.start();
    // Log.d("VOLLEY", "R " + Request.class.toString());
    return requestQueue.toString();
  }
Esempio n. 17
0
 /** Passes leader board information to online database for the user's acccount. */
 public void updateLeaderboard() {
   String url =
       "http://52.32.43.132:8080/updateLeaderboard?accountId="
           + this.player.getUserId()
           + "&level="
           + this.player.getLastMap()
           + "&accuracyPerLevel="
           + this.player.getTotalAcc()
           + "&highestAcc="
           + this.player.getHighestAcc()
           + "&maxTotalDmg="
           + this.player.getMaxTotalDamage()
           + "&maxSingleDmg="
           + this.player.getMaxSingleDamage()
           + "&operation="
           + this.player.getOperation()
           + "&target="
           + this.player.getTarget()
           + "&numberOfTries="
           + this.player.getNumberOfTries();
   RequestQueue queue = Volley.newRequestQueue(this);
   queue.start();
   StringRequest stringRequest =
       new StringRequest(
           Request.Method.PUT,
           url,
           new Response.Listener<String>() {
             @Override
             public void onResponse(String response) {
               if (!response.equals("No Powerups")) {}
             }
           },
           new Response.ErrorListener() {
             @Override
             public void onErrorResponse(VolleyError error) {}
           });
   queue.add(stringRequest);
 }
Esempio n. 18
0
  /**
   * 新建无缓存机制的请求队列 这块用处感觉不是很大??
   *
   * @param context
   * @return
   */
  public static RequestQueue newNoCacheRequestQueue(Context context) {

    String userAgent = "volley/0";
    try {
      String packageName = context.getPackageName();
      PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
      userAgent = packageName + "/" + info.versionCode;
    } catch (NameNotFoundException e) {
    }

    HttpStack stack = null;
    if (Build.VERSION.SDK_INT >= 9) {
      stack = new HurlStack();
    } else {
      HttpClient httpClient = HttpClients.custom().setUserAgent(userAgent).build();
      stack = new HttpClientStack(httpClient);
    }

    Network network = new BasicNetwork(stack);
    RequestQueue queue = new RequestQueue(new NoCache(), network);
    queue.start();
    return queue;
  }
Esempio n. 19
0
  /** Get the request queue for image */
  private static RequestQueue newRequestQueueForImage() {
    RequestQueue queue = new RequestQueue(openCacheForImage(), new BasicNetwork(new HurlStack()));
    queue.start();

    return queue;
  }
  public void execute() {
    // final TextView textView = (TextView) activity.findViewById(R.id.textView);
    Cache cache = new DiskBasedCache(context.getCacheDir(), 1024 * 1024); // 1MB cap
    final Network network = new BasicNetwork(new HurlStack());
    mRequestQueue = new RequestQueue(cache, network);
    mRequestQueue.start();
    StringRequest stringRequest =
        new StringRequest(
            Request.Method.GET,
            url,
            new Response.Listener<String>() {

              @Override
              public void onResponse(String response) {
                if (response != null
                    && !response.equalsIgnoreCase("null")
                    && !response.equalsIgnoreCase("\"Not found !\"")) {
                  ParseNotificationData parseNotificationData = new ParseNotificationData(response);
                  NotificationData notificationData = parseNotificationData.parse();
                  Log.d("NOT", notificationData.getId());
                  Log.d("NOT", notificationData.getTextMessage());
                  SharedPreferences sharedPreferences =
                      PreferenceManager.getDefaultSharedPreferences(
                          context.getApplicationContext());
                  String language =
                      sharedPreferences.getString(
                          context.getResources().getString(R.string.prefrance_language_key),
                          context.getResources().getString(R.string.pref_language_default));

                  SharedPreferences.Editor editor = sharedPreferences.edit();
                  switch (language) {
                    case "1":
                      if (sharedPreferences.getString("arabic_id", "-11").equals("-11"))
                        editor.putString("arabic_id", notificationData.getId());
                      else if (Integer.parseInt(notificationData.getId())
                          > Integer.parseInt(sharedPreferences.getString("arabic_id", "1"))) {
                        MyNotification myNotification = new MyNotification(context);
                        myNotification.notify(notificationData.getTextMessage());
                        editor.putString("arabic_id", notificationData.getId());
                      }
                      break;
                    case "2":
                      if (sharedPreferences.getString("franch_id", "-11").equals("-11"))
                        editor.putString("franch_id", notificationData.getId());
                      else if (Integer.parseInt(notificationData.getId())
                          > Integer.parseInt(sharedPreferences.getString("franch_id", "1"))) {
                        MyNotification myNotification = new MyNotification(context);
                        myNotification.notify(notificationData.getTextMessage());
                        editor.putString("franch_id", notificationData.getId());
                      }
                      break;
                    case "3":
                      if (sharedPreferences.getString("english_id", "-11").equals("-11"))
                        editor.putString("english_id", notificationData.getId());
                      else if (Integer.parseInt(notificationData.getId())
                          > Integer.parseInt(sharedPreferences.getString("english_id", "1"))) {
                        MyNotification myNotification = new MyNotification(context);
                        myNotification.notify(notificationData.getTextMessage());
                        editor.putString("english_id", notificationData.getId());
                      }
                      break;
                  }
                  editor.commit();
                }
              }
            },
            new Response.ErrorListener() {
              @Override
              public void onErrorResponse(VolleyError error) {
                // Handle erro
                // Toast.makeText(activity, "Error in network connection",
                // Toast.LENGTH_LONG).show();
              }
            });
    // stringRequest.setShouldCache(false);
    stringRequest.setRetryPolicy(
        new DefaultRetryPolicy(
            2 * 1000,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    mRequestQueue.add(stringRequest);
  }
Esempio n. 21
0
 public static <T> Request<T> startRequest(Request<T> paramRequest, Object paramObject) {
   paramRequest.setTag(paramObject);
   Request localRequest = queue.add(paramRequest);
   queue.start();
   return localRequest;
 }
  private void uploadImage(
      final Context context,
      File pictureFile,
      String pictureName,
      final VolleyImageUploadCallBack volleyImageUploadCallBack) {
    this.volleyImageUploadCallBack = volleyImageUploadCallBack;

    if (!TextUtils.isEmpty(pictureName) && pictureFile != null) {
      try {
        int size = (int) pictureFile.length();
        byte[] raw = new byte[size];
        try {
          BufferedInputStream buf = new BufferedInputStream(new FileInputStream(pictureFile));
          buf.read(raw, 0, raw.length);
          buf.close();
        } catch (FileNotFoundException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(bos);
        try {
          buildTextPart(dos, "mparam", "hekki");
          // the first file
          buildPart(dos, raw, pictureName);

          dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
          // pass to multipart body
          multipartBody = bos.toByteArray();
        } catch (IOException e) {
          e.printStackTrace();
        }

        String url = context.getString(R.string.upload_image_api);
        MultiPartRequest multipartRequest =
            new MultiPartRequest(
                url,
                null,
                mimeType,
                multipartBody,
                new Response.Listener<NetworkResponse>() {
                  @Override
                  public void onResponse(NetworkResponse response) {
                    String stringResponse = new String(response.data);

                    volleyImageUploadCallBack.uploaded(true, stringResponse);
                  }
                },
                new Response.ErrorListener() {
                  @Override
                  public void onErrorResponse(VolleyError error) {
                    if (error != null && !TextUtils.isEmpty(error.getMessage())) {
                      Toast.makeText(
                              context, "Upload failed!\r\n" + error.getMessage(), Toast.LENGTH_LONG)
                          .show();
                      Log.d("Response", error.getMessage());
                      error.printStackTrace();
                    }

                    volleyImageUploadCallBack.uploaded(false, null);
                  }
                });

        RequestQueue requestQueue = Volley.newRequestQueue(context);
        requestQueue.add(multipartRequest);

        requestQueue.start();

      } catch (Exception e) {
        e.printStackTrace();
      }
    } else {
      Log.d("xx", "something not right... :( ");
    }
  }
Esempio n. 23
0
 @Override
 public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   mRequestQueue = Volley.newRequestQueue(this);
   mRequestQueue.start();
 }
Esempio n. 24
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    requestQueue = Volley.newRequestQueue(this);

    JsonObjectRequest request =
        new JsonObjectRequest(
            Request.Method.GET,
            "api.openweathermap.org/data/2.5/weather?q=London",
            "",
            new Response.Listener<JSONObject>() {
              @Override
              public void onResponse(JSONObject response) {
                Log.d("VOLLEY", response.toString());
                // extraen los datos response.get...

              }
            },
            new Response.ErrorListener() {
              @Override
              public void onErrorResponse(VolleyError error) {
                Log.d("VOLLEY", error.toString());
              }
            });

    requestQueue.add(request);
    requestQueue.start();

    try {

      JSONObject invJson = new JSONObject();
      JSONArray invArray = new JSONArray();

      JSONObject json = new JSONObject(s);
      Log.d("JSONCLASE", json.toString());

      JSONArray arrayContacts = json.getJSONArray("contacts");
      Log.d("JSONCLASE", json.toString());

      for (int i = 0; i < arrayContacts.length(); i++) {
        Log.d("JSONCLASE", "Element " + i + ": " + arrayContacts.get(i).toString());

        JSONObject contactJson = arrayContacts.getJSONObject(i);
        String id = contactJson.getString("id");
        Log.d("JSONCLASE", id);
        String gender = contactJson.getString("gender");
        Log.d("JSONCLASE", gender);
        String address = contactJson.getString("address");
        Log.d("JSONCLASE", address);
        String email = contactJson.getString("email");
        Log.d("JSONCLASE", email);
        String name = contactJson.getString("name");
        Log.d("JSONCLASE", name);

        JSONObject phoneJson = contactJson.getJSONObject("phone");
        String office = phoneJson.getString("office");
        Log.d("JSONCLASE", office);
        String home = phoneJson.getString("home");
        Log.d("JSONCLASE", home);
        String mobile = phoneJson.getString("mobile");
        Log.d("JSONCLASE", mobile);

        // reconstruir JSON

        JSONObject invJsonContact = new JSONObject();
        invJsonContact.accumulate("id", id);
        invJsonContact.accumulate("gender", gender);
        invJsonContact.accumulate("phone", phoneJson);
        invJsonContact.accumulate("address", address);
        invJsonContact.accumulate("email", email);
        invJsonContact.accumulate("name", name);

        Log.d("JSONCLASE", "Reconstruido: " + invJson.toString());

        invArray.put(invJsonContact);
      }

      invJson.accumulate("contacts", invArray);
      Log.d("JSONCLASE", "Reconstruido: " + invJson.toString());

    } catch (JSONException e) {
    }
  }