Android Json with searchview - java

I'm having troubles with adding a searchview to a Json results. I can use the searchview without the Json, but not together.
In this example, If I write something on the searchview, all the gridview disappears. It´s like the searchview doesn´t receive anything.
I made the Json from this tutorial: http://www.wingnity.com/blog/android-json-parsing-and-image-loading-tutorial/
And the searchview from this: http://abhiandroid.com/ui/searchview
The results I have in a Gridview
public class Tab3
#SuppressWarnings("deprecation")
public class Tab3 extends Fragment implements SearchView.OnQueryTextListener {
SearchView editsearch;
GridView lv;
ArrayList < Actors > actorsList = new ArrayList < > ();
ActorAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View vw = inflater.inflate(R.layout.search_view, container, false);
GridView gridview = (GridView) vw.findViewById(R.id.gridviewFilms);
ArrayList < Actors > actorsList = getAllItemObject();
ActorAdapter customAdapter = new ActorAdapter(getActivity(), R.layout.jsonparsedata_item, actorsList);
gridview.setAdapter(customAdapter);
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView < ? > parent, View view, int position, long id) {
Intent filmInfo = new Intent(getContext(), FilmInfo.class);
filmInfo.putExtra("position", position);
startActivity(filmInfo);
}
});
new JSONAsynTask().execute("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
// adapter = new ActorAdapter(getActivity(), R.layout.jsonparsedata_item, actorsList);
// Locate the ListView in listview_main.xml
lv = (GridView) vw.findViewById(R.id.gridviewFilms);
// Pass results to ListViewAdapter Class
adapter = new ActorAdapter(getActivity(), R.layout.jsonparsedata_item, actorsList);
// Binds the Adapter to the ListView
lv.setAdapter(adapter);
editsearch = (SearchView) vw.findViewById(R.id.search);
editsearch.setOnQueryTextListener(this);
return vw;
}
class JSONAsynTask extends AsyncTask < String, Void, Boolean > {
String result;
#Override
protected Boolean doInBackground(String...urls) {
try {
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("actors");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Actors actor = new Actors();
actor.setName(object.getString("name"));
actor.setDescription(object.getString("description"));
actor.setDob(object.getString("dob"));
actor.setCountry(object.getString("country"));
actor.setHeight(object.getString("height"));
actor.setSpouse(object.getString("spouse"));
actor.setChildren(object.getString("children"));
actor.setImage(object.getString("image"));
actorsList.add(actor);
}
return true;
}
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
adapter.notifyDataSetChanged();
if (result == false) {
Toast.makeText(getActivity(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
}
private ArrayList < Actors > getAllItemObject() {
//esto devuelve los valores a los titulos. Esta muy guarro, deberia de estarlo arriba
return actorsList;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
String text = newText;
adapter.filter(text);
return false;
}
}
public class ActorAdapter
public class ActorAdapter extends ArrayAdapter < Actors > {
// ArrayList<Actors> actorList;
LayoutInflater vi;
int Resource;
ViewHolder holder;
private List < Actors > animalNamesList = null;
private ArrayList < Actors > arraylist;
public ActorAdapter(Context context, int resource, ArrayList < Actors > objects) {
super(context, resource, objects);
vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
// this.actorList = objects;
this.animalNamesList = objects;
this.arraylist = new ArrayList < Actors > ();
this.arraylist.addAll(objects);
}
static class ViewHolder {
public ImageView imageview;
public TextView tvName;
public TextView tvDescription;
public TextView tvDOB;
public TextView tvCountry;
public TextView tvHeight;
public TextView tvSpouse;
public TextView tvChildren;
}
#Override
public int getCount() {
return animalNamesList.size();
}
#Override
public Actors getItem(int position) {
return animalNamesList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// convert view = design
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = vi.inflate(Resource, null);
holder.imageview = (ImageView) v.findViewById(R.id.cover);
holder.tvName = (TextView) v.findViewById(R.id.name);
holder.tvCountry = (TextView) v.findViewById(R.id.director);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.imageview.setImageResource(R.drawable.clapboard);
new DownloadImageTask(holder.imageview).execute(animalNamesList.get(position).getImage());
holder.tvName.setText(animalNamesList.get(position).getName());
holder.tvCountry.setText(animalNamesList.get(position).getCountry());
return v;
}
private class DownloadImageTask extends AsyncTask < String,
Void,
Bitmap > {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String...urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream( in );
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
animalNamesList.clear();
if (charText.length() == 0) {
animalNamesList.addAll(arraylist);
} else {
for (Actors wp: arraylist) {
if (wp.getName().toLowerCase(Locale.getDefault()).contains(charText)) {
animalNamesList.add(wp);
}
}
}
notifyDataSetChanged();
}
}
public class Actors
public class Actors {
private String name;
private String description;
private String dob;
private String country;
private String height;
private String spouse;
private String children;
private String image;
public Actors() {
// TODO Auto-generated constructor stub
}
public Actors(String name, String description, String dob, String country,
String height, String spouse, String children, String image) {
super();
this.name = name;
this.description = description;
this.dob = dob;
this.country = country;
this.height = height;
this.spouse = spouse;
this.children = children;
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public String getSpouse() {
return spouse;
}
public void setSpouse(String spouse) {
this.spouse = spouse;
}
public String getChildren() {
return children;
}
public void setChildren(String children) {
this.children = children;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}}
jsonparse_fragment
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<SearchView
android:id="#+id/search"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:iconifiedByDefault="false"
android:queryHint="Pelikulen izenak..."
android:background="#f70">
<requestFocus />
</SearchView>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gridviewTab3"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/search"
android:gravity="center"
android:horizontalSpacing="4dp"
android:numColumns="2"
android:padding="4dp"
android:scrollbars="vertical"
android:scrollbarThumbVertical="#drawable/custom_scroll_style"
android:stretchMode="columnWidth"
android:verticalSpacing="4dp" />
jsonparsedata_item.xml
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
card_view:cardBackgroundColor="#color/colorText"
card_view:cardUseCompatPadding="true"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="15dp">
<RelativeLayout
android:layout_height="250dp"
android:layout_width="200dp"
android:paddingBottom="6dp">
<TextView
android:id="#+id/director"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world"
android:textColor="#color/colorTextDark"
android:textSize="10sp"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:paddingLeft="4dp" />
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world"
android:textColor="#color/colorTextDark"
android:textSize="12sp"
android:layout_above="#+id/director"
android:layout_alignParentStart="true"
android:paddingLeft="4dp" />
<ImageView
android:id="#+id/cover"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="#string/hello_world"
android:scaleType="fitXY"
android:src="#drawable/milian"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_above="#+id/name"
android:layout_alignParentEnd="true" />
</RelativeLayout>

Related

how to add like button in Recyclerview in android

I am a new application developer android app and need some help Please.
I need to know how to add the like button inside (Recyclerview) linked to a database (Mysql) and connect through a Volley library to save all user likes.And see how many likes each topic has.
An example that is in the picture..
I need to add it to this attached project.
MainActivity
public class MainActivity extends AppCompatActivity {
List<RecyclerViewData> recyclerViewDataList;
RecyclerView recyclerView;
private RVAdapter rvAdapter;
private static final String TAG="apple";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setTitle("Employee List");
recyclerViewDataList=new ArrayList<>();
recyclerView=findViewById(R.id.recyclerView);
LinearLayoutManager linearLayoutManager=new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
MakeVolleyConnection();
}
private void MakeVolleyConnection() {
recyclerViewDataList = new ArrayList<>();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
"http://10.0.13.45/v/parsing.php", null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray dataArray = response.getJSONArray("data");
for (int i = 0; i < dataArray.length(); i++) {
JSONObject userData = dataArray.getJSONObject(i);
RecyclerViewData recyclerViewData = new RecyclerViewData();
recyclerViewData.setId(userData.getInt("id"));
recyclerViewData.setFirstname(userData.getString("first_name"));
recyclerViewData.setLastname(userData.getString("last_name"));
recyclerViewData.setAvatar(userData.getString("avatar"));
recyclerViewDataList.add(recyclerViewData);
}
rvAdapter = new RVAdapter(recyclerViewDataList, MainActivity.this);
recyclerView.setAdapter(rvAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, ""+error.networkResponse,Toast.LENGTH_SHORT).show();
}
});
MySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest);
}
}
MySingleton
public class MySingleton {
private static MySingleton mInstance;
private RequestQueue mRequestQueue;
private static Context mContext;
private MySingleton(Context context){
// Specify the application context
mContext = context;
// Get the request queue
mRequestQueue = getRequestQueue();
}
public static synchronized MySingleton getInstance(Context context){
// If Instance is null then initialize new Instance
if(mInstance == null){
mInstance = new MySingleton(context);
}
// Return MySingleton new Instance
return mInstance;
}
public RequestQueue getRequestQueue(){
// If RequestQueue is null the initialize new RequestQueue
if(mRequestQueue == null){
mRequestQueue = Volley.newRequestQueue(mContext.getApplicationContext());
}
// Return RequestQueue
return mRequestQueue;
}
public<T> void addToRequestQueue(Request<T> request){
// Add the specified request to the request queue
getRequestQueue().add(request);
}
}
RecyclerViewData
public class RecyclerViewData {
private int id;
private String firstname;
private String lastname;
private String avatar;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
}
RVAdapter
public class RVAdapter extends RecyclerView.Adapter<RVAdapter.RVHOLDER> {
List<RecyclerViewData> recyclerViewDataList;
Context mContext;
// Constructor with List and Context which we'll pass from RecyclerView Activity after a connection to Volley. And application context for the listener that we'll implement this later.
public RVAdapter(List<RecyclerViewData> recyclerViewDataList, Context mContext) {
this.recyclerViewDataList = recyclerViewDataList;
this.mContext = mContext;
}
// Override the method onCreateViewHolder, which will call the custom view holder that needs to be initialized. We specify the layout that each item to be used, so we can achieve this using Layout Inflator to inflate the layout and passing the output to constructor of custom ViewHolder.
#NonNull
#Override
public RVHOLDER onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(mContext).inflate(R.layout.adapter_layout, viewGroup, false);
RVHOLDER rvholder = new RVHOLDER(itemView);
return rvholder;
}
//onBindViewHolder is for specifying the each item of RecyclerView. This is very similar to getView() method on ListView. In our example, this is where you need to set the user's id, name and image.
#Override
public void onBindViewHolder(#NonNull RVHOLDER rvholder, int i) {
rvholder.id.setText("User id is "+recyclerViewDataList.get(i).getId());
rvholder.first_name.setText(recyclerViewDataList.get(i).getFirstname() + " " + recyclerViewDataList.get(i).getLastname());
Picasso.get().load(recyclerViewDataList.get(i).getAvatar()).into(rvholder.avatar);
}
//We need to return the size for RecyclerView as how long a RecyclerView is, Our data is in list so passing data.size() will return the number as long as we have.
#Override
public int getItemCount() {
return recyclerViewDataList.size();
}
//This is CustomView holder that we had discuss it earlier above and inflated it in onCreateView() method. This constructor links with the xml to set the data, which we set into onBindViewHolder().
class RVHOLDER extends RecyclerView.ViewHolder {
TextView id;
private TextView first_name;
private ImageView avatar;
public RVHOLDER(#NonNull View itemView) {
super(itemView);
id = itemView.findViewById(R.id.id);
first_name = itemView.findViewById(R.id.firstname_lastname);
avatar = itemView.findViewById(R.id.avatar);
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.cardview.widget.CardView
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardCornerRadius="4dp"
card_view:cardUseCompatPadding="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="#+id/avatar"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginRight="16dp"
android:scaleType="fitCenter" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/firstname_lastname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:textAppearanceMedium" />
<TextView
android:id="#+id/id"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
</RelativeLayout>
<?php
$con=mysqli_connect("localhost","root","root","test");
$sql="SELECT * FROM testtable";
$result=mysqli_query($con,$sql);
$data=array();
while($row=mysqli_fetch_assoc($result)){
$data["data"][]=$row;
}
header('Content-Type:Application/json');
echo json_encode($data);
?>
#Override
public void onBindViewHolder(#NonNull RVHOLDER rvholder, int i) {
rvholder.id.setText("User id is "+recyclerViewDataList.get(i).getId());
rvholder.first_name.setText(recyclerViewDataList.get(i).getFirstname() + " " +
recyclerViewDataList.get(i).getLastname());
Picasso.get().load(recyclerViewDataList.get(i).getAvatar()).into(rvholder.avatar);
if()
}
if (recyclerViewDataList.get(i).getLiked()) {
// liked image
Picasso.get().load(gContextCompat.getDrawable(getActivity(), R.drawable.liked);).into(rvholder.like);
} else {
// without like image
Picasso.get().load(gContextCompat.getDrawable(getActivity(), R.drawable.not_like);).into(rvholder.like);
}
Add like boolean variable in RecyclerViewData Class. Add getter and setter of it. Add two drawables in drawable folder for Like and Not_like. Then Add this logic. Hope this will help. Thanks
#Override
public void onBindViewHolder(#NonNull RVHOLDER rvholder, int i) {
rvholder.id.setText("User id is "+recyclerViewDataList.get(i).getId());
rvholder.first_name.setText(recyclerViewDataList.get(i).getFirstname() + " " + recyclerViewDataList.get(i).getLastname());
Picasso.get().load(recyclerViewDataList.get(i).getAvatar()).into(rvholder.avatar);
Picasso.get().load(gContextCompat.getDrawable(getActivity(), if(recyclerViewDataList.get(i).getLiked())R.drawable.liked else R.drawable.not_like).into(rvholder.like);
}

Image click of RecyclerView

I know that there are already questions on this, but the format which I follow for my code is different so I am unable to find the answer to the question.
When I click on my RecyclerView item which includes TextView and ImageView, I want to show the image in a DetailActivity.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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:id="#+id/framelayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="pritish.sawant.com.photogallery.MainActivity">
</FrameLayout>
fragment_photo_gallery.xml
<RelativeLayout
android:orientation="vertical"
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"
tools:context="pritish.sawant.com.photogallery.PhotoGalleryFragment">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:id="#+id/recyclerview"
android:layout_height="match_parent"></android.support.v7.widget.RecyclerView>
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/loading_indicator"
style="#style/Widget.AppCompat.ProgressBar"
android:layout_centerInParent="true"/>
</RelativeLayout>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/textview"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
tools:text="Hi" />
<ImageView
android:id="#+id/imageview"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
tools:src="#drawable/image1">
</ImageView>
</LinearLayout>
activity_detail.xml
<?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"
tools:context="pritish.sawant.com.photogallery.DetailActivity">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/detailimageview"
tools:src="#drawable/image1"/>
</LinearLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
private FragmentManager fragmentManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setTitle("Photo Gallery");
fragmentManager=getSupportFragmentManager();
Fragment fragment=fragmentManager.findFragmentById(R.id.framelayout);
if(fragment==null){
fragment=new PhotoGalleryFragment();
fragmentManager.beginTransaction().add(R.id.framelayout,fragment).commit();
}
}
}
Photo.java
package pritish.sawant.com.photogallery;
public class Photo {
private String title;
private String author;
private String authorId;
private String link;
private String image;
private String tag;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getAuthorId() {
return authorId;
}
public void setAuthorId(String authorId) {
this.authorId = authorId;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
#Override
public String toString() {
return "Photo{" +
"title='" + title + '\'' +
", author='" + author + '\'' +
", authorId='" + authorId + '\'' +
", link='" + link + '\'' +
", image='" + image + '\'' +
", tag='" + tag + '\'' +
'}';
}
}
FlickrFetchr.java
package pritish.sawant.com.photogallery;
import android.net.Uri;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class FlickrFetchr {
private static final String TAG = "FlickrFetchr";
private List<Photo> photoList = null;
private String baseUrl="https://api.flickr.com/services/feeds/photos_public.gne";
public String getData(String url){
BufferedReader bufferedReader=null;
try {
URL url1=new URL(url);
HttpURLConnection httpURLConnection=(HttpURLConnection)url1.openConnection();
StringBuilder stringBuilder=new StringBuilder();
bufferedReader=new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String line;
while ((line=bufferedReader.readLine())!=null){
stringBuilder.append(line+"\n");
}
return stringBuilder.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
finally {
if(bufferedReader!=null){
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
}
private String buildURL(String searchPhoto, String lang, boolean match){
return Uri.parse(baseUrl).buildUpon().appendQueryParameter("tags", searchPhoto)
.appendQueryParameter("tagmode", match ? "ALL" : "ANY")
.appendQueryParameter("format", "json")
.appendQueryParameter("lang", lang)
.appendQueryParameter("nojsoncallback", "1").build().toString();
}
public List<Photo> fetchPhotos(String searchPhoto,String language,boolean matchAll){
String url=buildURL(searchPhoto,language,matchAll);
return downloadGalleyItem(url);
}
//To receive the json format
public List<Photo> downloadGalleyItem(String url){
photoList=new ArrayList<>();
Photo photo=new Photo();
String jsonString=getData(url);
try {
JSONObject jsonObject=new JSONObject(jsonString);
JSONArray jsonArray=jsonObject.getJSONArray("items");
for(int i=0;i<jsonArray.length();i++){
JSONObject jsonObject1=jsonArray.getJSONObject(i);
photo.setTitle(jsonObject1.getString("title"));
photo.setAuthor(jsonObject1.getString("author"));
photo.setAuthorId(jsonObject1.getString("author_id"));
photo.setTag(jsonObject1.getString("tags"));
JSONObject jsonMedia =jsonObject1.getJSONObject("media");
String imageUrl=jsonMedia.getString("m");
photo.setImage(jsonMedia.getString("m"));
//we are changing _m to _b so that when image is tapped we get biigger image
photo.setLink(imageUrl.replaceAll("_m.","_b."));
photoList.add(photo);
}
} catch (Exception e) {
e.printStackTrace();
}
return photoList;
}
}
RecyclerItemClickListener.java
public class RecyclerItemClickListener extends RecyclerView.SimpleOnItemTouchListener {
private static final String TAG = "RecyclerItemClickListen";
interface OnRecyclerClickListener{
void onItemClick(View view,int position);
void onItemLongClick(View view,int position);
}
private final OnRecyclerClickListener listener;
private final GestureDetectorCompat gestureDetectorCompat;
public RecyclerItemClickListener(Context context, final RecyclerView recyclerView, final OnRecyclerClickListener listener) {
this.listener = listener;
gestureDetectorCompat=new GestureDetectorCompat(context,new GestureDetector.SimpleOnGestureListener(){
#Override
public boolean onSingleTapUp(MotionEvent e) {
View childView=recyclerView.findChildViewUnder(e.getX(),e.getY());
if(childView!=null && listener!=null){
listener.onItemClick(childView,recyclerView.getChildAdapterPosition(childView));
}
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View childView=recyclerView.findChildViewUnder(e.getX(),e.getY());
if(childView!=null && listener!=null){
listener.onItemLongClick(childView,recyclerView.getChildAdapterPosition(childView));
}
}
});
}
public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent){
if (gestureDetectorCompat!=null){
boolean result=gestureDetectorCompat.onTouchEvent(motionEvent);
return result;
}else{
return false;
}
}
}
PhotoGalleryFragment.java
public class PhotoGalleryFragment extends Fragment implements RecyclerItemClickListener.OnRecyclerClickListener{
private RecyclerView recyclerView;
public ProgressBar progressBar;
public List<Photo> photos = new ArrayList<>();
public PhotoGalleryFragment() {
// Required empty public constructor
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_photo_gallery, container, false);
progressBar = (ProgressBar) view.findViewById(R.id.loading_indicator);
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getActivity(),recyclerView,this));
progressBar.setVisibility(View.GONE);
setUpAdapter();
new FetchTask().execute();
return view;
}
private void setUpAdapter() {
//isAdded checks whether fragment has been added to the activity
if (isAdded()) {
recyclerView.setAdapter(new PhotoAdapter(photos));
}
}
#Override
public void onItemClick(View view, int position) {
Toast.makeText(getActivity(),"Item Clicked",Toast.LENGTH_LONG).show();
Intent intent=new Intent(getActivity(),DetailActivity.class);
//what should i pass in putExtra of intent
//intent.putExtra("IMAGE",photo.getLink());
startActivity(intent);
}
#Override
public void onItemLongClick(View view, int position) {
Toast.makeText(getActivity(),"Item Long Clicked",Toast.LENGTH_LONG).show();
}
private class PhotoHolder extends RecyclerView.ViewHolder {
private ImageView imageView;
private TextView textView;
public PhotoHolder(View itemView) {
super(itemView);
imageView = (ImageView) itemView.findViewById(R.id.imageview);
textView = (TextView) itemView.findViewById(R.id.textview);
}
public void bindItems(Photo photos1) {
Picasso.with(getActivity()).load(photos1.getImage()).into(imageView);
textView.setText(photos1.getTitle());
// Glide.with(getActivity()).load(photos1.getImage()).into(imageView);
}
}
private class PhotoAdapter extends RecyclerView.Adapter<PhotoHolder> {
private List<Photo> galleryItems;
public PhotoAdapter(List<Photo> galleryItems) {
this.galleryItems = galleryItems;
}
#Override
public PhotoHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
View view = layoutInflater.inflate(R.layout.list_item, parent, false);
return new PhotoHolder(view);
}
#Override
public void onBindViewHolder(PhotoHolder holder, int position) {
Photo photos2 = galleryItems.get(position);
holder.bindItems(photos2);
}
#Override
public int getItemCount() {
return galleryItems.size();
}
}
private class FetchTask extends AsyncTask<Void, Void, List<Photo>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
if (photos.size() == 0) {
progressBar.setVisibility(View.VISIBLE);
}
}
#Override
protected List<Photo> doInBackground(Void... params) {
return new FlickrFetchr().fetchPhotos("android", "en-us", false);
}
#Override
protected void onPostExecute(List<Photo> photos1) {
super.onPostExecute(photos);
progressBar.setVisibility(View.GONE);
photos = photos1;
setUpAdapter();
}
}
}
DetailActivity.java
public class DetailActivity extends AppCompatActivity {
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
imageView=(ImageView)findViewById(R.id.detailimageview);
int img_id;
if (savedInstanceState != null ){
img_id = getIntent().getIntExtra("IMAGE",0);
imageView.setImageResource(img_id);
}
}
}
In onItemClick you can pass Like this
Toast.makeText(getActivity(),"Item Clicked",Toast.LENGTH_LONG).show();
Intent intent=new Intent(getActivity(),DetailActivity.class);
//what should i pass in putExtra of intent
intent.putExtra("IMAGE",photos.get(position).getLink());
startActivity(intent);
In DetailsActivity you can retrieve it by
if (getIntent().getStringExtra("IMAGE") != null) {
imageurl = getIntent().getStringExtra("IMAGE");
}

ListView not displayed in Fragment (Android)

So im following this tutorial http://www.wingnity.com/blog/android-json-parsing-and-image-loading-tutorial/ on how to parse a JSON Api and displays data into Listview
I tried to adapt the code in my fragment , in onCreateView method , but the Listview is not displayed (blank fragment). And i dont know why.
I imported all the required libs
Actor.java
public class Actors {
private String name;
private String description;
private String dob;
private String country;
private String height;
private String spouse;
private String children;
private String image;
public Actors() {
// TODO Auto-generated constructor stub
}
public Actors(String name, String description, String dob, String country,
String height, String spouse, String children, String image) {
super();
this.name = name;
this.description = description;
this.dob = dob;
this.country = country;
this.height = height;
this.spouse = spouse;
this.children = children;
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public String getSpouse() {
return spouse;
}
public void setSpouse(String spouse) {
this.spouse = spouse;
}
public String getChildren() {
return children;
}
public void setChildren(String children) {
this.children = children;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
ActorAdapter.java
import java.io.InputStream;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import info.androidhive.navigationdrawer.R;
public class ActorAdapter extends ArrayAdapter<Actors> {
ArrayList<Actors> actorList;
LayoutInflater vi;
int Resource;
ViewHolder holder;
public ActorAdapter(Context context, int resource, ArrayList<Actors> objects) {
super(context, resource, objects);
vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
actorList = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// convert view = design
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = vi.inflate(Resource, null);
holder.imageview = (ImageView) v.findViewById(R.id.ivImage);
holder.tvName = (TextView) v.findViewById(R.id.tvName);
holder.tvDescription = (TextView) v.findViewById(R.id.tvDescriptionn);
holder.tvDOB = (TextView) v.findViewById(R.id.tvDateOfBirth);
holder.tvCountry = (TextView) v.findViewById(R.id.tvCountry);
holder.tvHeight = (TextView) v.findViewById(R.id.tvHeight);
holder.tvSpouse = (TextView) v.findViewById(R.id.tvSpouse);
holder.tvChildren = (TextView) v.findViewById(R.id.tvChildren);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.imageview.setImageResource(R.drawable.imgadd);
new DownloadImageTask(holder.imageview).execute(actorList.get(position).getImage());
holder.tvName.setText(actorList.get(position).getName());
holder.tvDescription.setText(actorList.get(position).getDescription());
holder.tvDOB.setText("B'day: " + actorList.get(position).getDob());
holder.tvCountry.setText(actorList.get(position).getCountry());
holder.tvHeight.setText("Height: " + actorList.get(position).getHeight());
holder.tvSpouse.setText("Spouse: " + actorList.get(position).getSpouse());
holder.tvChildren.setText("Children: " + actorList.get(position).getChildren());
return v;
}
static class ViewHolder {
public ImageView imageview;
public TextView tvName;
public TextView tvDescription;
public TextView tvDOB;
public TextView tvCountry;
public TextView tvHeight;
public TextView tvSpouse;
public TextView tvChildren;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
Articles.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="4dp"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/ivImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:src="#drawable/imgadd" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/tvName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tom Cruise"
android:textColor="#166CED"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/tvDateOfBirth"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#D64530"
android:text="Date of Birth: July 3, 1962" />
<TextView
android:id="#+id/tvHeight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Height: 1.80 m"
android:textColor="#D64530"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/tvCountry"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#D64530"
android:text="United States" />
</LinearLayout>
</LinearLayout>
<TextView
android:id="#+id/tvDescriptionn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#009A57"
android:text="Description" />
<TextView
android:id="#+id/tvSpouse"
android:layout_width="wrap_content" android:textColor="#166CED"
android:layout_height="wrap_content"
android:text="Spouse: Katie Holmes" />
<TextView
android:id="#+id/tvChildren"
android:layout_width="wrap_content" android:textColor="#166CED"
android:layout_height="wrap_content"
android:text="Children: Suri Cruise, Isabella Jane Cruise, Connor Cruise" />
</LinearLayout>
Fragment_accueil.xml (my fragment layout)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="4dp"
android:orientation="vertical"
tools:context="info.androidhive.navigationdrawer.fragment.AccueilFragment">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:listitem="#layout/articles">
</ListView>
</LinearLayout>
fragment_accueil.java (my fragment activity)
//import.....
public class AccueilFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
int score = 0;
TextView t1, t2, t3,t4;
ImageView img;
private OnFragmentInteractionListener mListener;
public AccueilFragment() {
}
public static AccueilFragment newInstance(String param1, String param2) {
AccueilFragment fragment = new AccueilFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_accueil, container, false);
t1 = (TextView) view.findViewById(R.id.tvName);
t2 = (TextView) view.findViewById(R.id.tvDateOfBirth);
t3 = (TextView) view.findViewById(R.id.tvHeight);
t3 = (TextView) view.findViewById(R.id.tvCountry);
img = (ImageView) view.findViewById(R.id.ivImage);
ArrayList actorsList = new ArrayList<Actors>();
ListView listview = (ListView) view.findViewById(R.id.list);
ListAdapter adapter = new ActorAdapter(getActivity().getApplicationContext(), R.layout.articles, actorsList);
listview.setAdapter(adapter);
new getData().execute();
return view;
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
class getData extends AsyncTask<String, String, String> {
HttpURLConnection urlConnection;
#Override
protected String doInBackground(String... args) {
StringBuilder result = new StringBuilder();
try {
URL url = new URL("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
urlConnection.disconnect();
}
return result.toString();
}
#Override
protected void onPostExecute(String result) {
try {
JSONObject jsono = new JSONObject(result);
JSONArray jarray = jsono.getJSONArray("actors");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Actors actor = new Actors();
actor.setName(object.getString("name"));
actor.setDescription(object.getString("description"));
actor.setDob(object.getString("dob"));
actor.setCountry(object.getString("country"));
actor.setHeight(object.getString("height"));
actor.setSpouse(object.getString("spouse"));
actor.setChildren(object.getString("children"));
actor.setImage(object.getString("image"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}
What's the problem and how to fix that ? thanks
There is couple of things wrong:
1.You are not adding Actors actor = new Actors(); to the actorsList
2.Calling this:
ArrayList actorsList = new ArrayList<Actors>();
ListView listview = (ListView) view.findViewById(R.id.list);
ListAdapter adapter = new ActorAdapter(getActivity().getApplicationContext(), R.layout.articles, actorsList);
will reuslt in blank data in listview
I would suggest you to add the data in your onPostExecute() to the Arraylist and then initialize the adapter with the data.
or you can also call
adapter.notifyDataSetChanged() in onPostExecute()
Are you adding the ListView in your fragment that you want it to be displayed for example:
public class FragmentMain extends Fragment
{
private ListView listView; //Define the list view up here.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//Set the listview equal to the fragment name
listView = inflater.inflate(R.layout.fragment_name, container, false);
}
}
This should work, let me know if otherwize :)

Not able to get the XML DOM parsed data on Main thread of process

I am not getting the desired output from the code.
I used XML DOM parsing to fetch title, pubdate, description and image from link: http://autosportsindia.com/feed
Through the code written no output is obtained. Even though Logcat shows that data is being fetched from the link.
Kindly tell me what is the fault in my code. Suggest any other method of XML parsing with code or link.
public class MainActivity extends AppCompatActivity implements ResultsCallBack {
PlaceholderFragment taskFragment;
ListView articlesListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
taskFragment = new PlaceholderFragment();
getSupportFragmentManager().beginTransaction().add(taskFragment, "MyFragment").commit();
} else {
taskFragment = (PlaceholderFragment) getSupportFragmentManager().findFragmentByTag("MyFragment");
}
taskFragment.startTask();
articlesListView = (ListView) findViewById(R.id.articlesListView);
}
#Override
public void onPreExecute() {
}
#Override
public void onPostExecute(ArrayList<HashMap<String, String>> results) {
articlesListView.setAdapter(new MyAdapter(this, results));
}
public static class PlaceholderFragment extends Fragment {
AutoSportsIndia downloadTask;
ResultsCallBack callBack;
public PlaceholderFragment() {
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
callBack = (ResultsCallBack) activity;
if(downloadTask!=null)
{
downloadTask.onAttach(callBack);
}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
}
public void startTask() {
if (downloadTask != null) {
downloadTask.cancel(true);
} else {
downloadTask = new AutoSportsIndia(callBack);
downloadTask.execute();
}
}
#Override
public void onDetach() {
super.onDetach();
callBack = null;
if(downloadTask!=null) {
downloadTask.onDetach();
}
}
}
public static class AutoSportsIndia extends AsyncTask<Void, Void, ArrayList<HashMap<String, String>>> {
ResultsCallBack callBack =null;
public AutoSportsIndia(ResultsCallBack callBack) {
this.callBack = callBack;
}
public void onAttach(ResultsCallBack callBack) {
this.callBack = callBack;
}
public void onDetach() {
callBack = null;
}
protected void onPreExecute() {
if(callBack!=null)
{
callBack.onPreExecute();
}
}
#Override
protected ArrayList<HashMap<String, String>> doInBackground(Void... params) {
String downloadURL = "http://autosportsindia.com/feed";
ArrayList<HashMap<String, String>> results = new ArrayList<>();
try {
URL url = new URL(downloadURL);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
InputStream inputStream = connection.getInputStream();
processXML(inputStream);
} catch (Exception e) {
L.m(e + "");
}
return results;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
if(callBack!=null)
{
callBack.onPostExecute(result);
}
}
public ArrayList<HashMap<String, String>> processXML(InputStream inputStream) throws Exception {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document xmlDocument = documentBuilder.parse(inputStream);
Element rootElement = xmlDocument.getDocumentElement();
L.m("" + rootElement.getTagName());
NodeList itemsList = rootElement.getElementsByTagName("item");
NodeList itemChildren = null;
Node currentItem = null;
Node currentChild = null;
int count = 0;
ArrayList<HashMap<String, String>> results = new ArrayList<>();
HashMap<String, String> currentMap = null;
for (int i = 0; i < itemsList.getLength(); i++) {
currentItem = itemsList.item(i);
itemChildren = currentItem.getChildNodes();
currentMap = new HashMap<>();
for (int j = 0; j < itemChildren.getLength(); j++) {
currentChild = itemChildren.item(j);
if (currentChild.getNodeName().equalsIgnoreCase("title")) {
currentMap.put("title", currentChild.getTextContent());
String temp="title: "+currentChild.getTextContent();
L.m(temp);
}
if (currentChild.getNodeName().equalsIgnoreCase("pubDate")) {
String temp1="pubDate: "+currentChild.getTextContent();
currentMap.put("pubDate", currentChild.getTextContent());
L.m(temp1);
}
if (currentChild.getNodeName().equalsIgnoreCase("description")) {
currentMap.put("description", currentChild.getTextContent());
String temp="description: "+currentChild.getTextContent();
L.m(temp);
}
if (currentChild.getNodeName().equalsIgnoreCase("media:thumbnail")) {
count++;
if (count == 2) {
L.m(currentChild.getAttributes().item(0).getTextContent());
currentMap.put("imageURL", currentChild.getAttributes().item(0).getTextContent());
}
}
if (currentMap != null && !currentMap.isEmpty()) {
results.add(currentMap);
}
}
count = 0;
}
return results;
}
}
}
interface ResultsCallBack {
public void onPreExecute();
public void onPostExecute(ArrayList<HashMap<String, String>> results);
}
class MyAdapter extends BaseAdapter {
ArrayList<HashMap<String, String>> dataSource = new ArrayList<>();
Context context;
LayoutInflater layoutInflater;
public MyAdapter(Context context, ArrayList<HashMap<String, String>> dataSource) {
this.context = context;
this.dataSource = dataSource;
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return dataSource.size();
}
#Override
public Object getItem(int position) {
return dataSource.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
MyHolder holder = null;
if(row == null)
{
row = layoutInflater.inflate(R.layout.custom_view, parent, false);
holder = new MyHolder(row);
row.setTag(holder);
}
else
{
holder = (MyHolder)row.getTag();
}
HashMap<String, String> currentItem = dataSource.get(position);
holder.articleTitleText.setText(currentItem.get("title"));
holder.articlePublishedDateText.setText(currentItem.get("pubDate"));
// holder.articleImage.setImageURI(Uri.parse(currentItem.get("imageURL")));
holder.articleDescriptionText.setText(currentItem.get("description"));
return row;
}
}
class MyHolder {
TextView articleTitleText;
TextView articlePublishedDateText;
ImageView articleImage;
TextView articleDescriptionText;
public MyHolder(View view) {
articleTitleText = (TextView)
view.findViewById(R.id.articleTitleText);
articlePublishedDateText = (TextView) view.findViewById(R.id.articlePublishedDate);
articleImage = (ImageView) view.findViewById(R.id.articleImage);
articleDescriptionText = (TextView) view.findViewById(R.id.articleDescriptionText);
}
}
XML pages:-
activity_main.xml
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/articlesListView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
custom_view.xml
<TextView
android:id="#+id/articleTitleText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:padding="12dp"
android:text="Title"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#444"/>
<TextView
android:id="#+id/articlePublishedDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/articleTitleText"
android:paddingBottom="4dp"
android:paddingLeft="12dp"
android:paddingRight="12dp"
android:paddingTop="4dp"
android:text="Date"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#444"/>
<View
android:id="#+id/separator1"
android:layout_width="match_parent"
android:layout_height="2dp"
android:layout_below="#+id/articlePublishedDate"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
android:background="#e67e22"/>
<ImageView
android:id="#+id/articleImage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/separator1"
android:scaleType="fitCenter"
android:src="#drawable/ic_launcher"/>
<TextView
android:id="#+id/articleDescriptionText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/articleImage"
android:padding="12dp"
android:text="Description"
android:textColor="#444"/>
The processXML method builds and returns an ArrayList<HashMap<String, String>>.
It is called in the doInBackground method, but the return value is discarded. doInBackground then returns a local results object, which is an empty list.
If you had debugged your way through the processXML and doInBackground methods, you would have seen this. When I asked in a comment whether "you tried debugging your code, stepping through and seeing the values being processed", you obviously didn't.

How to get information of an item with button in Android

I need help with a project in Android where I'm working. I have an AsyncTask that external data collected through the internet with a custom adapter.
My view currently has a view that is generated by the adapter and outside of it, contains a button. I would like to press that button give me current information from view as for example the name of the element.
MainActivity.xml
<?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"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ebebeb"
android:orientation="vertical" >
<RelativeLayout
android:id="#+id/header"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#drawable/header" >
<TextView
android:layout_width="fill_parent"
android:layout_height="55dp"
android:gravity="center_vertical"
android:paddingLeft="35dp"
android:text="Menú"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFF" />
<TextView
android:id="#+id/openmenu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:background="#drawable/ic_action_overflow"
android:clickable="true"
android:contentDescription="Desc"
android:visibility="visible" />
<TextView
android:id="#+id/love"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#drawable/ic_action_love"
android:clickable="true"
android:contentDescription="Desc"
android:visibility="visible" />
<TextView
android:id="#+id/refresh"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/love"
android:layout_alignBottom="#+id/love"
android:layout_marginRight="5dp"
android:layout_toLeftOf="#+id/love"
android:background="#drawable/ic_action_refresh"
android:clickable="true"
android:contentDescription="Desc"
android:visibility="visible" />
</RelativeLayout>
<com.unomasdelafamilia.sevilla.CardContainer
android:id="#+id/layoutview"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#ebebeb" />
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center" >
<Button
android:id="#+id/infobtn"
android:layout_width="75dp"
android:layout_height="75dp"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/lovebtn"
android:background="#drawable/love" />
</RelativeLayout>
</LinearLayout>
MainActivity.class
private class JSONParse extends AsyncTask {
#Override
protected void onPreExecute() {
super.onPreExecute();
mCardContainer = (CardContainer) findViewById(R.id.layoutview);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Obteniendo datos ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONfromURL(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
if(json != null){
pDialog.dismiss();
try {
// Getting JSON Array
user = json.getJSONArray(TAG_USER);
for (int i = 0; i < user.length(); i++) {
JSONObject c = user.getJSONObject(i);
String id = c.getString(TAG_ID);
String image = c.getString(imagen);
adapter.add(new CardModel(id, "Sevilla", image));
}
mCardContainer.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}else{
pDialog.dismiss();
Toast.makeText(getApplicationContext(), "Compruebe su conexión e inténtelo de nuevo más tarde", Toast.LENGTH_SHORT).show();
//No hay datos
}
}
CardModel.class
public class CardModel {
private String title;
private String description;
//private Drawable cardImageDrawable;
private String image;
/* private Drawable cardLikeImageDrawable;
private Drawable cardDislikeImageDrawable;*/
private OnCardDimissedListener mOnCardDimissedListener = null;
private OnClickListener mOnClickListener = null;
public interface OnCardDimissedListener {
void onLike();
void onDislike();
}
public interface OnClickListener {
void OnClickListener();
}
/*public CardModel(String string, Drawable drawable) {
this(null, null, null);
}*/
public CardModel(String title, String description, String image) {
this.title = title;
this.description = description;
//this.cardImageDrawable = cardImage;
this.image = image;
}
public CardModel(String title, String description, Bitmap cardImage) {
this.title = title;
this.description = description;
//this.cardImageDrawable = new BitmapDrawable(null, cardImage);
}
public CardModel(HashMap<String, String> map) {
this.title = title;
this.description = description;
this.image = image;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public String getImage(){
return image;
}
public void setDescription(String description) {
this.description = description;
}
public void setImage(String image) {
this.image = image;
}
/*public Drawable getCardLikeImageDrawable() {
return cardLikeImageDrawable;
}
public void setCardLikeImageDrawable(Drawable cardLikeImageDrawable) {
this.cardLikeImageDrawable = cardLikeImageDrawable;
}
public Drawable getCardDislikeImageDrawable() {
return cardDislikeImageDrawable;
}
public void setCardDislikeImageDrawable(Drawable cardDislikeImageDrawable) {
this.cardDislikeImageDrawable = cardDislikeImageDrawable;
}
*/
/* public void setOnCardDimissedListener( OnCardDimissedListener listener ) {
this.mOnCardDimissedListener = listener;
}
public OnCardDimissedListener getOnCardDimissedListener() {
return this.mOnCardDimissedListener;
}
public void setOnClickListener( OnClickListener listener ) {
this.mOnClickListener = listener;
}
public OnClickListener getOnClickListener() {
return this.mOnClickListener;
}*/
}
SimpleCardStackAdapter.java
public final class SimpleCardStackAdapter extends CardStackAdapter {
public SimpleCardStackAdapter(Context mContext) {
super(mContext);
}
#Override
public View getCardView(int position, CardModel model, View convertView, ViewGroup parent) {
if(convertView == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.std_card_inner, parent, false);
assert convertView != null;
}
int loader = R.drawable.ic_launcher;
ImageView image = (ImageView) convertView.findViewById(R.id.sp_image);
ImageLoader imgLoader = new ImageLoader(mContext);
//((ImageView) convertView.findViewById(R.id.sp_image)).setImageDrawable(model.getImage());
((TextView) convertView.findViewById(R.id.textView1)).setText(model.getTitle());
((TextView) convertView.findViewById(R.id.textView2)).setText(model.getDescription());
imgLoader.DisplayImage(model.getImage(), loader, image);
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Toast.makeText(getContext(), "Pulsado", Toast.LENGTH_SHORT).show();
((ViewManager)v.getParent()).removeView(v);
}
});
return convertView;
}
}
In short, how I can get ítem information when the button is pressed. Thank you very much to all, Greetings
You should use the tag property of views in Android.
So, you can dynamically set the tag like
String item = "item";
Button button = findViewById(R.id.Button);
button.setTag(item);
where and whenever is appropriate in you code.
Then, you can retrieve the tag when clicked like
#Override
public void onClick(View button) {
String myString = (String) button.getTag();
}
Update
After understanding OPs requirement.
In your overridden getCardView handler, after you instantiate the ImageView like
ImageView image = (ImageView) convertView.findViewById(R.id.sp_image);
set its tag from the model object like
image.setTag(model.getTitle());
then, in your click handler, get the tag of the ImageView like
#Override
public void onClick(View button) {
ImageView image = (ImageView) getView().findViewById(R.id.sp_image);
String item = (String)image.getTag();
}

Categories

Resources