activity_main.xml 里面什么也没有

AndroidManifest.xml(重点是android:name="com.example.volley.MyApplication")

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.volley"
android:versionCode="1"
android:versionName="1.0" > <uses-sdk
android:minSdkVersion="18"
android:targetSdkVersion="18" /> <application
android:name="com.example.volley.MyApplication"
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application> <uses-permission android:name="android.permission.INTERNET" /> </manifest>

MyApplication

package com.example.volley;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley; import android.app.Application; public class MyApplication extends Application {
public static RequestQueue queue; /** 一旦创建就创建RequestQueue请求队列 */
@Override
public void onCreate() {
super.onCreate();
queue = Volley.newRequestQueue(getApplicationContext()); } /** 对外提供静态的方法 */
public static RequestQueue getHttpRequestQueue() {
return queue;
}
}

MainActivity

package com.example.volley;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map; import org.json.JSONObject; import com.android.volley.Request.Method;
import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest; import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast; public class MainActivity extends Activity { /**
* 关联activity。退出之后取消全部的网络请求,释放资源
*/
@Override
protected void onStop() {
super.onStop();
MyApplication.getHttpRequestQueue().cancelAll("abcGet"); }
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// volley_get();
volley_post();
} /**
* get请求方式
*/
private void volley_get() { /**
* String类型
*/
String url = "http://www.imooc.com/api/teacher? type=4&num=30";
StringRequest request = new StringRequest(Method.GET, url,
new Listener<String>() { @Override
public void onResponse(String arg0) {
//返回正确后的操作
Log.e("TAG", ""+arg0);
}
}, new Response.ErrorListener() { @Override
public void onErrorResponse(VolleyError arg0) { }
});
// 设置标签
request.setTag("abcGet");
MyApplication.getHttpRequestQueue().add(request);
MyApplication.getHttpRequestQueue().start(); /**
* JsonObjectRequest类型 由于get參数已经在url写好了,所以传空就可以
*/
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Method.GET,
url, null, new Listener<JSONObject>() { @Override
public void onResponse(JSONObject arg0) {
Toast.makeText(MainActivity.this, arg0.toString(), 0)
.show();
}
}, new Response.ErrorListener() { @Override
public void onErrorResponse(VolleyError arg0) { }
});
// 设置标签
jsonObjectRequest.setTag("bcdGet");
MyApplication.getHttpRequestQueue().add(jsonObjectRequest);
MyApplication.getHttpRequestQueue().start();
/**
* 还有jsonArray方式,这里省略了。。。
*/
} /**
* post请求方式
*/
private void volley_post() {
/**
* StringRequest---post方式
*/
String url = "http://www.imooc.com/api/teacher? ";
StringRequest request = new StringRequest(Method.POST, url,
new Listener<String>() { @Override
public void onResponse(String arg0) {
Log.e("TAG", ""+arg0);
}
}, new Response.ErrorListener() { @Override
public void onErrorResponse(VolleyError arg0) { }
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
//传递參数
Map<String, String> map = new HashMap<String, String>();
map.put("type", "4");
map.put("num", "30");
return map;
}
};
// 设置标签
request.setTag("abcPost");
MyApplication.getHttpRequestQueue().add(request);
MyApplication.getHttpRequestQueue().start();
/**
* jsonObject--post方式
*/
HashMap<String, String> map = new HashMap<String, String>();
map.put("type", "4");
map.put("num", "30");
// 将map转为jsonObject对象
JSONObject object = new JSONObject(map); JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Method.POST, url,
object, new Listener<JSONObject>() { @Override
public void onResponse(JSONObject arg0) {
Log.e("TAG", arg0.toString()); }
}, new Response.ErrorListener() { @Override
public void onErrorResponse(VolleyError arg0) { }
});
// 设置标签
jsonObjectRequest.setTag("bcdPost");
MyApplication.getHttpRequestQueue().add(jsonObjectRequest);
MyApplication.getHttpRequestQueue().start();
}
}

*************************************************下载网络图片**********************************************

AndroidManifest.xml(重点是 android:name="com.example.volleyimagedemo.MyApplication")

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.volleyimagedemo"
android:versionCode="1"
android:versionName="1.0" > <uses-sdk
android:minSdkVersion="18"
android:targetSdkVersion="18" /> <application
android:name="com.example.volleyimagedemo.MyApplication"
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application> <uses-permission android:name="android.permission.INTERNET"/>
</manifest>

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.volleyimagedemo.MainActivity" > <!-- 方式一 -->
<ImageView
android:id="@+id/imageview1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" /> <!-- 方式二 -->
<ImageView
android:id="@+id/imageview2"
android:layout_width="fill_parent"
android:layout_height="wrap_content" /> <!-- 方式三 -->
<com.android.volley.toolbox.NetworkImageView
android:id="@+id/networkImageview"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</com.android.volley.toolbox.NetworkImageView> </LinearLayout>

MyApplication

package com.example.volleyimagedemo;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley; import android.app.Application; public class MyApplication extends Application {
public static RequestQueue queue; @Override
public void onCreate() {
super.onCreate();
queue = Volley.newRequestQueue(getApplicationContext()); } public static RequestQueue getHttpRequestQueue() { return queue;
}
}

BitMapCache

package com.example.volleyimagedemo;

import android.graphics.Bitmap;
import android.util.LruCache; import com.android.volley.toolbox.ImageLoader.ImageCache; public class BitMapCache implements ImageCache{ public LruCache<String, Bitmap> cache;
//超过10兆,自己主动回收
public int max = 10*1024*1024;
public BitMapCache(){
cache = new LruCache<String, Bitmap>(max){
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes()*value.getHeight();
}
};
}
@Override
public Bitmap getBitmap(String arg0) {
return cache.get(arg0);
} @Override
public void putBitmap(String arg0, Bitmap arg1) {
cache.put(arg0, arg1);
} }

MainActivity

package com.example.volleyimagedemo;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.os.Bundle;
import android.widget.ImageView; import com.android.volley.Response;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.NetworkImageView; public class MainActivity extends Activity {
private ImageView imageview1;
private ImageView imageview2;
private NetworkImageView networkImageView; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/** 获取控件、图片url地址 */
imageview1 = (ImageView) findViewById(R.id.imageview1);
imageview2 = (ImageView) findViewById(R.id.imageview2);
networkImageView = (NetworkImageView) findViewById(R.id.networkImageview);
String url = "http://img.mukewang.com/55237dcc0001128c06000338-300-170.jpg"; /**
* 下载图片的另外一种方式ImageLoader+BitMapCache
*/
// imageCache单肚使用是不到缓存效果,须要结合lruCache
ImageLoader imageLoader1 = new ImageLoader(
MyApplication.getHttpRequestQueue(), new BitMapCache());
networkImageView.setDefaultImageResId(R.drawable.ic_launcher);
networkImageView.setErrorImageResId(R.drawable.ic_launcher);
networkImageView.setImageUrl(url, imageLoader1); /**
* 下载图片的第三种种方式
*/
ImageLoader imageLoader2 = new ImageLoader(
MyApplication.getHttpRequestQueue(), new BitMapCache());
// view视图,默认的图片,错误的图片
ImageListener listener = imageLoader1.getImageListener(imageview2,
R.drawable.ic_launcher, R.drawable.ic_launcher);
imageLoader2.get(url, listener); /**
* 下载网络图片的第一种方式ImageRequest
*/
// // 0 是原图的方式载入--Config.RGB_565原图
ImageRequest imageRequest = new ImageRequest(url,
new Listener<Bitmap>() {
//
@Override
public void onResponse(Bitmap arg0) {
imageview1.setImageBitmap(arg0);
}
}, 0, 0, Config.RGB_565, new Response.ErrorListener() { @Override
public void onErrorResponse(VolleyError arg0) {
imageview1
.setBackgroundResource(R.drawable.ic_launcher);
}
}); MyApplication.getHttpRequestQueue().add(imageRequest);
MyApplication.getHttpRequestQueue().start();
} }

Volley的Get、Post方式(JsonObjectRequest、StringRequest)以及Volley获取图片的3种方式的更多相关文章

  1. Spring获取ApplicationContext方式,和读取配置文件获取bean的几种方式

    转自:http://chinazhaokeke.blog.163.com/blog/static/109409055201092811354236  Spring获取ApplicationContex ...

  2. Java基础知识强化之IO流笔记44:IO流练习之 复制图片的 4 种方式案例

    1. 复制图片的 4 种方式案例: 分析: 复制数据,如果我们知道用记事本打开并能够读懂,就用字符流,否则用字节流. 通过该原理,我们知道我们应该采用字节流. 而字节流有4种方式,所以做这个题目我们有 ...

  3. 获取Type的三种方式

    using System;using UnityEngine; public class Type_Test : MonoBehaviour{    private void Awake()    { ...

  4. java动态获取WebService的两种方式(复杂参数类型)

    java动态获取WebService的两种方式(复杂参数类型) 第一种: @Override public OrderSearchListRes searchOrderList(Order_Fligh ...

  5. AngularJS中获取数据源的几种方式

    在AngularJS中,可以从$rootScope中获取数据源,也可以把获取数据的逻辑封装在service中,然后注入到app.run函数中,或者注入到controller中.本篇就来整理获取数据的几 ...

  6. java 获取时间戳的三种方式

      java 获取时间戳的三种方式 CreationTime--2018年7月13日16点29分 Author:Marydon 1.实现方式 方式一:推荐使用 System.currentTimeMi ...

  7. 【Struts2】Struts2获取session的三种方式

    1.Map<String,Object> map =  ActionContext.getContext().getSession(); 2.HttpSession session = S ...

  8. js获取时间戳的三种方式

      js获取时间戳的三种方式 CreateTime--2018年5月23日08:44:10 Author:Marydon // 方式一:推荐使用 var timestamp=new Date().ge ...

  9. Struts2(四.注册时检查用户名是否存在及Action获取数据的三种方式)

    一.功能 1.用户注册页面 <%@ page language="java" contentType="text/html; charset=UTF-8" ...

随机推荐

  1. 21、uwp UI自动化测试(WinAppDriver)

    使用 UI自动化测试的好处就是在代码逻辑中写好 case 后,来实现 “一劳永逸” 的作用,并且自动化测试能够模拟人工达不到要求,比如快速切换页面.快速点击按钮等,对于提高软件的稳定性很有帮助. 安装 ...

  2. ZooKeeper示例 分布式锁

    [转载请注明作者和原文链接,  如有谬误, 欢迎在评论中指正. ] 场景描述 在分布式应用, 往往存在多个进程提供同一服务. 这些进程有可能在相同的机器上, 也有可能分布在不同的机器上. 如果这些进程 ...

  3. gradle查看依赖关系并写入到文本文件的命令

    gradle dependencies>xx.txt

  4. Python获取间隔时间段的时间戳数据

    import time import datetime today = datetime.datetime.now() # delta = datetime.timedelta(hours=1) de ...

  5. SparkStreaming python 读取kafka数据将结果输出到单个指定本地文件

    # -*- coding: UTF-8 -*- #!/bin/env python3 # filename readFromKafkaStreamingGetLocation.py import IP ...

  6. Android开发(四)——Android中的颜色

    Android开发中关于资源文件的存储操作.对于Android资源也是非常重要的,主要包括文本字符串(strings).颜色(colors).数组(arrays).动画(anim).布局(layout ...

  7. iOS实现tableViewCell或collectionCell中点击界面按钮跳转

    //找到父类界面 - (UIViewController *)viewController { for (UIView* next = [self superview]; next; next = n ...

  8. Android 两级菜单栏

    这里来记录下,android 的两级菜单栏,就是顶部切换,和底部的切换.因为在这个上面整了太久的时间,所以特此记录下. 第一种: 先介绍一个网上别人写出来的效果吧,这个当时积分真的很高..CSDN30 ...

  9. Android学习笔记(38):Handler消息传递处理机制

    先说为什么须要Handler: Android的主线程又叫UI线程,用于处理与UI相关的时间.Android仅仅同意在主线程中改动UI组件,当我们在其它线程中须要改动UI界面时.就须要发送消息到主线程 ...

  10. linux进程cpu资源分配命令nice,renice,taskset

    进程cpu资源分配就是指进程的优先权(priority).优先权高的进程有优先执行权利.配置进程优先权对多任务环境的linux很有用,可以改善系统性能.还可以把进程运行到指定的CPU上,这样一来,把不 ...