尝试将JSON提取到recyclerview,但在应用启动后屏幕显示为空白

时间:2018-02-06 16:40:48

标签: android json android-recyclerview

我想在Application["CompanyName']=CompanyName中将json提取到recyclerview但是当我运行应用时,用户界面未更新应用显示空白屏幕,我没有得到错误在哪里,尝试了可能的代码,但没有工作。 屏幕仍然是空白的,那么确切的错误在哪里?解决方案是什么?

items.xml

cardview

main_activity.java

<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:elevation="8dp"
    app:cardCornerRadius="5dp"
    android:layout_marginTop="5dp"
    android:layout_marginLeft="5dp"
    android:layout_marginRight="5dp"
    android:padding="25dp">

        <LinearLayout

            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal">
        <ImageView
            android:id="@+id/avatar"
            android:layout_width="108dp"
            android:layout_height="108dp"
            android:padding="15dp"
            tools:src="@mipmap/ic_launcher" />
            <LinearLayout
                android:paddingRight="15dp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="vertical">



            <TextView
                android:id="@+id/login"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:paddingTop="15dp"
                tools:text="LOGIN_USER" />
            <TextView
                android:id="@+id/type"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:paddingTop="3dp"
                tools:text="USER_TYPE" />
            </LinearLayout>
        </LinearLayout>
    </android.support.v7.widget.CardView>

QueryUtils.java

public class MainActivity extends AppCompatActivity {
    RecyclerView recyclerView;
    UserAdapter mAdapter;
    public ArrayList<User> users = new ArrayList();

    RecyclerView.LayoutManager layoutManager;
    private static final String JSON_URL = "https://api.github.com/users";
    private static final String LOG_TAG = MainActivity.class.getSimpleName();

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


        recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        mAdapter = new UserAdapter(users,this);


        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(mAdapter);

        UserAsyncTask task = new UserAsyncTask();
        task.execute(JSON_URL);


    }

    public class UserAsyncTask extends AsyncTask<String, Void, List<User>>{
        @Override
        protected List<User> doInBackground(String... urls) {

            if(urls.length < 1 || urls[0] == null ){
                return null;
            }

            List<User> result = null;
            try{
                result = QueryUtils.fetchJson(urls[0]);
            } catch (JSONException e) {
                Log.e(LOG_TAG,"Error in fetching json",e);
            }


            return result;
        }

        @Override
        protected void onPostExecute(List<User> users) {

            //clear previous data

            mAdapter.clear();
            if(users != null){

                mAdapter.addAll(users);
             mAdapter.notifyDataSetChanged();
            }
        }
    }
    }

UserAdapter

public class QueryUtils {

    private static final String LOG_TAG = QueryUtils.class.getSimpleName();
    public QueryUtils() {
    }

    public static List<User> fetchJson(String requestUrl) throws JSONException{
        //create URL object
        URL url = createUrl(requestUrl);
        //perform http request to the URL and receive a json

        String jsonResponse = null;
        try {
            jsonResponse = makeHttpRequest(url);
        } catch (IOException e) {
            Log.e(LOG_TAG,"problem in making http request",e);
        }

        List<User> users = extractJson(jsonResponse);

        return users;


    }






    /**
     * Returns new URL object from the given string URL.
     */
    private static URL createUrl(String stringUrl){
        URL url = null;
        try{
            url = new URL(stringUrl);
        } catch (MalformedURLException e) {
            Log.e(LOG_TAG,"Error in creating Url",e);
        }
        return url;
    }
    /**
     * Make an HTTP request to the given URL and return a String as the response.
     */
    private static String makeHttpRequest(URL url) throws IOException{
        String jsonResponse = "";
        //if url == null, return early
        if(url == null){
            return jsonResponse;
        }

        HttpURLConnection urlConnection = null;
        InputStream inputStream = null;
        try {
            urlConnection = (HttpURLConnection)url.openConnection();
            urlConnection.setReadTimeout(10000);
            urlConnection.setConnectTimeout(15000);
            urlConnection.setRequestMethod("GET");

            if(urlConnection.getResponseCode() == 200){
                inputStream = urlConnection.getInputStream();
                jsonResponse = readFromStream(inputStream);
            }else {
                Log.e(LOG_TAG,"Error response code" + urlConnection.getResponseCode());
            }


        }catch (IOException e){
            Log.e(LOG_TAG,"Problem in retrieving Json Response",e);
        }finally {
            if (urlConnection != null){
                urlConnection.disconnect();
            }
            if (inputStream !=null){
                inputStream.close();
            }
        }
        return jsonResponse;
    }

    private static String readFromStream(InputStream inputStream) throws IOException {
        StringBuilder output = new StringBuilder();

        if(inputStream != null){
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
            BufferedReader reader = new BufferedReader(inputStreamReader);

            String line = reader.readLine();

            while (line != null){
                output.append(line);
                line = reader.readLine();
            }

        }
        return output.toString();
    }

    private static List<User> extractJson(String json) throws JSONException{

        // If the JSON string is empty or null, then return early.
        if(TextUtils.isEmpty(json)){
            return null;
        }

        //create an empty arrylist
        List<User> users = new ArrayList<>();

        try{
            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i<jsonArray.length(); i++){
                JSONObject jsonObject = jsonArray.getJSONObject(i);

                String login = jsonObject.getString("login");
                String type = jsonObject.getString("type");
                String avatar = jsonObject.getString("avatar_url");

                User user = new User(login,type,avatar);

                users.add(user);
            }
        }catch (JSONException e){
            Log.e(LOG_TAG,"Error in parsing the JSON",e);
        }

        return users;

    }

}

User.java

public class UserAdapter extends RecyclerView.Adapter<UserAdapter.UserViewHolder> {


    ArrayList<User> users = new ArrayList<>();
    Context context;



    public UserAdapter(ArrayList<User> users, Context context) {
        this.users = users;
        this.context = context;
    }

    @Override
    public UserViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.items,parent,false);

        return new UserViewHolder(view);
    }

    @Override
    public void onBindViewHolder(UserViewHolder holder, int position) {
        holder.login.setText(users.get(position).getUser_login());
        holder.type.setText(users.get(position).getType());
        Picasso.with(context).load(String.valueOf(users.get(position))).into(holder.avatar);
    }

    @Override
    public int getItemCount() {
        return users.size();
    }



    public class UserViewHolder extends RecyclerView.ViewHolder {

        TextView login;
        TextView type;
        ImageView avatar;

        public UserViewHolder(View itemView) {
            super(itemView);
            login = (TextView)itemView.findViewById(R.id.login);
            type = (TextView)itemView.findViewById(R.id.type);
            avatar = (ImageView)itemView.findViewById(R.id.avatar);
        }
    }

    //for clearing previous data in adapter

    public void clear(){
        int itemCount = getItemCount();
        users.clear();

        //notify the adapter that data has been changed
        if(itemCount > 0){
            notifyItemRangeRemoved(0,itemCount);
        }
    }

    //for adding items to the adapter
    public void addAll(List<User> addUser){
        for (User user : addUser){
            users.add(1,user);
        }
        //notify adapter that data has changed
        notifyItemInserted(users.size());
    }
}

3 个答案:

答案 0 :(得分:0)

更改 main_activity.java

recyclerView.setLayoutManager(new LinearLayoutManager(this));

        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setAdapter(mAdapter);

UserAdapter 不要创建ArrayList的对象。

    ArrayList<User> users;
    Context context;

Put Log并检查ArrayList是否有数据:

mAdapter = new UserAdapter(users,this);
Log.e("SIZE",""+users.size());

答案 1 :(得分:0)

你可以试试这个

mAdapter.notifyDataSetChanged();

并从代码中删除以下行

    Course_2013     AP  Advanced    Vocational  Basic   ESL 
0   7th Math Enrich  0    1             0         0      0   
1   8th Math Enrich  0    1             0         0      0   
2   8th Science Enr  0    1             0         0      0   
3   Accounting I     0    0             0         1      0               
4   Accounting II    0    0             0         0      1   

答案 2 :(得分:0)

更改此

    @Override
    protected void onPostExecute(List<User> users) {

        //clear previous data

        mAdapter.clear();
        if(users != null){

            mAdapter.addAll(users);
         mAdapter.notifyDataSetChanged();
        }
    }

到这个

    @Override
    protected void onPostExecute(List<User> newUsers) {

        //clear previous data
        users.clear();

        if(newUsers!= null){
            // Add new set of users
            users.addAll(newUsers);
            mAdapter.notifyDataSetChanged();
        }
    }