Thanks in advance for the help, my code below is taken in a Text File and Displaying it in a ListView, i have Name and youtube in one Line inside the text field.
but what i am looking at trying to do is get the youtube String inside the text file and pass that to my new Activity class as a webview to play the video
just wondering how can this be done, how can i pass this String into my Setters inside my Model class in order to get an Instance of it, do i need to convert String to ArrayListString ?
public class menuFragment extends ListFragment {
ArrayList<model> songList = new ArrayList<model>();
public String[] listSongs = new String[]{};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.list_fragment, container, false);
loadSongs();
return view;
}
public void loadSongs() {
try {
Resources ResFiles = getResources();
InputStream ReadDbFile = ResFiles.openRawResource(R.raw.songs);
byte[] Bytes = new byte[ReadDbFile.available()];
ReadDbFile.read(Bytes);
String DbLines = new String(Bytes);
listSongs = DbLines.split(",");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, listSongs);
setListAdapter(adapter);
} catch (Exception e) {
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Intent i = new Intent(getActivity(), playVid.class);
model selectedSong = MainController.getInstance().getSongs().get(position);
i.putExtra("selectedSong", selectedSong);
startActivity(i);
}
public class model implements Serializable {
private String name;
private String url;
public model(String name, String url) {
this.name=name;
this.url = url;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl(){
return url;
}
public void setUrl(String url){
this.url = url;
}
public class MainController
{
private static MainController instance;
private ArrayList<model> songList;
private MainController()
{
this.songList = new ArrayList<model>();
}
public static MainController getInstance()
{
if(instance == null)
{
instance = new MainController();
}
return instance;
}
public void addFlight(String name, String singer, String url)
{
model f = new model(name,singer,url);
this.songList.add(f);
}
public ArrayList<model> getSongs()
{
return this.songList;
}
Suggestion class name should be start with capital - Model.
You have only three variables to pass to another activity, so you can have three putExtra with your intent no need for ArrayList, Sir.
Model selectedSong = MainController.getInstance().getSongs().get(position);
i.putExtra("name", selectedSong.getName());
i.putExtra("singer", selectedSong.getSinger());
i.putExtra("url", selectedSong.getUrl());
startActivity(i);
And inside onCreate of another Activity, we can access these three values like this way,
Intent mIntent = getIntent();
String name = mIntent.getStringExtra("name");
String singer = mIntent.getStringExtra("singer");
String url = mIntent.getStringExtra("url");
Related
I have trouble getting data from adapter to fragment. I want to display some information through recycler view but the problem is that I have an error in getting the data arraylist in my VaccineAdapter.
This is my patientlogin class once the user login the account. I want to display his/her personal information as well as the his her vaccine history in a recyclerView order.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_patient_login);
name = findViewById(R.id.fullName);
IdNo = findViewById(R.id.idNumber);
}
// Validate name
private Boolean validateName(){
String val = name.getText().toString();
if(val.isEmpty()){
name.setError("Field is Empty");
return false;
}else{
name.setError(null);
name.setEnabled(false);
return true;
}
}
// Validate ID number
private Boolean validateIdNumber(){
String val = IdNo.getText().toString();
if(val.isEmpty()){
IdNo.setError("Field cannot be empty");
return false;
}else{
IdNo.setError(null);
name.setEnabled(false);
return true;
}
}
public void loginPatient(View view){
//validate Login info
if (!validateName() | !validateIdNumber()) {
return;
}else{
isUser();
}
}
//if validation is correct
private void isUser() {
final String userEnteredIdNo = IdNo.getText().toString().trim();
final String userEnteredName = name.getText().toString().trim();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Patient List");
Query checkUser = reference.orderByChild("id").equalTo(userEnteredIdNo);
checkUser.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
IdNo.setError(null);
IdNo.setEnabled(false);
String IdNoFromDB = dataSnapshot.child(userEnteredIdNo).child("name").getValue(String.class);
if(IdNoFromDB.equals(userEnteredName)){
IdNo.setError(null);
IdNo.setEnabled(false);
String imageFromDB = dataSnapshot.child(userEnteredIdNo).child("image").getValue(String.class);
String idFromDB = dataSnapshot.child(userEnteredIdNo).child("id").getValue(String.class);
String nameFromDB = dataSnapshot.child(userEnteredIdNo).child("name").getValue(String.class);
String ageFromDB = dataSnapshot.child(userEnteredIdNo).child("age").getValue(String.class);
String birthdayFromDB = dataSnapshot.child(userEnteredIdNo).child("birthday").getValue(String.class);
String addressFromDB = dataSnapshot.child(userEnteredIdNo).child("address").getValue(String.class);
String vaccineNameFromDB= dataSnapshot.child(userEnteredIdNo).child("vaccine_Name").getValue(String.class);
String institutionNameFromDB = dataSnapshot.child(userEnteredIdNo).child("institution_Name").getValue(String.class);
String vaccineDateFromDB = dataSnapshot.child(userEnteredIdNo).child("vaccine_Date").getValue(String.class);
PatientInfoHelperClass helperClass = new PatientInfoHelperClass(imageFromDB , idFromDB , nameFromDB , ageFromDB , birthdayFromDB ,addressFromDB ,vaccineNameFromDB , vaccineDateFromDB , institutionNameFromDB);
Intent intent = new Intent( patientLogin.this , patientProfile.class);
Bundle bundle = new Bundle();
bundle.putParcelable("helperClass", Parcels.wrap(helperClass));
intent.putExtras(bundle);
startActivity(intent);
}
else{
name.setError("No such name exists");
name.requestFocus();
}
}
else{
IdNo.setError("Wrong Id Number");
IdNo.requestFocus();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
This is my VaccineAdapter this is the adapter
public VaccineAdapter(Context context, List<PatientInfoHelperClass> mList) {
this.mList = mList;
this.context = context;
}
#NonNull
#Override
public VaccineAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.vaccine_list,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull VaccineAdapter.MyViewHolder holder, int position) {
//get data
String vName = mList.get(position).getVaccine_Name();
String iName = mList.get(position).getInstitution_Name();
String vDate = mList.get(position).getVaccine_Date();
//set data
holder.vaccine_Name.setText(vName);
holder.institution_Name.setText(iName);
holder.vaccine_Date.setText(vDate);
}
#Override
public int getItemCount() {
return mList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder{
TextView vaccine_Name, institution_Name, vaccine_Date;
public MyViewHolder(View itemView){
super(itemView);
vaccine_Name = itemView.findViewById(R.id.vaccineName);
institution_Name = itemView.findViewById(R.id.institutionName);
vaccine_Date = itemView.findViewById(R.id.vaccineDate);
}
}
This is my HistoryFragment connected to vaccine adapter where I want to display vaccine history in a recyclerview order.
RecyclerView recyclerView;
List<PatientInfoHelperClass> mList;
VaccineAdapter adapter;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public HistoryFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment HistoryFragment.
*/
// TODO: Rename and change types and number of parameters
public static HistoryFragment newInstance(String param1, String param2) {
HistoryFragment fragment = new HistoryFragment();
Bundle bundle = new Bundle();
bundle.putString(ARG_PARAM1, param1);
bundle.putString(ARG_PARAM2, param2);
fragment.setArguments(bundle);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle args = getActivity().getIntent().getExtras();
View v = inflater.inflate(R.layout.fragment_history, container, false);
recyclerView = v.findViewById(R.id.historyRecyclerView);
mList = args.getParcelable("helperClass");
adapter = new VaccineAdapter (getActivity(), mList);
recyclerView.setAdapter(adapter);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return v;
}
This is my PatientInfoHelperClass
#Parcel
public class PatientInfoHelperClass {
String image, name, id, age, birthday, address, institution_Name, vaccine_Name, vaccine_Date;
public PatientInfoHelperClass() {
}
public PatientInfoHelperClass(String image, String name, String id, String age, String birthday, String address, String institution_Name, String vaccine_Name, String vaccine_Date) {
this.image = image;
this.name = name;
this.id = id;
this.age = age;
this.birthday = birthday;
this.address = address;
this.institution_Name = institution_Name;
this.vaccine_Name = vaccine_Name;
this.vaccine_Date = vaccine_Date;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getInstitution_Name() {
return institution_Name;
}
public void setInstitution_Name(String institution_Name) {
this.institution_Name = institution_Name;
}
public String getVaccine_Name() {
return vaccine_Name;
}
public void setVaccine_Name(String vaccine_Name) {
this.vaccine_Name = vaccine_Name;
}
public String getVaccine_Date() {
return vaccine_Date;
}
public void setVaccine_Date(String vaccine_Date) {
this.vaccine_Date = vaccine_Date;
}
}
I want to display the vaccine_Name, institution_Name, and vaccine_Date that I call in my adapter. but don't know how to get the data from my vaccineAdapter to the HistoryFragment.
This is the error I get.
This is the design of the app. Once I clicked the history in the bottomNavigation the error will appear.
The error is in your fragment in the line mList = getActivity().getIntent();
The getIntent() method essentially returns intent not a list so you can't equate your mList to getActivity().getIntent()! getIntent() is used to pass data from activity to activity/fragment to activity. It returns the intent that started the activity.
Example of getIntent(),
If you start an Activity with some data,
String someData = "StackOverflow is awesome";
Intent intent = new Intent(context, SomeActivity.class);
intent.putExtra("someKey", someData);
you can retrieve this data using getIntent in the receiver activity:
Intent intent = getIntent();
if (intent != null)
String gotBackSomeKey = intent.getExtra("someKey");
Now for passing data between fragments or from an activity to a fragment, we use Bundle.(Your case)
Example of Bundle,
Bundle bundle = new Bundle();
bundle.putParceableArrayList("YourListTag",mList);
FragmentClass fragInfo = new FragmentClass();
fragInfo.setArguments(bundle);
transaction.replace(R.id.fragment_single, fragInfo);
transaction.commit();
Make sure, unlike String or Int, you cannot pass List to your Bundle/Intent directly if you have a customized list. You will have to make your object of the list Parcelable or Serializable and then pass it like above example. You can read how to implement Parcelable/Serializable here
https://developer.android.com/reference/android/os/Parcelable
https://developer.android.com/reference/java/io/Serializable
I would like my child data to update in real-time when I change the data. I am new in Java programming. The error was when i tried to set the my list arraylist with new child data, there is a error for wrong 2nd argument. The Following is my code...Appreciate any helps, Thank in advance.
public class OverallResultFragment extends Fragment {
private static final String TAG = "OverallResultFragment";
private ArrayList<Booth> list = new ArrayList<>();;
private ArrayList<Booth> mkeys = new ArrayList<>();
ProductListAdapter adapter = null;
private Firebase mRef;
ListView gridView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Firebase.setAndroidContext(this.getContext());
View view = inflater.inflate(R.layout.activity_votingresult, container, false);
mRef = new Firebase("https://myfb.firebaseio.com/myfb");
gridView = (ListView) view.findViewById(R.id.gridView);
adapter = new ProductListAdapter(this.getContext(), R.layout.list_product_item, list);
gridView.setAdapter(adapter);
com.firebase.client.Query Queryref = mRef.orderByValue();
Queryref.addChildEventListener(new com.firebase.client.ChildEventListener() {
#Override
public void onChildAdded(com.firebase.client.DataSnapshot dataSnapshot, String s) {
String value = dataSnapshot.getValue(String.class);
String boothname = dataSnapshot.getKey();
list.add(new Booth(boothname, value));
mkeys.add(new Booth(boothname));
adapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(com.firebase.client.DataSnapshot dataSnapshot, String s) {
String value = dataSnapshot.getValue(String.class);
String boothname = dataSnapshot.getKey();
int index = mkeys.indexOf(boothname);
list.set(index, value);//error on "value" -> wrong 2nd argument.
adapter.notifyDataSetChanged();
}
}
And this is my Booth class:
public class Booth {
String rating;
String Boothname;
int index;
public Booth(String boothname, String Rating){
this.Boothname = boothname;
this.rating= Rating;
}
public String getBoothName(){
return Boothname;
}
public void setProductId(String boothname){
this.Boothname = boothname;
}
public String getRating(){
return rating;
}
public void setRating(String rating){
this.rating = rating;
}
}
Error is because it's not a string type 2nd Argument.
Replace that line with this:
list.set(index, new Booth(boothname,value));
It will work for you
Thanks and happy coding.
EDITED
Replace this line :
int index = mkeys.indexOf(boothname);
With this:
int index = mkeys.indexOf(new Booth(boothname));
It will solve your crash issue.
I have received a json data from rest api. This data contains id, title, body, an array of images "appImages" and a teaserImage. Now I deserialize the json in controller class. I have creted two adapters. First adpter is used for recyclerview. This recycler view is showing the title and and teasetImage. this portion working. If user click on item it redirect to detail activity, where he can see teaserImage as cover image, and the body as description. Now this layout I oroganised this way, at fisrt the ImageView for cover Image, TextView for Description. And below description I have created a recyclerView to show the array of images. The CoverImage and description of detail cativity is working well. For recyclerview I have created another Adpater, this adapter is used to show all the images based on the title of news. But I stuch to show those images in recyclerview. I have explained in deatil in my code.
My controller class
public class NewsController {
private static final String TAG = NewsController.class.getSimpleName();
private UserCallbackListener mListener;
private NewsRestApiManager mApiManager;
private AppImage appImages;
public NewsController(UserCallbackListener listener) {
mListener = listener;
mApiManager = new NewsRestApiManager();
}
public void startFetching(){
mApiManager.getNewsApi().getNews(new Callback<String>() {
#Override
public void success(String s, Response response) {
Log.d(TAG, "JSON :: " + s);
try {
JSONArray array = new JSONArray(s);
for(int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
NewsModel news = new NewsModel();
news.setTitle( jsonObject.optString( "title") );
news.setBody( jsonObject.optString( "body" ) );
ArrayList<AppImage> list = new ArrayList();
JSONArray imageArray =jsonObject.getJSONArray("appImages");
if (imageArray.length() > 1) {
for(int j=0; j<imageArray.length();j++){
appImages = new AppImage();
appImages.setSrc(new JSONArray( s ).getJSONObject( i ).getJSONArray( "appImages" ).getJSONObject( j ).getString( "src" ));
list.add(appImages);
}
}
news.setAppImages( list );
TeaserImageSmall coverImage=new TeaserImageSmall();
coverImage.setSrc( new JSONArray( s ).getJSONObject( i ).getJSONObject( "teaserImageSmall" ).getString( "src" ));
news.setTeaserImageSmall(coverImage);
mListener.onFetchProgressNews(news);
}
} catch (JSONException e) {
mListener.onFetchFailed();
}
mListener.onFetchComplete();
}
#Override
public void failure(RetrofitError error) {
Log.d(TAG, "Error :: " + error.getMessage());
mListener.onFetchComplete();
}
});
}
public interface UserCallbackListener{
void onFetchStart();
void onFetchProgressNews(NewsModel news);
void onFetchProgressNews(List<NewsModel> userList);
void onFetchComplete();
void onFetchFailed();
}
My adapter class for News Recyclerview. This is perfect now.
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.NewsHolder>
........
public void addNews(NewsModel news) {
Log.d(TAG,news.getTeaserImageSmall().getSrc());
mNews.add(news);
notifyDataSetChanged();
}
#Override
public void onBindViewHolder(NewsHolder holder, int position) {
final NewsModel currentNews = mNews.get(position);
Picasso.with(holder.itemView.getContext());
Picasso.with(holder.itemView.getContext()).load(currentNews.getTeaserImageSmall().getSrc()).into( holder.newsImage );
holder.newsHeadline.setText(currentNews.getTitle());
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i=new Intent(context,DetailNews.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("src",currentNews.getTeaserImageSmall().getSrc());
i.putExtra("title",currentNews.getTitle());
i.putExtra("body",currentNews.getBody());
context.startActivity(i);
}
});
Now Another Adapter for Array of images which will show in detail activity of news page.
Edited Adapter Class
public class NewsImageAdapter extends RecyclerView.Adapter<NewsImageAdapter.ImageHolder> {
public static String TAG = NewsImageAdapter.class.getSimpleName();
private Context context;
private List<AppImage> appImageList;
DetailNews detailNews = new DetailNews ();
public NewsImageAdapter(List<AppImage> imageObject,Context context) {
this.context = context;
this.appImageList = imageObject;
}
public void addImage(AppImage appImage) {
Log.d(TAG,appImage.getSrc());
appImageList.add(appImage);
notifyDataSetChanged();
}
#Override
public ImageHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.newsdetail_image_row,parent,false);
return new ImageHolder(view);
}
#Override
public void onBindViewHolder(ImageHolder holder, int position) {
final AppImage currentImage=appImageList.get(position);
//getting error for current news,
detailNews .navigate(context, appImageList, currentNews.getTeaserImageSmall().getSrc(), currentNews.getTitle(),currentNews.getBody());
Picasso.with(holder.itemView.getContext()).load(currentImage.getSrc()).into( holder.images);
}
#Override
public int getItemCount() {
return imageObject.size();
}
public class ImageHolder extends RecyclerView.ViewHolder {
public ImageView images;
public ImageHolder(View itemView) {
super(itemView);
images= itemView.findViewById(R.id.news_image);
}
}
}
Detail activity of news where I am shoing coverImage and description at this moment. But I also want to show the list of images below the description. I would like to how can I implement that.
Edited Detail Activity
public class DetailNews extends AppCompatActivity{
public class DetailNews extends AppCompatActivity{
private RecyclerView recyclerView;
private NewsImageAdapter adapter;
private List<AppImage> imageList= new ArrayList<>();
private NewsController mController;
private CardView cardview;
private ImageView _coverImage;
private TextView _newsHeading;
private TextView _description;
private TextView _newsDate;
private static List<AppImage> appImageList,mAppImageList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news_detail);
//newsObject=getAllImageList();
// setting up views and stuff
setUpUIViews();
Intent intent = getIntent();
//RECEIVE DATA
Log.e("_coverImage",""+_coverImage);
String coverImage = intent.getStringExtra ("src");
String heading=intent.getExtras().getString("title");
//String newsDate=intent.getExtras().getString("date");
String description=intent.getExtras().getString("body");
//BIND DATA
Picasso.with(this).load(coverImage ).into(_coverImage);
_newsHeading.setText(heading);
// _newsDate.setText(newsDate);
_description.setText(description);
Linkify.addLinks( _description,Linkify.WEB_URLS );
}
private void setUpUIViews() {
_coverImage=(ImageView)findViewById(R.id.news_cover);
_newsHeading=(TextView)findViewById(R.id.heading);
_description=(TextView)findViewById(R.id.news_description);
_newsDate=(TextView)findViewById(R.id.date);
cardview=(CardView) findViewById(R.id.cardView);
recyclerView = (RecyclerView)findViewById(R.id.image_list);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(DetailNews.this);
recyclerView.setLayoutManager(layoutManager);
adapter = new NewsImageAdapter(imageList,getApplicationContext() );
recyclerView.setAdapter(adapter);
}
#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();
if (id == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
public void navigate(Context activity, List<AppImage> appImageList, String src, String title, String body) {
mAppImageList = appImageList;
Intent intent = new Intent(activity, DetailNews .class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("src",src);
intent .putExtra("title",title);
intent .putExtra("body",body);
activity.startActivity(intent);
try {
if (activity instanceof NewasPage) { //Error for news
((NewsPage) activity).finish();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
My Mdel Class is
public class NewsModel {
#Expose
private String _id;
#Expose
private String body;
#Expose
private String title;
#Expose
private List<AppImage> appImages;
public List<AppImage> getAppImages() {
return appImages;
}
public void setAppImages(List<AppImage> appImages) {
this.appImages = appImages;
}
AppImage Model Class
public class AppImage {
#Expose
private String _id;
#Expose
private String alt;
#Expose
private String src;
public String get_id() {
return _id;
}
public void set_id(String _id) {
this._id = _id;
}
public String getAlt() {
return alt;
}
public void setAlt(String alt) {
this.alt = alt;
}
public String getSrc() {
return src;
}
public void setSrc(String src) {
this.src = src;
}
}
In DetailNews Activity, add a method
private static List<AppImage> appImageList mAppImageList;
public void navigate(Context activity, List<AppImage> appImageList,String src,String title,String body) {
mAppImageList = appImageList;
Intent intent = new Intent(activity, DetailNews .class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("src",src);
intent .putExtra("title",title);
intent .putExtra("body",body);
activity.startActivity(intent);
try {
if (activity instanceof FirstActivity) {
((FirstActivity) activity).finish();
}
} catch (Exception e) {
e.printStackTrace();
}
}
And in the adapter do as
DetailNews detailNews = new DetailNews ();
detailNews .navigate(context, appImageList, currentNews.getTeaserImageSmall().getSrc(), currentNews.getTitle(),currentNews.getBody());
Hello I'm new at Android. I want to populate a Spinner with a list of objects. I have googled how to do it but I just find examples with an array of strings.
Can any one help me?
This is my code:
Categories class:
public class Categories
{
#com.google.gson.annotations.SerializedName("id")
private String mId;
#com.google.gson.annotations.SerializedName("name")
private String mName;
public Categories()
{}
public Categories(String id, String name)
{
this.setId(id);
this.setName(name);
}
#Override
public String toString()
{
return mName;
}
// ******** GET *************
public String getId()
{
return mId;
}
public String getName()
{
return mName;
}
// ******** SET *************
public final void setId(String id)
{
mId = id;
}
public final void setName(String name)
{
mName = name;
}
}
This is my Activity code:
public class AgregarActividadActivity extends ActionBarActivity
{
private MobileServiceClient mClient;
private MobileServiceTable<Activities> mActivitiesTable;
private MobileServiceTable<Categories> mCategoriesTable;
private MobileServiceTable<Projects> mProjectsTable;
private EditText mTxtTitulo;
private EditText mTxtDescr;
String categryId = null;
List<Categories> catList = new ArrayList<Categories>();
Spinner spEstado;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_agregar_actividad);
try
{
mClient = new MobileServiceClient(
"https://site.azure-mobile.net/",
"AppKey",
this);
mActivitiesTable = mClient.getTable(Activities.class);
mCategoriesTable = mClient.getTable(Categories.class);
}
catch (MalformedURLException e)
{
createAndShowDialogExc(new Exception("There was an error creating the Mobile Service. Verify the URL"), "Error");
}
mTxtTitulo = (EditText) findViewById(R.id.txtTitulo);
mTxtDescr = (EditText) findViewById(R.id.txtDescripcion);
getCategories();
spEstado = (Spinner)this.findViewById(R.id.spEstado);
ArrayAdapter<Categories> Adapter = new ArrayAdapter<Categories>(this,
android.R.layout.simple_spinner_item, catList);
Adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spEstado.setAdapter(Adapter);
spEstado.setOnItemSelectedListener(
new AdapterView.OnItemSelectedListener() {
public void onItemSelected(
AdapterView<?> parent,
View view,
int position,
long id) {
Categories item = (Categories) parent.getItemAtPosition(position);
}
public void onNothingSelected(AdapterView<?> parent) {
}
}
);
spProjects = (Spinner)this.findViewById(R.id.spProyecto);
ArrayAdapter<Projects> proAdapter = new ArrayAdapter<Projects>(this,
android.R.layout.simple_spinner_item, proList);
proAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spProjects.setAdapter(proAdapter);
}
private void getCategories()
{
mCategoriesTable.execute(new TableQueryCallback<Categories>()
{
public void onCompleted(List<Categories> result, int count, Exception exception, ServiceFilterResponse response)
{
if (exception == null)
{
for (Categories item : result)
{
catList.add(item);
}
}
else
{
createAndShowDialog(exception, "Error");
}
}
});
}
}
I get the dropdownlist with the objects, but when I select one item, it is not displayed as the selected item, when the dropdownlist is hidden.
Any idea will help me! Thank you!!
You need to write a CustomAdapter for this. It is similar to writing a CustomAdapter for a ListView. You can look at Custom Adapter for List View for an idea
I have a SherlockFragmentActivity class that collects values from a server and loads it in to my database. This SherlockFragmentActivity as 3 Fragment called the Book, Video and Audios. Each of them are meant to show values that were downloaded into the db. By challenge now is when I open my UI i dont get to see the values on the fragments not until I start clicking each fragment before the values get populated into the list in the fragment. And I even notice a continuous addition of this values. My fragment class is pasted below.
public class BooksFragment extends SherlockListFragment{
TextView textview = null;
String CategoryID = null;
ArrayList<HashMap<String,String>> listBooks = null;
IDatabaseHelper databaseHelper = null;
Activity activity = null;
Context context = null;
ListAdapter adapter = null;
public BooksFragment(){
super();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.books, container, false);
// do your view initialization heres
textview = (TextView)view.findViewById(R.id.textView1);
return view;
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
listBooks = new ArrayList<HashMap<String,String>>();
}
#Override
public void onStart() {
super.onStart();
Bundle bundle =this.getArguments();
if(bundle != null){
CategoryID = bundle.getString("CategoryID");
}
this.initializeComponents();
this.populateListView();
}
#Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
activity = getActivity();
context = activity.getBaseContext();
databaseHelper= new DatabaseHelper(context);
}
//Now we are going to initialize components of the fragment
private void initializeComponents(){
ListView listview = getListView();
listview.setOnItemClickListener(listener);
}
//list item click listener
private OnItemClickListener listener = new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
}
};
//This method would be used to collect content from the database and populate the listview item
private void populateListView(){
MedicalBookModel[] booksmodel = this.databaseHelper.ReturnBooks(CategoryID);
if(booksmodel != null){
for(MedicalBookModel book : booksmodel){
HashMap<String,String> bookMap = new HashMap<String,String>();
bookMap.put(MedicalBookModel.MedicalBookModel_ID, book.getID());
bookMap.put(MedicalBookModel.MedicalBookModel_Name,book.getName());
Log.i("values",book.getName());
listBooks.add(bookMap);
}
}
adapter = new SimpleAdapter(context, listBooks,R.layout.list_book,new String[]{ "ID","Name"}, new int[]{ R.id.bookId, R.id.bookName});
setListAdapter(adapter);
}
}
For that you have several solutions :
1- Using the Application instance singleton which is global
2- Creating your own global class to manage your data
3- Use a service bound to the activity (or not) and call backs (maybe intent and broadcast receivers)
4- Pass your object as parceable in argument when adding the fragment
Note that sometimes you will need to invalidate views to force datas to refresh
EXEMPLE OF PARCEABLE OBJECT
public class ImageObject implements Parcelable {
/**
* ATTRIBUTES
*/
protected String _idPicture;
protected String _idAlbum;
protected String _name;
protected String _fileName;
protected String _imageUrl;
protected String _hierarchy;
public ImageObject(String _idPicture, String _idAlbum, String _name, String _fileName, String _imageUrl, String _hierarchy) {
super();
this._idPicture = _idPicture;
this._idAlbum = _idAlbum;
this._name = _name;
this._fileName = _fileName;
this._imageUrl = _imageUrl;
this._hierarchy = _hierarchy;
}
public ImageObject(Parcel in) {
String[] data = new String[6];
in.readStringArray(data);
this._idPicture = data[0];
this._idAlbum = data[1];
this._name = data[2];
this._fileName = data[3];
this._imageUrl = data[4];
this._hierarchy = data[5];
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public ImageObject createFromParcel(Parcel in) {
return new ImageObject(in);
}
public ImageObject[] newArray(int size) {
return new ImageObject[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeStringArray(new String[] { this._idPicture, this._idAlbum, this._name, this._fileName, this._imageUrl, this._hierarchy });
}
}