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.
Related
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;
}
}
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;
}
}
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);
Trying to parse using jackson through intent data and adding to pojo class and getting back but not able to send and fetch ?
MainActivity is..
public class MainActivity extends AppCompatActivity {
private Button getButton;
private TextView textView;
private String jsonData;
#Override
protected void onCreate(Bundle savedInstanceState)
{
setContentView(R.layout.activity_json);
super.onCreate(savedInstanceState);
getButton = (Button) findViewById(R.id.getButton);
textView = (TextView) findViewById(R.id.textView);
getButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
new JSONTask().execute("http://192.168.11.75/Headspire/api.php");
}
});
}
public class JSONTask extends AsyncTask<String, String, String>
{
private String json_string = "";
#Override
protected String doInBackground(String... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
InputStream stream = urlConnection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
while ((json_string = reader.readLine()) != null) {
buffer.append(json_string);
}
return buffer.toString();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(final String result) {
super.onPostExecute(result);
textView.setText(result);
jsonData = result;
}
}
public void parseJSON(View view)
{
if (jsonData == null)
{
Toast.makeText(getApplicationContext(),
"Get JSON data first", Toast.LENGTH_SHORT).show();
}
else
{
Intent intent = new Intent(this, ActivityListView.class);
intent.putExtra("json_data", jsonData);
startActivity(intent);
}
}
}
Here this is my ActivityListView class...
public class ActivityListView extends AppCompatActivity
{
private String jsonData;
private ListView listView;
private PersonAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_list_view);
listView = (ListView) findViewById(R.id.listView);
adapter = new PersonAdapter(this, R.layout.row);
listView.setAdapter(adapter);
jsonData = getIntent().getExtras().getString("json_data");
ObjectMapper mapper = new ObjectMapper();
try
{
PersonModel model = mapper.readValue(jsonData, PersonModel.class);
model.getName();
model.getId();
model.getDescription();
model.getRating();
adapter.add(model);
}
catch (JsonParseException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
My PersonAdapeter class looks like this
public class PersonAdapter extends ArrayAdapter
{
private List list = new ArrayList();
public PersonAdapter(Context context, int resource) {
super(context, resource);
}
#SuppressWarnings("unchecked")
public void add(PersonModel object)
{
super.add(object);
list.add(object);
}
#Override
public int getCount()
{
return list.size();
}
#Override
public Object getItem(int position)
{
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View row;
row = convertView;
NameHolder nameHolder;
if (row == null)
{
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.row, parent, false);
nameHolder = new NameHolder();
nameHolder.nameTextView = (TextView) row.findViewById(R.id.nameTextView);
nameHolder.idTextView = (TextView) row.findViewById(R.id.idTextView);
nameHolder.descriptionTextView = (TextView) row.findViewById(R.id.descriptionTextView);
nameHolder.ratingTextView = (TextView) row.findViewById(R.id.ratingTextView);
row.setTag(nameHolder);
}
else {
nameHolder = (NameHolder)row.getTag();
}
PersonModel model = (PersonModel) this.getItem(position);
nameHolder.nameTextView.setText(model.getName());
nameHolder.idTextView.setText(model.getId());
nameHolder.descriptionTextView.setText(model.getDescription());
nameHolder.ratingTextView.setText(model.getRating());
return row;
}
static class NameHolder
{
TextView nameTextView, idTextView, descriptionTextView, ratingTextView;
}
}
Here it is my PersonModel class...
#JsonIgnoreProperties(ignoreUnknown=true)
public class PersonModel extends AppCompatActivity
{
private String name;
private String id;
private String description;
private String rating;
public PersonModel(String name, String id, String description,
String rating)
{
this.name = name;
this.id = id;
this.description = description;
this.rating = rating;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getRating() {
return rating;
}
public void setRating(String rating) {
this.rating = rating;
}
#Override
public String toString()
{
return "PersonModel [name=" + name + ", id=" + id + ",
description=" + description + ", " +
"rating=" + rating +"]";
}
}
I am using volley to parse the Movie Details from a REST api and I am saving the parsed Data in an Arraylist of objects called detailsMovies. But I can't access the ArrayList outside the onResponse Method. I am new to Android So I dont know what to do exactly.
Any Help is appreciated!
Here's the code:`
public class MovieDetailsActivity extends AppCompatActivity {
TextView movieIdText;
private VolleySingleton volleySingleton;
private RequestQueue mRequestQueue;
private ArrayList<MovieDetails> detailsMovies = new ArrayList<>();
// private String movieTitle ;
// private String movieSummary ;
// private int movieYear;
// private long movieRating;
// private String movieYoutubeId;
// private String movieUrlThumbnail;
// private String movieDownloadLink720p;
// private String movieQuality720p;
// private String moviefileSize720p;
// private String movieDownloadLink1080p;
// private String movieQuality1080p;
// private String moviefileSize1080p;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_details);
Intent i = getIntent();
String movieId = i.getExtras().getString("movieId");
volleySingleton = VolleySingleton.getsInstance();
mRequestQueue = VolleySingleton.getmRequestQueue();
parseMovieDetails();
}
public void parseMovieDetails(){
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, getUrl(100), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
MovieDetails movieDetails = new MovieDetails();
if (response == null || response.length() == 0) {
Toast.makeText(getApplicationContext(), "Null Object", Toast.LENGTH_LONG).show();
}
try {
JSONObject movieData = response.getJSONObject("data");
JSONObject movieDetailsObject = movieData.getJSONObject(Keys.EndPointMovieDetails.KEYS_MOVIE);
String movieTitle = movieDetailsObject.getString(Keys.EndPointMovieDetails.KEYS_TITLE_LONG);
long movieRating = movieDetailsObject.getInt(Keys.EndPointMovieDetails.KEYS_RATING);
String movieSynopsis = movieDetailsObject.getString(Keys.EndPointMovieDetails.KEYS_DESCRIPTION);
String moviePosterUrl = movieDetailsObject.getString(Keys.EndPointMovieDetails.KEYS_COVER);
String movieYoutubeId = movieDetailsObject.getString(Keys.EndPointMovieDetails.KEY_YOUTUBE_ID);
movieDetails.setTitle(movieTitle);
movieDetails.setRating(movieRating);
movieDetails.setSummary(movieSynopsis);
movieDetails.setUrlThumbnail(moviePosterUrl);
movieDetails.setYoutube_id(movieYoutubeId);
detailsMovies.add(movieDetails);
JSONArray torrentDownloadLinks = movieDetailsObject.getJSONArray(Keys.EndPointMovieDetails.KEYS_TORRENTS);
for(int i=0;i<torrentDownloadLinks.length();i++) {
JSONObject urlInfo = torrentDownloadLinks.getJSONObject(i);
String urlTorrent = urlInfo.getString("url");
String quality = urlInfo.getString("quality");
String fileSize = urlInfo.getString("size");
movieDetails.setDownloadLink(urlTorrent);
movieDetails.setQuality(quality);
movieDetails.setFileSize(fileSize);
detailsMovies.add(movieDetails);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
mRequestQueue.add(jsonObjectRequest);
}
public String getUrl(int movieId){
return UrlEndPoints.URL_MOVIE_DETAILS+
UrlEndPoints.URl_CHAR_QUESTION+
UrlEndPoints.URL_PARAM_ID+movieId;
}
Define an Interface in your class and implement that.
So Simple trick here is interface with callback.
public class MovieDetailsActivity extends AppCompatActivity {
TextView movieIdText;
private VolleySingleton volleySingleton;
private RequestQueue mRequestQueue;
private ArrayList<MovieDetails> detailsMovies = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_details);
Intent i = getIntent();
String movieId = i.getExtras().getString("movieId");
volleySingleton = VolleySingleton.getsInstance();
mRequestQueue = VolleySingleton.getmRequestQueue();
parseMovieDetails(new CallBack() {
#Override
public void onSuccess(ArrayList<MovieDetails> detailsMovies) {
// Do Stuff
}
#Override
public void onFail(String msg) {
// Do Stuff
}
});
}
public void parseMovieDetails(final CallBack onCallBack){
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, getUrl(100), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
MovieDetails movieDetails = new MovieDetails();
if (response == null || response.length() == 0) {
Toast.makeText(getApplicationContext(), "Null Object", Toast.LENGTH_LONG).show();
}
try {
JSONObject movieData = response.getJSONObject("data");
JSONObject movieDetailsObject = movieData.getJSONObject(Keys.EndPointMovieDetails.KEYS_MOVIE);
String movieTitle = movieDetailsObject.getString(Keys.EndPointMovieDetails.KEYS_TITLE_LONG);
long movieRating = movieDetailsObject.getInt(Keys.EndPointMovieDetails.KEYS_RATING);
String movieSynopsis = movieDetailsObject.getString(Keys.EndPointMovieDetails.KEYS_DESCRIPTION);
String moviePosterUrl = movieDetailsObject.getString(Keys.EndPointMovieDetails.KEYS_COVER);
String movieYoutubeId = movieDetailsObject.getString(Keys.EndPointMovieDetails.KEY_YOUTUBE_ID);
movieDetails.setTitle(movieTitle);
movieDetails.setRating(movieRating);
movieDetails.setSummary(movieSynopsis);
movieDetails.setUrlThumbnail(moviePosterUrl);
movieDetails.setYoutube_id(movieYoutubeId);
detailsMovies.add(movieDetails);
JSONArray torrentDownloadLinks = movieDetailsObject.getJSONArray(Keys.EndPointMovieDetails.KEYS_TORRENTS);
for(int i=0;i<torrentDownloadLinks.length();i++) {
JSONObject urlInfo = torrentDownloadLinks.getJSONObject(i);
String urlTorrent = urlInfo.getString("url");
String quality = urlInfo.getString("quality");
String fileSize = urlInfo.getString("size");
movieDetails.setDownloadLink(urlTorrent);
movieDetails.setQuality(quality);
movieDetails.setFileSize(fileSize);
detailsMovies.add(movieDetails);
}
onCallBack.success(detailsMovies);
} catch (JSONException e) {
e.printStackTrace();
onCallBack.onFail(e.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
mRequestQueue.add(jsonObjectRequest);
}
public String getUrl(int movieId){
return UrlEndPoints.URL_MOVIE_DETAILS+
UrlEndPoints.URl_CHAR_QUESTION+
UrlEndPoints.URL_PARAM_ID+movieId;
}
public interface CallBack {
void onSuccess(ArrayList<MovieDetails> detailsMovies);
void onFail(String msg);
}