程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程綜合問答 >> recyclerview-哪位好心的大俠幫我看一下代碼,不知道為什麼一運行虛擬機就崩潰,謝謝啦

recyclerview-哪位好心的大俠幫我看一下代碼,不知道為什麼一運行虛擬機就崩潰,謝謝啦

編輯:編程綜合問答
哪位好心的大俠幫我看一下代碼,不知道為什麼一運行虛擬機就崩潰,謝謝啦

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class StartCanteenActivity extends AppCompatActivity {
private RecyclerView mRvDemoMain;
private Context mContext;
private List mList;
private MyRecyclerAdapter mAdapter;
private static final String urlPath = "http://www.imooc.com/api/teacher?type=4&num=30";
//private static final String urlPath = "http://14.117.17.161/json.php";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.canteen);

    // 1. 初始化RecyclerView中要顯示的數據
    initData();
    // 2. 初始化本頁面的控件
    initView();
}

/**
 * 初始化RecyclerView中要顯示的數據
 */
private void initData() {
}

/**
 * 初始化本頁面的控件
 */
private void initView() {
    mRvDemoMain = (RecyclerView) findViewById(R.id.canteen_recyclerview);

    // 設置RecyclerView的Adapter
    mAdapter = new MyRecyclerAdapter(mContext,mList,mRvDemoMain);
    mRvDemoMain.setAdapter(mAdapter);

    // zz 測試
    System.out.println("==== mRvDemoMain.setAdapter(mAdapter)執行完了");

    mRvDemoMain.setLayoutManager(new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL));
    mRvDemoMain.setItemAnimator(new DefaultItemAnimator());

    // 調用Adapter中的設置監聽器的方法
    mAdapter.setOnItemClickListener(new MyRecyclerAdapter.OnItemClickListener() {
        @Override
        public void onItemClick(View view, int position) {
            Toast.makeText(StartCanteenActivity.this, "click : " + position, Toast.LENGTH_SHORT).show();
        }
    });
}

/**
 * 實現網絡的異步訪問
 */
class NewAsyncTask extends AsyncTask<String, Void, List<NewsBeam>>
{
    @Override
    protected void onPostExecute(List<NewsBeam> newsBeams)
    {
        super.onPostExecute(newsBeams);
        MyRecyclerAdapter adapter = new MyRecyclerAdapter(StartCanteenActivity.this, newsBeams, mRvDemoMain);
        mRvDemoMain.setAdapter(adapter);
    }

    @Override
    protected List<NewsBeam> doInBackground(String... params)
    {
        return getJsonData(params[0]);
    }


    /**
     * 從 URL 中獲取數據
     *
     * @param url
     * @return
     */
    private List<NewsBeam> getJsonData(String url)
    {
        List<NewsBeam> newsBeamsList = new ArrayList<NewsBeam>();
        try
        {
            String jsonString = readStream(new URL(urlPath).openStream());

            JSONObject jsonObject;
            NewsBeam newsBeam;

            jsonObject = new JSONObject(jsonString);
            JSONArray jsonArray = jsonObject.getJSONArray("data");
            for(int i = 0; i < jsonArray.length(); i++)
            {
                jsonObject = jsonArray.getJSONObject(i);
                newsBeam = new NewsBeam();
                newsBeam.newsIconUrl = jsonObject.getString("picSmall");
                newsBeam.newsTitle = jsonObject.getString("name");
                newsBeamsList.add(newsBeam);
            }

        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        catch(JSONException e)
        {
            e.printStackTrace();
        }
        return newsBeamsList;
    }


    /**
     * 從 inpustStream 獲取的信息
     *
     * @param is
     * @return
     */
    private String readStream(InputStream is)
    {
        InputStreamReader isr;
        String result = "";
        try
        {
            isr = new InputStreamReader(is, "utf-8");
            BufferedReader br = new BufferedReader(isr);
            String line = "";
            while((line = br.readLine()) != null)
            {
                result += line;
            }

        }
        catch(UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        return result;
    }
}

}

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class MyRecyclerAdapter extends RecyclerView.Adapter {
protected LayoutInflater mLayoutInflater;
private Context mContext;
protected List mList;
private List mHeights; // 隨機高度的集合
private ImgLoader mImgLoader;
private int mStart;
private int mEnd;
public static String[] URLS;
private boolean mFirstIn;
private MyRecyclerAdapter(List mList) {
this.mList = mList;
}

/**
 * 自定義一個OnItemClickListener的回調接口
 */
public interface OnItemClickListener{
    void onItemClick(View view, int position);
}

/**
 * 創建接口的成員變量
 */
private OnItemClickListener mOnItemClickListener;

/**
 * 設置監聽器的方法
 * @param listener listener
 */
public void setOnItemClickListener(OnItemClickListener listener){
    this.mOnItemClickListener = listener;
}

/**
 * 構造方法
 * @param context context
 * @param data data
 */
public MyRecyclerAdapter(Context context, List<NewsBeam> data,RecyclerView recyclerView) {
    this.mContext = context;
    this.mList = data;
    mLayoutInflater = LayoutInflater.from(mContext);
    mImgLoader = new ImgLoader(recyclerView);
    mLayoutInflater = LayoutInflater.from(mContext);
    mHeights = new ArrayList<Integer>();
    // 向隨機高度集合中添加隨機數(100 ~ 400)
    for (int i = 0; i < mList.size(); i++) {
        mHeights.add((int) (100 + Math.random() * 300));
    }
    URLS = new String[data.size()];
    for(int i = 0; i < data.size(); i++)
    {
        URLS[i] = data.get(i).newsIconUrl;
    }
    mFirstIn = true;
}

/**
 * RecyclerView中條目的數量
 *
 * @return count
 */
@Override
public int getItemCount() {
    return mList.size();
}

/**
 * 創建ViewHolder
 *
 * @param parent   parent
 * @param viewType viewType
 * @return holder
 */
@Override
public MyRecyclerHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    // zz 測試
    System.out.println("====onCreateViewHolder : " + viewType + " == " + parent);

    View view = mLayoutInflater.inflate(R.layout.recycler_item, parent, false);
    MyRecyclerHolder mHolder = new MyRecyclerHolder(view);
    return mHolder;
}

/**
 * 綁定ViewHolder
 *
 * @param holder   holder
 * @param position position
 */
@Override
public void onBindViewHolder(final MyRecyclerHolder holder, final int position) {
    // 為ViewHolder的父控件(也即一條Item)設置高度
    ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();
    lp.height = mHeights.get(position);
    holder.itemView.setLayoutParams(lp);
    holder.mIvItem.setImageResource(R.mipmap.ic_launcher);
    String url = mList.get(position).newsIconUrl;
    holder.mIvItem.setTag(url);
    mImgLoader.showImgByAysncTask(holder.mIvItem, url);
    holder.mTvItem.setText(mList.get(position).newsTitle);

    // 調用條目的點擊事件設置方法
    setUpItemEvent(holder);

    // zz 測試
    System.out.println("====onBindViewHolder : " + position + " == " + holder);

}

/**
 * 設置條目的點擊事件(點按)
 * @param holder holder
 */
protected void setUpItemEvent(final MyRecyclerHolder holder) {
    if (mOnItemClickListener != null) {
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int layoutPosition = holder.getLayoutPosition();
                mOnItemClickListener.onItemClick(holder.itemView, layoutPosition);
            }
        });
    }
}

/**
 * RecyclerView的ViewHolder類
 */
public class MyRecyclerHolder extends RecyclerView.ViewHolder {
    ImageView mIvItem;
    TextView mTvItem;

    public MyRecyclerHolder(View itemView) {
        super(itemView);
        mIvItem = (ImageView) itemView.findViewById(R.id.id_image);
        mTvItem = (TextView) itemView.findViewById(R.id.id_name);
    }
}

}

最佳回答:


自己看logcat中的輸出信息,會提示你,什麼錯誤,在哪個文件,第幾行,自己調試

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved