How Do We Set id For Data That Showed With Volley Json Array Request

房东的猫 提交于 2020-01-01 19:38:49

问题


I have some problem about setting and getting id from data that showed with volley JSon array request.

I've tried to do this, but it fail.

ChildTidur.java

public class ChildTidur extends AppCompatActivity implements TidurAdapter.ContactsAdapterListener {
    private static final String TAG = ChildTidur.class.getSimpleName();
    private RecyclerView recyclerView;
    private List<Story> storyList;
    private TidurAdapter mAdapter;
    private SearchView searchView;
    private TextView noFavtsTV;
    private AppPreferences appPreferences;

    // CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
    public static final int CONNECTION_TIMEOUT = 2000;
    public static final int READ_TIMEOUT = 2000;
    final String KEY_SAVED_RADIO_BUTTON_INDEX = "SAVED_RADIO_BUTTON_INDEX";

    // url to fetch contacts json
    private static final String URL = "https://api.kafeinkode.com/childtidur.json";

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

        AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);

        SwipeRefreshLayout pullToRefresh = findViewById(R.id.pullToRefresh);
        pullToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                finish();
                startActivity(getIntent());
            }
        });

        //toolbar logo and desc
        Toolbar topToolBar = (Toolbar) findViewById(R.id.toolbarTidur);
        setSupportActionBar(topToolBar); //munculkan menu ke toolbar
        getSupportActionBar().setDisplayHomeAsUpEnabled(true); //this line shows back button

        recyclerView = findViewById(R.id.recycler_view);
        noFavtsTV = findViewById(R.id.no_favt_text);
        storyList = new ArrayList<>();
        mAdapter = new TidurAdapter(this, storyList, this, appPreferences);

        // white background notification bar
        whiteNotificationBar(recyclerView);

        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.addItemDecoration(new TidurDekor(this, DividerItemDecoration.VERTICAL, 36));
        recyclerView.setAdapter(mAdapter);

        //Make call to AsyncTask
        new AsyncLogin().execute();

        //Get radio button value
        LoadPreferences();

    } //OnCreate

    private void showNoFavtText(boolean show) {
        noFavtsTV.setVisibility(show ? View.VISIBLE : View.GONE); //jika data yang ditampilkan tidak ada, maka show noFavsTv
        recyclerView.setVisibility(show ? View.GONE : View.VISIBLE); //jika data yang ditampilkan tidak ada, maka don't show rV
    }

    private void LoadPreferences(){
        LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View contentView = inflater.inflate(R.layout.activity_settings, null,false);
        RadioGroup radioGroup = (RadioGroup)contentView.findViewById(R.id.radioSex);
        SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
        int savedRadioIndex = sharedPreferences.getInt(KEY_SAVED_RADIO_BUTTON_INDEX, 0);
        RadioButton savedCheckedRadioButton = (RadioButton)radioGroup.getChildAt(savedRadioIndex);
        savedCheckedRadioButton.setChecked(true);

        RadioGroup genderGroup = (RadioGroup) contentView.findViewById(R.id.radioSex);
        RadioButton male = (RadioButton) contentView.findViewById(R.id.theme1);
        RadioButton female = (RadioButton) contentView.findViewById(R.id.theme2);

        if (genderGroup.getCheckedRadioButtonId() == -1) {
            Toolbar tb = (Toolbar) findViewById(R.id.toolbarTidur);
            tb.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
        }
        else {
            if (male.isChecked()) {     // one of the radio buttons is checked
                Toolbar tb1 = (Toolbar) findViewById(R.id.toolbarTidur);
                tb1.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
            }
            else if (female.isChecked()) {
                Toolbar tb2 = (Toolbar) findViewById(R.id.toolbarTidur);
                tb2.setBackgroundColor(getResources().getColor(R.color.colorAccent));
            }
        }
    }


    private class AsyncLogin extends AsyncTask<String, String, String> {
        ProgressDialog pdLoading = new ProgressDialog(ChildTidur.this);
        HttpURLConnection conn;
        java.net.URL url = null;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            //this method will be running on UI thread
            showNoFavtText(false);
            pdLoading.setMessage("\tMencoba terhubung ke internet...");
            pdLoading.setCancelable(false);
            pdLoading.show();

        }

        @Override
        protected String doInBackground(String... params) {
            try {

                // Enter URL address where your json file resides
                // Even you can make call to php file which returns json data
                url = new URL("https://api.kafeinkode.com/childtidur.json");

            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return e.toString();
            }
            try {

                // Setup HttpURLConnection class to send and receive data from php and mysql
                conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(READ_TIMEOUT);
                conn.setConnectTimeout(CONNECTION_TIMEOUT);
                conn.setRequestMethod("GET");

                // setDoOutput to true as we recieve data from json file
                conn.setDoOutput(true);

            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
                return e1.toString();
            }

            try {

                int response_code = conn.getResponseCode();

                // Check if successful connection made
                if (response_code == HttpURLConnection.HTTP_OK) {

                    // Read data sent from server
                    InputStream input = conn.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                    StringBuilder result = new StringBuilder();
                    String line;

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

                    // Pass data to onPostExecute method
                    return (result.toString());

                } else {
                    return("koneksi gagal");
                }

            } catch (IOException e) {
                e.printStackTrace();
                return e.toString();
            } finally {
                conn.disconnect();
            }

        }

        /**
         * fetches json by making http calls
         */
        protected void onPostExecute(String result) {

            JsonArrayRequest request = new JsonArrayRequest(URL, new Response.Listener<JSONArray>() {

                @Override
                public void onResponse(JSONArray response) {
                    pdLoading.dismiss();

                    Log.d(TAG, response.toString());
                    if (response.length() > 0) {
                        // Parsing json
                        List<Story> items = new Gson().fromJson(response.toString(), new TypeToken<List<Story>>() {

                        }.getType());
                        // adding contacts to contacts list
                        storyList.clear();
                        storyList.addAll(items);
                        // refreshing recycler view
                        mAdapter.notifyDataSetChanged();

                        for (int i=0; i<storyList.size(); i++) {
                            Story story = new Story();
                            story.setIdStory(String.valueOf(i));
                        }
                    }

                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    pdLoading.dismiss();
                    // error in getting json
                    Log.e(TAG, "Error: " + error.getMessage());
                    Toast.makeText(getApplicationContext(), "Tidak bisa menampilkan data. Periksa kembali sambungan internet Anda", Toast.LENGTH_LONG).show();

                    AlertDialog alertDialog = new AlertDialog.Builder(ChildTidur.this).create();
                    alertDialog.setTitle("Error");
                    alertDialog.setMessage("Data Tidak bisa ditampilkan. Periksa kembali sambungan internet Anda");
                    alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            });
                    alertDialog.show();
                    showNoFavtText(true);
                }
            });

            TidurSearch.getInstance().addToRequestQueue(request);
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.search_tidur, menu);
        getMenuInflater().inflate(R.menu.menu_main, menu);

        // Associate searchable_tidur configuration with the SearchView
        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        searchView = (SearchView) menu.findItem(R.id.action_search2).getActionView();
        searchView.setSearchableInfo(searchManager
                .getSearchableInfo(getComponentName()));
        searchView.setMaxWidth(Integer.MAX_VALUE);

        // listening to search query text change
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                // filter recycler view when query submitted
                mAdapter.getFilter().filter(query);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String query) {
                // filter recycler view when text is changed
                mAdapter.getFilter().filter(query);
                return false;
            }
        });
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_search2) {
            return true;
        }

        //Menu
        if (id == R.id.action_settings) {
            startActivity(new Intent(this, SettingsActivity.class));
            return true;
        }
        else
        if (id == R.id.about_us) {
            startActivity(new Intent(this, AboutUs.class));
            return true;
        }
        else
        if (id == R.id.favlist) {
            startActivity(new Intent(this, ShowFavouriteList.class));
            return true;
        }

        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish();
                return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        // close search view on back button pressed
        if (!searchView.isIconified()) {
            searchView.setIconified(true);
            return;
        }
        super.onBackPressed();
    }

    private void whiteNotificationBar(View view) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int flags = view.getSystemUiVisibility();
            flags |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
            view.setSystemUiVisibility(flags);
            getWindow().setStatusBarColor(Color.WHITE);
        }
    }

    @Override
    public void onContactSelected(Story story) {
        Toast.makeText(getApplicationContext(), "Selected: " + story.getName(), Toast.LENGTH_LONG).show();
    }
}

TidurAdapter.java

public void onClick(View view) {
                    // Another problem lays here when I get id of data
                    Story story = storyList.get(getLayoutPosition());
                    int ambilId = Integer.parseInt(story.getIdStory());

                    if ( 0 == ambilId ) {

                        Intent myIntent = new Intent(view.getContext(), DoaMauTidur.class);
                        view.getContext().startActivity(myIntent);

                    }
                    else if ( 1 == getAdapterPosition() )
                    {
                        Intent myIntent = new Intent(view.getContext(), DoaBangunt.class);
                        view.getContext().startActivity(myIntent);
                    }
                    else if ( 2 == getAdapterPosition() )
                    {
                        Intent myIntent = new Intent(view.getContext(), DoaJimak.class);
                        view.getContext().startActivity(myIntent);
                    }
                }

This is a full code:

Story.java

    public Story(){}

    String name;
    String nomor;
    private String idStory;
    private int isLiked;

    public String getName() {
        return name;
    }
    public String getNomor() { return nomor; }

    public void setIdStory(String isStory) {
        this.idStory = isStory;
    }
    public String getIdStory() {
        return idStory;
    }

    public void setIsLiked(int isLiked) {
        this.isLiked = isLiked;
    }
    public int getIsLiked() {
        return isLiked;
    }

}

ChildTidur.java

 /**
         * fetches json by making http calls
         */
        protected void onPostExecute(String result) {

            JsonArrayRequest request = new JsonArrayRequest(URL, new Response.Listener<JSONArray>() {

                @Override
                public void onResponse(JSONArray response) {
                    pdLoading.dismiss();

                    Log.d(TAG, response.toString());
                    if (response.length() > 0) {
                        // Parsing json
                        List<Story> items = new Gson().fromJson(response.toString(), new TypeToken<List<Story>>() {

                        }.getType());
                        // adding contacts to contacts list
                        storyList.clear();
                        storyList.addAll(items);
                        // refreshing recycler view
                        mAdapter.notifyDataSetChanged();

                        for (int i=0; i<storyList.size(); i++) {
                            Story story = new Story();
                            story.setIdStory(String.valueOf(i));
                        }
                    }

                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    pdLoading.dismiss();
                    // error in getting json
                    Log.e(TAG, "Error: " + error.getMessage());
                    Toast.makeText(getApplicationContext(), "Tidak bisa menampilkan data. Periksa kembali sambungan internet Anda", Toast.LENGTH_LONG).show();

                    AlertDialog alertDialog = new AlertDialog.Builder(ChildTidur.this).create();
                    alertDialog.setTitle("Error");
                    alertDialog.setMessage("Data Tidak bisa ditampilkan. Periksa kembali sambungan internet Anda");
                    alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            });
                    alertDialog.show();
                    showNoFavtText(true);
                }
            });

            TidurSearch.getInstance().addToRequestQueue(request);
        }
    }

TidurAdapter.java

public class TidurAdapter extends RecyclerView.Adapter<TidurAdapter.TidurViewHolder> implements Filterable {

    private Context context;
    private List<Story> storyList;
    private List<Story> storyListFiltered;
    private ContactsAdapterListener listener;

    private int changedItemPosition;
    public boolean isLiked;
    private AppPreferences appPreferences;
    Boolean checked = false;

    public TidurAdapter(Context context, List<Story> storyList, ContactsAdapterListener listener, AppPreferences appPreferences) {
        this.context = context;
        this.listener = listener;
        this.storyList = storyList;
        this.storyListFiltered = storyList;
        this.appPreferences = appPreferences;
    }

    @Override
    public TidurViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.child_row_item_tidur, parent, false);
        return new TidurViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull TidurViewHolder holder, int position) {
        final Story story = storyListFiltered.get(position);
        holder.name.setText(story.getName());
        holder.nomor.setText(story.getNomor());
        holder.setViewData(storyList.get(position), holder.getAdapterPosition());
    }

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


    public interface ContactsAdapterListener {
        void onContactSelected(Story story);
    }

    //ViewHolder
    public class TidurViewHolder extends RecyclerView.ViewHolder {

        public TextView name;
        public TextView nomor;
        public ImageView mFavorite;
        private CheckBox likeCheckBox;
        final String KEY_SAVED_RADIO_BUTTON_INDEX = "SAVED_RADIO_BUTTON_INDEX";

        public TidurViewHolder(View view) {
            super(view);
            name = view.findViewById(R.id.name);
            nomor = view.findViewById(R.id.nomor);
            likeCheckBox = itemView.findViewById(R.id.like_button_cb);

            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // get id of data
                    Story story = storyList.get(getLayoutPosition());
                    int ambilId = Integer.parseInt(story.getIdStory());

                    if ( 0 == ambilId ) {

                        Intent myIntent = new Intent(view.getContext(), DoaMauTidur.class);
                        view.getContext().startActivity(myIntent);

                    }
                    else if ( 1 == getAdapterPosition() )
                    {
                        Intent myIntent = new Intent(view.getContext(), DoaBangunt.class);
                        view.getContext().startActivity(myIntent);
                    }
                    else if ( 2 == getAdapterPosition() )
                    {
                        Intent myIntent = new Intent(view.getContext(), DoaJimak.class);
                        view.getContext().startActivity(myIntent);
                    }
                }
            });

            //Get radio button value
            LayoutInflater inflater = (LayoutInflater) view.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View cV = inflater.inflate(R.layout.activity_settings, null,false);
            RadioGroup radioGroup = (RadioGroup)cV.findViewById(R.id.radioSex);
            SharedPreferences sharedPreferences = view.getContext().getSharedPreferences("MY_SHARED_PREF", Activity.MODE_PRIVATE);
            int savedRadioIndex = sharedPreferences.getInt(KEY_SAVED_RADIO_BUTTON_INDEX, 0);
            RadioButton savedCheckedRadioButton = (RadioButton)radioGroup.getChildAt(savedRadioIndex);
            savedCheckedRadioButton.setChecked(true);

            RadioGroup genderGroup = (RadioGroup) cV.findViewById(R.id.radioSex);
            RadioButton male = (RadioButton) cV.findViewById(R.id.theme1);
            RadioButton female = (RadioButton) cV.findViewById(R.id.theme2);

            if (genderGroup.getCheckedRadioButtonId() == -1) {
                nomor.setBackgroundColor(view.getResources().getColor(R.color.colorPrimaryDark));
            } else {
                if (male.isChecked()) {     // one of the radio buttons is checked
                    nomor.setBackgroundDrawable(ContextCompat.getDrawable(view.getContext(), R.drawable.rounded_drawable));
                }
                else if (female.isChecked()) {
                    nomor.setBackgroundDrawable(ContextCompat.getDrawable(view.getContext(), R.drawable.rounded_drawable_red));
                }
            }

        } //TidurViewHolder(View view)


        public void setViewData(final Story story, final int adapterPosition) {

            if (story.getIsLiked() == 1) {
                likeCheckBox.setChecked(true);
            }
            else {
                likeCheckBox.setChecked(false);
            }

            likeCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                    changedItemPosition = adapterPosition;

                    if (buttonView.isPressed()) {
                        if (isChecked) {
                            isLiked = true;
                            updateLikes();
                            appPreferences.saveFavouriteCard(story);
                            Toast.makeText(context, "Saved", Toast.LENGTH_SHORT).show();
                        }
                        else {
                            isLiked = false;
                            updateLikes();
                            appPreferences.deleteCard(story.getIdStory());
                            Toast.makeText(context, "Removed", Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            });

        } //setviewdata

        public void updateLikes() {
            if (isLiked && storyList.get(changedItemPosition).getIsLiked() == 0) { //jika dilakukan like (pada posisi hati kosong) di halaman home
                storyList.get(changedItemPosition).setIsLiked(1); //maka jadikan hati berwarna merah di halaman favourite list
                notifyItemChanged(changedItemPosition, ACTION_LIKE_IMAGE_CLICKED);
            }
            else if (!isLiked && storyList.get(changedItemPosition).getIsLiked() == 1) { //jika like dicabut (pada posisi hati yang sedang merah) di halaman home
                storyList.get(changedItemPosition).setIsLiked(0); //maka cabut juga warna merah di halaman favourite list
                notifyItemChanged(changedItemPosition, ACTION_LIKE_IMAGE_CLICKED);
            }

        } //updateLikes

    }//Class TidurViewHolder

}

The error result is, it is showing null... Which mean no ID that can be obtained.


回答1:


In your for loop you are not setting id of your List, but your new Story.

Instead of:

for (int i=0; i<storyList.size(); i++) {
   Story story = new Story();
   story.setIdStory(String.valueOf(i));
}

Use this:

for (int i=0; i<storyList.size(); i++) {
    storyList.get(i).setIdStory(String.valueOf(i));
}

Also because your index i=0 starts from zero, you should change for loop index i to start from 1 like this:

for (int i=1; i<=storyList.size(); i++) {
    storyList.get(i).setIdStory(String.valueOf(i));
}

Check this main activity:

public class MainActivity extends AppCompatActivity {
    private static final String TAG = MainActivity.class.getSimpleName();

    // CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
    private ArrayList<Story> storyList;

    // url to fetch contacts json
    private static final String URL = "https://api.kafeinkode.com/childtidur.json";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        storyList = new ArrayList<>();

        //Fetch JSON data
        fetchData();
    }

    private void fetchData(){
        JsonArrayRequest request = new JsonArrayRequest(URL, new Response.Listener<JSONArray>() {

            @Override
            public void onResponse(JSONArray response) {
                Log.d(TAG, response.toString());
                if (response.length() > 0) {
                    // Parsing json
                    List<Story> items = new Gson().fromJson(response.toString(), new TypeToken<List<Story>>() {}.getType());
                    // adding contacts to contacts list
                    storyList.clear();
                    storyList.addAll(items);

                for (int i=0; i<storyList.size(); i++) {
                    storyList.get(i).setIdStory(String.valueOf(i + 1));
                }
                Log.d("StoryLid: ", storyList.toString());
                }    
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                // error in getting json
                Log.e(TAG, "Error: " + error.getMessage());
            }
        });

       VolleyService.getInstance(this).getRequestQueue().add(request);
    }
}

As a result you have response:



来源:https://stackoverflow.com/questions/56739408/how-do-we-set-id-for-data-that-showed-with-volley-json-array-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!