程序员人生 网站导航

Storage--5大存储一博打尽

栏目:综合技术时间:2015-03-19 08:07:50


activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="测试各种数据存储方式" android:textSize="20sp" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="onClickSP" android:text="SharedPreference存储" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="onClickIF" android:text="内部文件存储" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="onClickOF" android:text="外部文件存储" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="onClickDB" android:text="数据库存储" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="onClickNW" android:text="网络存储" /> </LinearLayout>

MainActivity.java

package com.example.storage; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; /** * 主界面 * @author xfzhang * */ public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void onClickSP(View view) { startActivity(new Intent(this, SPActivity.class)); } public void onClickIF(View view) { startActivity(new Intent(this, IFActivity.class)); } public void onClickOF(View view) { startActivity(new Intent(this, SDActivity.class)); } public void onClickDB(View view) { startActivity(new Intent(this, DBActivity.class)); } // public void onClickNW(View view) { startActivity(new Intent(this, NetWorkActivity.class)); } }

-----------------------------sp存储------------------------------------------------


activity_sp.xml

<?xml version="1.0" encoding="utf⑻"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <EditText android:id="@+id/et_sp_name" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="存储的key" > </EditText> <EditText android:id="@+id/et_sp_value" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="存储的value" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:id="@+id/btn_sp_save" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="SAVE" /> <Button android:id="@+id/btn_sp_read" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="READ" /> </LinearLayout> </LinearLayout>

SPActivity.java

/** * 保存路径为--->/data/data/包名/shared_prefs/文件.xml */ package com.example.storage; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class SPActivity extends Activity implements OnClickListener { private EditText et_sp_name; private EditText et_sp_value; private Button btn_sp_save; private Button btn_sp_read; private SharedPreferences sp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sp); et_sp_name = (EditText) findViewById(R.id.et_sp_name); et_sp_value = (EditText) findViewById(R.id.et_sp_value); btn_sp_save = (Button) findViewById(R.id.btn_sp_save); btn_sp_read = (Button) findViewById(R.id.btn_sp_read); btn_sp_read.setOnClickListener(this); btn_sp_save.setOnClickListener(this); //得到sp对象 sp = getSharedPreferences("sp", Context.MODE_PRIVATE); } @Override public void onClick(View v) { //读写 if (v==btn_sp_read) { String name = et_sp_name.getText().toString(); //根据name值获得value值 String value = sp.getString(name, null); //或叫回显 et_sp_value.setText(value); } //保存 if (v==btn_sp_save) { String name = et_sp_name.getText().toString(); String value = et_sp_value.getText().toString(); //通过sp获得edit编辑器,寄存数据,进行保存 sp.edit().putString(name, value).commit(); //给出提示 Toast.makeText(this, "保存成功", 0).show(); } } }
----------------------------下边是手机内部存储-------------------------------------------

activity_if.xml

<?xml version="1.0" encoding="utf⑻"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="将assets下的logo.png保存得手机内部" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" > <Button android:id="@+id/btn_if_save" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="SAVE" android:onClick="testSaveInnerFile"/> <Button android:id="@+id/btn_if_read" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="READ" android:onClick="testReadInnerFile"/> </LinearLayout> <ImageView android:id="@+id/iv_if_icon" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_launcher" /> </LinearLayout>

IFActivity.java

<pre name="code" class="java">/** * 向--->/data/data/包名/files/文件.xml */ package com.example.storage; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import android.app.Activity; import android.content.Context; import android.content.res.AssetManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.view.View; import android.widget.ImageView; import android.widget.Toast; public class IFActivity extends Activity { private ImageView iv_if_icon; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_if); iv_if_icon = (ImageView) findViewById(R.id.iv_if_icon); } public void testSaveInnerFile(View view){ //获得assetManager对象 AssetManager assetManager = getAssets(); //从assets中获得资源 try { InputStream is = assetManager.open("01.png"); //获得输出流 OutputStream os = this.openFileOutput("01.png", Context.MODE_PRIVATE); byte[] buffer = new byte[1024]; int len = ⑴; while((len=is.read(buffer))>0) { os.write(buffer,0,len); } os.close(); is.close(); }catch (IOException e) { e.printStackTrace(); } Toast.makeText(this, "保存成功", 0).show(); } //读取 public void testReadInnerFile(View view) { //读取手机内存文件 FileInputStream fis = null; try { fis = this.openFileInput("01.png"); } catch (FileNotFoundException e) { e.printStackTrace(); } //保装为1个图片对象 Bitmap bitmap = BitmapFactory.decodeStream(fis); //显示 iv_if_icon.setImageBitmap(bitmap); } }



------------------------------------------------------下边是sd卡存储-------------------------------------------------

activity_sd.xml

<?xml version="1.0" encoding="utf⑻"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <EditText android:id="@+id/et_sd_filename" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="存储的文件名"> </EditText> <EditText android:id="@+id/et_sd_content" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="存储的文本内容"/> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" > <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="SAVE" android:onClick="save1" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="READ" android:onClick="read1"/> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" > <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="SAVE" android:onClick="save2"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="READ" android:onClick="read2"/> </LinearLayout> </LinearLayout>

SDActivity.java

/** 保存在--> /storage/sdcard/文件夹/xx.txt * */ package com.example.storage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import android.app.Activity; import android.os.Bundle; import android.os.Environment; import android.view.View; import android.widget.EditText; import android.widget.Toast; public class SDActivity extends Activity { private EditText et_sd_filename; private EditText et_sd_content; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 记载视图 setContentView(R.layout.activity_sd); et_sd_filename = (EditText) findViewById(R.id.et_sd_filename); et_sd_content = (EditText) findViewById(R.id.et_sd_content); } /** * 保存数据得手机sd卡 保存在--> /storage/sdcard/文件夹/xx.tx */ public void save1(View view) { String fileName = et_sd_filename.getText().toString(); String content = et_sd_content.getText().toString(); // sd卡挂载在手机上 if (Environment.MEDIA_MOUNTED.equals(Environment .getExternalStorageState())) { // sd卡文件夹对应的file目录对象 File sdfFile = Environment.getExternalStorageDirectory(); File dirFile = new File(sdfFile, "dataStorage"); if (!dirFile.exists()) { dirFile.mkdirs(); } //创建文件 File file = new File(dirFile, fileName); try { //创建包括输出地址的文件输出流 OutputStream os = new FileOutputStream(file); os.write(content.getBytes("utf⑻")); os.close(); } catch (IOException e) { e.printStackTrace(); } Toast.makeText(this, "保存成功", 0).show(); } else { Toast.makeText(this, "sd卡没有挂载", 0).show(); } } /** * 读取数据 * * @param view */ public void read1(View view) { String fileName = et_sd_filename.getText().toString(); if (Environment.MEDIA_MOUNTED.equals(Environment .getExternalStorageState())) { // sd卡文件夹对应的file目录对象 File sdfFile = Environment.getExternalStorageDirectory(); File dirFile = new File(sdfFile, "dataStorage"); if (!dirFile.exists()) { dirFile.mkdirs(); } //创建文件对象 File file = new File(dirFile, fileName); ByteArrayOutputStream baos = null; try { //先将sd卡中的信息输入到内存中,然后在输出流输出得手机文本框中 FileInputStream fis = new FileInputStream(file); baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = fis.read(buffer)) > 0) { baos.write(buffer, 0, len); } baos.close(); fis.close(); } catch (IOException e) { e.printStackTrace(); } String content = baos.toString(); et_sd_content.setText(content); } else { Toast.makeText(this, "sd卡没有挂载", 0).show(); } } /** * 获得的是--->/storage/sdcard/Android/data/app_package/files/ * 利用卸载后,sd卡中的也被清除 */ public void save2(View view) { String fileName = et_sd_filename.getText().toString(); String content = et_sd_content.getText().toString(); // sd卡挂载在手机上 if (Environment.MEDIA_MOUNTED.equals(Environment .getExternalStorageState())) { File filesDir = this.getExternalFilesDir(null); File file = new File(filesDir, fileName); try { OutputStream os = new FileOutputStream(file); os.write(content.getBytes("utf⑻")); os.close(); } catch (IOException e) { e.printStackTrace(); } Toast.makeText(this, "保存成功", 0).show(); } else { Toast.makeText(this, "sd卡没有挂载", 0).show(); } } /** * 读取方法2 */ public void read2(View view) { String fileName = et_sd_filename.getText().toString(); if (Environment.MEDIA_MOUNTED.equals(Environment .getExternalStorageState())) {// sd卡挂载在手机上了 // 获得 : /storage/sdcard/Android/data/app_package/files/ File filesDir = this.getExternalFilesDir(null); File file = new File(filesDir, fileName); ByteArrayOutputStream baos = null; try { FileInputStream fis = new FileInputStream(file); baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = ⑴; while ((len = fis.read(buffer)) > 0) { baos.write(buffer, 0, len); } baos.close(); fis.close(); } catch (IOException e) { e.printStackTrace(); } String content = baos.toString(); et_sd_content.setText(content); } else { Toast.makeText(this, "sd卡没有正常挂载!", 0).show(); } } }

-----------------------------------以下是数据库存储----------------------------


activity_db.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Create DB" android:onClick="create"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Insert" android:onClick="insert"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Update" android:onClick="update"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Delete" android:onClick="delete" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="query" android:onClick="query" /> </LinearLayout>

DBHelper.java

package com.example.storage; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DBHelper extends SQLiteOpenHelper{ private static final String DB_NAME = "atguigu.db"; public static final String TABLE_EMPLOYEE = "employee"; private static int version = 1; //构造器 public DBHelper(Context context) { super(context, DB_NAME, null, version); } //带版本更新的构造器 public DBHelper(Context context,int version) { super(context, DB_NAME, null, version); DBHelper.version = version; } //创建数据库的时候调用(只调用1次) @Override public void onCreate(SQLiteDatabase db) { //创建表 db.execSQL("create table employee(id integer primary key autoincrement,name,salary double,birthday date)"); //初始化数据 db.execSQL("insert into employee(name,salary,birthday)values('Tom1',8000,'1988-09⑴2')"); db.execSQL("insert into employee(name,salary,birthday)values('Tom2',9000,'1988-09⑴3')"); } //版本更新时候调用 @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }

DBActivity.java

package com.example.storage; import android.app.Activity; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Toast; public class DBActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_db); } public void create(View view) { DBHelper dbHelper = new DBHelper(this); // 是去获得数据库连接, 如果数据库还没有创建, 立即创建数据库, 并返回与数据库的连接对象 SQLiteDatabase database = dbHelper.getReadableDatabase(); } public void insert(View view) { DBHelper dbHelper = new DBHelper(this); // 是去获得数据库连接, 如果数据库还没有创建, 立即创建数据库, 并返回与数据库的连接对象 SQLiteDatabase database = dbHelper.getReadableDatabase(); // 准备数据 ContentValues values = new ContentValues(); values.put("name", "Tom3"); values.put("salary", "5000"); values.put("birthday", "1992-09⑴4"); // 插入操 database.insert(table, nullColumnHack, values) long id = database.insert(DBHelper.TABLE_EMPLOYEE, null, values); // toast提示 Toast.makeText(this, "插入成功" + id, 0).show(); // 关闭资源 database.close(); } public void update(View view) { DBHelper dbHelper = new DBHelper(this); // 是去获得数据库连接, 如果数据库还没有创建, 立即创建数据库, 并返回与数据库的连接对象 SQLiteDatabase database = dbHelper.getReadableDatabase(); // 准备数据 ContentValues values = new ContentValues(); values.put("name", "BOB3"); values.put("salary", 6200); values.put("birthday", "1993⑴2⑴3"); // 更新资源database.update(table, values, whereClause, whereArgs) int updateCount = database.update(DBHelper.TABLE_EMPLOYEE, values, "id=?", new String[] { "3" }); // toast提示 Toast.makeText(this, "更新成功" + updateCount, 0).show(); // 关闭资源 database.close(); } public void delete(View view) { DBHelper dbHelper = new DBHelper(this); // 是去获得数据库连接, 如果数据库还没有创建, 立即创建数据库, 并返回与数据库的连接对象 SQLiteDatabase database = dbHelper.getReadableDatabase(); int deleteCount = database.delete(DBHelper.TABLE_EMPLOYEE, "id=?", new String[] { "2" }); // toast提示 Toast.makeText(this, "删除成功" + deleteCount, 0).show(); // 关闭资源 database.close(); } public void query(View view) { DBHelper dbHelper = new DBHelper(this); // 是去获得数据库连接, 如果数据库还没有创建, 立即创建数据库, 并返回与数据库的连接对象 SQLiteDatabase database = dbHelper.getReadableDatabase(); // 查询全部返回结果集合 Cursor cursor = database.query(DBHelper.TABLE_EMPLOYEE, null, null, null, null, null, null); while (cursor.moveToNext()) { int id = cursor.getInt(0); String name = cursor.getString(1); double salary = cursor.getDouble(2); String brithday = cursor.getString(cursor.getColumnIndex("birthday")); Log.e("Query", id + "_" + name + "_" + salary + "_" + brithday); } cursor.close(); database.close(); } }

-------------------------------网络存储---------------------


activity_net.xml上面截图布局文件省略

NetWorkActivity.java

package com.example.storage; public class NetWorkActivity extends Activity { private EditText et_main_content1; private EditText et_main_content2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_net); et_main_content1 = (EditText) findViewById(R.id.et_main_content1); et_main_content2 = (EditText) findViewById(R.id.et_main_content2); } /*使用httpUrlConnection提交get要求*/ public void url_get(View view) { final String path = et_main_content1.getText().toString() + "?name=Tom1&age=1"; //ProgressDialog是AlertDialog的自类,调用静态方法show返回ProgressDialog final ProgressDialog progressDialog = ProgressDialog.show(this, null, "加载中..."); new Thread() { public void run() { try { // 得到url对象 URL url = new URL(path); // 得到连接 HttpURLConnection connection = (HttpURLConnection) url .openConnection(); // 设置要求方式(只能大写) connection.setRequestMethod("GET"); // 设置可以读取服务器返回的数据 connection.setDoInput(true); // 设置可以向服务端发送数据,如果为true就是post要求 // connection.setDoOutput(true); // 设置连接超时时间 connection.setConnectTimeout(5000); // 设置读取服务器返回数据的时间 connection.setReadTimeout(5000); // 连接服务器 connection.connect(); // 获得要求码 int responseCode = connection.getResponseCode(); // 判断要求码 if (responseCode == 200) { // 得到从服务器返回的数据输入流 InputStream inputStream = connection.getInputStream(); // 获得字节数组输出流--将返回的结果写到输出流中 ByteArrayOutputStream baos = new ByteArrayOutputStream(); // 读取输入流中,讲数据换为字符串 int len = 0; byte[] buffer = new byte[1024]; while ((len = inputStream.read(buffer)) != ⑴) { baos.write(buffer, 0, len); } baos.close(); inputStream.close(); //字节数组转为字符串 final String result = baos.toString(); // 只有主线程可以更新界面 runOnUiThread(new Runnable() { public void run() { // 移除进度条 progressDialog.dismiss(); // 显示结果 et_main_content2.setText(result); } }); } } catch (Exception e) { e.printStackTrace(); Log.e("TAG", "联网要求失败"); } } }.start(); } /* * 使用httpUrlConnection提交post要求 */ public void url_post(View view) { // ---http://192.168.30.41:8080/android/index.jsp final String path = et_main_content1.getText().toString(); final ProgressDialog progressDialog = ProgressDialog.show(this, null, "加载中..."); new Thread() { public void run() { try { // 得到url对象 URL url = new URL(path); // 得到连接 HttpURLConnection connection = (HttpURLConnection) url .openConnection(); // 设置要求方式(只能大写) connection.setRequestMethod("POST"); // 设置可以读取服务器返回的数据 connection.setDoInput(true); // 设置可以向服务端发送数据 connection.setDoOutput(true); // 设置连接超时时间 connection.setConnectTimeout(5000); // 设置读取服务器返回数据的时间 connection.setReadTimeout(5000); // 连接服务器 connection.connect(); // 通过流的方式向服务端提交要求参数 String data = "name=Tom2&age=2"; // 得到输出流 OutputStream outputStream = connection.getOutputStream(); // 向服务器写数据 outputStream.write(data.getBytes("utf⑻")); int responseCode = connection.getResponseCode(); if (responseCode == 200) { // 得到返回的输入流 InputStream inputStream = connection.getInputStream(); // 准备输出流 ByteArrayOutputStream baos = new ByteArrayOutputStream(); int len = 0; byte[] buffer = new byte[1024]; while ((len = inputStream.read(buffer)) != ⑴) { baos.write(buffer, 0, len); } baos.close(); inputStream.close(); //字节数组转为字符串 final String result = baos.toString(); runOnUiThread(new Runnable() { public void run() { progressDialog.dismiss(); et_main_content2.setText(result); } }); } } catch (Exception e) { e.printStackTrace(); Log.e("TAG", "联网要求失败"); } } }.start(); } /* * 使用httpClient提交get要求 */ public void client_get(View view) { // ---http://192.168.30.41:8080/android/index.jsp final String path = et_main_content1.getText().toString() + "?name=Tom3&age=3"; final ProgressDialog progressDialog = ProgressDialog.show(this, null, "加载中..."); new Thread() { public void run() { try { // 创建客户端对象 HttpClient httpClient = new DefaultHttpClient(); // 设置超时时间 HttpParams params = httpClient.getParams(); HttpConnectionParams.setConnectionTimeout(params, 5000); HttpConnectionParams.setSoTimeout(params, 5000); // 创建get要求(包括路径) HttpGet request = new HttpGet(path); // 获得响应对象--客户端对象履行要求获得相应对象 HttpResponse httpResponse = httpClient.execute(request); // 获得要求码 int statusCode = httpResponse.getStatusLine() .getStatusCode(); // 进行判断 if (statusCode == 200) { // 获得响应体数据 HttpEntity entity = httpResponse.getEntity(); // 利用工具类获得响应数据 final String result = EntityUtils.toString(entity); runOnUiThread(new Runnable() { public void run() { // 移除 progressDialog.dismiss(); et_main_content2.setText(result); } }); } } catch (Exception e) { e.printStackTrace(); Log.e("TAG", "联网要求失败"); } } }.start(); } /* * 使用httpClient提交post要求 */ public void client_post(View view) { // ---http://192.168.30.41:8080/android/index.jsp final String path = et_main_content1.getText().toString(); final ProgressDialog progressDialog = ProgressDialog.show(this, null, "加载中..."); new Thread() { public void run() { try { // 创建客户端对象 HttpClient httpClient = new DefaultHttpClient(); // 设置超时时间 HttpParams params = httpClient.getParams(); HttpConnectionParams.setConnectionTimeout(params, 5000); HttpConnectionParams.setSoTimeout(params, 5000); // 创建post要求对象 HttpPost request = new HttpPost(path); // 设置要求体 List<NameValuePair> parameters = new ArrayList<NameValuePair>(); parameters.add(new BasicNameValuePair("name", "Tom4")); parameters.add(new BasicNameValuePair("age", "4")); HttpEntity entity = new UrlEncodedFormEntity(parameters, "utf⑻"); request.setEntity(entity); // 获得响应对象 HttpResponse httpResponse = httpClient.execute(request); // 获得要求码 int statusCode = httpResponse.getStatusLine() .getStatusCode(); // 进行判断 if (statusCode == 200) { // 获得响应体数据 HttpEntity entityRequest = httpResponse.getEntity(); // 利用工具类 final String result = EntityUtils .toString(entityRequest); runOnUiThread(new Runnable() { public void run() { // 移除 progressDialog.dismiss(); et_main_content2.setText(result); } }); } } catch (Exception e) { e.printStackTrace(); Log.e("TAG", "联网要求失败"); } } }.start(); } /* * 使用Volley提交get要求 */ public void Volley_get(View view) { //创建要求地址信息 final String path = et_main_content1.getText().toString() + "?name=Tom5&age=5"; //显示进度条 final ProgressDialog progressDialog = ProgressDialog.show(this, null, "加载中..."); StringRequest request = new StringRequest(Request.Method.GET, path, new Response.Listener<String>() { @Override public void onResponse(String result) { progressDialog.dismiss(); et_main_content2.setText(result); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError arg0) { progressDialog.dismiss(); Toast.makeText(NetWorkActivity.this, "联网失败", 0).show(); } }); //创建1个要求队列 RequestQueue requestQueue = Volley.newRequestQueue(this); //添加要求履行要求 requestQueue.add(request); } /* * 使用Volley提交post要求 */ public void Volley_post(View view) { final String path = et_main_content1.getText().toString(); final ProgressDialog progressDialog = ProgressDialog.show(this, null, "加载中..."); StringRequest request = new StringRequest(Request.Method.POST, path, new Response.Listener<String>() { @Override public void onResponse(String result) { progressDialog.dismiss(); et_main_content2.setText(result); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError arg0) { progressDialog.dismiss(); Toast.makeText(NetWorkActivity.this, "联网失败", 0).show(); } }) { @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> map = new HashMap<String, String>(); map.put("name", "Tom6"); map.put("age", "6"); return map; } }; //创建要求队列,处理要求 RequestQueue requestQueue = Volley.newRequestQueue(this); requestQueue.add(request); } }




------分隔线----------------------------
------分隔线----------------------------

最新技术推荐