Skip to content

Instantly share code, notes, and snippets.

@ben4562002
Last active October 6, 2019 04:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ben4562002/921c4001443dbe2b3ee696e6881d711b to your computer and use it in GitHub Desktop.
Save ben4562002/921c4001443dbe2b3ee696e6881d711b to your computer and use it in GitHub Desktop.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ListView
android:id="@+id/mylistview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
</ListView>
</LinearLayout>
package com.example.stock;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
public class FinNews extends AppCompatActivity {
ListView listview; // 把視圖的元件宣告成全域變數
String result; // 儲存JSON資料用的字串
ArrayList<News> arrayOfWebData = new ArrayList<>();
static ArrayList<String> resultRow;
// this is the result object
class News {
public String title;
public String url;
public String urlToImage;
public String publishedAt;
}
FancyAdapter aa = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fin_news);
// 宣告執行緒
Thread thread = new Thread(mutiThread);
thread.start(); // 開始執行
listview = (ListView) findViewById(R.id.mylistview);
//we initialize our fancy adapter object, we already declared it above
//in the class definition
aa = new FancyAdapter();
// here we set the adapter, this turns it on
listview.setAdapter(aa);
}
class FancyAdapter extends ArrayAdapter<News>{
FancyAdapter() {
super(FinNews.this, android.R.layout.simple_list_item_1, arrayOfWebData);
}
public View getView(int position, View convertView,
ViewGroup parent) {
ViewHolder holder;
//we call an if statement on our view that is passed in,
//to see if it has been recycled or not. if it has been recycled,
//then it already exists and we do not need to call the inflater function
//this saves us A HUGE AMOUNT OF RESOURCES AND PROCESSING
//this is the proper way to do it
if (convertView==null) {
LayoutInflater inflater=getLayoutInflater();
convertView=inflater.inflate(R.layout.news_row, null);
//here is something new. we are using a class called a view holder
holder=new ViewHolder(convertView);
//we are using that class to cache the result of the findViewById function
//which we then store in a tag on the view
convertView.setTag(holder);
}
else
{
holder=(ViewHolder)convertView.getTag();
}
holder.populateFrom(arrayOfWebData.get(position));
return(convertView);
}
}
class ViewHolder {
public TextView title = null;
public TextView url = null;
public TextView urlToImage = null;
public TextView publishedAt = null;
ViewHolder(View row) {
title=(TextView)row.findViewById(R.id.title);
url=(TextView)row.findViewById(R.id.url);
urlToImage=(TextView)row.findViewById(R.id.urlToImage);
publishedAt=(TextView)row.findViewById(R.id.publishedAt);
}
//notice we had to change our populate from to take an arguement of type person
void populateFrom(News r) {
title.setText(r.title);
url.setText(r.url);
urlToImage.setText(r.urlToImage);
publishedAt.setText(r.publishedAt);
}
}
/* ======================================== */
// 建立一個執行緒執行的事件取得網路資料
// Android 有規定,連線網際網路的動作都不能再主線程做執行
// 畢竟如果使用者連上網路結果等太久整個系統流程就卡死了
private Runnable mutiThread = new Runnable(){
public void run()
{
try {
URL url = new URL("http://25.94.188.7/GetData.php"); // 25.94.188.7 // 192.168.43.88
// 開始宣告 HTTP 連線需要的物件,這邊通常都是一綑的
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 建立 Google 比較挺的 HttpURLConnection 物件
connection.setRequestMethod("POST");
// 設定連線方式為 POST
connection.setDoOutput(true); // 允許輸出
connection.setDoInput(true); // 允許讀入
connection.setUseCaches(false); // 不使用快取
connection.connect(); // 開始連線
int responseCode =
connection.getResponseCode();
// 建立取得回應的物件
if(responseCode ==
HttpURLConnection.HTTP_OK){
// 如果 HTTP 回傳狀態是 OK ,而不是 Error
InputStream inputStream =
connection.getInputStream();
// 取得輸入串流
BufferedReader bufReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"), 8);
// 讀取輸入串流的資料
String box = ""; // 宣告存放用字串
String line = null; // 宣告讀取用的字串
while((line = bufReader.readLine()) != null) {
box += line + "\n";
// 每當讀取出一列,就加到存放字串後面
}
inputStream.close(); // 關閉輸入串流
result = box; // 把存放用字串放到全域變數
}
// 讀取輸入串流並存到字串的部分
// 取得資料後想用不同的格式
// 例如 Json 等等,都是在這一段做處理
// parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i = 0; i < jArray.length(); i++){
//get our object, this is one person's worth of data
JSONObject json_data = jArray.getJSONObject(i);
//create a new person
News resultRow = new News();
//set that person's attributes
resultRow.title = json_data.getString("title");
resultRow.url = json_data.getString("url");
resultRow.urlToImage = json_data.getString("urlToImage");
resultRow.publishedAt = json_data.getString("publishedAt");
//this is our arrayList object, we add our Person object to it
arrayOfWebData.add(resultRow);
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
catch(Exception e) {
result = e.toString(); // 如果出事,回傳錯誤訊息
}
Log.e("執行完","Thread");
}
};
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#EE0000" />
<TextView
android:id="@+id/url"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#00EE00" />
<TextView
android:id="@+id/urlToImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#0000EE" />
<TextView
android:id="@+id/publishedAt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FF00FF" />
</LinearLayout>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment