Why I can't define FindViewById() on Fragment with Volley Library - java

I am trying to define FindViewById() on Fragment with Volley Library. Also, I put FindViewById() on method OnResponse(), but I am getting an error. Do you have any solution? Here is my code.
package com.smktelkommlg.prakerinlistview;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class SecondFragment extends Fragment {
private static final String BASE_URL = "Some Base URL";
private final String EndPoint = "Somr EndPoint";
List<Result> resultsLists;
ListView listView;
public SecondFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_second, container, false);
resultsLists = new ArrayList<>();
listView = rootView.findViewById(R.id.listView);
ProgressBar progressBar = rootView.findViewById(R.id.rolling);
loadResultsList();
// Instantiate the RequestQueue.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String idToDetail = String.valueOf(resultsLists.get(position).getId());
Intent detailIntent = new Intent(getActivity(),DetailActivity.class);
detailIntent.putExtra("idMoveIntent", idToDetail);
startActivity(detailIntent);
}
});
return rootView;
}
private void loadResultsList () {
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, BASE_URL+EndPoint+"?limit=1000&offset=0", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
ProgressBar progressBar = findViewById(R.id.rolling);
Log.d("Json Response", response);
try {
JSONObject obj = new JSONObject(response);
JSONArray heroArray = obj.getJSONArray("results");
for (int i = 0; i < heroArray.length(); i++) {
JSONObject heroObject = heroArray.getJSONObject(i);
Result superHero = new Result(heroObject.getString("name"), heroObject.getInt("id"), heroObject.getJSONObject("device_role").getString("name"), heroObject.getJSONObject("status").getString("value"), heroObject.getJSONObject("device_type").getJSONObject("manufacturer").getString("slug"));
resultsLists.add(superHero);
}
ListViewAdapter adapter = new ListViewAdapter(resultsLists, getActivity().getApplicationContext());
listView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap header = new HashMap();
header.put("Content-Type", "application/json");
header.put("Authorization", "Token eaaa9e72d1a4f4c75aef7a7492e07785d853b6b4");
return header;
}
};
RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());
queue.add(stringRequest);
}
#Override
public void onViewCreated (#NonNull View view, #Nullable Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Results");
getContext();
}
}
I can't define this ProgressBar progressBar = findViewById(R.id.rolling);
Do I have to put ProgressBar progressBar = findViewById(R.id.rolling); in OnCreateView and use rootView? What should I do?
I meant to call progressBar before receive through the API.
(I'm sorry for my grammar. I hope you understand)
And here's my xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ProgressBar
android:id="#+id/rolling"
style="?android:attr/progressBarStyleLarge"
android:layout_width="match_parent"
android:indeterminate="true"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"/>
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>

Use Global Variable
In your SecondFragment:
ProgressBar progressBar;
in OnCreateView:
progressBar = rootView.findViewById(R.id.rolling);
Remove ProgressBar progressBar = findViewById(R.id.rolling); from loadResultsList() method.

Related

Why JSON data can't reach ViewPager?

I want to fetch Images using Volley JSON in PagerAdapter for slider , but problem is that data fetched using JSON is reached till constructor but not reatched to InstantiateItem method.
This is my xml File.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<androidx.viewpager.widget.ViewPager
android:layout_width="match_parent"
android:layout_height="#dimen/_200sdp"
android:id="#+id/view_pager">
</androidx.viewpager.widget.ViewPager>
<TextView
android:layout_width="match_parent"
android:layout_height="#dimen/_50sdp"
android:text="#string/app_name"
android:textSize="#dimen/_30sdp"
android:textColor="#color/colorPrimaryDark"
android:id="#+id/txt"/>
</LinearLayout>
MainActivity.java
package com.example.sliderwithvolleyjson;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ViewPager viewPager;
String slider_url="Here is my API";
ArrayList<String> image=new ArrayList<>();
RequestQueue queue;
Slider_Adapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
queue= Volley.newRequestQueue(getApplicationContext());
viewPager=findViewById(R.id.view_pager);
getImageByJson();
viewPager.setAdapter(adapter);
}
public void getImageByJson(){
JsonObjectRequest request=new JsonObjectRequest(Request.Method.GET, slider_url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray array=response.getJSONArray("slider");
for (int i=0;i<array.length();i++){
JSONArray jsonData=array.getJSONArray(i);
image.add(jsonData.getString(1));
}
String[] imageUrls=new String[image.size()];
imageUrls=image.toArray(imageUrls);
for (String s : imageUrls){
Log.d("String",s);
}
adapter=new Slider_Adapter(getApplicationContext(),imageUrls);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),String.valueOf(e),Toast.LENGTH_LONG).show();
Log.d("ath",String.valueOf(e));
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),String.valueOf(error),Toast.LENGTH_LONG).show();
Log.d("Error",String.valueOf(error));
}
});
queue.add(request);
}
}
I fetch images from my server using API in mainactivity class. I use Volley JSON to do it. Then i passed this images to PagerAdapter class using viewpager.
PagerAdapter Class
package com.example.sliderwithvolleyjson;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import com.squareup.picasso.Picasso;
public class Slider_Adapter extends PagerAdapter {
LayoutInflater inflater;
private Context context;
private String[] imageurls;
public Slider_Adapter(Context context, String[] imageurls) {
this.context = context;
this.imageurls = imageurls;
Toast.makeText(context, String.valueOf(imageurls[1]), Toast.LENGTH_SHORT).show();
}
#Override
public int getCount() {
return imageurls.length;
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view==object;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view=inflater.inflate(R.layout.activity_main,container);
ImageView imageView=new ImageView(container);
TextView textView=view.findViewById(R.id.txt);
textView.setText(String.valueOf(imageurls.length));
Picasso.with(context).load(imageurls[position]).fit().into(imageView);
ViewPager pager=(ViewPager)container;
pager.addView(view);
return view;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((View)object);
}
}
That Images is arrived till constructor (I tried it using toast message) but We can't find that images/data in InstantiateItem method and other functions.
Thanks in Advance.
public class MainActivity extends AppCompatActivity {
ViewPager viewPager;
String slider_url="Here is my API";
ArrayList<String> image=new ArrayList<>();
RequestQueue queue;
Slider_Adapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
queue= Volley.newRequestQueue(getApplicationContext());
viewPager=findViewById(R.id.view_pager);
getImageByJson();
}
public void getImageByJson(){
JsonObjectRequest request=new JsonObjectRequest(Request.Method.GET, slider_url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray array=response.getJSONArray("slider");
for (int i=0;i<array.length();i++){
JSONArray jsonData=array.getJSONArray(i);
image.add(jsonData.getString(1));
}
String[] imageUrls=new String[image.size()];
imageUrls=image.toArray(imageUrls);
for (String s : imageUrls){
Log.d("String",s);
}
adapter=new Slider_Adapter(getApplicationContext(),imageUrls);
viewPager.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),String.valueOf(e),Toast.LENGTH_LONG).show();
Log.d("ath",String.valueOf(e));
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),String.valueOf(error),Toast.LENGTH_LONG).show();
Log.d("Error",String.valueOf(error));
}
});
queue.add(request);
}
}
for (String s : imageUrls){
Log.d("String",s);
}
adapter=new Slider_Adapter(getApplicationContext(),imageUrls);
After this line of codes in your onResponse method, add this code.
viewPager.setAdapter(adapter);
And remove it from onCreate because it is not necessary.

java.lang.ClassCastException: CustomAdapter cannot be cast to android.widget.ArrayAdapter in java

I am trying to load json data into a scrollable spinner. But I am getting the error that the CustomAdapter is not able to cast into ArrayAdapter. Can you help me with this?
Provide_Food.xml: This is the file where the spinner is located
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/grdnt"
tools:context=".Provide_food">
<com.toptoche.searchablespinnerlibrary.SearchableSpinner
android:id="#+id/select_food"
android:layout_width="120dp"
android:layout_height="50dp"
android:layout_marginTop="250dp"
android:background="#color/bgcolor"
app:hintText="Select Item"
/>
<Button
android:id="#+id/select_food_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/select_food"
android:layout_marginTop="250dp"
android:layout_marginLeft="40dp"
android:text="Add Item"/>
</RelativeLayout>
Provide_Food.java: The java class for loading the json data into the spinner
package com.example.helping_hands_individual;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ContentResolver;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.textclassifier.TextLinks;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.firebase.database.annotations.Nullable;
import com.google.gson.JsonArray;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class Provide_food extends AppCompatActivity {
Spinner spinner;
String url = "api_link"; //can't mention the link here
List<Item_Model> list = new ArrayList<>();
List<String> list1 = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_provide_food);
spinner = (Spinner)findViewById(R.id.select_food);
new Getdata().execute();
}
class Getdata extends AsyncTask<Void,Void,String>{
String result;
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
CustomAdapter adapter = new CustomAdapter(Provide_food.this, list);
spinner.setAdapter(adapter);
}
#Override
protected String doInBackground(Void... voids) {
try {
URL mainurl = new URL(url);
HttpURLConnection connection = (HttpURLConnection)mainurl.openConnection();
InputStreamReader streamReader = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null){
builder.append(line);
}
result = builder.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
JSONArray array = new JSONArray(result);
for (int i=0; i<array.length(); i++){
Item_Model item_model = new Item_Model();
JSONObject object = array.getJSONObject(i);
String itemname = object.getString("Item Name");
item_model.setItemname(itemname);
list.add(item_model);
}
}
catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
}
}
Item_Model.java: The model class for getting the item name from the json api
package com.example.helping_hands_individual;
public class Item_Model {
String itemname;
public String getItemname() {
return itemname;
}
public void setItemname(String itemname) {
this.itemname = itemname;
}
}
CustomAdapter.java: The custom adapter used for parsing the data into the spinner
package com.example.helping_hands_individual;
import android.content.Context;
import android.transition.Slide;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;
public class CustomAdapter extends BaseAdapter {
LayoutInflater inflater;
Context context;
List<Item_Model> list;
public CustomAdapter(Context applicationContext, List<Item_Model> list){
this.context = applicationContext;
this.list = list;
inflater = (LayoutInflater.from(applicationContext));
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = inflater.inflate(R.layout.item,null);
TextView itemname = (TextView)view.findViewById(R.id.item_names);
itemname.setText(list.get(i).itemname);
return view;
}
}
item.xml: The sample layout file where it contains only the textview which will be displayed in the spinner
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/item_names"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="20dp"
android:textSize="18dp"
android:text="Demo"/>
</LinearLayout>
Your CustomAdapter should extends ArrayAdapter, so you can change your class in this way:
public class CustomAdapter extends ArrayAdapter {
LayoutInflater inflater;
Context context;
List<Item_Model> list;
public CustomAdapter(Context applicationContext, int resources, List<Item_Model> list) {
super(applicationContext, resources);
this.context = applicationContext;
this.list = list;
inflater = (LayoutInflater.from(applicationContext));
}
//...
}
Consider using the parameterized ArrayAdapter<T> feature

Fragment, Volley and RecyclerView JSON

I hope someone there will help me solve my problem. I have an Android application that uses the fragment. I want to download data using Volley from a JSON file. The program does not throw out any errors but CardView does not display with the ordered data. I looked at other topics with a similar problem, but I sit on it for a long time and nothing good happens.
AdapterZabytki.java
package eu.aisen.kamil.miejskiprzewodnik;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.List;
import zabytki.Zabytki;
public class AdapterZabytki extends RecyclerView.Adapter<AdapterZabytki.ViewHolder> {
private List<Zabytek>list_data;
private Zabytki context;
public AdapterZabytki(List<Zabytek> list_data, Zabytki context) {
this.list_data = list_data;
this.context = context;
}
#Override
public AdapterZabytki.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
CardView view= (CardView) LayoutInflater.from(parent.getContext()).inflate(R.layout.obiectcard,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Zabytek zabytek = list_data.get(position);
Picasso.get()
.load(zabytek
.getImage_url())
.into(holder.img);
holder.txtname.setText(zabytek.getName());
}
#Override
public int getItemCount() {
return list_data.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private ImageView img;
private TextView txtname;
public ViewHolder(View view) {
super(view);
img=(ImageView)itemView.findViewById(R.id.info_image);
txtname=(TextView)itemView.findViewById(R.id.info_text);
}
}
}
Zabytek.java
package eu.aisen.kamil.miejskiprzewodnik;
public class Zabytek {
private String name;
private String image_url;
private String opis;
public Zabytek(String name, String image_url, String opis) {
this.name = name;
this.image_url = image_url;
this.opis = opis;
}
public String getName() {
return name;
}
public String getImage_url() {
return image_url;
}
public String getOpis() {
return opis;
}
}
Zabytki.java (fragment)
package zabytki;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import eu.aisen.kamil.miejskiprzewodnik.AdapterZabytki;
import eu.aisen.kamil.miejskiprzewodnik.R;
import eu.aisen.kamil.miejskiprzewodnik.Zabytek;
public class Zabytki extends Fragment {
private static final String HI = "https://wydzialedukacji.rzeszow.pl/testowy.json";
private ArrayList<Zabytek>list_data;
private AdapterZabytki mSensorAdapter;
private RecyclerView mRyclerView;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.zabytki_fragment, container, false);
mRyclerView = view.findViewById(R.id.main_list);
mRyclerView.setHasFixedSize(true);
mRyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
list_data = new ArrayList<>();
getData();
mSensorAdapter = new AdapterZabytki(list_data, this);
mRyclerView.setAdapter(mSensorAdapter);
mSensorAdapter.notifyDataSetChanged();
return view;
}
private void getData() {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, HI, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("results");
for(int i=0; i < jsonArray.length(); i++){
JSONObject object = jsonArray.getJSONObject(i);
String name = object.getString("name");
String image_url = object.getString("image_url");
String opis = object.getString("opis");
list_data.add(new Zabytek(name, image_url, opis));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
Volley.newRequestQueue(getActivity()).add(request);
}
}
zabytki_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView android:id="#+id/main_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
</android.support.v7.widget.RecyclerView>
obiectcard.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="200dp"
android:id="#+id/card_view"
android:layout_margin="5dp"
card_view:cardCornerRadius="4dp">
<android.support.constraint.ConstraintLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="16dp">
<ImageView
android:id="#+id/info_image"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginBottom="24dp"
android:layout_weight="1.0"
android:scaleType="centerCrop"
card_view:layout_constraintBottom_toBottomOf="parent"
card_view:srcCompat="#android:drawable/sym_def_app_icon"
tools:ignore="MissingConstraints" />
<TextView
android:id="#+id/info_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginEnd="16dp"
android:text="tytułzabytku"
card_view:layout_constraintEnd_toEndOf="parent"
card_view:layout_constraintTop_toBottomOf="#+id/info_image" />
</android.support.constraint.ConstraintLayout>
</android.support.v7.widget.CardView>
I have 2 concerns about your code:
1. in onResponse, after you added all items to to list_data, you must call notifyDatasetChanged on RecyclerView adapter (AdapterZabytki)
2. Also, info_image in your ViewHolder seems to have zero height, because it has no top alignment and layout_height="0dp"
I am still wondering how to transfer this data to ZabytekDetailActivity.class
I have this:
mSensorAdapter.setListener(new AdapterZabytki.Listener() {
public void onClick(int position) {
ArrayList<Zabytek> object = new ArrayList<Zabytek>();
Intent intent = new Intent(getActivity(), ZabytekDetailActivity.class);
}
});
Now the question is how to attach the results from list_data so that they can be displayed in MonumentDetailActivity.class

How to implement custom listview adapter in tabbed activity?

I am trying to implement the custom list view in tabbed activity for youtube video playing app. I could not able to call custom listview adapter in fragment java class. I have tried to pass getActivity() to custom adapter but the app crashes. If any one know the solution please help me.
The java class are as follows:
HomeFragment.java
package layout;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
import in.testapp.app1.R;
public class HomeFragment extends Fragment {
static class Adapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList();
private final List<String> mFragmentTitleList = new ArrayList();
public Adapter(FragmentManager manager) {
super(manager);
}
public Fragment getItem(int position) {
return (Fragment) this.mFragmentList.get(position);
}
public int getCount() {
return this.mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
this.mFragmentList.add(fragment);
this.mFragmentTitleList.add(title);
}
public CharSequence getPageTitle(int position) {
return (CharSequence) this.mFragmentTitleList.get(position);
}
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
ViewPager viewPager = (ViewPager) view.findViewById(R.id.viewpager);
setupViewPager(viewPager);
((TabLayout) view.findViewById(R.id.tablayout)).setupWithViewPager(viewPager);
return view;
}
private void setupViewPager(ViewPager viewPager) {
Adapter adapter = new Adapter(getChildFragmentManager());
adapter.addFragment(new YouTubeFragment(), "Tab 1");
adapter.addFragment(new SecondFragment(), "Tab 2");
viewPager.setAdapter(adapter);
}
}
YouTubeFragment.java
package layout;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import in.testapp.app1.AppUtils;
import in.testapp.app1.ChannelActivity;
import in.testapp.app1.CustomListAdapter;
import in.testapp.app1.R;
import in.testapp.app1.VideoDetails;
public class YouTubeFragment extends Fragment {
String TAG="MainActivity2";
ListView lvVideo;
ArrayList<VideoDetails> videoDetailsArrayList;
CustomListAdapter customListAdapter;
//{youtube_api_key} is replaced by actual key
String URL="https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UC5Eg6bkwsdCd-ZlcB3nt1dg&maxResults=25&key={youtube_api_key}";
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_you_tube, container, false);
lvVideo=(ListView)view.findViewById(R.id.videoList);
videoDetailsArrayList=new ArrayList<>();
//App crashes here in the beolw line
customListAdapter=new CustomListAdapter(getActivity(),videoDetailsArrayList);
//App crashes here in the above line
showVideo();
return view;
}
private void showVideo() {
RequestQueue requestQueue= Volley.newRequestQueue(getContext());
StringRequest stringRequest=new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject=new JSONObject(response);
JSONArray jsonArray=jsonObject.getJSONArray("items");
for(int i=1;i<jsonArray.length();i++){
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
JSONObject jsonVideoId=jsonObject1.getJSONObject("id");
JSONObject jsonsnippet= jsonObject1.getJSONObject("snippet");
JSONObject jsonObjectdefault = jsonsnippet.getJSONObject("thumbnails").getJSONObject("medium");
VideoDetails videoDetails=new VideoDetails();
String videoid=jsonVideoId.getString("videoId");
Log.e(TAG," New Video Id" +videoid);
videoDetails.setURL(jsonObjectdefault.getString("url"));
videoDetails.setVideoName(jsonsnippet.getString("title"));
videoDetails.setVideoDesc(jsonsnippet.getString("description"));
videoDetails.setVideoId(videoid);
videoDetailsArrayList.add(videoDetails);
}
lvVideo.setAdapter(customListAdapter);
customListAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
int socketTimeout = 30000;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
requestQueue.add(stringRequest);
}
}
CustomListAdapter.java
package in.testapp.app1;
import android.app.Activity;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import java.util.ArrayList;
public class CustomListAdapter extends BaseAdapter {
Activity activity;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
private LayoutInflater inflater;
ArrayList<VideoDetails> singletons;
public CustomListAdapter(Activity activity, ArrayList<VideoDetails> singletons) {
this.activity = activity;
this.singletons = singletons;
}
public int getCount() {
return this.singletons.size();
}
public Object getItem(int i) {
return this.singletons.get(i);
}
public long getItemId(int i) {
return (long) i;
}
public View getView(int i, View convertView, ViewGroup viewGroup) {
if (this.inflater == null) {
this.inflater = (LayoutInflater) this.activity.getLayoutInflater();
// getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (convertView == null) {
convertView = this.inflater.inflate(R.layout.videolist, null);
}
if (this.imageLoader == null) {
this.imageLoader = AppController.getInstance().getImageLoader();
}
NetworkImageView networkImageView = (NetworkImageView) convertView.findViewById(R.id.video_image);
final TextView imgtitle = (TextView) convertView.findViewById(R.id.video_title);
final TextView imgdesc = (TextView) convertView.findViewById(R.id.video_descriptio);
final TextView tvURL=(TextView)convertView.findViewById(R.id.tv_url);
final TextView tvVideoID=(TextView)convertView.findViewById(R.id.tv_videoId);
((LinearLayout) convertView.findViewById(R.id.asser)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=new Intent(view.getContext(), VideoActivity.class);
intent.putExtra("videoId",tvVideoID.getText().toString());
view.getContext().startActivity(intent);
}
});
VideoDetails singleton = (VideoDetails) this.singletons.get(i);
networkImageView.setImageUrl(singleton.getURL(), this.imageLoader);
tvVideoID.setText(singleton.getVideoId());
imgtitle.setText(singleton.getVideoName());
imgdesc.setText(singleton.getVideoDesc());
return convertView;
}
}
VideoDeatils.java
package in.testapp.app1;
public class VideoDetails {
String VideoName;
String VideoDesc;
String URL;
String VideoId;
public void setVideoName(String VideoName){
this.VideoName=VideoName;
}
public String getVideoName(){
return VideoName;
}
public void setVideoDesc(String VideoDesc){
this.VideoDesc=VideoDesc;
}
public String getVideoDesc(){
return VideoDesc;
}
public void setURL(String URL){
this.URL=URL;
}
public String getURL(){
return URL;
}
public void setVideoId(String VideoId){
this.VideoId=VideoId;
}
public String getVideoId(){
return VideoId;
}
}

Tablet UI not working

I am working on an app that presents a grid of popular movies to the users and when the user clicks on one of the items, it shows the details of the movie.
The app is working fine on phones but my tablet UI implementation is not working
I don't get any crashes as such it's just that when I tap on a movie, the Details don't show up on tablets.
Here's the link to the GitHub repo - https://github.com/Hackertronix/Project-Motion/tree/Stage_2?files=1
And here are the files which concern with the Tablet UI
activity_movies.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/viewpager_container">
</FrameLayout>
activity_movies.xml (layout-sw600dp )
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:id="#+id/viewpager_container">
<FrameLayout
android:id="#+id/details_container"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
>
</FrameLayout>
</FrameLayout>
</LinearLayout>
</FrameLayout>
MoviesActivity.java
package com.execube.genesis.views.activities;
import android.app.ActivityOptions;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.transition.Explode;
import android.view.View;
import com.execube.genesis.R;
import com.execube.genesis.model.Movie;
import com.execube.genesis.views.fragments.DetailsFragment;
import com.execube.genesis.views.fragments.PopularMoviesFragment;
import com.execube.genesis.views.fragments.TopRatedMoviesFragment;
import com.execube.genesis.views.fragments.ViewPagerFragment;
public class MoviesActivity extends AppCompatActivity implements PopularMoviesFragment.openDetailsListener,
TopRatedMoviesFragment.openDetailsListener{
boolean isTablet;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movies);
if (findViewById(R.id.details_container) == null)//CHECKING FOR TABLET CONFIGURATION
{
isTablet=false;
}
else{
isTablet=true;
}
View view= findViewById(R.id.viewpager_container);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
getWindow().setStatusBarColor(Color.TRANSPARENT);
}
if (Build.VERSION.SDK_INT >= 21) {
getWindow().setExitTransition(new Explode());
}
FragmentManager fragmentManager= getSupportFragmentManager();
Fragment fragment;
fragmentManager.findFragmentById(R.id.viewpager_container);
if(savedInstanceState==null)
{
fragment= new ViewPagerFragment();
fragmentManager.beginTransaction()
.add(R.id.viewpager_container,fragment)
.commit();
}
}
#Override
public void openDetails(Movie movie,ActivityOptions options) {
//options parameter is for the transition
if(isTablet)
{
//TODO Retain the transitions.
Bundle bundle=new Bundle();
bundle.putParcelable("PARCEL",movie);
DetailsFragment fragment= new DetailsFragment();
fragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction()
.replace(R.id.details_container,fragment)
.commit();
}
else{
Intent intent= new Intent(this,DetailsActivity.class);
intent.putExtra("PARCEL",movie);
startActivity(intent,options.toBundle());
}
}
}
DetailsActivity.java
package com.execube.genesis.views.activities;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.transition.Fade;
import android.transition.Slide;
import android.view.Gravity;
import android.view.View;
import com.execube.genesis.R;
import com.execube.genesis.views.fragments.DetailsFragment;
/**
* Created by Prateek Phoenix on 5/1/2016.
*/
public class DetailsActivity extends FragmentActivity {
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
if (Build.VERSION.SDK_INT >= 21) {
getWindow().setStatusBarColor(getResources().getColor(R.color.details_status_bar));
Slide slide=new Slide(Gravity.BOTTOM);
slide.excludeTarget(android.R.id.statusBarBackground,true);
slide.excludeTarget(android.R.id.navigationBarBackground,true);
getWindow().setEnterTransition(slide);
postponeEnterTransition();
}
FragmentManager fragmentManager= getSupportFragmentManager();
Fragment fragment= fragmentManager.findFragmentById(R.id.details_container);
if(fragment==null)
{
Bundle arguments = new Bundle();
arguments.putParcelable("PARCEL",
getIntent().getParcelableExtra("PARCEL"));
fragment = new DetailsFragment();
fragment.setArguments(arguments);
fragmentManager.beginTransaction()
.add(R.id.details_container,fragment)
.commit();
}
}
}
DetailsFragment.java
package com.execube.genesis.views.fragments;
import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import com.execube.genesis.R;
import com.execube.genesis.model.Movie;
import com.execube.genesis.model.Review;
import com.execube.genesis.utils.API;
import com.execube.genesis.utils.OkHttpHandler;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import okhttp3.Call;
import okhttp3.Response;
/**
* Created by Prateek Phoenix on 4/30/2016.
*/
public class DetailsFragment extends Fragment {
private static final String TAG = "DETAILS";
private static final int DEFAULT_NUM_COLORS = 5;
private Movie mMovie;
public Intent intent;
private TextView mDetailTitle;
private TextView mReleaseDate;
private TextView mOverview;
private TextView mOverviewHeader;
private ImageView mBackdrop;
private Toolbar mToolbar;
private RatingBar mRatingBar;
private ArrayList<Review> mReviews;
public DetailsFragment() {
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_detail, container, false);
mBackdrop = (ImageView) view.findViewById(R.id.details_poster);
mToolbar = (Toolbar) view.findViewById(R.id.toolbar);
mDetailTitle = (TextView) view.findViewById(R.id.detail_title_text);
mReleaseDate = (TextView) view.findViewById(R.id.release_date);
mOverview = (TextView) view.findViewById(R.id.overview);
mOverviewHeader = (TextView) view.findViewById(R.id.overview_header);
mRatingBar = (RatingBar) view.findViewById(R.id.movie_rating);
Bundle bundle=getArguments();
mMovie=bundle.getParcelable("PARCEL");
String id = String.valueOf(mMovie.getId());
String reviewQueryUrl = API.MOVIES_BASE_URL + id + "/reviews" + API.API_KEY;
String trailerQueryUrl = API.MOVIES_BASE_URL+id+"/videos"+API.API_KEY;
mDetailTitle.setText(mMovie.getTitle());
mReleaseDate.setText(mMovie.getReleaseDate());
mRatingBar.setProgress((int) mMovie.getVoteAverage());
mOverview.setText(mMovie.getOverview());
if (Build.VERSION.SDK_INT != 21) {
Typeface fontBold = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Gotham-Rounded-Bold.ttf");
Typeface fontMedium = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Gotham-Rounded-Medium.ttf");
Typeface fontMediumLight = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Gotham-Rounded-Book_.ttf");
mDetailTitle.setTypeface(fontBold);
mReleaseDate.setTypeface(fontMedium);
mOverview.setTypeface(fontMediumLight);
mOverviewHeader.setTypeface(fontBold);
}
OkHttpHandler handler = new OkHttpHandler(reviewQueryUrl, mCallback);
handler.fetchData();
Picasso.with(getActivity()).load(API.IMAGE_URL + API.IMAGE_SIZE_500 + mMovie.getPosterPath())
.into(mBackdrop);
getActivity().startPostponedEnterTransition();
return view;
}
private okhttp3.Callback mCallback = new okhttp3.Callback() {
#Override
public void onFailure(Call call, IOException e) {
//TODO handle failure on UI thread
}
#Override
public void onResponse(Call call, Response response) throws IOException,IllegalStateException{
try {
String jsonResponse= response.body().string();
Log.v(TAG,jsonResponse );
JSONObject jsonObject = new JSONObject(jsonResponse);
int resultCount = jsonObject.getInt("total_results");
if (resultCount != 0) {
mReviews = parseReviews(jsonObject);
} else
mReviews = null;
} catch (JSONException e) {
}
catch (IllegalStateException e){}
}
};
private ArrayList<Review> parseReviews(JSONObject jsonObject) throws JSONException {
ArrayList<Review> Reviews = new ArrayList<>();
JSONArray reviewsJSONArray = jsonObject.getJSONArray("results");
for (int i = 0; i < reviewsJSONArray.length(); i++) {
Review review = new Review();
JSONObject reviewJson = reviewsJSONArray.getJSONObject(i);
review.setId(reviewJson.getInt("id"));
review.setAuthor(reviewJson.getString("author"));
review.setContent(reviewJson.getString("content"));
review.setTotalResults(reviewJson.getInt("total_results"));
Reviews.add(review);
}
return Reviews;
}
}
I think you should write same xml file for mobile and tablet in layout and
layout-sw600dp folder. System will pick by folder name. If you will open in phone it picks up layout from layout folder and if you will open in tablet it picks up
layout from layout-sw600dp folder.

Categories

Resources