my project has problem saving ArrayList<T> with SharedPreferences - java

i have a problem which is making me crazy.
i know how to use "SharedPreferences" in android but i dont know where to put it in my project,like onCreate(),onDestroy() or somewhere else.
*i want to save NoteLab.mNotes in NoteListFragment
*Note.java
package notes.com.example.alireza;
public class Note {
public UUID nId;
public Date nDate;
public String nTitle;
public String nDetails;
public Note(){
nId = UUID.randomUUID();
nDate = new Date();
}
public Date getnDate(){
return nDate;
}
public UUID getnUUID(){
return nId;
}
public String getnTitle() {
return nTitle;
}
public void setnTitle(String nTitle) {
this.nTitle = nTitle;
}
public String getnDetails() {
return nDetails;
}
public void setnDetails(String nDetails) {
this.nDetails = nDetails;
}
}
*NoteLab.java
package notes.com.example.alireza;
import android.content.Context;
import java.util.ArrayList;
import java.util.UUID;
class NoteLab {
public static ArrayList<Note> mNotes;
public static NoteLab noteLab;
public Context mAppContext;
private NoteLab(Context AppContext){
mAppContext = AppContext;
mNotes = new ArrayList<Note>();
}
public static NoteLab get(Context context){
if (noteLab == null){
noteLab = new NoteLab(context.getApplicationContext());
}
return noteLab;
}
public static ArrayList<Note> getNotes(){
return mNotes;
}
public static Note getNote(UUID mId){
for (Note n: mNotes){
if (mId == n.getnUUID()){
return n;
}
}
return null;
}
}
*NoteListFragment.java
package notes.com.example.alireza;
public class NoteListFragment extends ListFragment {
Note note;
ArrayList<Note> notes;
public static Date date;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
notes = NoteLab.get(getActivity()).getNotes();
myArrayAdapter arrayAdapter = new myArrayAdapter(notes);
setListAdapter(arrayAdapter);
}
#Override
public void onStart() {
super.onStart();
View emptyView = getActivity().getLayoutInflater().inflate(R.layout.emptymainlist,null);
((ViewGroup)getListView().getParent()).addView(emptyView);
getListView().setEmptyView(emptyView);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
int checked = 1;
Note c = ((myArrayAdapter)getListAdapter()).getItem(position);
Intent i = new Intent(getActivity(),NoteActivity.class);
i.putExtra("id",c.getnUUID());
i.putExtra(NoteListActivity.EXTRA_DATE,checked);
startActivity(i);
}
//custom arrayList
public class myArrayAdapter extends ArrayAdapter<Note> {
public myArrayAdapter(ArrayList<Note> notes) {
super(getActivity(), 0, notes);
}
#SuppressLint("SetTextI18n")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = getActivity().getLayoutInflater().inflate(R.layout.notelistfragment_item, null);
}
Note n = getItem(position);
date = n.getnDate();
PersianCalendar persianCalendar = new PersianCalendar();
persianCalendar.setTime(date);
TextView titleTextView = convertView.findViewById(R.id.titleTextView);
titleTextView.setText(n.getnTitle());
TextView detailTextView = convertView.findViewById(R.id.detailsTextView);
detailTextView.setText(n.getnDetails());
TextView dateTextView = convertView.findViewById(R.id.dateTextView);
dateTextView.setText(DateFormat.getDateInstance(DateFormat.FULL).format(date) + " : تاریخ ذخیره ");
return convertView;
}
}
#Override
public void onResume() {
super.onResume();
((myArrayAdapter)getListAdapter()).notifyDataSetChanged();
}
as you understand from the codes, i want to save my mNotes arrayList which is placed in NoteLab.java.there is NoteListActivtiy.java too which is supporting NoteListFragment but i think this can be done in NoteListFragment.
thanks to stackoverflow and everyone who tryes to help me.

You can use Gson library to convert what you want to String then you can get it back again.
Where should you put your code ?? it depends on your business (or requirements).
If you want to pass your array of items to fragment or another activity you can use Gson lib to convert it to string then put it into bundle and pass this bundle to whatever you want. Then in the fragment or the activity you can get this array by Gson also.
Here is an example:
Gson gson = new Gson();
gson.toSring(yourData);
// then you can get the data by
Gson gson = new Gson();
String data = yourBundle.getString("your_key");
yourDataModel = gson.fromJson(data, YourDataModel.class);
// it will work even with ArrayList

Related

How to parse json data from json array to recyclerview java android?

I can parse json data to my recyclerview. but when i meet json that has array data in it, my app forceclose when i try to get that. How to solve this? or anyone has similar sample code with this case?
Api:
https://v1.nocodeapi.com/fariz/fit/FunuohzdbtxBkVtC/aggregatesDatasets?dataTypeName=steps_count,heart_minutes,weight,activity_summary
Activity_Stepcounter.java
Call<nodeApi> call = jsonPlaceHolderApi.getNode();
call.enqueue(new Callback<nodeApi>() {
#Override
public void onResponse(Call<nodeApi> call, Response<nodeApi> response) {
progressBar.setVisibility(View.GONE);
nodeApi resource = response.body();
List<nodeApi.steps_count> dataList = resource.steps_count;
Adapter_meeting rv_adapter = new Adapter_meeting(dataList, Activity_Stepcounter.this);
rv.setLayoutManager(new LinearLayoutManager(Activity_Stepcounter.this));
rv.setAdapter(rv_adapter);
rv.hasFixedSize();
rv_adapter.notifyDataSetChanged();
}
#Override
public void onFailure(Call<nodeApi> call, Throwable t) {
call.cancel();
}
});
Adapter_meeting.java
public class Adapter_meeting extends RecyclerView.Adapter<Adapter_meeting.viewHolder> {
private final List<nodeApi.steps_count> mitem_meeting;
private final Context mContext;
public Adapter_meeting(List<nodeApi.steps_count> Item_meeting, Context mContext) {
this.mitem_meeting = Item_meeting;
this.mContext = mContext;
}
#NonNull
#Override
public viewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
final View view;
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rv_step_counter, parent, false);
final viewHolder vHolder = new viewHolder(view);
return vHolder;
}
#Override
public void onBindViewHolder(#NonNull viewHolder holder, int position) {
holder.tv_namaEvent.setText(mitem_meeting.get(position).getValue());
holder.tv_lokasiEvent.setText(mitem_meeting.get(position).getStartTime());
holder.tv_waktuEvent.setText(mitem_meeting.get(position).getEndTime());
holder.tv_tanggalEvent.setText(mitem_meeting.get(position).getStartTimeMillis());
}
#Override
public int getItemCount() {
return mitem_meeting.size();
}
public class viewHolder extends RecyclerView.ViewHolder {
private final TextView tv_namaEvent;
private final TextView tv_lokasiEvent;
private final TextView tv_waktuEvent;
private final TextView tv_tanggalEvent;
public viewHolder(#NonNull View itemView) {
super(itemView);
tv_namaEvent = (TextView) itemView.findViewById(R.id.id_tv_namaEvent);
tv_lokasiEvent = (TextView) itemView.findViewById(R.id.id_tv_lokasiEvent);
tv_waktuEvent = (TextView) itemView.findViewById(R.id.id_tv_waktuEvent);
tv_tanggalEvent = (TextView) itemView.findViewById(R.id.id_tv_tanggalEvent);
}
}}
JsonPlaceHolderApi.java
public interface JsonPlaceHolderApi {
#GET("aggregatesDatasets?dataTypeName=steps_count,heart_minutes,weight,activity_summary")
Call<nodeApi> getNode();}
nodeApi.java
public class nodeApi {
#SerializedName("steps_count")
public List<steps_count> steps_count = null;
public class steps_count {
public Integer value;
public String startTimeMillis;
public String endTimeMillis;
public String startTime;
public String endTime;
public steps_count(Integer value, String startTimeMillis, String endTimeMillis, String startTime, String endTime) {
this.value = value;
this.startTimeMillis = startTimeMillis;
this.endTimeMillis = endTimeMillis;
this.startTime = startTime;
this.endTime = endTime;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
public String getStartTimeMillis() {
return startTimeMillis;
}
public void setStartTimeMillis(String startTimeMillis) {
this.startTimeMillis = startTimeMillis;
}
public String getEndTimeMillis() {
return endTimeMillis;
}
public void setEndTimeMillis(String endTimeMillis) {
this.endTimeMillis = endTimeMillis;
}
public String getStartTime() {
return startTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
public String getEndTime() {
return endTime;
}
public void setEndTime(String endTime) {
this.endTime = endTime;
}
}
}
error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.iot.testapp, PID: 12849
android.content.res.Resources$NotFoundException: String resource ID #0x19
at android.content.res.Resources.getText(Resources.java:335)
at android.widget.TextView.setText(TextView.java:4555)
at com.iot.testapp.adapter.Adapter_meeting.onBindViewHolder(Adapter_meeting.java:47)
at com.iot.testapp.adapter.Adapter_meeting.onBindViewHolder(Adapter_meeting.java:26)
On these lines:
holder.tv_tanggalEvent.setText(mitem_meeting.get(position).getStartTimeMillis());
holder.tv_lokasiEvent.setText(mitem_meeting.get(position).getStartTime());
holder.tv_waktuEvent.setText(mitem_meeting.get(position).getEndTime());
Compilator thinks, that you are passing String resource, but you are actually passing simple String. Just add +"" and it should start working.
holder.tv_tanggalEvent.setText(mitem_meeting.get(position).getStartTimeMillis()+"");
holder.tv_namaEvent.setText(mitem_meeting.get(position).getStartTime()+"");
holder.tv_waktuEvent.setText(mitem_meeting.get(position).getEndTime()+"");
You should pass text to textviews in form of String resource with placeholders, but it doesn't really make sense, when you don't pass there anything except the changing value.
holder.tv_namaEvent.setText(mitem_meeting.get(position).getValue());
You are trying to set Int.
Try:
String value = String.valueOf(mitem_meeting.get(position).getValue());
holder.tv_namaEvent.setText(value);
Please check all fields for null and read about name convention in Android :)
Also time in milis should be stored in Long type.
You can also read about Kotlin language, mvvn pattern etc.
Thanks, i got help from discord
I have to make jsonresponse first and then convert it to arraylist using nodeApi.java.
public class JsonResponse {
private nodeApi[] steps_count;
public nodeApi[] getStep_count() {
return steps_count;
}
public void setnodeApi(nodeApi[] step_count) {
this.steps_count = step_count;
}
}
Activity_Stepcounter.java
Call<JsonResponse> call = jsonPlaceHolderApi.getStep();
call.enqueue(new Callback<JsonResponse>() {
#Override
public void onResponse(Call<JsonResponse> call, Response<JsonResponse> response) {
progressBar.setVisibility(View.GONE);
JsonResponse jsonResponse = response.body();
listStep = new ArrayList<>(Arrays.asList(jsonResponse.getStep_count()));
Adapter_meeting rv_adapter = new Adapter_meeting(listStep, Activity_Stepcounter.this);
rv.setLayoutManager(new LinearLayoutManager(Activity_Stepcounter.this));
rv.setAdapter(rv_adapter);
rv.hasFixedSize();
rv_adapter.notifyDataSetChanged();
}
#Override
public void onFailure(Call<JsonResponse> call, Throwable t) {
call.cancel();
}
});
**there are some refactor/rename.

Passing data in recycler view from API

I tried to make a covid-19 tracking app by watching Youtube tutorials.
My app shows the country list with flags and when you click on any country it opens an activity and shows the details of that country i.e total cases, deaths, recovered, etc. The video on Youtube uses ListView and I am using recyclerView
I fetched the country list successfully and set onClickListener on the view and it opens second activity which shows the case in detail. But I don't know how to show the data.
my adapter class:
class Countries_adapter extends RecyclerView.Adapter<Countries_adapter.MyViewHolder> {
Context ct;
List<Countries_data> list;
public Countries_adapter(Context context,List<Countries_data> country)
{
ct=context;
list=country;
}
#Override
public MyViewHolder onCreateViewHolder( ViewGroup parent, int viewType) {
View v = LayoutInflater.from(ct).inflate(R.layout.countries_row,parent,false);
return new MyViewHolder(v);
}
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
holder.tvCountryName.setText(list.get(position).getCountry());
holder.tvtotal.setText(list.get(position).getActive());
Glide.with(ct).load(list.get(position).getFlag()).into(holder.imageView);
holder.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(ct,CountriesDetails.class);
i.putExtra("Country",list.get(position).getCountry());
ct.startActivity(i);
}
});
}
#Override
public int getItemCount() {
return list.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView tvCountryName,tvtotal;
ImageView imageView;
LinearLayout linearLayout;
public MyViewHolder( View itemView) {
super(itemView);
tvCountryName = itemView.findViewById(R.id.tvCountryName);
tvtotal=itemView.findViewById(R.id.tvCountrytotalcaese);
imageView = itemView.findViewById(R.id.imageFlag);
linearLayout=itemView.findViewById(R.id.linear_layout);
}
}
my AffectedCoutries class activity is as follows:
public class AffectedCountries extends AppCompatActivity {
EditText edtSearch;
RecyclerView recyclerView;
SimpleArcLoader simpleArcLoader;
public static ArrayList countryList = new ArrayList<>();
Countries_data countryData;
Countries_adapter CountriesAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_affected_countries);
edtSearch = findViewById(R.id.edtSearch);
recyclerView=findViewById(R.id.recyclerAffectedCountries);
simpleArcLoader = findViewById(R.id.loader);
fetchData();
}
private void fetchData() {
String url = "https://corona.lmao.ninja/v2/countries/";
simpleArcLoader.start();
StringRequest request = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
for(int i=0;i<jsonArray.length();i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String countryName = jsonObject.getString("country");
String cases = jsonObject.getString("cases");
String todayCases = jsonObject.getString("todayCases");
String deaths = jsonObject.getString("deaths");
String todayDeaths = jsonObject.getString("todayDeaths");
String recovered = jsonObject.getString("recovered");
String active = jsonObject.getString("active");
String critical = jsonObject.getString("critical");
JSONObject object = jsonObject.getJSONObject("countryInfo");
String flagUrl = object.getString("flag");
countryData = new Countries_data(flagUrl,countryName,cases,todayCases,deaths,todayDeaths,recovered,active,critical);
countryList.add(countryData);
}
CountriesAdapter = new Countries_adapter(AffectedCountries.this,countryList);
recyclerView.setLayoutManager(new LinearLayoutManager(AffectedCountries.this));
recyclerView.setAdapter(CountriesAdapter);
simpleArcLoader.stop();
simpleArcLoader.setVisibility(View.GONE);
} catch (JSONException e) {
e.printStackTrace();
simpleArcLoader.start();
simpleArcLoader.setVisibility(View.GONE);
Toast.makeText(AffectedCountries.this,"catch response", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
simpleArcLoader.stop();
simpleArcLoader.setVisibility(View.GONE);
Toast.makeText(AffectedCountries.this,"error response", Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(request);
}
}
my Countries_data class(model class)
public class Countries_data {
public String country;
public String cases;
public String todayCases;
public String deaths;
public String todayDeaths;
public String recovered;
public String active;
public String critical;
public String flag;
public Countries_data(String flag, String country, String cases, String
todayCases, String deaths, String todayDeaths, String recovered,
String active, String critical) {
this.country = country;
this.cases = cases;
this.todayCases = todayCases;
this.deaths = deaths;
this.todayDeaths = todayDeaths;
this.recovered = recovered;
this.active = active;
this.critical = critical;
this.flag = flag;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCases() {
return cases;
}
public void setCases(String cases) {
this.cases = cases;
}
public String getTodayCases() {
return todayCases;
}
public void setTodayCases(String todayCases) {
this.todayCases = todayCases;
}
public String getDeaths() {
return deaths;
}
public void setDeaths(String deaths) {
this.deaths = deaths;
}
public String getTodayDeaths() {
return todayDeaths;
}
public void setTodayDeaths(String todayDeaths) {
this.todayDeaths = todayDeaths;
}
public String getRecovered() {
return recovered;
}
public void setRecovered(String recovered) {
this.recovered = recovered;
}
public String getActive() {
return active;
}
public void setActive(String active) {
this.active = active;
}
public String getCritical() {
return critical;
}
public void setCritical(String critical) {
this.critical = critical;
}
public String getFlag() {
return flag;
}
public void setFlag(String flag) {
this.flag = flag;
}
}
my Country_details class
public class CountriesDetails extends AppCompatActivity {
TextView tvCountry, tvCases, tvRecovered,tvdeaths;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_countries_details2);
tvCountry = findViewById(R.id.tvCountry);
tvCases = findViewById(R.id.tvCases);
tvRecovered = findViewById(R.id.tvRecovered);
tvdeaths=findViewById(R.id.tvTotalDeaths);
String positionCountry = getIntent().getStringExtra("Country");
Log.i("country name", positionCountry);
}
}
How to set the data in tvcases?
How can I show the data? Do I have to create a separate recycler view and then fetch the data from the API or can I use my main activity to show the data?
I have some sad information for you: Google Play policy restricts such apps from being published in store... especially when you are showing deaths count. Been there, done that, my app was blocked...
besides above:
you are passing country name in intent:
i.putExtra("Country",list.get(position).getCountry());
but trying to read "position" in details Activity - it will be always 0 (default)
edit due to comments:
pass position of clicked View
holder.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(ct,CountriesDetails.class);
i.putExtra("position", position);
ct.startActivity(i);
}
});
in CountriesDetailss onCreate method receive this position and restore proper Countries_data object from your static countryList array in AffectedCountries
int position = getIntent().getIntExtra("position", 0);
Countries_data country = AffectedCountries.countryList.get(position);
tvCountry.setText(country.getCountry());
that should work, but this isn't best way to store data, in fact its very weak... after downloading data (list of countries) you should store it somehow, e.g. SQLite/Room lib or at least SharedPreferences... then in details activity you should restore int position and using it take proper object from database or preferences, instead of stright from static array
it may be also useful to implement Parcelable inteface to your Countries_data - this will allow to put whole Countries_data object into Intents extras, not only primitive int with position in array. in this case details activity won't even need access to whole array or sql database/preferences, it will get whole object straight from Intents extras

How to add a search filter in RecyclerView to filter through parsed JSON data? edited

I am developing an android app which shows a list of countries affected by Coronavirus , the total number of confirmed cases and total Deaths. I am using a JSON API to get the data and displaying it using a RecyclerView . The app works fine , and i get a list of all the countries with their respective case counts. I want to add a search option so that the users can filter the list and find a specific country. How do i do that? I am new to programming , if someone could help with this that would be awesome.
Here is the code snippet
MainActivity.java
private RecyclerView mRecyclerView;
private Corona_Stats_Adapter mCorona_Stats_Adapter;
private TextView mErrorDisplay;
private ProgressBar mProgressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.corona_stats);
mRecyclerView = (RecyclerView)findViewById(R.id.Corona_stats_recycler);
mErrorDisplay = (TextView) findViewById(R.id.tv_error_message_display);
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(layoutManager);
mRecyclerView.setHasFixedSize(true);
mCorona_Stats_Adapter = new Corona_Stats_Adapter();
mRecyclerView.setAdapter(mCorona_Stats_Adapter);
mProgressBar = (ProgressBar)findViewById(R.id.pb_loading_indicator) ;
loadCoronaData();
}
private void loadCoronaData(){
showCoronaDataView();
//String Country = String.valueOf(mSearchQuery.getText());
new Fetch_data().execute();
}
private void showCoronaDataView(){
mErrorDisplay.setVisibility(View.INVISIBLE);
mRecyclerView.setVisibility(View.VISIBLE);
}
private void showErrorMessage(){
mRecyclerView.setVisibility(View.INVISIBLE);
mErrorDisplay.setVisibility(View.VISIBLE);
}
public class Fetch_data extends AsyncTask<Void,Void,String[]> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressBar.setVisibility(View.VISIBLE);
}
#Override
protected String[] doInBackground(Void... voids) {
URL covidRequestURL = NetworkUtils.buildUrl();
try {
String JSONCovidResponse = NetworkUtils.getResponseFromHttpUrl(covidRequestURL);
String[] simpleJsonCovidData = CovidJSON_Utils.getSimpleStringFromJson(MainActivity.this, JSONCovidResponse);
return simpleJsonCovidData;
} catch (IOException | JSONException e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(String[] coronaData) {
mProgressBar.setVisibility(View.INVISIBLE);
if(coronaData !=null){
showCoronaDataView();
mCorona_Stats_Adapter.setCoronaData(coronaData);
} else{
showErrorMessage();
}
}
}
}
RecyclerView Adapter class Corona_stats_Adapter.java
public class Corona_Stats_Adapter extends RecyclerView.Adapter<Corona_Stats_Adapter.Corona_Stats_AdapterViewHolder>
{
private Context context;
// private List<Country> countryList;
// private List<Country> countryListFiltered;
private String[] mCoronaData;
public Corona_Stats_Adapter(){
}
#NonNull
#Override
public Corona_Stats_AdapterViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int viewType) {
Context context = viewGroup.getContext();
int LayoutIdForListItem =R.layout.corona_stats_list_item;
LayoutInflater inflater =LayoutInflater.from(context);
boolean ShouldAttachToParentImmediately = false;
View view = inflater.inflate(LayoutIdForListItem,viewGroup,ShouldAttachToParentImmediately);
return new Corona_Stats_AdapterViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull Corona_Stats_AdapterViewHolder corona_stats_adapterViewHolder, int position) {
String coronaStats = mCoronaData[position];
corona_stats_adapterViewHolder.mCoronaTextView.setText(coronaStats);
}
#Override
public int getItemCount() {
if(null == mCoronaData) return 0;
return mCoronaData.length;
// return countryListFiltered.size();
}
public class Corona_Stats_AdapterViewHolder extends RecyclerView.ViewHolder {
public final TextView mCoronaTextView;
public Corona_Stats_AdapterViewHolder(#NonNull View view) {
super(view);
mCoronaTextView = (TextView) view.findViewById(R.id.tv_corona_data);
}
}
public void setCoronaData(String[] coronaData){
mCoronaData = coronaData;
notifyDataSetChanged();
}
}
Parsing the JSON data in CovidJSON_Utils.java
public final class CovidJSON_Utils {
public static String[] getSimpleStringFromJson(Context context, String codivJsonString)
throws JSONException {
final String COV_COUNTRY = "Countries";
final String COV_CONFIRMED = "confirmed";
final String COV_DEATHS = "deaths";
final String COV_MESSAGE_CODE = "code";
String[] parsedCovidData = null;
JSONObject covidJsonObject = new JSONObject(codivJsonString);
if (covidJsonObject.has(COV_MESSAGE_CODE)) {
int errorCode = covidJsonObject.getInt(COV_MESSAGE_CODE);
switch (errorCode) {
case HttpURLConnection.HTTP_OK:
break;
case HttpURLConnection.HTTP_NOT_FOUND:
return null;
default:
return null;
}
}
JSONArray countryCovidArray = covidJsonObject.getJSONArray(COV_COUNTRY);
parsedCovidData = new String[countryCovidArray.length()];
for (int i = 0; i < countryCovidArray.length(); i++) {
JSONObject countryJSONObject = countryCovidArray.getJSONObject(i);
String Country = countryJSONObject.getString("Country");
String Confirmed = String.valueOf(countryJSONObject.getInt("TotalConfirmed"));
String Deaths = String.valueOf(countryJSONObject.getInt("TotalDeaths"));
parsedCovidData[i] = Country + "- Cases " + Confirmed + "- Deaths " + Deaths;
}
return parsedCovidData;
}
}
The problem is with below initialization in the MainActivity.Oncreate method
mCorona_Stats_Adapter = new Corona_Stats_Adapter(this,countries);
Initialize the adapter in onPostExecute method with updated countries data.
Hope this will help you.
You have to set arraylist to update country data in adapter after getting data from the server.
Public void setCoronaData (Arraylist coronaData) {
countryList = coronaData;
notifyDataSetChanged ();
}

how display string array content through recycleview adapter

I have this structure of json api:
{
seasons: [
{
seasonstitle: "Season 1",
titles: "S1E1; S1E2; S1E3",
},
{
seasonstitle: "Season 2",
titles: "S2E1; S2E2; S2E3",
},
]
}
and I'm trying to display the values of these two keys: seasonstitle and titles but as you see the titles key has multiple values so I parsing the json like this:
ParsingClass:
public final class JsonDetailSeries {
public static ArrayList<SeriesItem> getSimpleMovieStringsFromJson(Context context, String moviesJsonString)
throws JSONException {
final String SEASONS = "seasons";
final String SEASONTITLE = "seasonstitle";
final String TITLES = "titles";
ArrayList<SeriesItem> parsedMovieData = new ArrayList<>();
JSONObject moviesObject = new JSONObject(moviesJsonString);
JSONArray moviesArray = moviesObject.getJSONArray(SEASONS);
for (int i = 0; i < moviesArray.length(); i++) {
String seasontitle;
String titles;
moviesObject = moviesArray.getJSONObject(i);
seasontitle = moviesObject.getString(SEASONTITLE);
titles = moviesObject.getString(TITLES);
String[] titlesArrray = titles.split(Pattern.quote(";"));
for (int j=0; j<titlesArrray.length; j++) {
Log.i("titles ", "=" + titlesArrray[j]);
}
parsedMovieData.add(new SeriesItem(seasontitle, titlesArrray));
}
return parsedMovieData;
}
}
when I saw it in log cat it splits correctly like this:
titles = S1E1
titles = S1E2
titles = S1E3
and so on, in my custom arraylist class which I return the data for it:
public class SeriesItem implements Parcelable {
private String seasontitle;
private String[] titlesArrray;
public SeriesItem(String seasontitle, String[] titlesArrray) {
this.seasontitle = seasontitle;
this.titlesArrray = titlesArrray;
}
#Override
public void writeToParcel(Parcel out, int flags) {
out.writeString(seasontitle);
out.writeStringArray(titlesArrray);
}
private SeriesItem(Parcel in) {
this.seasontitle = in.readString();
this.titlesArrray = in.createStringArray();
}
public SeriesItem() {
}
#Override
public int describeContents() {
return 0;
}
public static final Creator<SeriesItem> CREATOR = new Creator<SeriesItem>() {
#Override
public SeriesItem createFromParcel(Parcel in) {
return new SeriesItem(in);
}
#Override
public SeriesItem[] newArray(int i) {
return new SeriesItem[i];
}
};
public String getSeasontitle() {
return seasontitle;
}
public String[] gettitlesArrray() {
return titlesArrray;
}
}
when I debug this class the data of titlesArrray recevied well each title split from the other one
so I'm trying to display this data in recyleview like this way:
Season1
S1E1
S1E2
S1E3
Season2
S2E1
S2E2
S2E3
so this is my adapter of recycleview:
public class SeriesAdapter extends RecyclerView.Adapter<SeriesAdapter.RecyclerViewHolder> {
ArrayList<SeriesItem> mMoviesItems;
private Context context;
private final SeriesAdapterOnClickHandler mClickHandler;
public interface SeriesAdapterOnClickHandler {
void onClick(SeriesItem movie);
}
public SeriesAdapter(SeriesAdapterOnClickHandler clickHandler) {
mClickHandler = clickHandler;
}
class RecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public final TextView seasontitle;
public final ListView titlesArray;
public RecyclerViewHolder(View view) {
super(view);
seasontitle = (TextView)itemView.findViewById(R.id.seasontitle);
titlesArray = (ListView) itemView.findViewById(R.id.titlesArray);
view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int adapterPosition = getAdapterPosition();
SeriesItem movie = mMoviesItems.get(adapterPosition);
mClickHandler.onClick(movie);
}
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
context = viewGroup.getContext();
int layoutIdForListItem = R.layout.series_list_item;
LayoutInflater inflater = LayoutInflater.from(context);
boolean shouldAttachToParentImmediately = false;
View view = inflater.inflate(layoutIdForListItem, viewGroup, shouldAttachToParentImmediately);
return new RecyclerViewHolder(view);
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
holder.seasontitle.setText(String.valueOf(mMoviesItems.get(position).getSeasontitle()));
holder.titlesArray.setText(String.valueOf(mMoviesItems.get(position).gettitlesArrray()));
}
#Override
public int getItemCount() {
if (null == mMoviesItems)
return 0;
else {
return mMoviesItems.size();
}
}
public void setMovieData(ArrayList<SeriesItem> movieData) {
mMoviesItems = movieData;
notifyDataSetChanged();
}
}
I tried to include a listview to display the titlesArray inside this recycleview and the problem is with this line:
holder.titlesArray.setText(String.valueOf(mMoviesItems.get(position).gettitlesArrray()));
I can't use setText for ListView so how can to display the titlesArray content inside this recycleview?
I tried to include a listview to display the titlesArray inside this recycleview
Do not do that.
What you want to do is handle two different types, the season and the episode. This question that will help you with that.
How to create RecyclerView with multiple view type?
Use Gson to parse Json instead of the native, it is much easier to implement.

Having troubles getting data from List Adapter for OnItemClick

Im having an issue with getting data that is obtained when my listadapter is set to my listview. Im trying to get this data in onItemClick so that i can put it into my intent extra's for my other activity to obtain.
The Problem
Currently i've created null string variables and then in my adapter assigning the strings with the desired text by methods within my model. However the problem im having is that the text that is being pulled is not the correct text for the position that onitemclick was called for.
Here some code...
XMLParseActivity
public class XMLParseActivity extends Activity implements AdapterView.OnItemClickListener {
private ListView mIssueListView;
private IssueParser mIssueParser;
private List<IssueFeed> mIssueList;
private IssueAdapter mIssueAdapter;
private String result_connectedtype = "";
private String result_symptom = "";
private String result_problem = "";
private String result_solution = "";
private String result_comments = "";
...
public class IssueAdapter extends ArrayAdapter<IssueFeed> {
public List<IssueFeed> issueFeedList;
public IssueAdapter(Context context, int textViewResourceId, List<IssueFeed> issueFeedList) {
super(context, textViewResourceId, issueFeedList);
this.issueFeedList = issueFeedList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
IssueHolder issueHolder = null;
if (convertView == null) {
view = View.inflate(XMLParseActivity.this, R.layout.issue_list_item, null);
issueHolder = new IssueHolder();
issueHolder.issueConnectedType = (TextView) view.findViewById(R.id.result_connected_type);
issueHolder.issueSymptomView = (TextView) view.findViewById(R.id.result_symptom);
view.setTag(issueHolder);
} else {
issueHolder = (IssueHolder) view.getTag();
}
IssueFeed issueFeed = issueFeedList.get(position);
issueHolder.issueConnectedType.setText(issueFeed.getConnected_type());
issueHolder.issueSymptomView.setText(issueFeed.getSymptom());
//THE DATA I WANT TO USE IN MY INTENT
result_solution = issueFeed.getSolution();
result_comments = issueFeed.getComments();
result_connectedtype = issueFeed.getConnected_type();
result_problem = issueFeed.getProblem();
result_symptom = issueFeed.getSymptom();
return view;
}
}
static class IssueHolder {
public TextView issueSymptomView;
public TextView issueConnectedType;
}
#Override
public void onItemClick(AdapterView<?> adapterView, View v, int position, long id) {
//Put the strings in intent extra
Intent intent = new Intent(this, SpecificIssueActivity.class);
intent.putExtra("symptom", result_symptom);
intent.putExtra("problem", result_problem);
intent.putExtra("solution", result_solution);
intent.putExtra("comments", result_comments);
intent.putExtra("connectedtype", result_connectedtype);
startActivity(intent);
}
The listAdapter is set in a asynctask in the below code
public class DoLocalParse extends AsyncTask<String, Void, List<IssueFeed>> {
ProgressDialog prog;
String jsonStr = null;
Handler innerHandler;
#Override
protected void onPreExecute() {
prog = new ProgressDialog(XMLParseActivity.this);
prog.setMessage("Loading....");
prog.show();
}
#Override
protected List<IssueFeed> doInBackground(String... params) {
mIssueParser = new IssueParser(null);
mIssueList = mIssueParser.parseLocally(params[0]);
return mIssueList;
}
#Override
protected void onPostExecute(List<IssueFeed> result) {
prog.dismiss();
runOnUiThread(new Runnable() {
#Override
public void run() {
mIssueAdapter = new IssueAdapter(XMLParseActivity.this, R.layout.issue_list_item,
mIssueList);
int count = mIssueAdapter.getCount();
if (count != 0 && mIssueAdapter != null) {
mIssueListView.setAdapter(mIssueAdapter);
}
}
});
}
}
And my model IssueFeed looks like this
public class IssueFeed implements Serializable {
private String connected_type;
private String symptom;
private String problem;
private String solution;
private String comments;
public IssueFeed() {
}
public IssueFeed(String connected_type, String symptom, String problem, String solution, String comments) {
this.connected_type = connected_type;
this.symptom = symptom;
this.problem = problem;
this.solution = solution;
this.comments = comments;
}
public String getConnected_type() {
return connected_type;
}
public String getSymptom() {
return symptom;
}
public String getProblem() {
return problem;
}
public String getSolution() {
return solution;
}
public String getComments() {
return comments;
}
public void setConnected_type(String connected_type) {
this.connected_type = connected_type;
}
public void setSymptom(String symptom) {
this.symptom = symptom;
}
public void setProblem(String problem) {
this.problem = problem;
}
public void setSolution(String solution) {
this.solution = solution;
}
public void setComments(String comments) {
this.comments = comments;
}
}
I have solve the issue by getting the data from some simple methods in my model to obtain the values.

Categories

Resources