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);
Related
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);
}
I'm new coder of android and trying to get list of images in my server and database(mysql) but I got error and I don't know what is causing it...
the error is 'E/RecyclerView: No adapter attached; skipping layout' and it happen when I'm running, anyone can help me??
public class LoadListFromServer extends AsyncTask<String, Void, String> {
private RecyclerView recyclerView;
private Context context;
private ArrayList<ImageGalleryItem> imageGalleryItems;
private boolean pattern;
public LoadListFromServer(RecyclerView recyclerView, Context context, boolean pattern) {
this.recyclerView = recyclerView;
this.context = context;
this.pattern = pattern;
}
public ArrayList<ImageGalleryItem> getImageGalleryItems() {
return imageGalleryItems;
}
#Override
protected String doInBackground(String... strings) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Content-type", "application/json");
int responseCode = urlConnection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
return readStream(urlConnection.getInputStream());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(context,2);
recyclerView.setLayoutManager(layoutManager);
imageGalleryItems = prepareData(response);
MyAdapter adapter = new MyAdapter(context, imageGalleryItems);
recyclerView.setAdapter(adapter);
}
private String readStream(InputStream in) {
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(in, "UTF-8"), 8);
String line = "";
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response.toString();
}
private ArrayList<ImageGalleryItem> prepareData(String response) {
ArrayList<ImageGalleryItem> result = null;
try {
JSONArray jsonArray = new JSONArray(response);
result = new ArrayList<>(jsonArray.length());
for (int i=0; i < jsonArray.length(); i++) {
try {
JSONObject oneObject = jsonArray.getJSONObject(i);
String id = oneObject.getString("id");
String name = oneObject.getString("name");
result.add(new ImageGalleryItem(name, Long.parseLong(id), pattern));
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
if(result == null) {
return new ArrayList<>();
} else {
return result;
}
}
}
I wrote my adapter as MyAdapter.java:
class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private ArrayList<ImageGalleryItem> galleryList;
public MyAdapter(Context context, ArrayList<ImageGalleryItem> galleryList) {
this.galleryList = galleryList;
}
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cell_layout, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(MyAdapter.ViewHolder viewHolder, int i) {
final ImageGalleryItem imageGalleryItem = galleryList.get(i);
viewHolder.title.setText(imageGalleryItem.getName());
viewHolder.img.setScaleType(ImageView.ScaleType.FIT_XY);
String imageFolderName;
final boolean isPattern = imageGalleryItem.isPattern();
if(isPattern) {
imageFolderName = viewHolder.img.getContext().getString(R.string.patterns_directory);
} else {
imageFolderName = viewHolder.img.getContext().getString(R.string.collections_directory);
}
LoadSVGFromServer loadSVGFromServer = new LoadSVGFromServer(viewHolder.img);
loadSVGFromServer.execute(viewHolder.img.getContext().getString(R.string.server_base_address)
+ imageFolderName
+ imageGalleryItem.getID() + ".svg");
viewHolder.img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Activity activity = (Activity) v.getContext();
if(isPattern) {
Intent intent = new Intent(activity, ColoringActivity.class);
Bundle b = new Bundle();
b.putSerializable(activity.getString(R.string.CURRENT_COLLECTION_BUNDLE_KEY), imageGalleryItem);
intent.putExtras(b);
activity.startActivity(intent);
} else {
Intent intent = new Intent(activity, ShowPatternsActivity.class);
Bundle b = new Bundle();
b.putSerializable(activity.getString(R.string.CURRENT_COLLECTION_BUNDLE_KEY), imageGalleryItem);
intent.putExtras(b);
activity.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return galleryList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView title;
private ImageView img;
public ViewHolder(View view) {
super(view);
title = (TextView)view.findViewById(R.id.title);
img = (ImageView) view.findViewById(R.id.img);
}
}
}
You can setup your recyclerView and set items when data received.
activity code for setup recycler view:
public class MainActivity extends AppCompatActivity {
private MyAdapter mAdapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupRecyclerView();
}
private void setupRecyclerView(){
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(context,2);
recyclerView.setLayoutManager(layoutManager);
mAdapter = new MyAdapter(context);
recyclerView.setAdapter(mAdapter);
}
}
Pass adapter to async task:
public class LoadListFromServer extends AsyncTask<String, Void, String> {
private MyAdapter mAdapter;
private Context context;
private ArrayList<ImageGalleryItem> imageGalleryItems;
private boolean pattern;
public LoadListFromServer(MyAdapter adapter, Context context, boolean pattern) {
this.mAdapter = adapter;
this.context = context;
this.pattern = pattern;
}
public ArrayList<ImageGalleryItem> getImageGalleryItems() {
return imageGalleryItems;
}
#Override
protected String doInBackground(String... strings) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Content-type", "application/json");
int responseCode = urlConnection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
return readStream(urlConnection.getInputStream());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
imageGalleryItems = prepareData(response);
mAdapter.setItems(imageGalleryItems);
}
private String readStream(InputStream in) {
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(in, "UTF-8"), 8);
String line = "";
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response.toString();
}
private ArrayList<ImageGalleryItem> prepareData(String response) {
ArrayList<ImageGalleryItem> result = null;
try {
JSONArray jsonArray = new JSONArray(response);
result = new ArrayList<>(jsonArray.length());
for (int i=0; i < jsonArray.length(); i++) {
try {
JSONObject oneObject = jsonArray.getJSONObject(i);
String id = oneObject.getString("id");
String name = oneObject.getString("name");
result.add(new ImageGalleryItem(name, Long.parseLong(id), pattern));
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
if(result == null) {
return new ArrayList<>();
} else {
return result;
}
}
}
Adapter with setItems method:
class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private ArrayList<ImageGalleryItem> galleryList;
public MyAdapter(Context context) {
}
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cell_layout, viewGroup, false);
return new ViewHolder(view);
}
public void setItems(ArrayList<ImageGalleryItem> galleryList){
this.galleryList = galleryList;
notifyDataSetChanged();
}
#Override
public void onBindViewHolder(MyAdapter.ViewHolder viewHolder, int i) {
final ImageGalleryItem imageGalleryItem = galleryList.get(i);
viewHolder.title.setText(imageGalleryItem.getName());
viewHolder.img.setScaleType(ImageView.ScaleType.FIT_XY);
String imageFolderName;
final boolean isPattern = imageGalleryItem.isPattern();
if(isPattern) {
imageFolderName = viewHolder.img.getContext().getString(R.string.patterns_directory);
} else {
imageFolderName = viewHolder.img.getContext().getString(R.string.collections_directory);
}
LoadSVGFromServer loadSVGFromServer = new LoadSVGFromServer(viewHolder.img);
loadSVGFromServer.execute(viewHolder.img.getContext().getString(R.string.server_base_address)
+ imageFolderName
+ imageGalleryItem.getID() + ".svg");
viewHolder.img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Activity activity = (Activity) v.getContext();
if(isPattern) {
Intent intent = new Intent(activity, ColoringActivity.class);
Bundle b = new Bundle();
b.putSerializable(activity.getString(R.string.CURRENT_COLLECTION_BUNDLE_KEY), imageGalleryItem);
intent.putExtras(b);
activity.startActivity(intent);
} else {
Intent intent = new Intent(activity, ShowPatternsActivity.class);
Bundle b = new Bundle();
b.putSerializable(activity.getString(R.string.CURRENT_COLLECTION_BUNDLE_KEY), imageGalleryItem);
intent.putExtras(b);
activity.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return galleryList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView title;
private ImageView img;
public ViewHolder(View view) {
super(view);
title = (TextView)view.findViewById(R.id.title);
img = (ImageView) view.findViewById(R.id.img);
}
}
}
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,
I'm trying to pass an Arraylist with Objects obtained from a JSON, and pass to another fragment in Android Studio.
Here is the class that i want to receive the array
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_car, container, false);
new AsyncTaskParseJson().execute();
mRecyclerView = (RecyclerView) view.findViewById(R.id.rv_list);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.addOnItemTouchListener(new RecyclerViewTouchListener( getActivity(), mRecyclerView, this ));
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
llm.setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(llm);
CarAdapter adapter = new CarAdapter(getActivity(), mList);
mRecyclerView.setAdapter( adapter );
return view;
}
That is my class that is creating the array:
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
final String TAG = "AsyncTaskParseJson.java";
String yourJsonStringUrl = "http://marciowelben.servidorturbo.net/getjson.php";
JSONArray dataJsonArr = null;
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(String... arg0) {
try {
JsonParser jParser = new JsonParser();
JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);
dataJsonArr = json.getJSONArray("emp_info");
for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(i);
// Storing each json item in variable
String firstname = c.getString("employee name");
String lastname = c.getString("employee no");
Car d = new Car(firstname, lastname, R.mipmap.ic_launcher );
listAux.add(d);
}
} catch (JSONException e) {
e.printStackTrace();
}
mList = listAux;
return null;
}
}
So i just want to populate my Recyclerview with this array.
Since you are adding the adapter first before waiting for the data to return you will have to call notifyDataSetChanged() for the adapter to redraw the list after it is done parsing. Another way of accomplishing this is waiting for the result to come back and then set the adapter. See below
public class MainActivity extends AppCompatActivity {
private static final String TAG = "RecyclerViewExample";
private List<FeedItem> feedItemList = new ArrayList<FeedItem>();
private RecyclerView mRecyclerView;
private MyRecyclerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* Initialize recyclerview */
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
/*Downloading data from below url*/
final String url = "http://javatechig.com/api/get_category_posts/?dev=1&slug=android";
new AsyncHttpTask().execute(url);
}
public class AsyncHttpTask extends AsyncTask<String, Void, Integer> {
#Override
protected void onPreExecute() {
setProgressBarIndeterminateVisibility(true);
}
#Override
protected Integer doInBackground(String... params) {
InputStream inputStream = null;
Integer result = 0;
HttpURLConnection urlConnection = null;
try {
/* forming th java.net.URL object */
URL url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
/* for Get request */
urlConnection.setRequestMethod("GET");
int statusCode = urlConnection.getResponseCode();
/* 200 represents HTTP OK */
if (statusCode == 200) {
BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
response.append(line);
}
parseResult(response.toString());
result = 1; // Successful
}else{
result = 0; //"Failed to fetch data!";
}
} catch (Exception e) {
Log.d(TAG, e.getLocalizedMessage());
}
return result; //"Failed to fetch data!";
}
#Override
protected void onPostExecute(Integer result) {
setProgressBarIndeterminateVisibility(false);
/* Download complete. Lets update UI */
if (result == 1) {
adapter = new MyRecyclerAdapter(MainActivity.this, feedItemList);
mRecyclerView.setAdapter(adapter);
} else {
Log.e(TAG, "Failed to fetch data!");
}
}
}
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONArray posts = response.optJSONArray("posts");
/*Initialize array if null*/
if (null == feedItemList) {
feedItemList = new ArrayList<FeedItem>();
}
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.optJSONObject(i);
FeedItem item = new FeedItem();
item.setTitle(post.optString("title"));
item.setThumbnail(post.optString("thumbnail"));
feedItemList.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
1.Design Recycleview in layout
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="10dp"
android:layout_weight="1"
/>
2.add dependency in gradle.build
compile 'com.android.support:recyclerview-v7:23.1.1'
3.Write the code in Activity
public class DoctorInformationActivity extends AppCompatActivity {
String URL="YOUR URL";
JSONArray Cities=null;
ArrayList<DocotorInformation> doctorList =new ArrayList<DocotorInformation>();
Sqlitedatabase sql;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.doctor_information_listview);
sql=new Sqlitedatabase(getApplicationContext());
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if(activeNetworkInfo != null && activeNetworkInfo.isConnected())
{
Toast.makeText(getApplicationContext()," connect",Toast.LENGTH_LONG).show();
new JSONAsyncTask().execute();
}
else
{
ArrayList<DocotorInformation> listdata=sql.getAllContacts();
doctorList=listdata;
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
DoctorAdapter mAdapter = new DoctorAdapter(getApplicationContext(), doctorList);
recyclerView.setAdapter(mAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
Toast.makeText(getApplicationContext(),"Not connect",Toast.LENGTH_LONG).show();
}
}
private class JSONAsyncTask extends AsyncTask<String, Void, JSONArray> {
private ProgressDialog dialog = new ProgressDialog(DoctorInformationActivity.this);
#Override
protected void onPreExecute() {
this.dialog.setMessage("Please wait");
this.dialog.show();
}
#Override
protected JSONArray doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(URL);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
Cities = jsono.getJSONArray("SearchDoctorsData");
return Cities;
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return Cities;
}
protected void onPostExecute(JSONArray result) {
dialog.dismiss();
System.out.println(result);
for (int i = 0; i < result.length(); i++) {
JSONObject c = null;
try {
DocotorInformation doc=new DocotorInformation();
c = result.getJSONObject(i);
doc.setName(c.getString("DoctorName"));
doc.setNumber(c.getString("Mobile"));
doctorList.add(doc);
sql.insertData(doc);
} catch (JSONException e) {
e.printStackTrace();
}
}
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
DoctorAdapter mAdapter = new DoctorAdapter(getApplicationContext(), doctorList);
recyclerView.setAdapter(mAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
}
}
}
public class DoctorAdapter extends RecyclerView.Adapter<DoctorAdapter.ViewHolder> {
private ArrayList<DocotorInformation> countries;
Context con;
public DoctorAdapter(Context c ,ArrayList<DocotorInformation> countries) {
this.con=c;
this.countries = countries;
}
#Override
public DoctorAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.doctor_textviews, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(DoctorAdapter.ViewHolder viewHolder, int i) {
viewHolder.name.setText(countries.get(i).getName());
viewHolder.number.setText(countries.get(i).getNumber());
}
#Override
public int getItemCount() {
return countries.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView name,number;
public ViewHolder(View view) {
super(view);
name = (TextView)view.findViewById(R.id.name);
number = (TextView)view.findViewById(R.id.numebr);
}
}
}
i am not able to populate the imageview textview inside gridview using fragments.
It is showing blank intead of gridview populating in my project can please anyone see the code below and let me know what i have to change
And the populating the image and text is from the mysql database dynamically
public class StoreHomeFragment extends Fragment {
final ArrayList<HashMap<String, String>> MyArrList = new ArrayList<HashMap<String, String>>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.store_home, container, false);
final GridView gridView1 = (GridView)rootView.findViewById(R.id.store_home_gridview);
gridView1.setAdapter(new ImageAdapter(rootView.getContext(), MyArrList));
return rootView;
}
//Activity is created
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String url = "http://192.168.1.132/Android/App/good.php"; //url where i am using select query and retrieving it from database
try {
JSONArray data = new JSONArray(getJSONUrl(url));
HashMap<String, String> map;
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);//retrieving from db
map = new HashMap<String, String>();
map.put("name", c.getString("name"));
map.put("artist", c.getString("artist"));
map.put("price", c.getString("price"));
map.put("image", c.getString("image"));
MyArrList.add(map);
}
//gridView1.setAdapter(new ImageAdapter(this,MyArrList));
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
//I have used imageAdapter
class ImageAdapter extends BaseAdapter
{
private Context context;
public ImageView imageView;
private ArrayList<HashMap<String, String>> MyArr = new ArrayList<HashMap<String, String>>();
public ImageAdapter(Context c,ArrayList<HashMap<String, String>> list)
{
context = c;
MyArr = list;
}
public int getCount() {
return MyArr.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.store_home_gridview_row, null);
}
TextView tv_title = (TextView) convertView.findViewById(R.id.textview_name);
tv_title.setText("Title:"+MyArr.get(position).get("name"));
TextView tv_artist = (TextView) convertView.findViewById(R.id.textview_artist);
tv_artist.setText("Artist:"+MyArr.get(position).get("artist"));
TextView tv_duration = (TextView) convertView.findViewById(R.id.textview_price);
tv_duration.setText("Price:"+MyArr.get(position).get("price"));
String abc = (MyArr.get(position).get("image"));
String abcd = "http://192.168.1.132/images/products/"+abc;
imageView = (ImageView) convertView.findViewById(R.id.imageView1);
try
{
URL url3 = null;
try {
url3 = new URL(abcd);
} catch (Exception e) {
e.printStackTrace();
}
Bitmap bmp = BitmapFactory.decodeStream(url3.openConnection().getInputStream()); //image is populated
imageView.setImageBitmap(bmp);
}
catch(Exception par)
{
imageView.setImageResource(android.R.drawable.ic_menu_report_image);
}
return convertView;
}
}
/*** Get JSON Code from URL ***/
public String getJSONUrl(String url) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try
{
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
System.out.println ( "status Code : " + statusCode );
if (statusCode == 200)
{
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null)
{
str.append(line);
}
}
else
{
Log.e("Log", "Failed to download file..");
}
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
System.out.println ( "str : " + str.toString() );
return str.toString();
}
}
Follow the steps Hope this helps you
1) Remove these lines from onCreateView() method
final GridView gridView1 = (GridView)rootView.findViewById(R.id.store_home_gridview);
gridView1.setAdapter(new ImageAdapter(rootView.getContext(), MyArrList));
2)Modify onActivityCreated() as follow
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
String url = "http://192.168.1.132/Android/App/good.php";
try {
JSONArray data = new JSONArray(getJSONUrl(url));
HashMap<String, String> map;
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, String>();
map.put("name", c.getString("name"));
map.put("artist", c.getString("artist"));
map.put("price", c.getString("price"));
map.put("image", c.getString("image"));
MyArrList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
final GridView gridView1 = (GridView) rootView.findViewById(R.id.store_home_gridview);
gridView1.setAdapter(new ImageAdapter(getActivity(), MyArrList));
}
}.execute();
}