package com.example.monthly_test05; |
import android.support.v7.app.AppCompatActivity; |
import android.os.Bundle; |
import android.util.Xml; |
import android.widget.ListView; |
import com.example.bean.Bean; |
import com.lidroid.xutils.HttpUtils; |
import com.lidroid.xutils.exception.HttpException; |
import com.lidroid.xutils.http.ResponseInfo; |
import com.lidroid.xutils.http.callback.RequestCallBack; |
import com.lidroid.xutils.http.client.HttpRequest; |
import org.xmlpull.v1.XmlPullParser; |
import org.xmlpull.v1.XmlPullParserException; |
import java.io.IOException; |
import java.io.InputStream; |
import java.io.InputStreamReader; |
import java.net.HttpURLConnection; |
import java.net.MalformedURLException; |
import java.net.URL; |
import java.util.ArrayList; |
import java.util.List; |
public class MainActivity extends AppCompatActivity { |
private ListView listView; |
private String name; |
private Bean bean; |
private List<Bean> list= new ArrayList<>(); |
@Override |
protected void onCreate(Bundle savedInstanceState) { |
super .onCreate(savedInstanceState); |
setContentView(R.layout.activity_main); |
listView = (ListView) findViewById(R.id.list); |
new Thread( new Runnable() { |
@Override |
public void run() { |
getdate(); |
} |
}).start(); |
} |
private void getdate(){ |
String str= "http://apis.juhe.cn/catering/query?key=469ecc4cc89313f091ebf2375f5b0460&lng=116.3883&lat=39.9289&dtype=xml" ; |
URL url= null ; |
try { |
url = new URL(str); |
try { |
HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection(); |
httpURLConnection.setRequestMethod( "GET" ); |
httpURLConnection.setReadTimeout( 5000 ); |
httpURLConnection.setConnectTimeout( 5000 ); |
int code = httpURLConnection.getResponseCode(); |
if (code== 200 ){ |
InputStream inputStream = httpURLConnection.getInputStream(); |
XmlPullParser xmlPullParser = Xml.newPullParser(); |
try { |
xmlPullParser.setInput( new InputStreamReader(inputStream)); |
int type = xmlPullParser.getEventType(); |
while (type!=XmlPullParser.END_DOCUMENT){ |
switch (type){ |
case XmlPullParser.START_TAG: |
name = xmlPullParser.getName(); |
if (name.equals( "item" )){ |
bean = new Bean(); |
} else |
if (name.equals( "name" )){ |
bean.name=xmlPullParser.nextText(); |
} else |
if (name.equals( "photos" )){ |
bean.photos=xmlPullParser.nextText(); |
} |
break ; |
case XmlPullParser.END_TAG: |
name = xmlPullParser.getName(); |
if (name.equals( "item" )){ |
list.add(bean); |
} |
break ; |
} |
type=xmlPullParser.next(); |
} |
} catch (XmlPullParserException e) { |
e.printStackTrace(); |
} |
} |
} catch (IOException e) { |
e.printStackTrace(); |
} |
} catch (MalformedURLException e) { |
e.printStackTrace(); |
} |
runOnUiThread( new Runnable() { |
@Override |
public void run() { |
Myadapter myadapter= new Myadapter(MainActivity. this ,list); |
listView.setAdapter(myadapter); |
} |
}); |
} |
} |
初级程序员
by: 云代码会员 发表于:2016-12-23 21:16:45 顶(0) | 踩(0) 回复
可读性真差
回复评论