how I can show a html/php code in a toast - java

I read data from php file a put in a array.and i want show description in a toast but toast show html/php tags. how i can remove it?
News.java
public class News {
int information_id;
int language_id;
String title;
String description;
public int getinformation_id() {
return information_id;
}
public int getlanguage_id() {
return language_id;
}
public String gettitle() {
return title;
}
public String getdescription() {
return description;
}
public void setinformation_id(int information_id) {
this.information_id = information_id;
}
public void setlanguage_id(int language_id) {
this.language_id = language_id;
}
public void settitle(String title) {
this.title = title;
}
public void setdescription(String description) {
this.description = description;
}
}
Main.java
ArrayList<News> news;
public ArrayList<String> infoid, lanid, titlenews, desnews;
JSONObject json_data;
JSONArray jArray;
private void get_news() {
try {
url = "http://www.learnroid.ir/bigshop/get_news.php";
dbGetData = new DbGetData();
new Thread(new Runnable() {
public void run() {
data = dbGetData.getDataFromDB(url);
runOnUiThread(new Runnable() {
#Override
public void run() {
news = parseJSON(data);
}
});
}
}).start();
Toast.makeText(context, "Please wait ....", 5000).show();
} catch (Exception e) {
}
}
public ArrayList<News> parseJSON(String result) {
news = new ArrayList<News>();
try {
jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
n = new News();
information_id = json_data.getString("information_id");
language_id = json_data.getString("language_id");
title = json_data.getString("title");
description = json_data.getString("description");
n.setinformation_id(Integer.parseInt(information_id));
n.setlanguage_id(Integer.parseInt(language_id));
n.settitle(title);
n.setdescription(description);
infoid.add(information_id);
lanid.add(language_id);
titlenews.add(title);
desnews.add(description);
news.add(n);
/* int information_id;
int language_id;
String title;
String description;*/
}
showdata();
size = infoid.size();
Toast.makeText(context, String.valueOf(size), Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
}
return news;
}
// for get data from php and put in array lists infoid, lanid,.............
and i create a function for show data from array
private void showdata() {
Object[] Arraydes = desnews.toArray();
Object[] Arraylan = lanid.toArray();
for(int i = 0; i < Arraydes.length ; i++){
String s = Arraylan[i].toString();
if (s.equals("2")) {
Toast.makeText(context, String.valueOf(Arraydes[i]),Toast.LENGTH_LONG).show();
}
}
data form table is:
information_id: 6
language_id: 1
title: Hot News
description: <p> Delivery Information</p>
But i need Delivery Information only for show in Toast
my toast text is "<p> Delivery Information</p&gt"

You could create a function to strip html tags, something like :
public String stripHtml(String html) {
return Html.fromHtml(html).toString();
}
Output the returned string in the toast

Related

How can i make an Arraylist of Objects from response received with volley

I am trying to make an ArrayList of objects .But the logd at the last is always showing an empty ArrayList.How can I do it.With the present code I tried few things but they didn't work.I guess i have to return the ArrayList but I am confused.
This is my code in MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<News> newsArrayList = new ArrayList<>();
RequestQueue requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, mURL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray articles = response.getJSONArray("articles");
for (int i = 0; i < 10; i++) {
JSONObject news = articles.getJSONObject(i);
title = news.getString("title");
img_url = news.getString("image");
desc = news.getString("description");
news_url = news.getString("url");
newsArrayList.add(new News(title, img_url, desc, news_url));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "onErrorResponse: Something went Wrong");
}
});
requestQueue.add(jsonObjectRequest);
Log.d(TAG, "onCreate: " + newsArrayList);
This is News.java
public class News {
private String mTitle;
private String mImg_url;
private String mNews_url;
private String mDesc;
public News(String title, String img_url, String desc, String news_url) {
this.mTitle = title;
this.mImg_url = img_url;
this.mDesc = desc;
this.mNews_url = news_url;
}
public String getmTitle() {
return mTitle;
}
public String getmImg_url() {
return mImg_url;
}
public String getmNews_url() {
return mNews_url;
}
public String getmDesc() {
return mDesc;
}
}

Unable to link URL from ListView in Android

Hello I am trying to click ListView and Open URL from the ListView.
I could set the URL addresses using setter methods on the ListView, however when I try to display the URLs using Toast messages, it shows different URL.
I use for loop for adding multiple items on ListView news_ListView
If you have any suggestions, please help me out.
private NewsListAdapter newsListAdapter;
private ArrayList<NewsContents> newsContents_View;
private String title_String;
private String body_String;
private String source_String;
private String source_iconUrl_String;
private String image_Url_String;
private String url_String;
private int column_num;
private int num;
private int num_plus;
private int num_plus_plus;
private View mfooter;
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ListView news_ListView = Objects.requireNonNull(getView()).findViewById(R.id.news_ListView);
newsContents_View = new ArrayList<>();
newsListAdapter = new NewsListAdapter(Objects.requireNonNull(getActivity()).getApplicationContext());
newsListAdapter.setNewsContents(newsContents_View);
news_ListView.setAdapter(newsListAdapter);
news_ListView.addFooterView(getfooter());
num = 0;
num_plus = num + 5;
//Set newsList
for (column_num = num; column_num < num_plus; column_num++){
//Set news to listview according to the column num
Set_Content_to_NewsList(column_num);
}
news_ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getActivity(),""+url_String,Toast.LENGTH_SHORT).show();
}
});
}
private void Set_Content_to_NewsList(final int column_num){
HttpRequest_News httpRequest_news = new HttpRequest_News(Objects.requireNonNull(getActivity()).getApplicationContext());
httpRequest_news.news_From_API(news_Url + news_Url1 + API_KEY, column_num, new HttpRequest_News.ApiCallback() {
#Override
public void onOkHttpResponse(String title, String body, String source, String source_iconurl, String img_url,String url) {
title_String = title;
body_String = body;
source_String = source;
source_iconUrl_String = source_iconurl;
image_Url_String = img_url;
url_String = url;
setItem(column_num,title_String,body_String,source_String,source_iconUrl_String,image_Url_String,url_String);
}
#Override
public void onOkHttpFailure(Exception exception) {}
});
}
private void setItem(int column_num,String title_String, String body_String, String source_String,String source_iconUrl_String, String image_Url_String, String url_String){
NewsContents newsContents = new NewsContents();
newsContents.setId(column_num);
newsContents.setTitle_Name(title_String);
newsContents.setBody_Name(body_String);
newsContents.setSource_Name(source_String);
newsContents.setSource_icon_imgUrl(source_iconUrl_String);
newsContents.setImgUrl(image_Url_String);
newsContents.setUrl(url_String);
newsContents_View.add(newsContents);
newsListAdapter.notifyDataSetChanged();
}
This is the HttpRequestNews class:
public class HttpRequest_News {
private Context context;
public HttpRequest_News(Context current){
this.context = current;
}
public void news_From_API(String url_news, final int index, final ApiCallback apiCallback){
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url_news)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(#NotNull Call call, #NotNull IOException e) {
apiCallback.onOkHttpFailure(e);
}
#Override
public void onResponse(#NotNull Call call, #NotNull Response response) throws IOException {
final String jsonStr = Objects.requireNonNull(response.body()).string();
final String title_Str = jsonarray_news_extract_Title(jsonStr, index);
final String body_Str = jsonarray_news_extract_Body(jsonStr,index);
final String source_Str = jsonarray_news_extract_Source(jsonStr,index);
final String source_icon_url_Str = jsonarray_news_extract_icon_Source(jsonStr,index);
final String image_url_Str = jsonarray_news_extract_ImgUrl(jsonStr,index);
final String url_Str = jsonarray_news_extract_Url(jsonStr,index);
Handler mainHandler = new Handler(Looper.getMainLooper());
mainHandler.post(new Runnable() {
#Override
public void run() {
apiCallback.onOkHttpResponse(title_Str,body_Str,source_Str,source_icon_url_Str,image_url_Str,url_Str);
}
});
}
});
}
private String jsonarray_news_extract_Title(String jsonString_News, int index){
try {
JSONObject jsonObject = new JSONObject(jsonString_News);
JSONArray jsonArray = jsonObject.getJSONArray("Data");
return jsonArray.getJSONObject(index).getString("title");
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
private String jsonarray_news_extract_Body(String jsonString_News, int index){
try {
JSONObject jsonObject = new JSONObject(jsonString_News);
JSONArray jsonArray = jsonObject.getJSONArray("Data");
return jsonArray.getJSONObject(index).getString("body");
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
private String jsonarray_news_extract_Source(String jsonString_News, int index){
try {
JSONObject jsonObject = new JSONObject(jsonString_News);
JSONArray jsonArray = jsonObject.getJSONArray("Data");
return jsonArray.getJSONObject(index).getString("source");
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
private String jsonarray_news_extract_icon_Source(String jsonString_News, int index){
try {
JSONObject jsonObject = new JSONObject(jsonString_News);
JSONArray jsonArray = jsonObject.getJSONArray("Data");
JSONObject jsonObject1 = jsonArray.getJSONObject(index).getJSONObject("source_info");
return jsonObject1.getString("img");
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
private String jsonarray_news_extract_ImgUrl(String jsonString_News, int index){
try {
JSONObject jsonObject = new JSONObject(jsonString_News);
JSONArray jsonArray = jsonObject.getJSONArray("Data");
return jsonArray.getJSONObject(index).getString("imageurl");
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
private String jsonarray_news_extract_Url(String jsonString_News, int index){
try {
JSONObject jsonObject = new JSONObject(jsonString_News);
JSONArray jsonArray = jsonObject.getJSONArray("Data");
return jsonArray.getJSONObject(index).getString("url");
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
public interface ApiCallback{
void onOkHttpResponse(String title, String body, String source, String source_iconUrl, String img_url, String url);
void onOkHttpFailure(Exception exception);
}}
This is the NewsContents class:
public class NewsContents {
private long id;
private String Title_Name;
private String Body_Name;
private String Url;
private String Source_Name;
private String imgUrl;
private String source_icon_imgUrl;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle_Name() {
return Title_Name;
}
public void setTitle_Name(String title_Name) {
this.Title_Name = title_Name;
}
public String getSource_Name() {
return Source_Name;
}
public void setSource_Name(String source_Name) {
this.Source_Name = source_Name;
}
public String getUrl() {
return Url;
}
public void setUrl(String url) {
this.Url = url;
}
public String getBody_Name() {
return Body_Name;
}
public void setBody_Name(String body_Name) {
Body_Name = body_Name;
}
public String getImgUrl() {
return imgUrl;
}
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
public String getSource_icon_imgUrl() {
return source_icon_imgUrl;
}
public void setSource_icon_imgUrl(String source_icon_imgUrl) {
this.source_icon_imgUrl = source_icon_imgUrl;
}}
this is adapter for the listView
public class NewsListAdapter extends BaseAdapter {
private Context context;
private LayoutInflater layoutInflater;
private ArrayList<NewsContents> newsContents;
public NewsListAdapter(Context current){
this.context = current;
this.layoutInflater = (LayoutInflater)current.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void setNewsContents(ArrayList<NewsContents> newsContents){
this.newsContents = newsContents;
}
#Override
public int getCount() {
return newsContents.size();
}
#Override
public Object getItem(int position) {
return newsContents.get(position);
}
#Override
public long getItemId(int position) {
return newsContents.get(position).getId();
}
#SuppressLint({"ViewHolder", "InflateParams"})
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = layoutInflater.inflate(R.layout.news_row,parent,false);
((TextView)convertView.findViewById(R.id.News_Title)).setText(newsContents.get(position).getTitle_Name());
((TextView)convertView.findViewById(R.id.news_body)).setText(newsContents.get(position).getBody_Name());
((TextView)convertView.findViewById(R.id.news_sourceName)).setText(newsContents.get(position).getSource_Name());
((TextView)convertView.findViewById(R.id.url_text)).setText(newsContents.get(position).getUrl());
Picasso.
get().
load(newsContents.get(position).getImgUrl()).
into((ImageView) convertView.findViewById(R.id.news_img));
Picasso.
get().
load(newsContents.get(position).getSource_icon_imgUrl()).
into((ImageView) convertView.findViewById(R.id.news_icon_img));
return convertView;
}}
Thank you for reading the codes!
Your toast message is taken from 'url_String'.
The 'url_String' is updated when 'onOkHttpResponse()' is triggered.
The 'onOkHttpResponse()' is called when 'Set_Content_to_NewsList()' is triggered.
The 'Set_Content_to_NewsList()' is triggered 5 times.
The toast message will always get the latest 'url_String' and not from any other rows.
A quick fix would be to store each 'url_String' in an array, and using 'position' as an index to this array.

How to parse JSON data without array name?

I'm new to JSON parsing. This code works. But how I can access directly to "likes" and "webformatURL" if there were not "totalHits" and "hits" on JSON array?
private void parseJSON() {
String url="https://pixabay.com/api/?key=8947271-cb39739eaa5835e1eaa2f53c6&q=yellow+flowers&image_type=photo&pretty=true";
JsonObjectRequest request = new JsonObjectRequest(
Request.Method.GET,
url,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("hits");
for (int i = 0; i < jsonArray.length(); i++){
JSONObject hit = jsonArray.getJSONObject(i);
String imageUrl = hit.getString("webformatURL");
int likeCount = hit.getInt("likes");
mExampleList.add(new ExampleItem(imageUrl, likeCount));
}
mExampleAdapter = new ExampleAdapter(MainActivity.this, mExampleList);
mRecyclerView.setAdapter(mExampleAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}
);
}
You can use Google Gson library to parse your json to directly ArrayList object.
You can do this.
JsonArray itemArray = new JsonArray(response);
Type listType = new TypeToken<List<Model>>() {
}.getType();
List<Model> yourList = new Gson().fromJson(itemArray, listType);
for (Model model : yourList) {
// use this list
System.out.println(model.toString());
}
Here is your model class.
class Model {
private int id;
private String title;
private long date_add;
private String poster;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public long getDate_add() {
return date_add;
}
public void setDate_add(long date_add) {
this.date_add = date_add;
}
public String getPoster() {
return poster;
}
public void setPoster(String poster) {
this.poster = poster;
}
#Override
public String toString() {
return "Model{" +
"id=" + id +
", title='" + title + '\'' +
", date_add=" + date_add +
", poster='" + poster + '\'' +
'}';
}
}
To add Gson to your project. Just add this dependency in your build.gradle
dependencies {
compile 'com.google.code.gson:gson:2.8.4'
}

JSON and Android Studio

My API : http://maps.googleapis.com/maps/api/distancematrix/json?origins=45.067381,%202.988574&destinations=45.067381,%202.988574&mode=driving&language=en-US&sensor=false
My code on android studio :
private class GetDistance extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
String jsonStr = sh.makeServiceCall("http://maps.googleapis.com/maps/api/distancematrix/json?origins=45.067381,%202.988574&destinations=45.067381,%202.988574&mode=driving&language=en-US&sensor=false");
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONObject contacts = jsonObj.getJSONObject("rows");
JSONArray childrenArray = contacts.getJSONArray("elements");
for (int i = 0; i < childrenArray.length(); i++) {
JSONObject childrenData = childrenArray.getJSONObject(i);
String json_distance = childrenData.getString("status");
test58 = json_distance;
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {}
return null;
}
Error : Json parsing error: Value [{"elements":[{"distance":{"text":"1 m","value":0},"duration":{"text":"1 min","value":0},"status":"OK"}]}] at rows of type org.json.JSONArray cannot be converted to JSONObject
How do I get access to rows -> elements -> distance -> text ?
Thanks.
JSONObject contacts = jsonObj.getJSONObject("rows");
The Key "rows" returns an array and not an Object.
Change the above statement to
JSONArray rowArray = jsonObj.getJSONArray("rows");
Now select the first element in rowArray array
JSONObject firstRow = rowArray.getJSONObject(0);
From this object obtain the array associated with elements key
JSONArray elementArray = firstRow.getJSONArray("elements");
Then,
JSONObject firstElement = elementArray.getJSONObject(0);
JSONObject distance = firstElement.getJSONObject("distance");
String text = distance.getString("text");
My new code :
if (jsonStr != null) {
try {
JSONObject object = new JSONObject(jsonStr);
JSONArray rows = object.getJSONArray("rows");
JSONArray elements = rows.getJSONArray("elements");
JSONObject distance = elements.getJSONObject("distance");
test58 = distance.getString("text");
}
error with rows.getJSONArray("elements") and elements.getJSONObject("distance")
getJsonArray (int) in JsonArray cannot be applied to (java.lang.string)
this is idea #Override
#Override
protected Void doInBackground(Void... params) {
System.out.println("Menu doInBackground");
ParseJson parseJson = new ParseJson();
JSONObject jsonObject = parseJson.getJsonFromURL("YOUR LINK");
try {
JSONArray jsonArray = jsonObject.getJSONArray("rows");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObjectRow = jsonArray.getJSONObject(i);
for(int j= 0; j< jsonObjectRow; j++){
JSONObject jsonObjectElements = jsonArray.getJSONObject(j);
....
for(int k = 0; k< jsonObjectElements; k++){
JSONObject jsonObjectDistance = jsonArray.getJSONObject(j);
...
}
}
}
} catch (JSONException e) {
}
return null;
}
your Model
public class MyModel{
private String[] destinationAddress;
private String[] originAddresses;
private List<Row> listRow;
private String status;
public class Row{
private String estatus;
private List<Elements> listElements;
public class Elements{
private List<Distance> distance;
public class Distance {
private String text;
private int value;
public Distance(String text, int value) {
this.text = text;
this.value = value;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
public Elements(List<Distance> distance) {
this.distance = distance;
}
public List<Distance> getDistance() {
return distance;
}
public void setDistance(List<Distance> distance) {
this.distance = distance;
}
}
public Row(String estatus, List<Elements> listElements) {
this.estatus = estatus;
this.listElements = listElements;
}
public String getEstatus() {
return estatus;
}
public void setEstatus(String estatus) {
this.estatus = estatus;
}
public List<Elements> getListElements() {
return listElements;
}
public void setListElements(List<Elements> listElements) {
this.listElements = listElements;
}
}
public MyModel(String[] destinationAddress, String[] originAddresses, List<Row> listRow, String status) {
this.destinationAddress = destinationAddress;
this.originAddresses = originAddresses;
this.listRow = listRow;
this.status = status;
}
public String[] getDestinationAddress() {
return destinationAddress;
}
public void setDestinationAddress(String[] destinationAddress) {
this.destinationAddress = destinationAddress;
}
public String[] getOriginAddresses() {
return originAddresses;
}
public void setOriginAddresses(String[] originAddresses) {
this.originAddresses = originAddresses;
}
public List<Row> getListRow() {
return listRow;
}
public void setListRow(List<Row> listRow) {
this.listRow = listRow;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}

How to Change order of List view's Items according to some Specific input

I want to change the sequence of my list view's items according to a specific input string which is matches with any of list view items contents and that item comes on the top of list view. I have tried hard but getting no success till now.if any other query please ask.
Here is the code for fetching data from server:
Here date2 is string input which I'm trying to compare
private void caladata() {
// showing refresh animation before making http call
swipeRefreshLayout.setRefreshing(false);
// Volley's json array request object
StringRequest stringRequest = new StringRequest(Request.Method.POST, CALENDAR_DATA,
new Response.Listener < String > () {
#Override
public void onResponse(String response) {
// Log.d(TAG, response.toString());
// hidePDialog();
JSONObject object = null;
try {
object = new JSONObject(response);
} catch (JSONException e) {
e.printStackTrace();
}
JSONArray jsonarray = null;
try {
jsonarray = object.getJSONArray("Table");
} catch (JSONException e) {
e.printStackTrace();
}
Calenndar_Model movie = new Calenndar_Model();
for (int i = 0; i < jsonarray.length(); i++) {
try {
JSONObject obj = jsonarray.getJSONObject(i);
movie.setUserid(obj.getString("userid"));
movie.setHost(obj.getString("eventname"));
String str = obj.getString("eventdate").replaceAll("\\D+","");
String upToNCharacters = str.substring(0, Math.min(str.length(), 13));
DateFormat timeZoneFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
timeZoneFormat.setTimeZone(TimeZone.getTimeZone("GMT-8"));
Date time = new Date(Long.parseLong(upToNCharacters));
// System.out.println(time);
movie.setDate(String.valueOf(timeZoneFormat.format(time)));
movie.setColor(obj.getString("eventcolor"));
movie.setAutoid(obj.getString("autoid"));
// Toast.makeText(getApplicationContext(), "server data respone", Toast.LENGTH_LONG).show();
int index=calList.indexOf(date2);
calList.add(movie);
calList.remove(date2);
calList.add(0, movie);
} catch (JSONException e) {
// Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
// listView.smoothScrollToPositionFromTop(selectedPos,0,300);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// VolleyLog.d(TAG, "Error: " + error.getMessage());
// hidePDialog();
}
}) {
#Override
protected Map < String, String > getParams() {
Map < String, String > params = new HashMap < String, String > ();
params.put("clientid", get1);
return params;
}
};
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(stringRequest);
}
Here is my adapter class:
public class CalendarListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Calenndar_Model> movieList;
public CalendarListAdapter(Activity activity, List<Calenndar_Model> movieList) {
this.activity = activity;
this.movieList = movieList;
}
public void swapList(List<Calenndar_Model> movieList) {
this.movieList = movieList;
notifyDataSetChanged();
}
#Override
public int getCount() {
return movieList.size();
}
#Override
public Object getItem(int location) {
return movieList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.calendar_listrow, null);
ImageView serial = (ImageView) convertView.findViewById(R.id.serial);
TextView title = (TextView) convertView.findViewById(R.id.title);
TextView date1 = (TextView) convertView.findViewById(R.id.date1);
title.setText(movieList.get(position).getHost());
date1.setText(movieList.get(position).getDate());
return convertView;
}
}
Model Class:
public class Calenndar_Model {
private String host, date,userid,color,autoid;
//private double rating;
public Calenndar_Model() {
}
public Calenndar_Model(String host,String date,String userid,String color,String autoid) {
this.host = host;
this.date = date;
this.userid = userid;
this.color = color;
this.autoid = autoid;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getAutoid() {
return autoid;
}
public void setAutoid(String autoid) {
this.autoid = autoid;
}
}
UPDATE: I found usage of date2 (the real name of variable, not data2 as you menthioned in description).
All you need is to sort your List<Calenndar_Model>:
private void caladata() {
// showing refresh animation before making http call
swipeRefreshLayout.setRefreshing(false);
// Volley's json array request object
StringRequest stringRequest = new StringRequest(Request.Method.POST, CALENDAR_DATA,
new Response.Listener < String > () {
#Override
public void onResponse(String response) {
// Log.d(TAG, response.toString());
// hidePDialog();
JSONObject object = null;
try {
object = new JSONObject(response);
} catch (JSONException e) {
e.printStackTrace();
}
JSONArray jsonarray = null;
try {
jsonarray = object.getJSONArray("Table");
} catch (JSONException e) {
e.printStackTrace();
}
calList = new ArrayList<>();
for (int i = 0; i < jsonarray.length(); i++) {
try {
JSONObject obj = jsonarray.getJSONObject(i);
Calenndar_Model movie = new Calenndar_Model();
movie.setUserid(obj.getString("userid"));
movie.setHost(obj.getString("eventname"));
String str = obj.getString("eventdate").replaceAll("\\D+","");
String upToNCharacters = str.substring(0, Math.min(str.length(), 13));
DateFormat timeZoneFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
timeZoneFormat.setTimeZone(TimeZone.getTimeZone("GMT-8"));
Date time = new Date(Long.parseLong(upToNCharacters));
//System.out.println(time);
movie.setDate(String.valueOf(timeZoneFormat.format(time)));
movie.setColor(obj.getString("eventcolor"));
movie.setAutoid(obj.getString("autoid"));
//Toast.makeText(getApplicationContext(), "server data respone", Toast.LENGTH_LONG).show();
calList.add(movie);
} catch (JSONException e) {
// Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
}
//sort calList list
Comparator<Calenndar_Model> calendarModelComparator = new Comparator<Calenndar_Model>() {
#Override
public int compare(Calenndar_Model cm1, Calenndar_Model cm2) {
boolean firstContainsData2 = calendarModelContainsData2(cm1);
boolean secondContainsData2 = calendarModelContainsData2(cm2);
if (firstContainsData2 && secondContainsData2) {
return 0;
} else if (firstContainsData2) {
return -1;
} else if (secondContainsData2) {
return 1;
} else return cm2.getData().compareTo(cm1.getData());
}
private boolean calendarModelContainsData2(Calenndar_Model cm) {
return cm.getData().contains(data2);
}
};
Collections.sort(calList, calendarModelComparator);
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.swapList(calList);
//listView.smoothScrollToPositionFromTop(selectedPos,0,300);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// VolleyLog.d(TAG, "Error: " + error.getMessage());
// hidePDialog();
}
}) {
#Override
protected Map < String, String > getParams() {
Map < String, String > params = new HashMap < String, String > ();
params.put("clientid", get1);
return params;
}
};
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(stringRequest);
}
Suppose date2 is eventname you want to compare.
if(date2.equals(movie.getHost())
{
// store Movie object on index 0, if it equals date2
calList.add(0, movie);
}
else
{
calList.add(movie);
}
Remove the Following Lines from caladata().
int index=calList.indexOf(date2);
calList.add(movie);
calList.remove(date2);
calList.add(0, movie);

Categories