I've built a SAX based XML parser for android however I'm getting duplicate data when I attempt to execute it. I'm not sure exactly what I've done wrong (I had a similar issue once before and the issue lied with a problem on the line: if (qName.equalsIgnoreCase("Video")) { however I've looked the code over several times so I'm not sure exactly what I can do to resolve the issue and or how to prevent the duplicate data.
Screenshot
SAXXMLHandler.java
public class SAXXMLHandler extends DefaultHandler {
private List<Cmd> videos;
private String tempVal;
// to maintain context
private Cmd cmd;
public SAXXMLHandler() {
videos = new ArrayList<Cmd>();
}
public List<Cmd> getResponse() {
return videos;
}
// Event Handlers
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// reset
tempVal = "";
if (qName.equalsIgnoreCase("Video")) {
// create a new instance of cmd
cmd = new Cmd();
}
}
public void characters(char[] ch, int start, int length)
throws SAXException {
tempVal = new String(ch, start, length);
}
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (qName.equalsIgnoreCase("videos")) {
// add it to the list
} else if (qName.equalsIgnoreCase("videos")) {
cmd.setSuccess(tempVal);
} else if (qName.equalsIgnoreCase("videos")) {
cmd.setNumberOfVideos(tempVal);
} else if (qName.equalsIgnoreCase("videos")) {
cmd.setVideos(videos);
} else if (qName.equalsIgnoreCase("video")) {
cmd.setVideo(tempVal);
} else if (qName.equalsIgnoreCase("videoname")) {
cmd.setVideoName(tempVal);
} else if (qName.equalsIgnoreCase("videourl")) {
cmd.setVideoURL(tempVal);
videos.add(cmd); //You only need store an instance of your Cmd
}
}
}
CustomListViewAdapter.java
public class CustomListViewAdapter extends ArrayAdapter<Cmd> {
Activity context;
List<Cmd> videos;
public CustomListViewAdapter(Activity context, List<Cmd> videos) {
super(context, R.layout.list_item2, videos);
this.context = context;
this.videos = videos;
}
/* private view holder class */
private class ViewHolder {
ImageView imageView;
TextView txtSuccess;
TextView txtCmd;
TextView txtPrice;
}
public void run() {
Intent intent = new Intent(context, ViewVideo.class);
String txt=Cmd.getVideoURL();
intent.putExtra("videofilename", txt);
context.startActivity(intent);
}
public Cmd getItem(int position) {
return videos.get(position);
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item2, null);
holder = new ViewHolder();
holder.txtSuccess = (TextView) convertView
.findViewById(R.id.success);
holder.txtCmd = (TextView) convertView.findViewById(R.id.cmd);
holder.txtPrice = (TextView) convertView.findViewById(R.id.price);
holder.imageView = (ImageView) convertView
.findViewById(R.id.thumbnail);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final Cmd cmd = (Cmd) getItem(position);
holder.txtSuccess.setText(cmd.getVideoName());
holder.txtSuccess.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
run();
}
});
holder.txtCmd.setText(cmd.getCmd());
holder.txtCmd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
run();
}
});
holder.txtPrice.setText(cmd.getVideoURL() + "");
holder.txtPrice.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
run();
}
});
holder.imageView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
run();
}
});
return convertView;
}
}
SAXParserAsyncTaskActivity.java
public class SAXParserAsyncTaskActivity extends Activity implements
OnClickListener, OnItemClickListener {
ListView listView;
List<Cmd> videos = new ArrayList<Cmd>();
CustomListViewAdapter listViewAdapter;
static final String URL = "http://mobile.example.com/api/xmlrpc.php?cmd=getVideos&username=fake&password=fake";
public static final String LIBRARY = "Library";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.parser_main);
findViewsById();
listView.setOnItemClickListener(this);
GetXMLTask task = new GetXMLTask(this);
task.execute(new String[] { URL });
}
private void findViewsById() {
listView = (ListView) findViewById(R.id.cmdList);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
}
#Override
public void onClick(View view) {
}
// private inner class extending AsyncTask
private class GetXMLTask extends AsyncTask<String, Void, List<Cmd>> {
private Activity context;
public GetXMLTask(Activity context) {
this.context = context;
}
protected void onPostExecute(List<Cmd> videos) {
listViewAdapter = new CustomListViewAdapter(context, videos);
listView.setAdapter(listViewAdapter);
}
private String getXmlFromUrl(String urlString) {
StringBuffer output = new StringBuffer("");
try {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(stream));
String s = "";
while ((s = buffer.readLine()) != null)
output.append(s);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return output.toString();
}
#Override
protected List<Cmd> doInBackground(String... urls) {
List<Cmd> videos = null;
String xml = null;
for (String url : urls) {
xml = getXmlFromUrl(url);
InputStream stream = new ByteArrayInputStream(xml.getBytes());
videos = SAXXMLParser.parse(stream);
for (Cmd cmd : videos) {
String videoName = cmd.getVideoName();
}
}
return videos;
}
}
}
Cmd.java
public class Cmd implements ListAdapter {
private String success;
private String cmd;
List<Cmd> videos;
private String video;
private String numberofvideos;
private static String videoname;
private static String videourl;
private LayoutInflater mInflater;
Button fav_up_btn1;
Button fav_dwn_btn1;
Context my_context;
Bitmap imageBitmap;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// If convertView wasn't null it means we have already set it to our
// list_item_user_video so no need to do it again
if (convertView == null) {
// This is the layout we are using for each row in our list
// anything you declare in this layout can then be referenced below
convertView = mInflater.inflate(R.layout.list_item_user_video,
parent, false);
}
// We are using a custom imageview so that we can load images using urls
ImageView thumb = (ImageView) convertView
.findViewById(R.id.userVideoThumbImageView);
//thumb.setScaleType(ScaleType.FIT_XY);
TextView title = (TextView) convertView
.findViewById(R.id.userVideoTitleTextView);
TextView uploader = (TextView) convertView
.findViewById(R.id.userVideouploaderTextView);
TextView viewCount = (TextView) convertView
.findViewById(R.id.userVideoviewsTextView);
uploader.setText(videos.get(position).getTitle());
viewCount.setText(videos.get(position).getviewCount() + " views");
fav_up_btn1 = (Button) convertView.findViewById(R.id.fav_up_btn1);
fav_up_btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
boolean favIsUp = fav_up_btn1
.getBackground()
.getConstantState()
.equals(my_context.getResources()
.getDrawable(R.drawable.fav_up_btn1)
.getConstantState());
// set the background
fav_up_btn1
.setBackgroundResource(favIsUp ? R.drawable.fav_dwn_btn1
: R.drawable.fav_up_btn1);
}
});
// Get a single video from our list
final Cmd video = videos.get(position);
// Set the image for the list item
// / thumb.setImageDrawable(video.getThumbUrl());
//thumb.setScaleType(ScaleType.FIT_XY);
// Set the title for the list item
title.setText(video.getTitle());
uploader.setText("by " + video.getUploader() + " | ");
return convertView;
}
public String getUploader() {
// TODO Auto-generated method stub
return null;
}
public String getviewCount() {
// TODO Auto-generated method stub
return null;
}
public CharSequence getTitle() {
// TODO Auto-generated method stub
return null;
}
public String getCmd() {
return cmd;
}
public void setCmd(String cmd) {
this.cmd = cmd;
}
public String getSuccess() {
return success;
}
public void setSuccess(String success) {
this.success = success;
}
public String getNumberOfVideos() {
return numberofvideos;
}
public void setNumberOfVideos(String numberofvideos) {
this.numberofvideos = numberofvideos;
}
public List<Cmd> getVideos() {
return videos;
}
public void setVideos(List<Cmd> videos) {
this.videos = videos;
}
public String getVideo() {
return video;
}
public void setVideo(String video) {
this.video = video;
}
public static String getVideoName() {
return videoname;
}
public void setVideoName(String videoname) {
this.videoname = videoname;
}
public static String getVideoURL() {
return videourl;
}
public void setVideoURL(String videourl) {
this.videourl = videourl;
}
#Override
public int getCount() {
return videos.size();
}
#Override
public Object getItem(int position) {
return videos.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public int getViewTypeCount() {
// TODO Auto-generated method stub
return 0;
}
#Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean isEmpty() {
// TODO Auto-generated method stub
return false;
}
#Override
public void registerDataSetObserver(DataSetObserver observer) {
// TODO Auto-generated method stub
}
#Override
public void unregisterDataSetObserver(DataSetObserver observer) {
// TODO Auto-generated method stub
}
#Override
public boolean areAllItemsEnabled() {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean isEnabled(int position) {
// TODO Auto-generated method stub
return false;
}
public String getId() {
// TODO Auto-generated method stub
return null;
}
}
XML
<response>
<cmd>getVideos</cmd>
<success>1</success>
<NumberOfVideos>4</NumberOfVideos>
<Videos>
<Video>
<VideoName>sample_iPod</VideoName>
<VideoDesc/>
<VideoUrl>
http://mobile.example.com/api/wp-content/uploads/sites/6/2014/01/api/1/06087297988b.m4v
</VideoUrl>
<VideoTags/>
</Video>
<Video>
<VideoName>sample_mpeg4</VideoName>
<VideoDesc/>
<VideoUrl>
http://mobile.example.com/api/wp-content/uploads/sites/6/2014/01/api/1/b5ed9e7100e2.mp4
</VideoUrl>
<VideoTags/>
</Video>
<Video>
<VideoName>sample_sorenson</VideoName>
<VideoDesc/>
<VideoUrl>
http://mobile.example.com/api/wp-content/uploads/sites/6/2014/01/api/1/2a8e64b24997.mov
</VideoUrl>
<VideoTags/>
</Video>
<Video>
<VideoName>sample_iTunes</VideoName>
<VideoDesc/>
<VideoUrl>
http://mobile.example.com/api/wp-content/uploads/sites/6/2014/01/api/1/6c7f65254aad.mov
</VideoUrl>
<VideoTags/>
</Video>
</Videos>
</response>
1) You don´t need to declare your object Cmd as an Adapter, why 2 adapters :P!
2) your variables videoname and videourl are static!, thats the reason for what you are gettin the same values,change to:
private String videoname;
private String videourl;
you only need an object Cmd as follows:
public class Cmd {
private String success;
private String cmd;
List<Cmd> videos;
private String video;
private String numberofvideos;
private String videoname;
private String videourl;
public String getCmd() {
return cmd;
}
public void setCmd(String cmd) {
this.cmd = cmd;
}
public String getSuccess() {
return success;
}
public void setSuccess(String success) {
this.success = success;
}
public String getNumberOfVideos() {
return numberofvideos;
}
public void setNumberOfVideos(String numberofvideos) {
this.numberofvideos = numberofvideos;
}
public List<Cmd> getVideos() {
return videos;
}
public void setVideos(List<Cmd> videos) {
this.videos = videos;
}
public String getVideo() {
return video;
}
public void setVideo(String video) {
this.video = video;
}
public String getVideoName() {
return videoname;
}
public void setVideoName(String videoname) {
this.videoname = videoname;
}
public String getVideoURL() {
return videourl;
}
public void setVideoURL(String videourl) {
this.videourl = videourl;
}
}
Related
I have a listview getting filtered by an edit text on top. However, when I click on the item searched I get the result of another item being selected.
I Know similar questions are asked and answered by many already, but I went through all the forum but I am breaking my head from long back and sorry newbie much.
Any help will be appreciated.
My adapter:
public class Srv_Adapter extends RecyclerView.Adapter<Srv_Adapter.MyViewHolder> implements Filterable {
List<Srv_Pets> pets, srvPetsFilter;
private Context context;
private RecyclerViewClickListener mListener;
Srv_CustomFilter filter;
public Srv_Adapter(List<Srv_Pets> pets, Context context, RecyclerViewClickListener listener) {
this.pets = pets;
this.srvPetsFilter = pets;
this.context = context;
this.mListener = listener;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_srv, parent, false);
return new MyViewHolder(view, mListener);
}
#SuppressLint("CheckResult")
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
holder.mName.setText(pets.get(position).getName());
holder.mType.setText(pets.get(position).getModel() + " / "
+ pets.get(position).getCreated_by());
holder.mDate.setText(pets.get(position).getBirth());
RequestOptions requestOptions = new RequestOptions();
requestOptions.skipMemoryCache(true);
requestOptions.diskCacheStrategy(DiskCacheStrategy.NONE);
requestOptions.placeholder(R.drawable.logo);
requestOptions.error(R.drawable.logo);
Glide.with(context)
.load(pets.get(position).getPicture())
.apply(requestOptions)
.into(holder.mPicture);
final Boolean love = pets.get(position).getLove();
if (love){
holder.mLove.setImageResource(R.drawable.likeon);
} else {
holder.mLove.setImageResource(R.drawable.likeof);
}
}
#Override
public int getItemCount() {
return pets.size();
}
#Override
public Filter getFilter() {
if (filter==null) {
filter=new Srv_CustomFilter((ArrayList<Srv_Pets>) srvPetsFilter,this);
}
return filter;
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private RecyclerViewClickListener mListener;
private CircleImageView mPicture;
private ImageView mLove;
private TextView mName, mType, mDate;
private RelativeLayout mRowContainer;
public MyViewHolder(View itemView, RecyclerViewClickListener listener) {
super(itemView);
mPicture = itemView.findViewById(R.id.picture);
mName = itemView.findViewById(R.id.name);
mType = itemView.findViewById(R.id.type);
mLove = itemView.findViewById(R.id.love);
mDate = itemView.findViewById(R.id.date);
mRowContainer = itemView.findViewById(R.id.row_container);
mListener = listener;
mRowContainer.setOnClickListener(this);
mLove.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.row_container:
mListener.onRowClick(mRowContainer, getAdapterPosition());
break;
case R.id.love:
mListener.onLoveClick(mLove, getAdapterPosition());
break;
default:
break;
}
}
}
public interface RecyclerViewClickListener {
void onRowClick(View view, int position);
void onLoveClick(View view, int position);
}
}
Search Menu Activity
public class Service_Main extends AppCompatActivity{
SharedPreferences prf;
Intent intent;
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private Srv_Adapter srvAdapter;
private List<Srv_Pets> srvPetsList;
Srv_ApiInterface srvApiInterface;
Srv_Adapter.RecyclerViewClickListener listener;
ProgressBar progressBar;
private String userInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.service_main);
srvApiInterface = Srv_ApiClient.getApiClient().create(Srv_ApiInterface.class);
progressBar = findViewById(R.id.progress);
recyclerView = findViewById(R.id.recyclerView);
layoutManager = new LinearLayoutManager(this);
TextView result = (TextView)findViewById(R.id.result);
recyclerView.setLayoutManager(layoutManager);
prf = getSharedPreferences("user_details",MODE_PRIVATE);
intent = new Intent(Service_Main.this, loginActivity.class);
userInfo = prf.getString("username",null);
listener = new Srv_Adapter.RecyclerViewClickListener() {
private Srv_Pets getIteamposition(int position)
{
return srvPetsList.get(position);
}
#Override
public void onRowClick(View view, final int position) {
Intent intent = new Intent(Service_Main.this, Service_edit.class);
intent.putExtra("id", srvPetsList.get(position).getId());
intent.putExtra("name", srvPetsList.get(position).getName());
intent.putExtra("species", srvPetsList.get(position).getSpecies());
intent.putExtra("jobcard", srvPetsList.get(position).getJobcard());
intent.putExtra("model_code", srvPetsList.get(position).getModel_code());
intent.putExtra("picture", srvPetsList.get(position).getPicture());
intent.putExtra("birth", srvPetsList.get(position).getBirth());
intent.putExtra("entry_mode", srvPetsList.get(position).getEntry_mode());
intent.putExtra("pickup_done_by_code", srvPetsList.get(position).getPickup_done_by_code());
intent.putExtra("drop_mode", srvPetsList.get(position).getDrop_mode());
intent.putExtra("service_type", srvPetsList.get(position).getDrop_mode());
intent.putExtra("drop_done_by_code", srvPetsList.get(position).getDrop_done_by_code());
intent.putExtra("pick_emp_name", srvPetsList.get(position).getPick_emp_name());
intent.putExtra("drop_emp_name", srvPetsList.get(position).getDrop_emp_name());
startActivity(intent);
final int id = srvPetsList.get(position).getId();
final Boolean love = srvPetsList.get(position).getLove();
final ImageView mLove = view.findViewById(R.id.love);
if (love){
mLove.setImageResource(R.drawable.likeof);
srvPetsList.get(position).setLove(false);
updateLove("Rd_status", id, false);
srvAdapter.notifyDataSetChanged();
} else {
mLove.setImageResource(R.drawable.likeon);
srvPetsList.get(position).setLove(true);
updateLove("Rd_status", id, true);
srvAdapter.notifyDataSetChanged();
}
}
#Override
public void onLoveClick(View view, int position) {
// final int id = srvPetsList.get(position).getId();
// final Boolean love = srvPetsList.get(position).getLove();
// final ImageView mLove = view.findViewById(R.id.love);
// if (love){
// mLove.setImageResource(R.drawable.likeof);
// srvPetsList.get(position).setLove(false);
// updateLove("Rd_status", id, false);
// srvAdapter.notifyDataSetChanged();
// } else {
// mLove.setImageResource(R.drawable.likeon);
// srvPetsList.get(position).setLove(true);
// updateLove("Rd_status", id, true);
// srvAdapter.notifyDataSetChanged();
// }
}
};
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(Service_Main.this, Service_edit.class));
}
});
FloatingActionButton fab1 = findViewById(R.id.log_out);
fab1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Service_Main.this, HomePage.class));
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
final SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
MenuItem searchMenuItem = menu.findItem(R.id.action_search);
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName())
);
searchView.setQueryHint("Search Pet...");
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(final String query) {
srvAdapter.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
srvAdapter.getFilter().filter(newText);
return false;
}
});
searchMenuItem.getIcon().setVisible(false, false);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void getPets(){
String username = userInfo;
Call<List<Srv_Pets>> call = srvApiInterface.getPets(username);
call.enqueue(new Callback<List<Srv_Pets>>() {
#Override
public void onResponse(Call<List<Srv_Pets>> call, Response<List<Srv_Pets>> response) {
progressBar.setVisibility(View.GONE);
srvPetsList = response.body();
Log.i(Service_Main.class.getSimpleName(), response.body().toString());
srvAdapter = new Srv_Adapter(srvPetsList, Service_Main.this, listener);
recyclerView.setAdapter(srvAdapter);
srvAdapter.notifyDataSetChanged();
}
#Override
public void onFailure(Call<List<Srv_Pets>> call, Throwable t) {
Toast.makeText(Service_Main.this, "rp :"+
t.getMessage().toString(),
Toast.LENGTH_SHORT).show();
}
});
}
public void updateLove(final String key, final int id, final Boolean love){
String night_updated_by = userInfo;
String reg_num = userInfo;
Call<Srv_Pets> call = srvApiInterface.updateLove(key, id, love, night_updated_by, reg_num);
call.enqueue(new Callback<Srv_Pets>() {
#Override
public void onResponse(Call<Srv_Pets> call, Response<Srv_Pets> response) {
Log.i(Service_Main.class.getSimpleName(), "Response "+response.toString());
String value = response.body().getValue();
String message = response.body().getMassage();
if (value.equals("1")){
Toast.makeText(Service_Main.this, message, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(Service_Main.this, message, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<Srv_Pets> call, Throwable t) {
Toast.makeText(Service_Main.this, t.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
protected void onResume() {
super.onResume();
getPets();
}
}
List of Items from PHP, MYSQL using Volly
package com.haerul.mypets.service;
import com.google.gson.annotations.SerializedName;
public class Srv_Pets {
#SerializedName("id")
private int id;
#SerializedName("name")
private String name;
#SerializedName("species")
private String species;
#SerializedName("breed")
private String breed;
#SerializedName("model_code")
private int model_code;
#SerializedName("jobcard")
private int jobcard;
#SerializedName("birth")
private String birth;
#SerializedName("picture")
private String picture;
#SerializedName("love")
private Boolean love;
#SerializedName("value")
private String value;
#SerializedName("message")
private String massage;
#SerializedName("model")
private String model;
#SerializedName("entry_mode")
private int entry_mode;
#SerializedName("drop_mode")
private int drop_mode;
#SerializedName("pickup_done_by_code")
private String pickup_done_by_code;
#SerializedName("service_type")
private int service_type;
#SerializedName("drop_done_by_code")
private String drop_done_by_code;
#SerializedName("pick_emp_name")
private String pick_emp_name;
#SerializedName("drop_emp_name")
private String drop_emp_name;
#SerializedName("created_by")
private String created_by;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSpecies() {
return species;
}
public void setSpecies(String species) {
this.species = species;
}
public int getModel_code() {
return model_code;
}
public void setModel_code(int gender) {
this.model_code = model_code;
}
public int getJobcard() {
return jobcard;
}
public void setJobcard(int jobcard) {
this.jobcard = jobcard;
}
public String getBirth() {
return birth;
}
public void setBirth(String birth) {
this.birth = birth;
}
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
public Boolean getLove() {
return love;
}
public void setLove(Boolean love) {
this.love = love;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getMassage() {
return massage;
}
public void setMassage(String massage) {
this.massage = massage;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getEntry_mode(){
return entry_mode;
}
public void setEntry_mode(int entry_mode){
this.entry_mode = entry_mode;
}
public String getPickup_done_by_code() {
return pickup_done_by_code;
}
public void setPickup_done_by_code(String pickup_done_by_code) {
this.pickup_done_by_code = pickup_done_by_code;
}
public int getDrop_mode(){
return drop_mode;
}
public void setDrop_mode(int drop_mode){
this.drop_mode = drop_mode;
}
public int getService_type(){
return service_type;
}
public void setService_type(){
this.service_type = service_type;
}
public String getDrop_done_by_code(){
return drop_done_by_code;
}
public void setDrop_done_by_code(String drop_done_by_code){
this.pickup_done_by_code = drop_done_by_code;
}
public String getPick_emp_name(){
return pick_emp_name;
}
public void setPick_emp_name(String pick_emp_name){
this.pick_emp_name = pick_emp_name;
}
public String getDrop_emp_name(){
return drop_emp_name;
}
public void setDrop_emp_name(String drop_emp_name){
this.pick_emp_name = pick_emp_name;
}
public String getCreated_by(){
return created_by;
}
public void setCreated_by(String created_by){
this.created_by = created_by;
}
}
This is the Data model
package com.basirahmad.qpaisa.data_model;
public class Banner_data_model {
private String banner_url_com_logo;
private String banner_txt_title;
private String banner_txt_name;
private String banner_txt_description;
private String banner_url_banner;
private String banner_date_publish;
private String banner_date_expire;
private String banner_max_view;
private int banner_com_id;
private int banner_schedual_id;
private int banner_id;
public String getBanner_url_com_logo() {
return banner_url_com_logo;
}
public void setBanner_url_com_logo(String banner_url_com_logo) {
this.banner_url_com_logo = banner_url_com_logo;
}
public String getBanner_txt_title() {
return banner_txt_title;
}
public void setBanner_txt_title(String banner_txt_title) {
this.banner_txt_title = banner_txt_title;
}
public String getBanner_txt_name() {
return banner_txt_name;
}
public void setBanner_txt_name(String banner_txt_name) {
this.banner_txt_name = banner_txt_name;
}
public String getBanner_txt_description() {
return banner_txt_description;
}
public void setBanner_txt_description(String banner_txt_description) {
this.banner_txt_description = banner_txt_description;
}
public String getBanner_url_banner() {
return banner_url_banner;
}
public void setBanner_url_banner(String banner_url_banner) {
this.banner_url_banner = banner_url_banner;
}
public String getBanner_date_publish() {
return banner_date_publish;
}
public void setBanner_date_publish(String banner_date_publish) {
this.banner_date_publish = banner_date_publish;
}
public String getBanner_date_expire() {
return banner_date_expire;
}
public void setBanner_date_expire(String banner_date_expire) {
this.banner_date_expire = banner_date_expire;
}
public String getBanner_max_view() {
return banner_max_view;
}
public void setBanner_max_view(String banner_max_view) {
this.banner_max_view = banner_max_view;
}
public int getBanner_com_id() {
return banner_com_id;
}
public void setBanner_com_id(int banner_com_id) {
this.banner_com_id = banner_com_id;
}
public int getBanner_schedual_id() {
return banner_schedual_id;
}
public void setBanner_schedual_id(int banner_schedual_id) {
this.banner_schedual_id = banner_schedual_id;
}
public int getBanner_id() {
return banner_id;
}
public void setBanner_id(int banner_id) {
this.banner_id = banner_id;
}
}
This is the Adapter Class
package com.basirahmad.qpaisa.adapter;
public class Banner_adapter_con extend
RecyclerView.Adapter<Banner_adapter_con.BannerViewHolder> {
private Context context;
private List<Banner_data_model> banner_data_models;
//the class canstractor;
public Banner_adapter_con(Context context, List<Banner_data_model>banner_data_models ){
this.context = context;
this.banner_data_models = banner_data_models;
}
#Override
public BannerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.banner_view,parent,false);
return new BannerViewHolder(view);
}
#Override
public void onBindViewHolder(BannerViewHolder holder, int position) {
Banner_data_model data_model = banner_data_models.get(position);
holder.company_logo.setImageURI(Uri.parse(data_model.getBanner_url_com_logo()));
holder.title.setText(data_model.getBanner_txt_title());
holder.name.setText(data_model.getBanner_txt_name());
holder.description.setText(data_model.getBanner_txt_description());
holder.banner.setImageURI(Uri.parse(data_model.getBanner_url_banner()));
}
#Override
public int getItemCount() {
return banner_data_models.size();
}
public class BannerViewHolder extends RecyclerView.ViewHolder{
private ImageView company_logo;
private ImageView banner;
private TextView title;
private TextView name;
private ReadMoreTextView description;
public BannerViewHolder(View itemView) {
super(itemView);
company_logo = (ImageView) itemView.findViewById(R.id.img_company_logo);
banner = (ImageView) itemView.findViewById(R.id.img_banner);
title = (TextView) itemView.findViewById(R.id.banner_txt_title);
name = (TextView) itemView.findViewById(R.id.banner_txt_name);
description = (ReadMoreTextView) itemView.findViewById(R.id.banner_txt_description);
}
}
}
This is the Fragment Class
package com.basirahmad.qpaisa.Fragment;
public class Banner_fragment extends Fragment {
private RecyclerView recyclerView;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable final ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.banner_fragment,container,false);
Banner_data_server banner_data_server = new Banner_data_server(this.getActivity());
recyclerView = (RecyclerView)view.findViewById(R.id.banner_fragment);
banner_data_server.getBanner(new Banner_data_server.OnbannerRecevid() {
#Override
public void onRecevid(List<Banner_data_model> banner_data_models) {
Banner_adapter banner_adapter =new Banner_adapter(getActivity(),banner_data_models);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false));
recyclerView.setAdapter(banner_adapter);
}
});
return view;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
It will not throw any error. It just means when you initialized your RecyclerView you've not set its adapter,
IF you still want to remove this warning, you can call
recyclerview.setAdapter(adapter)
just after its initialization. will remove the warning.
how derar this is the class the get data from server i forgot this class to add to the quastion.
enter code here the class code
package com.basirahmad.qpaisa.connect_to_server;
public class Banner_data_server {
private Context context;
public Banner_data_server(Context context){
this.context = context;
}
public void getBanner(final OnbannerRecevid onbannerRecevid){
JsonArrayRequest arrayRequest = new JsonArrayRequest(Request.Method.POST, Url_of_server.urlReadBanner, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
List<Banner_data_model> banner_data_models = new ArrayList<>();
for (int i =0;i<response.length();i++){
Banner_data_model data_model = new Banner_data_model();
try {
JSONObject jsonObject =response.getJSONObject(i);
data_model.setBanner_id(jsonObject.getInt("Banner_id"));
data_model.setBanner_txt_name(jsonObject.getString("Banner_name"));
data_model.setBanner_txt_description(jsonObject.getString("Banner_description"));
data_model.setBanner_url_banner(jsonObject.getString("location"));
data_model.setBanner_schedual_id(jsonObject.getInt("id"));
data_model.setBanner_date_publish(jsonObject.getString("date_publish"));
data_model.setBanner_date_expire(jsonObject.getString("expire_date"));
data_model.setBanner_com_id(jsonObject.getInt("com_id"));
data_model.setBanner_url_com_logo(jsonObject.getString("logo"));
banner_data_models.add(data_model);
} catch (JSONException e) {
e.printStackTrace();
}
}
onbannerRecevid.onRecevid(banner_data_models);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context,error.getMessage(),Toast.LENGTH_LONG).show();
}
});
arrayRequest.setRetryPolicy(new DefaultRetryPolicy(18000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(arrayRequest);
}
public interface OnbannerRecevid{
void onRecevid(List<Banner_data_model> banner_data_models);
}
}
Main Code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.movie);
lv =(ListView)findViewById(R.id.lstMovieData);
moviename.clear();
// tv = (TextView) findViewById(R.id.tv);
Bundle b = getIntent().getExtras();
try {
Title = b.getString("MOVIE");
t = replace(Title);
} catch (Exception e) {
}
String API = "https://api.cinemalytics.com/v1/movie/title/?value=" + t + "&auth_token=<token>";
Toast.makeText(getApplicationContext(), Title, Toast.LENGTH_LONG).show();
OkHttpClient Client = new OkHttpClient();
Request request = new Request.Builder()
.url(API).build();
Call call = Client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
}
#Override
public void onResponse(final Response response) throws IOException {
try {
String json = response.body().string();
Log.v(TAG, json);
if (response.isSuccessful()) {
getDATA(json);
runOnUiThread(new Runnable() {
#Override
public void run() {
mAdapter = new MovieAdapter(getApplicationContext(),moviename);
lv.setAdapter(mAdapter);
}
});
} else {
}
} catch (Exception e) {
}
}
});
}
public String replace(String str) {
return str.replaceAll(" ", "%20");
}
private void getDATA(String json) throws JSONException {
try {
moviename = new ArrayList<>();
Currentmovie c = new Currentmovie();
String story = "About The Story";
JSONArray values = new JSONArray(json);
for(int i = 0; i < values.length(); i++) {
JSONObject jsonObject = values.getJSONObject(i);
String movieTitle = jsonObject.getString("Title");
String disc = jsonObject.getString("Description");
Log.e(TAG,"GIRISH"+movieTitle);
c= new Currentmovie();
c.setTitle("Movie Name::"+movieTitle);
c.setDesc(story+"::\n"+disc);
if(jsonObject.getString("Description")==null)
{
c.setDesc(story+"::Not Available");
}
moviename.add(c);
}
}
catch (Exception e)
{
System.out.println("Error in Result as " + e.toString());
}
}
2.MovieAdapter.java
public class MovieAdapter extends BaseAdapter {
Context context;
private List<Currentmovie> movieData;
private static LayoutInflater inflater = null;
public MovieAdapter( Context context,List<Currentmovie> movieData)
{
this.context = context;
this.movieData = movieData;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return movieData.size();
}
#Override
public Object getItem(int position) {
return movieData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public static class ViewHolder{
public TextView movieTitle,movieDesc;
public ImageView movieImage;
}
public View getView(int position, View convertView, ViewGroup parent)
{
View vi = convertView;
ViewHolder holder;
if(convertView==null){
vi = inflater.inflate(R.layout.row, null);
holder = new ViewHolder();
holder.movieTitle = (TextView) vi.findViewById(R.id.tv);
holder.movieDesc=(TextView)vi.findViewById(R.id.tv1);
vi.setTag( holder );
}
else
holder=(ViewHolder)vi.getTag();
holder.movieTitle.setText(movieData.get(position).getTitle());
holder.movieDesc.setText(movieData.get(position).getDesc());
return vi;
}
}
//i can successfully show all data except image
//image link comes with "posterpath" key
//tell me how to load image in viewholder of MovieAdapter
//currentmovie is just a getter and setter class
3.Currentmovie.java
public class Currentmovie {
private String mTitle;
private String Description;
public String getDesc() {
return Description;
}
public void setDesc(String desc) {
Description = desc;
}
public String getTitle() {
return mTitle;
}
public void setTitle(String title) {
mTitle = title;
}
}
I am using this library and loading images by
first creating the Display options object by
DisplayImageOptions builder = new DisplayImageOptions.Builder()
.cacheOnDisk(true)
.showImageOnLoading(R.drawable.empty_photo)
.showImageForEmptyUri(R.drawable.empty_photo)
.build();
Then initialze the image loader by
ImageLoader imageLoader = ImageLoader.getInstance();
and load images by
imageLoader.displayImage(url, imageView, builder);
Hope this helps..
also add this to you gradle
compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
Refer this first
EDIT: Add this to onCreate() of activity
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
...
.build();
ImageLoader.getInstance().init(config);
or this
ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(Activity.this));
Add getter and setter methods for your Image like
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imgUrl) {
imageUrl= imgUrl;
}
Add this code in your adapter class after adding Picasso library to your project:
String imageUrl = movieData.get(position).getImageUrl();
Picasso.with(getContext())
.load(imageUrl)
.into(holder.movieImage, new com.squareup.picasso.Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
}
});
I am making a call to a server using Retrofit and getting a json response. The error I'm getting is:
Expected BEGIN_OBJECT but was BEGIN_ARRAY
This is my code
Main method,
public class MainActivity extends ListActivity {
List<Movie> movieList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final RestAdapter restadapter = new RestAdapter.Builder().setEndpoint("http://api.themoviedb.org").build();
api movieapi = restadapter.create(api.class);
movieapi.getData(new Callback<List<Movie>>() {
#Override
public void success(List<Movie> movies, Response response) {
movieList = movies;
adapter adapt = new adapter(getApplicationContext(),R.layout.item_file,movieList);
//ListView listView = (ListView) findViewById(R.id.list);
setListAdapter(adapt);
}
#Override
public void failure(RetrofitError error) {
Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
Interface api
public interface api {
#GET("/3/discover/movie?sort_by=popularity.desc&api_key=e2a804764747474747474574817b218e")
public void getData(Callback<List<Movie>> response);
}
class adapter
public class adapter extends ArrayAdapter<Movie> {
String url = "http://image.tmdb.org/t/p/w185";
private Context context;
private List<Movie> movieList;
public adapter(Context context, int resource, List<Movie> objects) {
super(context, resource, objects);
this.context = context;
this.movieList = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.item_file,parent,false);
Movie movie = movieList.get(position);
TextView tv = (TextView) view.findViewById(R.id.name);
tv.setText(movie.getTitle());
ImageView img = (ImageView) view.findViewById(R.id.img);
Picasso.with(getContext()).load(url+movie.getPoster_path()).into(img);
return view;
}
}
Movie class (Where I handle the getters setters for json)
package com.wuno.moviesapp.model;
public class Movie
{
private String vote_average;
private String backdrop_path;
private String adult;
private String id;
private String title;
private String original_language;
private String overview;
private String[] genre_ids;
private String original_title;
private String release_date;
private String vote_count;
private String poster_path;
private String video;
private String popularity;
public String getVote_average ()
{
return vote_average;
}
public void setVote_average (String vote_average)
{
this.vote_average = vote_average;
}
public String getBackdrop_path ()
{
return backdrop_path;
}
public void setBackdrop_path (String backdrop_path)
{
this.backdrop_path = backdrop_path;
}
public String getAdult ()
{
return adult;
}
public void setAdult (String adult)
{
this.adult = adult;
}
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public String getTitle ()
{
return title;
}
public void setTitle (String title)
{
this.title = title;
}
public String getOriginal_language ()
{
return original_language;
}
public void setOriginal_language (String original_language)
{
this.original_language = original_language;
}
public String getOverview ()
{
return overview;
}
public void setOverview (String overview)
{
this.overview = overview;
}
public String[] getGenre_ids ()
{
return genre_ids;
}
public void setGenre_ids (String[] genre_ids)
{
this.genre_ids = genre_ids;
}
public String getOriginal_title ()
{
return original_title;
}
public void setOriginal_title (String original_title)
{
this.original_title = original_title;
}
public String getRelease_date ()
{
return release_date;
}
public void setRelease_date (String release_date)
{
this.release_date = release_date;
}
public String getVote_count ()
{
return vote_count;
}
public void setVote_count (String vote_count)
{
this.vote_count = vote_count;
}
public String getPoster_path ()
{
return poster_path;
}
public void setPoster_path (String poster_path)
{
this.poster_path = poster_path;
}
public String getVideo ()
{
return video;
}
public void setVideo (String video)
{
this.video = video;
}
public String getPopularity ()
{
return popularity;
}
public void setPopularity (String popularity)
{
this.popularity = popularity;
}
#Override
public String toString()
{
return "Movie [vote_average = "+vote_average+", backdrop_path = "+backdrop_path+", adult = "+adult+", id = "+id+", title = "+title+", original_language = "+original_language+", overview = "+overview+", genre_ids = "+genre_ids+", original_title = "+original_title+", release_date = "+release_date+", vote_count = "+vote_count+", poster_path = "+poster_path+", video = "+video+", popularity = "+popularity+"]";
}
}
Retrofit tries to parse the result to the type you've specified, and this is not the type that is returned. The list you've specified is a member of the object that returns.
You should create an object for the response:
public class MoviesResponse {
private int page;
private List<Movie> results;
private int total_pages;
private int total_results;
}
And change your callback:
#GET("/3/discover/movie?sort_by=popularity.desc&api_key=your_api_key")
public void getData(Callback<MoviesResponse> response);
I have a listView populated with JSON data obtained from YouTube:
private VideosListView listView;
As of now - the listView succesfully populates with the data I'm looking for however I need to be able to repopulate it with updated data. Currently - I execute/populate the initial listView using:
new GetYouTubeUserVideosTask(responseHandler, playlist).execute();
What I'd like to do is repopulate it using a different value for String playlist:
String playlist = "TheMozARTGROUP";
new GetYouTubeUserVideosTask(responseHandler, playlist)
.execute();
View vg = findViewById(R.layout.home);
vg.invalidate();
P.S.
What I've attempted to use thus far does not seem to be working - nothing happens when I swipe the ViewPager - however if I set a toast there it will appear when swiping it.
I don't know why this has been such a difficult issue to nail down - but I'd be more than happy to leave a tip via paypal for anyone who can solve this issue.
http://i.stack.imgur.com/e0QqU.png
JAVA: Home.java
public class Home extends YouTubeBaseActivity implements
VideoClickListener {
private VideosListView listView;
private int mCurrentTabPosition = NO_CURRENT_POSITION;
private static final int NO_CURRENT_POSITION = -1;
private ListView drawerListView;
String playlist = "knocksteadyTV";
Activity activity;
int imageArray[];
String[] stringArray;
String runPrevious = "No";
private OnPageChangeListener mPageChangeListener;
ImagePagerAdapter adapter = new ImagePagerAdapter();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
final ViewPager mPager = (ViewPager) findViewById(R.id.view_pager);
adapter.notifyDataSetChanged();
mPager.setAdapter(adapter);
mPager.setOnPageChangeListener(mPageChangeListener);
listView = (VideosListView) findViewById(R.id.videosListView);
listView.setOnVideoClickListener(this);
new GetYouTubeUserVideosTask(responseHandler, playlist).execute();
mPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int pos) {
Toast.makeText(getApplicationContext(), "onPageSelected",
Toast.LENGTH_SHORT).show();
String playlist = "TheMozARTGROUP";
new GetYouTubeUserVideosTask(responseHandler, playlist).execute();
adapter.notifyDataSetChanged();
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
// Toast.makeText(getApplicationContext(), "onPageScrolled",
// Toast.LENGTH_SHORT).show();
}
#Override
public void onPageScrollStateChanged(int pos) {
Toast.makeText(getApplicationContext(),
"onPageScrollStateChanged", Toast.LENGTH_SHORT).show();
String playlist = "TheMozARTGROUP";
new GetYouTubeUserVideosTask(responseHandler, playlist)
.execute();
adapter.notifyDataSetChanged();
}
});
mPageChangeListener = new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
onTabChanged(mPager.getAdapter(), mCurrentTabPosition, position);
position = mCurrentTabPosition;
int oldPos = mPager.getCurrentItem();
if (position > oldPos) {
System.out.print(position);
// Moving to the right
String playlist = "TheMozARTGROUP";
new GetYouTubeUserVideosTask(responseHandler, playlist)
.execute();
View vg = findViewById(R.layout.home);
vg.invalidate();
} else if (position < oldPos) {
// Moving to the Left
System.out.print(position);
String playlist = "TheMozARTGROUP";
new GetYouTubeUserVideosTask(responseHandler, playlist)
.execute();
View vg = findViewById(R.layout.home);
vg.invalidate();
}
mPager.setOnPageChangeListener(mPageChangeListener);
}
private void onTabChanged(PagerAdapter adapter,
int mCurrentTabPosition, int position) {
// TODO Auto-generated method stub
}
};}
private class MyActivityGetYouTubeUserVideosTask extends GetYouTubeUserVideosTask {
public MyActivityGetYouTubeUserVideosTask(Handler replyTo,
String username) {
super(replyTo, username);
// TODO Auto-generated constructor stub
}
#Override
protected void onPostExecute(Void result) {
if (result != null) {
// TODO update your list data
// note: assuming your data is stored in an ArrayList<MyData>,
// you cannot create a new one. you must clear() the current
// ArrayList and add() the result to it.
}
adapter.notifyDataSetChanged();
}
}
private void _initMenu() {
}
Handler replyTo = new Handler() {
#Override
public void handleMessage(Message msg) {
populateListWithVideos(msg);
};
};
Handler responseHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
populateListWithVideos(msg);
};
};
private void populateListWithVideos(Message msg) {
Library lib = (Library) msg.getData().get(
GetYouTubeUserVideosTask.LIBRARY);
listView.setVideos(lib.getVideos());
}
#Override
protected void onStop() {
responseHandler = null;
super.onStop();
}
#Override
public void onVideoClicked(Video video) {
Intent intent = new Intent(this, Player.class);
intent.putExtra("id", video.getId());
intent.putExtra("title", video.getTitle());
intent.putExtra("uploader", video.getUploader());
intent.putExtra("viewCount", video.getviewCount());
startActivity(intent);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class ImagePagerAdapter extends PagerAdapter {
public ImagePagerAdapter(Activity act, int[] mImages,
String[] stringArra) {
imageArray = mImages;
activity = act;
stringArray = stringArra;
}
// this is your constructor
public ImagePagerAdapter() {
super();
}
private int[] mImages = new int[] { R.drawable.selstation_up_btn,
R.drawable.classical_up_btn, R.drawable.country_up_btn,
R.drawable.dance_up_btn, R.drawable.hiphop_up_btn,
R.drawable.island_up_btn, R.drawable.latin_up_btn,
R.drawable.pop_up_btn, R.drawable.samba_up_btn };
private String[] stringArray = new String[] { "vevo",
"TheMozARTGROUP", "TimMcGrawVEVO", "TiestoVEVO",
"EminemVEVO" };
#Override
public int getCount() {
return mImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = Home.this;
ImageView imageView = new ImageView(context);
imageView.setScaleType(ScaleType.FIT_XY);
imageView.setImageResource(mImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view,
int position, long id) {
drawerListView.setItemChecked(position, true);
setTitle("......");
String text = "menu click... should be implemented";
Toast.makeText(Home.this, text, Toast.LENGTH_LONG).show();
drawerLayout.closeDrawer(drawerListView);
}
}
}
}
JAVA: GetYoutubeVideosTask.java
public class GetYouTubeUserVideosTask extends AsyncTask<Void, Void, Void> {
public static final String LIBRARY = "Library";
private final Handler replyTo;
private final String username;
public GetYouTubeUserVideosTask(Handler replyTo, String username) {
this.replyTo = replyTo;
this.username = username;
}
/*
* #see android.os.AsyncTask#doInBackground(Params[])
*/
#Override
protected Void doInBackground(Void... arg0) {
try {
HttpClient client = new DefaultHttpClient();
HttpUriRequest request = new HttpGet("https://gdata.youtube.com/feeds/api/videos?author="+username+"&v=2&alt=jsonc");
HttpResponse response = client.execute(request);
String jsonString = StreamUtils.convertToString(response.getEntity().getContent());
JSONObject json = new JSONObject(jsonString);
JSONArray jsonArray = json.getJSONObject("data").getJSONArray("items");
List<Video> videos = new ArrayList<Video>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String title = jsonObject.getString("title");
String id = jsonObject.getString("id");
String viewCount = jsonObject.getString("viewCount");
String uploader = jsonObject.getString("uploader");
String url;
try {
url = jsonObject.getJSONObject("player").getString("mobile");
} catch (JSONException ignore) {
url = jsonObject.getJSONObject("player").getString("default");
}
String thumbUrl = jsonObject.getJSONObject("thumbnail").getString("hqDefault");
videos.add(new Video(title, id, viewCount, uploader, url, thumbUrl));
}
Library lib = new Library(username, videos);
Bundle data = new Bundle();
data.putSerializable(LIBRARY, lib);
Message msg = Message.obtain();
msg.setData(data);
replyTo.sendMessage(msg);
} catch (ClientProtocolException e) {
Log.e("Feck", e);
} catch (IOException e) {
Log.e("Feck", e);
} catch (JSONException e) {
Log.e("Feck", e);
}
return null;
}
/*
* #see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
#Override
protected void onPostExecute(Void result) {
//adapter.notifyDataSetChanged();
}
}