JSON and Android Studio - java

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

Related

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

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

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

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

How to access json array that is passed from restful web service in android?

I have successfully created a rest web service and it returns jsonarray which has two fields
id and city from data base.
My resr web service is
#GET
#Path("city")
#Produces("application/json")
public String getJson() {
PropertyPojo propojo=null;
ArrayList cityList = new ArrayList();
JSONArray list = new JSONArray();
Map m1 = new LinkedHashMap();
List l1 = new LinkedList();
String jsonString = null;
try{
cityList=PDao.CityList();
Iterator it=cityList.iterator();
while(it.hasNext())
{
propojo=(PropertyPojo)it.next();
m1.put(propojo.getKeyid(),propojo.getKeyvalue());
}
}catch(Exception e){
}
l1.add(m1);
jsonString = JSONValue.toJSONString(l1);
return jsonString;
}
I just need to put these values into a spinner...
My android code is
public class MainActivity extends Activity {
Spinner spinner;
private static final String SERVICE_URL = "http://192.168.1.6:8080/eSava_RestWeb/webresources/service";
private static final String TAG = "AndroidRESTClientActivity";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
spinner = (Spinner) findViewById(R.id.city);
}
public void retrieveSampleData(View vw) {
String sampleURL = SERVICE_URL + "/city";
WebServiceTask wst = new WebServiceTask(WebServiceTask.GET_TASK,
this, "GETting data...");
wst.execute(new String[] { sampleURL });
}
#SuppressLint("NewApi")
public void handleResponse(String response) {
try {
// JSONObject jso = new JSONObject(response);
JSONArray json = new JSONArray(response);
ArrayList<String> list = new ArrayList<String>();
JSONArray jsonArray = (JSONArray) json;
if (jsonArray != null) {
int len = jsonArray.length();
for (int i = 0; i < len; i++) {
list.add(jsonArray.get(i).toString());
}
}
Spinner s = (Spinner) findViewById(R.id.city);
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, list);
s.setAdapter(adapter);
} catch (Exception e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
private class WebServiceTask extends AsyncTask<String, Integer, String> {
public static final int POST_TASK = 1;
public static final int GET_TASK = 2;
private static final String TAG = "WebServiceTask";
// connection timeout, in milliseconds (waiting to connect)
private static final int CONN_TIMEOUT = 3000;
// socket timeout, in milliseconds (waiting for data)
private static final int SOCKET_TIMEOUT = 5000;
private int taskType = GET_TASK;
private Context mContext = null;
private String processMessage = "Processing...";
private ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
private ProgressDialog pDlg = null;
public WebServiceTask(int taskType, Context mContext,
String processMessage) {
this.taskType = taskType;
this.mContext = mContext;
this.processMessage = processMessage;
}
public void addNameValuePair(String name, String value) {
params.add(new BasicNameValuePair(name, value));
}
private void showProgressDialog() {
pDlg = new ProgressDialog(mContext);
pDlg.setMessage(processMessage);
pDlg.setProgressDrawable(mContext.getWallpaper());
pDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDlg.setCancelable(false);
pDlg.show();
}
#Override
protected void onPreExecute() {
showProgressDialog();
}
protected String doInBackground(String... urls) {
String url = urls[0];
String result = "";
HttpResponse response = doResponse(url);
if (response == null) {
return result;
} else {
try {
result = inputStreamToString(response.getEntity()
.getContent());
} catch (IllegalStateException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
return result;
}
#Override
protected void onPostExecute(String response) {
JSONArray jsArray;
// jsArray = new JSONArray(response);
handleResponse(response);
pDlg.dismiss();
}
// Establish connection and socket (data retrieval) timeouts
private HttpParams getHttpParams() {
HttpParams htpp = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(htpp, CONN_TIMEOUT);
HttpConnectionParams.setSoTimeout(htpp, SOCKET_TIMEOUT);
return htpp;
}
private HttpResponse doResponse(String url) {
// Use our connection and data timeouts as parameters for our
// DefaultHttpClient
HttpClient httpclient = new DefaultHttpClient(getHttpParams());
HttpResponse response = null;
try {
switch (taskType) {
case POST_TASK:
HttpPost httppost = new HttpPost(url);
// Add parameters
httppost.setEntity(new UrlEncodedFormEntity(params));
response = httpclient.execute(httppost);
break;
case GET_TASK:
HttpGet httpget = new HttpGet(url);
response = httpclient.execute(httpget);
break;
}
} catch (Exception e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
return response;
}
private String inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(
new InputStreamReader(is));
try {
// Read response until the end
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
// Return full string
return total.toString();
}
}
}
Its better to create Model class and then you can parse the response with gson.
For example,
Imagine that you have your response with two strings Name and Mail. Create a model with two strings.
public class Sample{
public Sample()
{
}
#SerializedName("Name")//if needed
String name;
#SerializedName("Email")//if needed
String email;
public void set(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void set(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
}
Then parse your response with gson.
Sample sample = gson.fromJson(jsonRes.toString(), Sample.class);
Then you can access the members of the object sample. Change the Sample class as you needed(with the array of strings and int. You can use ArrayList instead of Array)
String[] city= {};
String[] id= {};
JSONArray jsonDetailsObj = json.getJSONArray("cityList");
JSONObject jsonLoop = null;
int noOfPoints = jsonDetailsObj.length();
city= new String[noOfPoints];
id= new String[noOfPoints];
for (int i=0 ; i < noOfPoints ; i++)
{
jsonLoop=jsonDetailsObj.getJSONObject(i);
city [i] = jsonLoop.getString("CityName");
id[i] = jsonLoop.getString("ID");
}

Categories