获取json url时屏幕为空白

时间:2018-02-04 17:48:41

标签: android json httpurlconnection

我试图将json解析到应用程序中,但是当应用程序打开时,屏幕显示为空白。我试图找到错误,但什么都没有,使用每一个可能的代码,我认为问题是在获取json时..请帮助我................... ....................

main_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<ListView
    android:id="@+id/list"
    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="examle.android.com.networkexample.MainActivity">
</ListView>

list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:padding="15dp"
xmlns:tools="http://schemas.android.com/tools"
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/login"
    tools:text="USER_LOGIN"
    android:textSize="18sp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
<TextView
    android:paddingTop="2dp"
    android:id="@+id/type"
    tools:text="USER_TYPE"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

</LinearLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {

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

    UserAdapter mAdapter;

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


        ListView listView = (ListView)findViewById(R.id.list);
        // Create a new adapter that takes an empty list of earthquakes as input
        mAdapter = new UserAdapter(this, new ArrayList<User>());

        listView.setAdapter(mAdapter);

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

    }



    private class UserAsync 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 the adapter of previous earthquake data
            mAdapter.clear();

            // If there is a valid list of {@link user}s, then add them to the adapter's
            // data set. This will trigger the ListView to update.

            if(users != null && users.isEmpty()){
                mAdapter.addAll(users);
            }



        }
    }

}

QueryUtils.java

public class QueryUtils {

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

    public QueryUtils() {
    }



    /**
     * Query the github dataset and return a list of {users} objects.
     */

    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);
        }

        // Extract relevant fields from the JSON response and create a list of {@link Users}
        List<User> users = extractFromJson(jsonResponse);

        //return list of {@link Users}
        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 is 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 the json response",e);
        }finally {
            if (urlConnection != null){
                urlConnection.disconnect();
            }
            if (inputStream != null){
                inputStream.close();
            }
        }

        return jsonResponse;
    }


    /**
     * Convert the {@link InputStream} into a String which contains the
     * whole JSON response from the server.
     */

    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> extractFromJson(String user) throws JSONException {
        // If the JSON string is empty or null, then return early.
        if (TextUtils.isEmpty(user)) {
            return null;
        }

        // Create an empty ArrayList that we can start adding earthquakes to

        List<User> users = new ArrayList<>();

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

                String login = jsonObject.getString("login");

                String type = jsonObject.getString("type");

                User user1 = new User(login,type);

                users.add(user1);

            }

        }catch (JSONException e){
            Log.e(LOG_TAG,"Problem in parsing user",e);
        }


        return users;
    }
}

UserAdapter.java

public class UserAdapter extends ArrayAdapter<User>{

    public UserAdapter(@NonNull Context context, @NonNull List<User> objects) {
        super(context, 0, objects);
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {

        View listView = convertView;
        if (listView == null){
            listView = LayoutInflater.from(getContext()).inflate(R.layout.list_item,parent,false);
        }

        User currentUser = getItem(position);

        TextView login = (TextView)listView.findViewById(R.id.login);
        login.setText(currentUser.getUser_login());

        TextView type = (TextView) listView.findViewById(R.id.type);

        type.setText(currentUser.getType());



        return listView;
    }
}

User.java

public class User {

    private String user_login;
    private String type;

    public User(String user_login, String type) {
        this.user_login = user_login;
        this.type = type;
    }

    public String getUser_login() {
        return user_login;
    }

    public String getType() {
        return type;
    }
}

4 个答案:

答案 0 :(得分:0)

您可能需要修改onPostExecute方法中的If语句。仅当用户不为null且用户为空时才更新适配器。您应该在非空的情况下更新适配器

if(users != null && users.isEmpty()){
      mAdapter.addAll(users);
 }

 if(users != null && !users.isEmpty()){
        mAdapter.addAll(users);
  }

答案 1 :(得分:0)

修改users.isEmpty()。条件永远不会满足。你必须改变它,你也必须拨打mAdapter.notifyDataSetChanged();

if(users != null && !users.isEmpty()){
                mAdapter.addAll(users);
                mAdapter.notifyDataSetChanged();
            }

答案 2 :(得分:0)

从头开始,适配器使用空数据初始化。完成异步任务后,您需要通过通知来更新UI。

 @Override
    protected void onPostExecute(List<User> users) {
        // Clear the adapter of previous earthquake data
        mAdapter.clear();

        // If there is a valid list of {@link user}s, then add them to the adapter's
        // data set. This will trigger the ListView to update.

        if(users != null && users.isEmpty()){
            mAdapter.addAll(users);
        // After adding user to the adapter, Notify adapter for UI update
           mAdapter.notifyDataSetChanged();
        }
    }

这将使用用户数据更新UI。

答案 3 :(得分:0)

代码适用于此更改

您可能需要修改onPostExecute方法中的If语句。仅当用户不为null且用户为空时才更新适配器。您应该在非空的情况下更新适配器

if(users != null && users.isEmpty()){
      mAdapter.addAll(users);
 }
To

 if(users != null && !users.isEmpty()){
        mAdapter.addAll(users);
  }