ViewPager Not getting Images from server - java

I am using ViewPager in my app and fetch the data(Images) from server(with JSON). Even if runs smoothly no image is shown in the viewpager.
I read so many tutorial regarding this, but nobody solve my problem. Please tell me where i am wrong...
Here is my code:
view_pager.xml
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="40dp" />
image_view.xml
<ImageView
android:id="#+id/image_adapter"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"/>
ViewPager_Adapter.java
public class ViewPager_Adapter extends PagerAdapter {
private String urls;
private LayoutInflater inflater;
private Context context;
ArrayList<String> mylist;
public ViewPager_Adapter(Context context, ArrayList<String> mylist) {
this.context = context;
this.urls = urls;
this.mylist = mylist;
inflater = LayoutInflater.from(context);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public int getCount() {
return mylist.size();
}
#Override
public Object instantiateItem(ViewGroup view, int position) {
View imageLayout = inflater.inflate(R.layout.image_view, null);
assert imageLayout != null;
final ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image_adapter);
Glide.with(context)
.load(mylist.get(position))
.into(imageView);
view.addView(imageLayout,0);
return imageLayout;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
#Override
public Parcelable saveState() {
return null;
}
}
View_Pager.Java
public class View_Pager extends Fragment {
private static ViewPager mPager;
JSONArray responsearray = null;
String imageOne;
private static final String TAG_PHOTO_ONE = "Gallery_Full";
ArrayList<String> myList;
HashMap<String, String> get;
ViewPager_Adapter viewpager_adapter;
LinearLayout addimages;
int REQUEST_CODE = 100;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.view_pager, null);
mPager = view.findViewById(R.id.viewpager);
new GetImages().execute(true);
return view;
}
class GetImages extends AsyncTask<Boolean, Void, String> {
#Override
protected String doInBackground(Boolean... booleans) {
ImageApi imageApi = new ImageApi();
String result = null;
try {
result = imageApi.galleryget(sharedPreferences.getString("id", ""));
JSONObject object = new JSONObject(result);
if (object.getString("error").equalsIgnoreCase("false")) {
responsearray = object.getJSONArray("response");
return "true";
} else {
String errormsg = object.getString(result);
return errormsg;
}
} catch (ApiException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (s != null) {
if (s.equalsIgnoreCase("true")) {
showList(responsearray);
}
}
}
}
public void showList(final JSONArray responsearray) {
try {
for (int i = 0; i < responsearray.length(); i++) {
JSONObject responseObject = responsearray.getJSONObject(i);
Log.e("COUNT" + i, String.valueOf(responseObject));
imageOne = responseObject.getString(TAG_PHOTO_ONE);
get = new HashMap<>();
get.put(TAG_PHOTO_ONE, imageOne);
myList = new ArrayList<>();
myList.add(String.valueOf(get));
}
viewpager_adapter = new ViewPager_Adapter(getActivity(), myList);
String test = String.valueOf(myList);
String imgpath = getString(R.string.imgpath);
String finalimgpath = imgpath + imageOne;
Log.e("FINALPATH", finalimgpath);
} catch (JSONException e) {
e.printStackTrace();
}
mPager.setAdapter(viewpager_adapter);
viewpager_adapter.notifyDataSetChanged();
}
}

Use this code for showList() as you are not populating you're arrayList properly the data is being over write in one position .
So , what you have to do is initialize it out side of for loop .
public void showList(final JSONArray responsearray) {
try {
//here
myList = new ArrayList<>();
for (int i = 0; i < responsearray.length(); i++) {
JSONObject responseObject = responsearray.getJSONObject(i);
Log.e("COUNT" + i, String.valueOf(responseObject));
imageOne = responseObject.getString(TAG_PHOTO_ONE);
get = new HashMap<>();
get.put(TAG_PHOTO_ONE, imageOne);
myList.add(String.valueOf(get));
}
viewpager_adapter = new ViewPager_Adapter(getActivity(), myList);
String test = String.valueOf(myList);
String imgpath = getString(R.string.imgpath);
String finalimgpath = imgpath + imageOne;
Log.e("FINALPATH", finalimgpath);
} catch (JSONException e) {
e.printStackTrace();
}
mPager.setAdapter(viewpager_adapter);
viewpager_adapter.notifyDataSetChanged();
}
Edit
Also if your final image path is as below then you have to update your code in adapter for image path as follow.
Update position in view.addView() too.
String test = String.valueOf(mylist.get(position));
String imgpath = getString(R.string.imgpath);
String finalimgpath = imgpath + test;
Glide.with(context)
.load(finalimgpath)
.into(imageView);
view.addView(imageLayout,position);
return imageLayout;

In your For loop you are initialising your list everytime
for (int i = 0; i < responsearray.length(); i++) {
JSONObject responseObject = responsearray.getJSONObject(i);
Log.e("COUNT" + i, String.valueOf(responseObject));
imageOne = responseObject.getString(TAG_PHOTO_ONE);
get = new HashMap<>();
get.put(TAG_PHOTO_ONE, imageOne);
myList = new ArrayList<>(); // THIS IS WRONG. don't initialise every time
myList.add(String.valueOf(get)); // THIS IS ALSO WRONG. you are adding hashmap object to list
}
So make your for loop like this
myList = new ArrayList<>();
for (int i = 0; i < responsearray.length(); i++) {
JSONObject responseObject = responsearray.getJSONObject(i);
Log.e("COUNT" + i, String.valueOf(responseObject));
imageOne = responseObject.getString(TAG_PHOTO_ONE);
get = new HashMap<>();
get.put(TAG_PHOTO_ONE, imageOne);
myList.add(imageOne);
}

Related

Cant get ArrayList from another class. Its always empty

im still Android beginner and new to Stackowerflow, i hope you will understand my problem. Im using Volley libary and Singleton class. I have JsonParser class which after parsing should return the filled list with objects.
public class JsonParse {
Context context;
public ArrayList<ParseItem> parseItemList = new ArrayList<>();
String json_url = "myurl";
public JsonParse(Context context) {
this.context = context;
}
public ArrayList<ParseItem> getList() {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, json_url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
ParseItem parseItem = new ParseItem();
String naslov = jsonObject.getString("naslov");
String url = jsonObject.getString("url");
parseItem.setTitle(naslov);
parseItem.setUrl(url);
JSONArray niz = jsonObject.getJSONArray("niz");
ArrayList<String> podnaslovTMP = new ArrayList<>();
ArrayList<String> podurlTMP = new ArrayList<>();
for (int j = 0; j < niz.length(); j++) {
JSONObject nizOBJ = niz.getJSONObject(j);
String podnaslov = nizOBJ.getString("podnaslov");
String podurl = nizOBJ.getString("podurl");
podnaslovTMP.add(podnaslov);
podurlTMP.add(podurl);
}
parseItemList.add(parseItem);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
MySingleton.getInstance(context).addToRequestQueue(jsonArrayRequest);
return parseItemList;
}}
Then im trying to call getList and take my list i HomeFragment.
public class HomeFragment extends Fragment implements View.OnClickListener {
private Context context;
private static final int REQUEST_CALL = 1;
private View view;
private ParseItem parseItem = new ParseItem();
public ArrayList<ParseItem>arrayList = new ArrayList<>();
public HomeFragment() {
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable final ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_home, container, false);
init();
JsonParse jsonParse = new JsonParse(getActivity());
arrayList = jsonParse.getList();
return view;
}
My arrayList is always empty. I hope someone can help me.
create listner
public interface GetArrayListListner{
void getArrayData(ArrayList<ParseItem>);
}
and
public class JsonParse {
private GetArrayListListner arrayListListner;// add this line
Context context;
public ArrayList<ParseItem> parseItemList = new ArrayList<>();
String json_url = "myurl";
public JsonParse(Context context,GetArrayListListner arrayListListner) {
this.context = context;
this.arrayListListner = arrayListListner; //Add this line
}
public void getList() {
new JsonArrayRequest(Request.Method.POST, json_url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
ParseItem parseItem = new ParseItem();
String naslov = jsonObject.getString("naslov");
String url = jsonObject.getString("url");
parseItem.setTitle(naslov);
parseItem.setUrl(url);
JSONArray niz = jsonObject.getJSONArray("niz");
ArrayList<String> podnaslovTMP = new ArrayList<>();
ArrayList<String> podurlTMP = new ArrayList<>();
for (int j = 0; j < niz.length(); j++) {
JSONObject nizOBJ = niz.getJSONObject(j);
String podnaslov = nizOBJ.getString("podnaslov");
String podurl = nizOBJ.getString("podurl");
podnaslovTMP.add(podnaslov);
podurlTMP.add(podurl);
}
parseItemList.add(parseItem);
} catch (JSONException e) {
e.printStackTrace();
}
}
arrayListListner.getArrayData(parseItemList);//add this line
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
MySingleton.getInstance(context).addToRequestQueue(jsonArrayRequest);
return parseItemList;
}
}
and call it
JsonParse jsonParse = new JsonParse(getActivity(),new GetArrayListListner(){
#Overrid void getArrayData(ArrayList<ParseItem>){
arrayList = jsonParse.getList();
}
});
Your method getList() calls a web service, which is executed on a separate thread. When you use MySingleton.getInstance(context).addToRequestQueue(jsonArrayRequest);
you are placing the request to a Queue, that means it is not gonna be executed right now, but you are already returning your array. As the request hasn't been executed yet, your array list hasn't been filled yet.
The practice recommended by Google today is using LiveData, it can be hard to a beginner, but with a little study, you can solve it.
https://developer.android.com/topic/libraries/architecture/livedata
Maybe you can look at Reactive Programming as well.
Another easy solution would be using interfaces, so you can pass the interface as a parameter, which will be triggered when your array gets filled.
Let me know if I was of any help, thanks

Unable to fetch images in Grid view

Main Activity:
public class MainActivity extends AppCompatActivity {
// ImageView iv;
public static StringBuffer finalparsedData;
public static GridView myGrid;
private static final String TAG = MainActivity.class.getSimpleName();
ArrayList<String> values = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myGrid=(GridView)findViewById(R.id.grid_view);
Button btnHit = (Button) findViewById(R.id.btnHit);
btnHit.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
new JSONTask().execute("https://api.flickr.com/services/rest/?method=flickr.photos.getRecent&" +
"api_key=46e71c8d2b35ba8c9c333a462ec8aea7&per_page=3&format=json&nojsoncallback=10");
}
});
values = new ArrayList<>();
}
/*static boolean isAirplaneModeOn(Context context) {
ContentResolver contentResolver = context.getContentResolver();
return Settings.System.getInt(contentResolver, AIRPLANE_MODE_ON, 0) != 0;
}*/
public class JSONTask extends AsyncTask<String, Void, String> {
String photoid;
int farm;
String server;
String secret;
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
StringBuffer buffer = null;
JSONArray parentarray = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
//JSONObject initialObject = new JSONObject("photos");
JSONObject initialObject = parentObject.getJSONObject("photos");
parentarray = initialObject.getJSONArray("photo");
finalparsedData = new StringBuffer();
for (int i = 0; i < parentarray.length(); i++) {
JSONObject finalObject = parentarray.getJSONObject(i);
photoid = finalObject.optString("id");
farm = finalObject.optInt("farm");
server = finalObject.optString("server");
secret = finalObject.optString("secret");
finalparsedData.append("https://farm" + farm + ".staticflickr.com/" + server + "/" + photoid+ "_" + secret + ".jpg" +"\n\n");
values.add(String.valueOf((finalparsedData)));
}
return "done";
} catch (MalformedURLException e) {
e.printStackTrace();
return "error";
} catch (IOException e) {
e.printStackTrace();
return "error";
} catch (JSONException e) {
e.printStackTrace();
return "error";
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
return "done";
}
} catch (IOException e) {
e.printStackTrace();
return "error";
}
}
}
#Override
protected void onPostExecute(String result) {
switch (result){
case "done":
MyImageAdapter adapter = new MyImageAdapter(MainActivity.this, values);
myGrid.setAdapter((ListAdapter) adapter);
break;
}
}
}
}
MyAdapterClass:
public class MyImageAdapter extends BaseAdapter {
ArrayList<String> values;
Context mContext;
public MyImageAdapter(Context mContext, ArrayList<String> values) {
this.values = values;
this.mContext = mContext;
}
#Override
public int getCount() {
return values.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder;
;
if (row == null){
LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.grid,parent,false);
holder = new ViewHolder();
holder.imageView = (ImageView) row.findViewById(R.id.image_View);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
String image = values.get(position);
Picasso.with(mContext).load(image).into(holder.imageView);
return row;
}
public class ViewHolder {
ImageView imageView;
}
}
I got a problem during images loading in gridview, out of 10 images only 1 image is shown and rest of them showing "this images is no longer available"
Hahaha, silly mistake. Just replace your for loop inside JSONTask with this,
.
.
.
for (int i = 0; i < parentarray.length(); i++) {
JSONObject finalObject = parentarray.getJSONObject(i);
photoid = finalObject.optString("id");
farm = finalObject.optInt("farm");
server = finalObject.optString("server");
secret = finalObject.optString("secret");
String fullPath = "https://farm" + farm + ".staticflickr.com/" + server + "/" + photoid+ "_" + secret + ".jpg";
values.add(fullPath);
}
.
.
.
No need to use StringBuffer. You should use normal String variable. :)

Create another ArrayList to populate a spinner in Android

I need to create another ArrayList with string values to fill a state spinner. When I initialize the application, the state spinner view is displaying blank data. Like this SS right here
Follow the code below.
public class Activity {
private Spinner states;
private Spinner cities;
ArrayList<String> statesList;
ArrayList<String> citiesList;
private void findcomponents() {
states = (Spinner) findViewById(R.id.spinner_cadastro_estado);
cities = (Spinner) findViewById(R.id.spinner_cadastro_cidade);
loadStatesAndCities();
states.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
State state = (State) states.getSelectedItem();
cities.setAdapter(new ArrayAdapter<>(Activity.this, android.R.layout.simple_spinner_dropdown_item, state.getCities()));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
cities.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void loadStatesAndCities() {
try {
JSONObject jsonObject = new JSONObject(loadJSONFromAsset());
JSONArray statesArray = jsonObject.getJSONArray("estados");
List<City> citiesList;
List<State> statesList;
statesList = new ArrayList<>();
for (int i = 0; i < statesArray.length(); i++) {
JSONObject states_object = statesArray.getJSONObject(i);
String estadoSigla = states_object.optString("sigla");
JSONArray citiesArray = states_object.getJSONArray("cidades");
citiesList = new ArrayList<>();
for (int j = 0; j < citiesArray.length(); j++) {
String cities_data = citiesArray.getString(j);
citiesList.add(new City(cities_data));
}
statesList.add(new State(estadoSigla,citiesList));
}
ArrayAdapter<State> stateAdapter;
stateAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, statesList);
stateAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
states.setAdapter(stateAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("estados-cidades.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}

Android how can i get value of ArrayList Hashmap in my baseadapter

I have an Activity called Myprofile and a baseAdapter called Myprofile_CustomView on my activity I get Json data which then I convert into a ArrayList with a hashmap and my question is how can I retrieve the values of the hashmap in the baseadapter ?
This is my activity Myprofile
public class Myprofile extends Activity {
String URI_URL;
Integer page;
ProgressBar pb;
ListView mm;
Myprofile_CustomView BA;
ArrayList<HashMap<String,String>> userslist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myprofile);
URI_URL = getResources().getString(R.string.PathUrl) + "/api/myprofile";
page=0;
// Listview for adapter
mm= (ListView)findViewById(R.id.myprofiles);
new Myprofile_Async().execute();
}
public class Myprofile_Async extends AsyncTask<String,String,String> {
HttpURLConnection conn;
URL url;
String result="";
DataOutputStream wr;
int id;
#Override
protected void onPreExecute() {
super.onPreExecute();
pb=(ProgressBar)findViewById(R.id.progressBar);
pb.setVisibility(View.VISIBLE);
id= getIntent().getExtras().getInt("id");
// page Int is used to keep count of scroll events
if(page==0)
{page=1;}
else {page=page+1;}
Toast.makeText(Myprofile.this,""+page,Toast.LENGTH_SHORT).show();
}
#Override
protected String doInBackground(String... params) {
// Gets data from api
BufferedReader reader=null;
String cert="id="+id+"&page="+page;
try{
url = new URL(URI_URL);
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.connect();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(cert);
wr.flush();
wr.close();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sBuilder = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
sBuilder.append(line + "\n");
}
result = sBuilder.toString();
reader.close();
conn.disconnect();
return result;
}
catch (Exception e)
{
e.printStackTrace();
}
System.err.println("cassies" + result);
return result;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
HashMap<String,String> map= new HashMap<>();
JSONObject jsonn= new JSONObject(result);
JSONArray jArray = jsonn.getJSONArray("myprofile");
JSONObject jobject=null;
JSONArray sss= new JSONArray();
for(int i=0; i < jArray.length(); i++) {
jobject= jArray.getJSONObject(i);
map.put("fullname",jobject.getString("fullname"));
sss.put(jobject);
}
jsonn.put("myprofile", sss);
// Add values to arrayList
userslist.add(map);
// Send information to BaseAdapter
BA= new Myprofile_CustomView(userslist,Myprofile.this);
mm.setAdapter(BA);
} catch (Exception e) {
System.err.println("mpee: " + e.toString());
}
pb.setVisibility(View.INVISIBLE);
}
}
}
this part above I have no issues with my problem is in the BaseAdapter with the ArrayList userList I don't know how to get HashMap keys from it. I am naming the keys because I have other fields that I will eventually do
public class Myprofile_CustomView extends BaseAdapter {
JSONObject names;
Context ctx;
LayoutInflater myiflater;
ArrayList<HashMap<String,String>> usersList;
// Have data come in and do a toast to see changes
public Myprofile_CustomView(ArrayList<HashMap<String,String>> arr, Context c) {
notifyDataSetChanged();
ctx = c;
usersList= arr;
myiflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
try {
JSONArray jaLocalstreams = names.getJSONArray("myprofile");
return jaLocalstreams.length();
} catch (Exception e) {
Toast.makeText(ctx, "Error: Please try again", Toast.LENGTH_LONG).show();
return names.length();
}
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row=convertView;
MyViewHolder holder=null;
try {
if(row==null) {
LayoutInflater li = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = li.inflate(R.layout.zmyprofile,parent,false);
holder=new MyViewHolder(row);
row.setTag(holder);
}
else
{
holder=(MyViewHolder)row.getTag();
}
// How can I get HashMap value for fullname here so I can set it to to Text
String fullname= usersList
holder.fullname.setText(fullname);
return row;
} catch (Exception e) {
e.printStackTrace();
}
return row;
}
class MyViewHolder{
TextView fullname;
MyViewHolder(View v)
{
fullname= (TextView)v.findViewById(R.id.fullname);
}
}
}
getCount should return the size of your dataset. In your case usersList
public int getCount() {
return usersList == null ? 0 : userLists.size();
}
int getView you want to retrieve the item at position:
HashMap<String, String> item = usersList.get(i);
String fullname = item.get("fullname");
the value of position changes with the scrolling,

Issues connecting to RecyclerView and CardAdapter to database

So my issue comes up with context in the library fragment. I get the following error.
CardAdapter(Android.content.Context, in ArrayList<Card> in
CardAdapter cannot be applied to Library ArrayList<Card>
I've got some of this code from a friend thankfully but we can't seem to figure out the difference/error in it.
In Library.java:
public class Library extends Fragment {
// Private variables
private RecyclerView recyclerView;
private CardAdapter cardAdapter;
private ArrayList<Card> cardArrayList;
private ArrayList<Card> tempList;
public Library() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate view
View view = inflater.inflate(R.layout.library, container, false);
// Find recyclerView
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
// Initialize cardArrayList
cardArrayList = new ArrayList<>();
// Initialize cardAdapter
cardAdapter = new CardAdapter(this.getContext(), cardArrayList);
// Initialize recyclerView
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(this.getContext(), 1);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(cardAdapter);
// Populate cardArrayList with test Cards
testCards();
// Return inflated view
return view;
}
public URL createURL(String constraint) {
try {
StringBuilder urlString = new StringBuilder();
//System.out.print(constraint);
if (constraint.length() > 0) {
urlString.append("https://camerondewey.000webhostapp.com/android_podcast_connect.php");
urlString.append(constraint);
System.out.print(urlString.toString());
}
String muhURL = urlString.toString();
//System.out.print(muhURL);
URL myURL = new URL(muhURL);
System.out.print(myURL);
return myURL;
//return new URL(muhURL);
} catch (Exception e) {
System.out.print("Failed to return url");
}
return null;
}
public class GetCardTask extends AsyncTask<URL, Void, JSONArray> {
#Override
protected JSONArray doInBackground(URL... params) {
//System.out.print("Params: " + params[0]);
HttpURLConnection connection = null;
StringBuilder result = new StringBuilder();
try {
connection = (HttpURLConnection) params[0].openConnection();
//System.out.println(connection.getResponseCode());
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
try {
//System.out.print("SUCCESS");
return new JSONArray(result.toString());
} catch (JSONException je) {
//System.out.print("FAILURE2");
JSONArray jArray = new JSONArray();
jArray.put(new JSONObject(result.toString()));
return jArray;
}
} else {
throw new Exception();
}
} catch (Exception e) {
System.out.print("FAILURE1");
e.printStackTrace();
} finally {
connection.disconnect();
}
return null;
}
#Override
protected void onPostExecute(JSONArray article) {
if (article != null) {
convertJSONtoArrayList(article);
Library.this.updateDisplay();
} else {
System.out.print("failure to execute json conversion");
}
}
}
private void convertJSONtoArrayList(JSONArray articles) {
cardArrayList = new ArrayList<Card>(); // clear old player data
tempList = new ArrayList<Card>();
try {
for (int i = 0; i < articles.length(); i++) {
JSONObject currentArticle = articles.getJSONObject(i);
cardArrayList.add(new Card(
currentArticle.has("name") ? currentArticle.getString("name") : "No Headline",
currentArticle.has("description") ? currentArticle.getString("description") : "No Name"
));
tempList.add(new Card(
currentArticle.has("name") ? currentArticle.getString("name") : "No Headline",
currentArticle.has("description") ? currentArticle.getString("description") : "No Name"
));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private void updateDisplay() {
if (cardArrayList == null) {
System.out.print("Display failed to update");
}
ArrayList<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();
for (Card item : cardArrayList) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", item.getCardName());
map.put("description", item.getDescription());
data.add(map);
}
int resource = R.layout.card;
String[] from = {"name", "description"};
int[] to = {R.id.card_name, R.id.podcast_desc};
//The error happens here.
CardAdapter cardAdapter = new CardAdapter(this, cardArrayList);
recyclerView.setAdapter(cardAdapter);
cardAdapter.notifyDataSetChanged();
}
In CardAdapter.java
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.CardViewHolder> implements Filterable {
// Private variables
private Context cardContext;
ArrayList<Card> cardList, filteredList;
public class CardViewHolder extends RecyclerView.ViewHolder{
public View view;
public TextView cardName;
public Card currentItem;
public CardViewHolder(View v) {
// Invoke super on view
super(v);
view = v;
this.cardName = (TextView) v.findViewById(R.id.card_name);
v.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
Intent i = new Intent(v.getContext(),PodcastPage.class);
//item clicked
v.getContext().startActivity(i);
}
});
// Find cardText
cardName = (TextView) view.findViewById(R.id.card_name);
}
}
public CardAdapter(Context c, ArrayList<Card> l) {
this.cardContext = c;
this.cardList = l;
this.filteredList = l;
}
#Override
public CardViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card, null);
return new CardViewHolder(view);
}
#Override
public void onBindViewHolder(final CardViewHolder holder, int position) {
Card card = cardList.get(position);
holder.currentItem = cardList.get(position);
holder.cardName.setText(card.getCardName());
}
#Override
public int getItemCount() {
return filteredList.size();
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence query) {
FilterResults results = new FilterResults();
if (query != null && query.length() > 0) {
query = query.toString().toUpperCase();
ArrayList<Card> searchResults = new ArrayList<Card>();
for (int i = 0; i < filteredList.size(); i++) {
if (filteredList.get(i).getCardName().toUpperCase().contains(query)) {
searchResults.add(filteredList.get(i));
}
else if (filteredList.get(i).getDescription().toUpperCase().contains(query)) {
searchResults.add(filteredList.get(i));
}
}
results.count = searchResults.size();
results.values = searchResults;
}
else {
results.count = filteredList.size();
results.values = filteredList;
}
return results;
}
#Override
protected void publishResults(CharSequence query, FilterResults results) {
filteredList = (ArrayList<Card>) results.values;
notifyDataSetChanged();
System.out.println(filteredList);
}
};
}
}
In your code in the line CardAdapter cardAdapter = new CardAdapter(this, cardArrayList); this is not a Context but a Fragment. Change the line to this:
CardAdapter cardAdapter = new CardAdapter(getActivity(), cardArrayList);

Categories