我還沒學android,以下代碼均借鑑於網絡,部分來自書籍(五一假光幹這事了,app開發到了一個little階段,先寫一篇博客祭奠我那逝去的三天),以下代碼均在Android Studio3.4實現,demo是不可能發的,我還要拿它來參加比賽(雖然距離完成還差了一大截)。
首先,也是最重要的是,新手碰到紅字就把鼠標放到紅字前面快捷鍵alt+enter,如果是import class就確定,create就算了
解析本地json數據:
首先要說明的一點是,我解析的是本地的json數據,以後會升級成服務器,不知道json的可以去百度,我需要的json數據比較簡單,所以我的代碼解析的也是這種格式的,網上有解析複雜格式的方法,這裏我還是不說明了(因爲之前使用有數組名字的json數據,導致後面的讀取有點複雜,就直接去了數組名)
[
{
"title": "balabalabalabalabalabalabalabalabalabalabalabalabalabala",
"summary": "balabalabalabalabalabalabalabalabalabalabalabalabalabala",
"url": "balabalabalabalabalabalabalabalabalabalabalabalabalabala"
}
]
格式就是上面這樣了,數組不斷重複
召喚:真:分割線
---------------------------------------------------------------------------------------------------------------------------------------------------
本地的json一般都保存在assests文件夾下面,這個百度能找到正確答案,我就不寫了,我的文件名字是test,格式是json,assests文件夾下面顯示的名字也是test,如果你顯示的是test.json,那下面的代碼就改改
// 解析Json數據
jiexiJson jiexiJ = new jiexiJson();
String str = jiexiJ.getJson();
Gson gson = new Gson();
//這個Bean是json返回的實體類
List<Bean> shops = gson.fromJson(str, new TypeToken<List<Bean>>() {}.getType());
這段代碼隨你放哪裏,新手還是放MainActivity.java,代碼非常簡單,對不對,但是你放上去肯定是不能運行的,網上好多人寫的文章代碼殘缺,對於我這種新人來說十分不友好,所以,,,,,,,,下面就一個一個說了
jiexiJson是我定義的一個public類,jiexiJ.getJson()是我的在那個類裏面定義的一個方法,Gson是官方的,進file->project structure導入,搜索gson試試,不行的話去百度gson,Bean還是自定義的一個實體類,其它紅色的就自己去alt+enter
首先是jiexiJson:
public class jiexiJson {
public String getJson() {
//將json數據變成字符串
StringBuilder stringBuilder = new StringBuilder();
try {
//獲取assets資源管理器
InputStream is = jiexiJson.this.getClass().getClassLoader().getResourceAsStream("assets/" + "test");
InputStreamReader streamReader = new InputStreamReader(is);
BufferedReader bf = new BufferedReader(streamReader);
String line;
while ((line = bf.readLine()) != null) {
stringBuilder.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
}
解析本地json數據花了我一天時間
獲取assests資源管理器那裏,網上好多人寫了一個函數,函數裏面有個變量叫做context,但是又沒有寫這麼用的,百度了好久,終於在簡書裏發現了原來這個context的實參就是:代碼所在類名(比如MainActivity).this
但是,找到了又怎麼樣,好多人用AssetManager assetManager = context.getAssets();獲取assests資源管理器,但是呢?空指針!愣是沒在網上找到一個寫了這個問題的人,大佬可以在評論區裏面留言解答一下,最後用的就是我註釋下面的一行代碼,不過這好像是指定路徑,但是app裏面就不行了,反正最後還是從網絡獲取數據,管他呢
try catch我就不寫了,百度能找到用法,選中你的代碼快捷鍵crtl+alt+t,我也不知道那段代碼爲什麼要寫在try catch裏面,寫在外面還會報紅線
以上可以單獨寫一篇博客
Bean這個實體類呢,是用Gsonformat創造出來的,用法自己去百度,簡單來說就是能根據你的json數據格式創造出它的實體類,不論你的json數據多麼複雜
大空白分割術
有了shops這個變量我們能幹嘛呢?我去百度了一下,沒找到答案,我嚴重懷疑那羣寫解析本都json數據的傢伙是不是互相copy的,自行摸索了好久:
// 數據傳輸
Getall getall = new Getall();
// 標題
ArrayList<String> title = getall.TitleToString(shops);
private String[] title_LIST = title.toArray(new String[title.size()]) ;
// 內容簡介
ArrayList<String> summary = getall.SummarryToString(shops);
private String[] summary_LIST = summary.toArray(new String[summary.size()]);
// 網址
ArrayList<String> url = getall.UrlToString(shops);
private String[] url_LIST = url.toArray(new String[url.size()]);
終於,我得到以上的代碼段,Getall是我定義的類,剩下的不能import的變量的紅字函數全是我在這個類下面寫的函數
public class Getall {
//數據傳輸
public ArrayList<String> TitleToString(List<Bean> shops){
ArrayList<String> titles = new ArrayList<>();
String temp = "x";
try {
int i = 0;
while(i < shops.size())
{
i++;
temp = shops.get(i).getTitle();
titles.add(temp);
}
} catch (Exception e) {
e.printStackTrace();
}
return titles;
}
public ArrayList<String> SummarryToString(List<Bean> shops){
ArrayList<String> summary = new ArrayList<>();
String temp = "x";
try {
int i = 0;
while(i < shops.size())
{
i++;
temp = shops.get(i).getSummary();
summary.add(temp);
}
} catch (Exception e) {
e.printStackTrace();
}
return summary;
}
public ArrayList<String> UrlToString(List<Bean> shops){
ArrayList<String> url = new ArrayList<>();
String temp = "x";
try {
int i = 0;
while(i < shops.size())
{
i++;
temp = shops.get(i).getUrl();
url.add(temp);
}
} catch (Exception e) {
e.printStackTrace();
}
return url;
}
}
OK,以上就是解析本地json的詳細過程了
傳輸數據到ListView
16:30了,不想寫了,自己看代碼,下週考試,我幹嘛花三天搞這個app
private List<News> newsList=new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initNews(); //初始化數據
NewsAdapter adapter=new NewsAdapter(MainActivity.this,R.layout.news_item, newsList);
ListView listview = (ListView) findViewById(R.id.LIST);
listview.setAdapter(adapter);
}
private void initNews(){
for(int j = 0; j < title.size(); j++)
{
News a = new News(summary_LIST[j],title_LIST[j]);
newsList.add(a);
}
}
放MainActivity.java裏面
News是仿照《第一行代碼》寫的類
public class News {
private String summary;
private String title;
public News(String summary,String title){
this.summary=summary;
this.title=title;
}
public String getSummary(){
return summary;
}
public String getTitles(){
return title;
}
}
LIST解釋(在activity_main.xml裏面):
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<HorizontalScrollView
android:id="@+id/horizontalScrollView"
android:layout_width="411dp"
android:layout_height="wrap_content"
android:background="#459B93"
android:scrollbars="none"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@id/searchView4">
<LinearLayout
android:id="@+id/horizontalScrollViewItemContainer"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="horizontal" />
</HorizontalScrollView>
<TextView
android:id="@+id/testTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="TextView_Test"
android:textSize="36sp"
tools:layout_editor_absoluteX="88dp"
tools:layout_editor_absoluteY="230dp"
app:layout_constraintTop_toBottomOf="@id/LIST"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"/>
<SearchView
android:id="@+id/searchView4"
android:layout_width="411dp"
android:layout_height="56dp"
android:iconifiedByDefault="false"
android:queryHint="搜索內容"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ListView
android:id="@+id/LIST"
android:layout_width="413dp"
android:layout_height="618dp"
app:layout_constraintLeft_toLeftOf="@id/horizontalScrollView"
app:layout_constraintTop_toBottomOf="@id/horizontalScrollView"
/>
</android.support.constraint.ConstraintLayout>
新手別copy上去,自己在design裏面拖動一個ListView就好了,記得它的id是LIST,覆蓋整個屏幕,再點擊那個魔法棒(百度了ConstraintLayout的人可以在代碼裏固定它的位置,大佬也可以直接在design裏面將它固定住)
NewsAdapter:
public class NewsAdapter extends ArrayAdapter<News> {
private int resourceId;
public NewsAdapter(Context context, int textViewResourceId, List<News> objects){
super(context,textViewResourceId,objects);
resourceId=textViewResourceId;
}
@Override
public View getView(int position, View convertView, ViewGroup parent){
News news=getItem(position); //獲取當前項的實例
View view= LayoutInflater.from(getContext()).inflate(resourceId,parent,false);
TextView newsTitle=(TextView) view.findViewById(R.id.titles);
TextView newsSummary=(TextView) view.findViewById(R.id.summary);
newsTitle.setText(news.getTitles());
newsSummary.setText(news.getSummary());
return view;
}
}
news_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/titles"
android:layout_width="411dp"
android:layout_height="30dp"
android:layout_gravity="center_vertical"
tools:layout_editor_absoluteY="16dp" />
<TextView
android:id="@+id/summary"
android:layout_width="411dp"
android:layout_height="70dp"
app:layout_constraintTop_toBottomOf="@id/titles"
android:layout_gravity="center_vertical"
tools:layout_editor_absoluteY="94dp" />
</android.support.constraint.ConstraintLayout>
這個新手可以copy上去,記得在layout下面新建一個xml文件
到這裏,我們居然在listview的每個item上面顯示了兩行textview數據,新手是不是很神奇,在listview插入圖片的方法你可以看看《第一行代碼》,也可以自行百度。
到這裏就結束了,聽說評論給積分
下面附贈兩段代碼,網上找的
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Bundle bundle = new Bundle();
bundle.putString("url_LIST", url_LIST[arg2]);
Intent intent = new Intent();
intent.putExtras(bundle);
intent.setClass(testURL.this, Article.class);
Log.i("url:", url_LIST[arg2]);
startActivity(intent);
}
});
關鍵字:MainActivity.java onCreate
public class Article extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news_article);
Bundle bundle=getIntent().getExtras();
String url=bundle.getString("url_LIST");
TextView tv=(TextView) findViewById(R.id.url);
tv.setText(url);
}
}
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/url"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="哈哈哈啊哈哈" />
</android.support.constraint.ConstraintLayout>
不解釋,我源代碼幾乎發給你們了,幾十分鐘搞定我三天的時間,想想都很爽,接下來我要搞點擊item進入url的網絡鏈接,好煩,代碼不給了,心理不平衡