Shubham Kumar
Shubham Kumar

Reputation: 295

screen is blank while fetching json url

I was trying to parse the json into the app but when the app opens the screen is blank. i tried to find the error but get nothing,used every possible code for this, i think the problem is while fetching the json.. please help me.......................................

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

Upvotes: 0

Views: 88

Answers (4)

Shubham Kumar
Shubham Kumar

Reputation: 295

The code worked with this change

You might need to modify the If statement in onPostExecute method. You were updating the Adapter only if user not null and user is empty. You should update the adapter in case of not empty

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

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

Upvotes: 1

Faysal Ahmed
Faysal Ahmed

Reputation: 7669

From the beginning, adapter initializes with empty data. After completing Async task, you need to update UI by notifying.

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

This will update UI with user data.

Upvotes: 0

Bishoy Kamel
Bishoy Kamel

Reputation: 2355

modify users.isEmpty(). the condition is never satisfied.you have to change it also you have to call mAdapter.notifyDataSetChanged();

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

Upvotes: 0

AnasAbubacker
AnasAbubacker

Reputation: 3607

You might need to modify the If statement in onPostExecute method. You were updating the Adapter only if user not null and user is empty. You should update the adapter in case of not empty

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

To

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

Upvotes: 0

Related Questions