程序中用到的有接口回調,接口回調在開發中是很重要的,能解決很多問題,如果有不懂得,可以繼續關注我的博客,部分博客中有我對於接口回調的理解,我會後續會寫更多的博客,我的技術有限,所以代碼都是以簡單的爲主,異步任務有不懂得,我的博客也有關於異步任務的一些介紹
值得注意的是:本程序的接口並沒有寫,讀者可自己尋找適合的接口進行操作
新聞資訊的基本佈局
<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="${packageName}.${activityClass}" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="新聞標題:" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="請點擊:" />
<Spinner
android:id="@+id/sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@null" />
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="20dp"
android:background="#00BFFF" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10px"
android:text="新聞內容:" />
<TextView
android:id="@+id/te"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
封裝好的異步任務工具類
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.security.auth.PrivateCredentialPermission;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;
public class PottingAsyncTask extends AsyncTask<String, Void, Object> {
private OnDownLitener onDownLitener;
private DownType downType;
public PottingAsyncTask(DownType downType) {
// TODO Auto-generated constructor stub
this.downType = downType;
}
//子線程
@Override
protected Object doInBackground(String... arg0) {
// TODO Auto-generated method stub
byte[] bs = getByteArray(arg0[0]);
if (bs != null) {
switch (downType) {
case JSON:
String json = new String(bs);
if(onDownLitener!=null){
Object datasObject=onDownLitener.downJson(json);
return datasObject;
}
break;
case IMAGE:
Bitmap bitmap = BitmapFactory.decodeByteArray(bs, 0, bs.length);
return bitmap;
default:
break;
}
}
return null;
}
//在執行完doInBackground後再執行onPostExecute
@Override
protected void onPostExecute(Object result) {
switch (downType) {
case JSON:
if(onDownLitener!=null){
onDownLitener.paresJson(result);
}
break;
case IMAGE:
if(onDownLitener!=null){
onDownLitener.setImage(result);
}
break;
default:
break;
}
}
//構建接口,使用接口回調的方式控制控件
public interface OnDownLitener{
Object downJson(String json);//用於下載json
void paresJson(Object object);//用於解析json
void setImage(Object object);//用於控制image控件
}
//獲得byte數組
private byte[] getByteArray(String urlString) {
InputStream in = null;
ByteArrayOutputStream ou = null;
URL url;
try {
url = new URL(urlString);
HttpURLConnection httpURLConnection = (HttpURLConnection) url
.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setReadTimeout(3000);
httpURLConnection.connect();
if (httpURLConnection.getResponseCode() == 200) {
in = httpURLConnection.getInputStream();
ou=new ByteArrayOutputStream();
byte[] buffer = new byte[1024 * 8];
int len = -1;
while ((len = in.read(buffer)) != -1) {
ou.write(buffer, 0, len);
}
return ou.toByteArray();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (ou != null) {
try {
ou.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
//藉助泛型,確定所需要的類型
public static enum DownType {
JSON, IMAGE
}
//接口回調的方法
public PottingAsyncTask setOnDownLitener(OnDownLitener onDownLitener) {
this.onDownLitener = onDownLitener;
return this;//返回this的原因是鏈式編程,返回當前PottingAsyncTask的對象
}
}
新聞資訊的主方法
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.day06_04.PottingAsyncTask.DownType;
import com.example.day06_04.PottingAsyncTask.OnDownLitener;
import android.R.integer;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
public class MainActivity extends Activity {
//需要自己填寫自己所需要的新聞接口
String urlString="";
private Spinner spinner=null;
private TextView textView=null;
private ArrayAdapter<String> adapter=null;
private List<Map<String, Object>> listmap=new ArrayList<Map<String,Object>>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView=(TextView) findViewById(R.id.te);
spinner=(Spinner) findViewById(R.id.sp);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// 判斷是否等於空的原因是因爲網絡加載時需要時間的,防止程序報錯
if(listmap!=null){
String dString=(String) listmap.get(arg2).get("summary");
textView.setText(dString);
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
new PottingAsyncTask(DownType.JSON).setOnDownLitener(new OnDownLitener() {
@Override
public void paresJson(Object object) {
// TODO Auto-generated method stub
List<String> list =(List<String>) object;
adapter=new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item,list);
spinner.setAdapter(adapter);
}
@Override
public Object downJson(String json) {
// TODO Auto-generated method stub
try {
//不同的接口,獲得不同的json,所以解析json的代碼也是不一樣的,可以仿造這部分的代碼
List<String> list=new ArrayList<String>();
JSONObject jsonObject=new JSONObject(json);
JSONArray jsonArray=jsonObject.getJSONArray("data");
for(int i=0;i<jsonArray.length();i++){
//利用Map原因是map可以存儲更多類型的數據
Map<String, Object> map=new HashMap<String, Object>();
String title = jsonArray.getJSONObject(i).getString("title");
String summary = jsonArray.getJSONObject(i).getString("summary");
int len=i+1;
list.add("【"+len+"】:"+title);
map.put("title", title);
map.put("summary", summary);
listmap.add(map);
}
return list;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
public void setImage(Object object) {
// TODO Auto-generated method stub
}
}).execute(urlString);
}
}