Google The official network framework -Volley The use of parsing Json And how to load network pictures


 Volley What is it? ?
Google I/O At the conference ,Google Introduction Volley A network framework for
Volley For what scene ?
Volley Suitable for frequent operation of network communication , And can realize multiple network communication at the same time .

Download address :http://download.csdn.net/detail/qq_26787115/9358787

1.Volley The use of parsing Json

We don't talk , Speak directly :

Our needs are simple , Is to do a small software to query the home , Use Volley Parse a section of address to get Json And analysis Json Show it , It's a simple requirement , It's also very basic , But it's intuitive !

Let's take a look at the renderings first !

step

1. The application address has been key
2. hold Volley Of jar File import project
3. Resolve the address to get json
4. analysis json fill

1. Applied Key:22a6ba14995ce26dd0002216be51dabb

2. Address of the interface ( Aggregate data application ):http://apis.juhe.cn/mobile/get?phone=13429667914&key= Your application KEY

3. take Volley Import the project

4. To start the

 Be sure to add permissions first :<uses-permission android:name="android.permission.INTERNET"/>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<RelativeLayout
android:id="@+id/tab1_rl"
android:layout_width="match_parent"
android:layout_height="51dp"
android:background="#34c083" >
<TextView
android:layout_width="wrap_content"
android:layout_height="51dp"
android:layout_centerHorizontal="true"
android:background="@null"
android:gravity="center"
android:text=" Place of ownership inquiry "
android:textColor="@android:color/white"
android:textSize="20dp" />
</RelativeLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
android:text=" Please enter your mobile phone number to find the information of your home location " />
<EditText
android:id="@+id/et"
android:layout_width="fill_parent"
android:layout_height="45dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="@drawable/ed_bg"
android:gravity="center"
android:hint=" Please enter the correct phone number " />
<Button
android:id="@+id/btn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:background="#34c083"
android:text=" Inquire about "
android:textColor="@android:color/white" />
<TextView
android:layout_width="fill_parent"
android:layout_height="1dp"
android:layout_marginTop="10dp"
android:background="#aeaea9" />
<TextView
android:id="@+id/tv1"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:gravity="center_vertical"
android:text=" Place of ownership :" />
<TextView
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#aeaea9" />
<TextView
android:id="@+id/tv2"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:gravity="center_vertical"
android:text=" Area code :" />
<TextView
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#aeaea9" />
<TextView
android:id="@+id/tv3"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:gravity="center_vertical"
android:text=" Operator, :" />
<TextView
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#aeaea9" />
<TextView
android:id="@+id/tv4"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:gravity="center_vertical"
android:text=" The user types :" />
<TextView
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#aeaea9" />
</LinearLayout>
 There's nothing to say here , The layout is the same as the preview interface
EditText: Enter the phone number id: android:id="@+id/et"
Button: Click to query android:id="@+id/btn"
TextView: Place of ownership , Area code , Operator, , The user types android:id="@+id/tv1234"

MainActivity.java

 First of all, let's talk about the steps :
1. Initialize these controls
2. to Button Add click event
// Here's how to judge user input , If the input is not empty, it will be executed Volley_Get(); Method
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
myPhone = et.getText().toString();
if (et == null) {
Toast.makeText(MainActivity.this, " The number cannot be empty ",
Toast.LENGTH_LONG).show();
} else {
Volley_Get();
}
}
});
3.Volley_Get The method is to parse the interface to get Json Character , And it USES the GET Method , also POST I won't elaborate on the method , throw away a brick in order to get a gem , I don't know my own way Google
 private void Volley_Get() {
// Address of the interface myphone The phone number you entered for us Key:22a6ba14995ce26dd0002216be51dabb
String url = "http://apis.juhe.cn/mobile/get?phone=" + myPhone
+ "&key=22a6ba14995ce26dd0002216be51dabb";
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Method.GET, url,
new Listener<String>() {
// success
@Override
public void onResponse(String json) {
Volley_Json(json);
Toast.makeText(MainActivity.this, " success :"+json, 1).show();
}
}, new Response.ErrorListener() {
// Failure
@Override
public void onErrorResponse(VolleyError errorLog) {
Toast.makeText(MainActivity.this, " Failure :"+errorLog.toString(),
Toast.LENGTH_LONG).show();
}
});
queue.add(request);
}

4.Volley_Json();

 When we parse this interface successfully, we get a json The string of , The concrete appearance is like this
 {
"resultcode": "200",
"reason": "Return Successd!",
"result": {
"province": " jiangxi ",
"city": " Ji'an ",
"areacode": "0796",
"zip": "343000",
"company": " China Unicom ",
"card": " Jiangxi Unicom GSM card "
},
"error_code": 0
}
 Let's create a new method Volley_Json() And define a String Parameters of , as follows :
private void Volley_Json(String json) {
//result by 200 It means success
try {
JSONObject jsonObject = new JSONObject(json);
JSONObject object = jsonObject.getJSONObject("result");
tv1.setText(" Place of ownership :" + object.getString("province") + "-"
+ object.getString("city"));
tv2.setText(" Area code :" + object.getString("areacode"));
tv3.setText(" Operator, :" + object.getString("company"));
tv4.setText(" The user types :" + object.getString("card"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

In this way, it can be resolved json In the string and display to achieve the query effect of the home , Here is MainActivity The complete code and Demo Download link :

package com.lgl.queryaddress;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
public class MainActivity extends Activity {
private TextView tv1, tv2, tv3, tv4;
private EditText et;
private Button btn;
private String myPhone;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
getActionBar().hide();
setContentView(R.layout.activity_main);
initView();
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
myPhone = et.getText().toString();
if (et == null) {
Toast.makeText(MainActivity.this, " The number cannot be empty ",
Toast.LENGTH_LONG).show();
} else {
Volley_Get();
}
}
});
}
private void initView() {
et = (EditText) findViewById(R.id.et);
btn = (Button) findViewById(R.id.btn);
tv1 = (TextView) findViewById(R.id.tv1);
tv2 = (TextView) findViewById(R.id.tv2);
tv3 = (TextView) findViewById(R.id.tv3);
tv4 = (TextView) findViewById(R.id.tv4);
}
private void Volley_Get() {
String url = "http://apis.juhe.cn/mobile/get?phone=" + myPhone
+ "&key=22a6ba14995ce26dd0002216be51dabb";
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Method.GET, url,
new Listener<String>() {
// success
@Override
public void onResponse(String json) {
Volley_Json(json);
Toast.makeText(MainActivity.this, " success :"+json, 1).show();
}
}, new Response.ErrorListener() {
// Failure
@Override
public void onErrorResponse(VolleyError errorLog) {
Toast.makeText(MainActivity.this, " Failure :"+errorLog.toString(),
Toast.LENGTH_LONG).show();
}
});
queue.add(request);
}
private void Volley_Json(String json) {
//result by 200 It means success
try {
JSONObject jsonObject = new JSONObject(json);
JSONObject object = jsonObject.getJSONObject("result");
tv1.setText(" Place of ownership :" + object.getString("province") + "-"
+ object.getString("city"));
tv2.setText(" Area code :" + object.getString("areacode"));
tv3.setText(" Operator, :" + object.getString("company"));
tv4.setText(" The user types :" + object.getString("card"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Demo Download address :http://download.csdn.net/detail/qq_26787115/9360953

2.Volley Load network pictures

 Relative to the request json character string , There are fewer steps to parse the pictures on the Internet , There are more ways to play , Let's start with simplicity , Let's take an example , Let's take a look at the renderings first !

It's just one. Button And a ImageView, Click on Button Load picture information

 step
1. Get links to pictures
2. Add permissions
3. Load network pictures

layout_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"
android:background="#FDFDFD">
<RelativeLayout
android:id="@+id/tab1_rl"
android:layout_width="match_parent"
android:layout_height="51dp"
android:background="#34c083" >
<TextView
android:layout_width="wrap_content"
android:layout_height="51dp"
android:layout_centerHorizontal="true"
android:background="@null"
android:gravity="center"
android:text=" Place of ownership inquiry "
android:textColor="@android:color/white"
android:textSize="20dp" />
</RelativeLayout>
<Button
android:id="@+id/btn"
android:textSize="20sp"
android:textColor="@android:color/white"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="30dp"
android:background="#34c083"
android:text=" Loading pictures " />
<ImageView
android:layout_marginTop="50dp"
android:layout_gravity="center_horizontal"
android:id="@+id/iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" />
</LinearLayout>
 One Button android:id="@+id/btn"
One imageview android:id="@+id/iv"

After initializing these two controls, you can parse them directly , Not much code , see MainActivity Complete code for

package com.lglvolleyiv;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.Volley;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends Activity {
private Button btn;
private ImageView iv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().hide();
setContentView(R.layout.activity_main);
iv = (ImageView) findViewById(R.id.iv);
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Volley_Iv();
}
});
}
// Loading pictures
protected void Volley_Iv() {
// The picture is from Baidu logo, Right click the browser to get the picture address
String url ="http://ss.bdimg.com/static/superman/img/logo/bd_logo1_31bdc765.png";
// request
RequestQueue queue = Volley.newRequestQueue(this);
/**
* ImageRequest The constructor of takes six arguments ,
* The first parameter is the image URL Address .
* The second parameter is the callback of the successful image request , Here we take the returned Bitmap The parameter is set to ImageView in .
* The third and fourth parameters are used to specify the maximum allowed width and height of the image respectively , Incorrect settings will compress the image .
* The fifth parameter specifies the color properties of the image ,Bitmap.Config The following constants can be used here .
* The sixth parameter is the callback for the failed picture request , Here we are when the request fails ImageView Show a default picture in .
*/
ImageRequest imageRequest = new ImageRequest(url, new Response.Listener<Bitmap>() {
@Override
public void onResponse(Bitmap response) {
// If you succeed, you can directly set the acquired bitmap picture
iv.setImageBitmap(response);
}
}, 0, 0, Config.RGB_565, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// failed
}
});
// In the end, I put this ImageRequest Object added to RequestQueue Just inside
queue.add(imageRequest);
}
}

Demo Download address :http://download.csdn.net/detail/qq_26787115/9362615

The complete idea of this project should be to query the operator and display the corresponding logo, But this part hasn't been done yet , Perfect the framework of the whole project and put it on the shelf , If you are interested, you can try :


Baidu :http://shouji.baidu.com/software/item?docid=8424313&from=as

91:http://apk.91.com/Soft/Android/com.lgl.queryaddress-1.html

Android :http://apk.hiapk.com/appinfo/com.lgl.queryaddress/1


Online project source code :http://download.csdn.net/detail/qq_26787115/9379019

It will be updated in the future , It's just a bit of a foundation , Don't spray !!!

Google The official network framework -Volley The use of parsing Json And more related articles about how to load web images

  1. Google The official network framework Volley actual combat ——QQ Good luck test , Namo Amitabha !

    Google The official network framework Volley actual combat --QQ Good luck test , Namo Amitabha ! This time we'll use a third-party interface to make a QQ Good or bad test program , The code is still relatively simple No plan, no truth It's just code , The detailed explanation has been written in the notes ...

  2. android Official open source high-performance asynchronous loading network pictures Gridview Example

    This is what I saw on the Android bus , Put it here and share it . This example android Official , It explains how to load network pictures asynchronously , And in gridview Efficient display of pictures, this code is a good solution to load a large number of pictures , newspaper OOM ...

  3. 【 Android requests open source framework Volley Source code analysis series 】 Customize your own Request Requests and Volley Framework source code analysis

    Through the previous study, we have mastered Volley The basic usage of , I suggest you read my blog first [ Android requests open source framework Volley Source code analysis series ] First time to know Volley And its basic usage . Such as StringRequest To ask for a ...

  4. Android Network framework Volley( Experience )

    Volley yes Google I/O 2013 Launched the network communication library , stay volley Before the launch, we generally choose a more mature third-party network communication library , Such as : android-async-http retrofit okhttp ...

  5. Android Network framework Volley

    Volley yes Google I/O 2013 Launched the network communication library , stay volley Before the launch, we generally choose a more mature third-party network communication library , Such as : android-async-http retrofit okhttp ...

  6. Android Network framework Volley( Actual combat )

      I said before ym—— Android Network framework Volley( Experience ), You should understand volley Use , Next we're going to see how to put volley Used in actual combat projects , Let's consider a few questions first : From the last article  mQu ...

  7. Android Network framework Volley Use

    Volley brief introduction In the normal development process , Our applications are almost always dealing with the Internet , stay android Network programming under is generally based on Http Agreed , Common is HttpURLConnection and HttpClient two ...

  8. Android Popular network framework Volley Detailed explanation

    .Volley brief introduction volley The English meaning of ‘ Mass hair ’.‘ Burst out ’.Volley yes 2013 Google officially released a Android Network communication library on the platform .Volley Very suitable for some small amount of data , But network operations that require frequent communication ...

  9. Android Network framework -Volley practice Use Volley Make your own definition ListView

    This article is translated from Ravi Tamada Blog Android Custom ListView with Image and Text using Volley Finally, the effect This ListView There are some shadows ...

Random recommendation

  1. iOS block Use

    I know block Is a very important knowledge point , After a long time, I forgot , This is an example I saw on the Internet .( Go back in the evening and sort out the other one ) In view A There's a button on it ( It's used to push out the view when you click b) And a label( It's used to show from b It came back ...

  2. ECSHOP Template settings , Front desk English, back desk Chinese , No need to copy

    Many friends of English station Just want the front desk to be displayed in English , Keep Chinese in the background . How to do this ? I see similar articles on the Internet , It seems that we have to copy and overlay the directory . I think the following method is simpler , No need to copy . First step : Through the background settings to achieve the front English . Get into ...

  3. web Front end Development Notes - Continuous updating

    This article is just for personal common code arrangement , For your daily reference html Browser kernel <!--[if IE]><![endif]--> <!--[if IE 6]><![endif ...

  4. rem ~~ Do you understand ?

    front end In the development of adaptation rem Have a pivotal position , It's ready , You are God , Not good , direct GG: It's not good to be ignorant , Be sensible . Get down to business : First we need to understand ,css There are several common layout units : 1.px (pix ...

  5. T-SQL:Varchar and Nvarchar difference ( 8、 ... and )

    General data types :CHAR and VARCHAR   Unicode data type NCHAR NVARCHAR General data types Will limit languages other than English     Unicode Will support multiple languages VAR difference : 1. ...

  6. Windows 8 The system is on by default .Net Framework The version is 4.0, And some users may need to use 3.5 Or the following , Simple addition method

    It's downloaded from the Internet .Net Framework3.5 Can't be directly in Windows 8 Installed on the system , We can go through Windows 8 To achieve 1. Open the control panel , Click on ” Enable or close Windows function “ ...

  7. Android Development ( nineteen )——ViewFlipper Medium onClick Events and onFling Conflict of events

    stay onDown Set in this.flipper.setClickable(true); And then in onFling In the method this.flipper.setClickable(false); ps: among setO ...

  8. R Based on learning ( Two )-- Connect sqlserver

    Test environment :win10+RStudio Three steps :(1) establish ODBC data source :(2)install.packages('RODBC') :(3) Write connection test scripts (1) establish ODBC data source Control panel -> ...

  9. .net Group discussion notes

    This article is .net Notes on the bits and pieces of knowledge learned by the group , Will continue to update Thanks to the gods in the group , Group number (128485855) 1. About URL Coding problem encodeURIComponent 2.c# Turn on this machine directly excel( Including other types ...

  10. JAVA Traverse Map Methods

    import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class TestMap { pu ...