How get spinner item position from Fragment to some Class? - java

I have some dummy problem, I need to get Spinner Item Position from the Fragment to this class:
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Spinner;
import com.example.nortti.politrange.R;
import com.example.nortti.politrange.intefaces.ICatalog;
import com.example.nortti.politrange.objects.Person;
import com.example.nortti.politrange.objects.Site;
import com.example.nortti.politrange.utils.WebApiAdapter;
import com.example.nortti.politrange.views.GeneralFragment;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
public class PersonCatalog implements ICatalog{
private final String COMMAND_PREFIX = "/api/stats/1";
private final WebApiAdapter apiAdapter = new WebApiAdapter(COMMAND_PREFIX);
private ArrayList<Person> catalogList = new ArrayList<Person>();
private Site site;
public PersonCatalog(Site site) {
this.site = site;
}
#Override
public ArrayList<Person> getCatalogList() {
return catalogList;
}
public void populateData() {
JSONArray jsonObject = null;
try {
jsonObject = (JSONArray)(new JSONParser()).parse(apiAdapter.select(null));
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
catalogList.clear();
Iterator<JSONObject> iterator = jsonObject.iterator();
while(iterator.hasNext()) {
JSONObject o = iterator.next();
catalogList.add(new Person((String)o.get("personName"),(int)(long)o.get("rank")));
}
}
}
I broke my head, I don't know how to do it. Please help! Should I use some Intents or create some getters?
UPD: Fragment Code
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import com.example.nortti.politrange.R;
import com.example.nortti.politrange.adapters.GenAdapter;
import com.example.nortti.politrange.adapters.SiteAdapter;
import com.example.nortti.politrange.intefaces.ICatalog;
import com.example.nortti.politrange.intefaces.impls.PersonCatalog;
import com.example.nortti.politrange.intefaces.impls.SitesCatalog;
import com.example.nortti.politrange.objects.Site;
public class GeneralFragment extends Fragment implements OnClickListener, OnItemSelectedListener {
private Button genApply;
private Spinner spinner;
private ListView genList;
private View header;
private ICatalog siteCatalogImpl;
private ICatalog personCatalogImpl;
public int Num;
public void setSpinnerSource(ICatalog siteCatalogImpl) {
this.siteCatalogImpl = siteCatalogImpl;
spinData();
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.general_fragment, container,false);
header = inflater.inflate(R.layout.gen_head, null);
spinner = (Spinner) v.findViewById(R.id.wSpin);
spinner.setOnItemSelectedListener(this);
genApply = (Button) v.findViewById(R.id.genApply);
genApply.setOnClickListener(this);
genList = (ListView) v.findViewById(R.id.genList);
genList.addHeaderView(header);
this.setSpinnerSource(new SitesCatalog());
Intent i = new Intent();
i.putExtra("spin", spinner.getSelectedItemPosition()+1);
return v;
}
private void spinData() {
siteCatalogImpl.populateData();
spinner.setAdapter(new SiteAdapter(getActivity(), siteCatalogImpl.getCatalogList()));
}
private void listData(Site site) {
personCatalogImpl = new PersonCatalog(site);
personCatalogImpl.populateData();
genList.setAdapter(new GenAdapter(getActivity(), personCatalogImpl.getCatalogList()));
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onClick(View v) {
int siteIndex = spinner.getSelectedItemPosition();
switch (v.getId()) {
case R.id.genApply:
listData((Site)siteCatalogImpl.getCatalogList().get(siteIndex));
break;
}
}
}
I calling PersonCatalog at the listdata method.

Try this.
final ArrayList<String> providerlist= new ArrayList<String>();
Spinner spinner1 = (Spinner) findViewById(R.id.prospin);
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, providerlist);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter1);
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
String item = providerlist.get(position);
// Showing selected spinner item
Toast.makeText(this,
"Selected Country : " + item, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});

Related

How to inflate another layout inside of another fragment

Hi i tried to inflate my home_items.xml in my application however it doesnt work it just gives me the fragment_home.xml ONLY im wondering how can i fix this? (I can send any part of my code.)
HomeAdapter.java:
package com.example.soulforge.adapter;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.example.soulforge.R;
import com.example.soulforge.model.HomeModel;
import java.util.List;
import java.util.Random;
import de.hdodenhof.circleimageview.CircleImageView;
public class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.HomeHolder>{
private List<HomeModel> list;
Context context;
public HomeAdapter(List<HomeModel> list, Context context) {
this.list = list;
this.context = context;
}
#NonNull
#Override
public HomeHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.home_items, parent, false);
return new HomeHolder(view);
}
#Override
public void onBindViewHolder(#NonNull HomeHolder holder, int position) {
holder.userNameTv.setText(list.get(position).getUserName());
holder.timeTv.setText(""+list.get(position).getTimestamp());
int count = list.get(position).getLikeCount();
if(count ==0){
holder.likeCountTv.setVisibility(View.INVISIBLE);
}else if (count == 1){
holder.likeCountTv.setText(count + " like");
}else{
holder.likeCountTv.setText(count + " likes");
}
holder.descriptionTv.setText(list.get(position).getDescription());
Random random = new Random();
int color = Color.argb(255, random.nextInt(256), random.nextInt(256), random.nextInt(256));
Glide.with(context.getApplicationContext())
.load(list.get(position).getProfileImage())
.placeholder(R.drawable.ic_person)
.timeout(6500)
.into(holder.profileImage);
Glide.with(context.getApplicationContext())
.load(list.get(position).getImageUrl())
.placeholder(new ColorDrawable(color))
.timeout(7000)
.into(holder.imageView);
}
#Override
public int getItemCount() {
return list.size();
}
static class HomeHolder extends RecyclerView.ViewHolder{
private CircleImageView profileImage;
private TextView userNameTv, timeTv, likeCountTv, descriptionTv;
private ImageView imageView;
private ImageButton likeBtn, commentBtn, shareBtn;
public HomeHolder(#NonNull View itemView) {
super(itemView);
profileImage = itemView.findViewById(R.id.profileImage);
imageView = itemView.findViewById(R.id.imageView);
userNameTv = itemView.findViewById(R.id.nameTv);
timeTv = itemView.findViewById(R.id.timeTv);
likeCountTv = itemView.findViewById(R.id.likeCountTv);
likeBtn = itemView.findViewById(R.id.likeBtn);
commentBtn = itemView.findViewById(R.id.commentBtn);
shareBtn = itemView.findViewById(R.id.shareBtn);
descriptionTv = itemView.findViewById(R.id.descTv);
}
}
}
Home.java:
package com.example.soulforge.fragments;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.soulforge.R;
import com.example.soulforge.adapter.HomeAdapter;
import com.example.soulforge.model.HomeModel;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class Home extends Fragment {
private RecyclerView recyclerView;
HomeAdapter adapter;
private List<HomeModel> list;
private FirebaseUser user;
public Home() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_home, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
init(view);
list = new ArrayList<>();
adapter = new HomeAdapter(list, getContext());
recyclerView.setAdapter(adapter);
loadDataFromFirestore();
}
private void init(View view) {
Toolbar toolbar = view.findViewById(R.id.toolbar);
if (getActivity() != null)
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
recyclerView = view.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
FirebaseAuth auth = FirebaseAuth.getInstance();
user = auth.getCurrentUser();
}
public void loadDataFromFirestore() {
CollectionReference reference = FirebaseFirestore.getInstance().collection("Users")
.document(user.getUid())
.collection("Post Images");
reference.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot value, #Nullable FirebaseFirestoreException error) {
if (error != null) {
Log.e("Error: ", error.getMessage());
return;
}
if (value == null)
return;
for (QueryDocumentSnapshot snapshot : value) {
if (!snapshot.exists())
return;
HomeModel model = snapshot.toObject(HomeModel.class);
list.add(new HomeModel(
model.getUserName(),
model.getProfileImage(),
model.getImageUrl(),
model.getUid(),
model.getComments(),
model.getDescription(),
model.getId(),
model.getTimestamp(),
model.getLikeCount()
));
}
adapter.notifyDataSetChanged();
}
});
}
}
Any idea how to fix this? I tried to use inflate however it failed to work as shown it is missing the home items xml enter image description here.
Before you say i have cleared and rebuild and all the FAQ ways to fix this
You're updating wrong list instance
Create one method inside adapter
public updateList(List<HomeModel> list) {
this.list = list;
notifyDataSetChanged()
}
And call it like :
reference.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot value, #Nullable FirebaseFirestoreException error) {
...
adapter.updateList(new HomeModel(
model.getUserName(),
model.getProfileImage(),
model.getImageUrl(),
model.getUid(),
model.getComments(),
model.getDescription(),
model.getId(),
model.getTimestamp(),
model.getLikeCount()
));
}
}
});

In GridView after filtering the list, the index changes and the context of item is wrong

I am having a GridList View in which I am passing data from firebase. When I click on the items it works fine without filtering but when I filter it with searchView then it does not update the index of the list and then provides a different item's context.
I do not know how to update the item while filtering.
Homepage.Activity
package com.project.quizapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;
import android.app.SearchManager;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.GridView;
import android.widget.ListAdapter;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import static com.project.quizapp.LogIn.catList;
import static com.project.quizapp.LogIn.selected_cat_index_app;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.project.quizapp.CatGridAdapter;
public class HomePage extends AppCompatActivity {
CatGridAdapter adapter;
private GridView catGrid;
private FirebaseFirestore firebasefirestore;
public static List<CategoryModelClass> resultData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
//Binding view and adding toolbar
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Subjects");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(HomePage.this, dashActivity.class));
}
});
//Adapter to set all the views
catGrid = findViewById(R.id.catGridview);
adapter = new CatGridAdapter(catList);
catGrid.setAdapter(adapter);
}
//Filtering all tthe views
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//Inflating all the views and filtering
getMenuInflater().inflate(R.menu.search, menu);
MenuItem menuitem = menu.findItem(R.id.searchMenu);
SearchView searchview = (SearchView) menuitem.getActionView();
searchview.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
//Calling filters on the search attempt
//adapter.getFilter().filter(newText);
resultData = new ArrayList<>();
for(CategoryModelClass categoryModelClass:catList){
if(categoryModelClass.getName().toLowerCase().contains(newText.toLowerCase())){
resultData.add(categoryModelClass);
}
adapter = new CatGridAdapter(resultData);
catGrid.setAdapter(adapter);
}
return true;
}
});
return true;
}
//Adding search icon to the toolbar
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if(id == R.id.searchMenu){
return true;
}
return super.onOptionsItemSelected(item);
}
}
CatGridAdapter.java
package com.project.quizapp;
import android.content.Intent;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import static com.project.quizapp.LogIn.selected_cat_index_app;
import static java.security.AccessController.getContext;
//Creating the adapter wih the default BaseAdapter
//Also implementing
public class CatGridAdapter extends BaseAdapter {
//List of all the class variables
private List<CategoryModelClass> catList;
//Initializing the list wih constructor
public CatGridAdapter(List<CategoryModelClass> catList) {
this.catList = catList;
}
#Override
public int getCount() {
return catList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if(convertView == null){
//Adding all the views as we get the data from firebase
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cat_item_layout,parent,false);
}
else{
view = convertView;
}
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//selected_cat_index_app = position;
// Toast.makeText(parent.getChildAt(position), catList.get(position).getName()+" "+String.valueOf(catList.indexOf(position)), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(parent.getContext(), SetsActivity.class);
parent.getContext().startActivity(intent);
}
});
((TextView) view.findViewById(R.id.catName)).setText(catList.get(position).getName());
Random rnd = new Random();
int color = Color.argb(255,rnd.nextInt(255),rnd.nextInt(255),rnd.nextInt(255));
view.setBackgroundColor(color);
return view;
}
}
CategoryModelClass.java
package com.project.quizapp;
//Model class to fetch the quiz subjects from the Cloud Firestone
public class CategoryModelClass {
//private variable for ID and the name of
private String id;
private String name;
//constructor
public CategoryModelClass(String id, String name) {
this.id = id;
this.name = name;
}
//methods
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Either implement a Filterable interface in the adapter or update your onQueryTextChange implementation.
Whenever you are typing, every time you are creating a new adapter with filtered data.
try this.. create new method in adapter
public void updateData(List<CategoryModelClass> catList){
this.catList = catList;
notifyDataSetChanged();
}
and call from onQueryTextChange
#Override
public boolean onQueryTextChange(String newText) {
//adapter.getFilter().filter(newText);
resultData = new ArrayList<>();
for (CategoryModelClass categoryModelClass : catList) {
if (categoryModelClass.getName().toLowerCase().contains(newText.toLowerCase())) {
resultData.add(categoryModelClass);
}
adapter.updateData(resultData);
}
return true;
}

Show Edittext & Textview when checkbox is clicked

I make an application, with CRUD function in Android using Room Database.
When i checked the checkbox like this, Error Pictures 1 i want that application show textview & edittext. But, after i press next button, it won't show textview & edittext based on checked in the checkbox Error Pictures 2 or textview & edittext showed up but that's not based by checkbox isChecked
This is the code :
AdapterTargetIbadah.java
package skripsi.com.ggr.managementibadah.adapter;
import android.arch.persistence.room.Room;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import skripsi.com.ggr.managementibadah.R;
import skripsi.com.ggr.managementibadah.data.factory.AppDatabase;
import skripsi.com.ggr.managementibadah.model.Ibadah;
public class AdapterTargetIbadah extends RecyclerView.Adapter<AdapterTargetIbadah.ViewHolder>{
private ArrayList<Ibadah> targetIbadah;
private Context context;
private AppDatabase db;
public AdapterTargetIbadah(ArrayList<Ibadah> targets, Context ctx) {
targetIbadah = targets;
context = ctx;
db = Room.databaseBuilder(context.getApplicationContext(),
AppDatabase.class, "ibadahdb").allowMainThreadQueries().build();
}
class ViewHolder extends RecyclerView.ViewHolder {
TextView tv_target;
EditText et_Target;
ViewHolder(View itemView) {
super(itemView);
tv_target = itemView.findViewById(R.id.tv_target);
et_Target = itemView.findViewById(R.id.et_Target);
}
}
#Override
public AdapterTargetIbadah.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_target, parent, false);
AdapterTargetIbadah.ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(#NonNull AdapterTargetIbadah.ViewHolder holder, int position) {
Ibadah iba = targetIbadah.get(position);
if (iba.getTargetIbadah()!=null) {
holder.tv_target.setText(iba.getTargetIbadah());
iba.setEtTarget(holder.et_Target.getText().toString());
} else {
targetIbadah.remove(position);
}
}
#Override
public int getItemCount() {
return targetIbadah.size();
}
}
AdapterCheckboxTarget.java
package skripsi.com.ggr.managementibadah.adapter;
import android.arch.persistence.room.Room;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import skripsi.com.ggr.managementibadah.R;
import skripsi.com.ggr.managementibadah.data.factory.AppDatabase;
import skripsi.com.ggr.managementibadah.model.Ibadah;
public class AdapterCheckboxTarget extends RecyclerView.Adapter<AdapterCheckboxTarget.ViewHolder> {
private ArrayList<Ibadah> targetIbadah;
private Context context;
private AppDatabase db;
public AdapterCheckboxTarget(ArrayList<Ibadah> targets, Context ctx) {
targetIbadah = targets;
context = ctx;
db = Room.databaseBuilder(context.getApplicationContext(),
AppDatabase.class, "ibadahdb").allowMainThreadQueries().build();
}
class ViewHolder extends RecyclerView.ViewHolder {
CheckBox cbTarget;
ViewHolder(View itemView) {
super(itemView);
cbTarget = itemView.findViewById(R.id.cbTarget);
}
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_targethome, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, int position) {
final String name = targetIbadah.get(position).getNamaIbadah();
holder.cbTarget.setText(name);
holder.cbTarget.setChecked(targetIbadah.get(position).getStatus());
holder.cbTarget.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (holder.cbTarget.isChecked()) {
targetIbadah.get(position).setStatus(true);
targetIbadah.get(position).setTargetIbadah(targetIbadah.get(position).getNamaIbadah());
Toast.makeText(context, "checklist", Toast.LENGTH_SHORT).show();
} else {
targetIbadah.get(position).setStatus(false);
Toast.makeText(context, "unchecklist", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public int getItemCount() {
return targetIbadah.size();
}
}
TargetHome.java ==> Activity using AdapterTargetIbadah.java
package skripsi.com.ggr.managementibadah;
import android.app.Activity;
import android.arch.persistence.room.Room;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import skripsi.com.ggr.managementibadah.adapter.AdapterCheckboxTarget;
import skripsi.com.ggr.managementibadah.adapter.AdapterTargetIbadah;
import skripsi.com.ggr.managementibadah.data.factory.AppDatabase;
import skripsi.com.ggr.managementibadah.model.Ibadah;
public class TargetHome extends AppCompatActivity {
private AppDatabase db;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private ArrayList<Ibadah> targetIbadah;
RecyclerView rvTarget;
Button btSimpan;
Context ctx;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.target_ibadah);
setTitle("Target Ibadah");
btSimpan = (Button)findViewById(R.id.btSimpanTarget);
targetIbadah = new ArrayList<>();
db = Room.databaseBuilder(getApplicationContext(),
AppDatabase.class, "ibadahdb").allowMainThreadQueries().build();
rvTarget = findViewById(R.id.rvTar);
rvTarget.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
rvTarget.setLayoutManager(layoutManager);
targetIbadah.addAll(Arrays.asList(db.ibadahDAO().selectAllStatus()));
adapter = new AdapterTargetIbadah(targetIbadah, this);
rvTarget.setAdapter(adapter);
Ibadah ib = new Ibadah();
if (ib.getTargetIbadah()!=null) {
ib.setTvTarget(ib.getTargetIbadah());
ib.setEtTarget("");
db.ibadahDAO().insertCapai(ib);
}
btSimpan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(MainActivity.getActIntent(TargetHome.this));
}
});
}
public static Intent getActIntent(Activity activity) {
// kode untuk pengambilan Intent
return new Intent(activity, TargetHome.class);
}
}
CheckboxTarget.java ==> Activity using AdapterCheckboxTarget
package skripsi.com.ggr.managementibadah;
import android.app.Activity;
import android.arch.persistence.room.Room;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import skripsi.com.ggr.managementibadah.adapter.AdapterCatatIbadah;
import skripsi.com.ggr.managementibadah.adapter.AdapterCheckboxTarget;
import skripsi.com.ggr.managementibadah.data.factory.AppDatabase;
import skripsi.com.ggr.managementibadah.model.Ibadah;
public class CheckboxTarget extends AppCompatActivity {
private AppDatabase db;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private ArrayList<Ibadah> targetIbadah;
RecyclerView rvCb;
Button btNext;
Context ctx;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.target_home);
setTitle("Target Ibadah");
btNext = (Button) findViewById(R.id.btNextTarget);
targetIbadah = new ArrayList<>();
db = Room.databaseBuilder(getApplicationContext(),
AppDatabase.class, "ibadahdb").allowMainThreadQueries().build();
rvCb = findViewById(R.id.rvTarHome);
rvCb.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
rvCb.setLayoutManager(layoutManager);
targetIbadah.addAll(Arrays.asList(db.ibadahDAO().selectAllStatus()));
adapter = new AdapterCheckboxTarget(targetIbadah, this);
rvCb.setAdapter(adapter);
final Ibadah ibadah = (Ibadah) getIntent().getSerializableExtra("data");
if (ibadah != null) {
Ibadah ib = new Ibadah();
ib.setStatus(ib.status);
db.ibadahDAO().insertTarget(ib);
}
}
public static Intent getActIntent(Activity activity) {
// kode untuk pengambilan Intent
return new Intent(activity, CheckboxTarget.class);
}
}
Ibadah.java ==> Model
package skripsi.com.ggr.managementibadah.model;
import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;
import java.io.Serializable;
#Entity(tableName = "tibadah")
public class Ibadah implements Serializable {
#PrimaryKey(autoGenerate = true)
public int idIbadah;
#ColumnInfo(name = "nama_ibadah")
public String namaIbadah;
#ColumnInfo(name = "deskripsi_ibadah")
public String deskripsiIbadah;
#ColumnInfo(name = "target_ibadah")
public String targetIbadah;
#ColumnInfo(name = "tv_target")
public String tvTarget;
#ColumnInfo(name = "et_target")
public String etTarget;
#ColumnInfo(name = "et_capaian")
public String etCapaian;
#ColumnInfo(name = "status")
public boolean status;
public String getTvTarget() {
return tvTarget;
}
public void setTvTarget(String tvTarget) {
this.tvTarget = tvTarget;
}
public String getTargetIbadah() {
return targetIbadah;
}
public void setTargetIbadah(String targetIbadah) {
this.targetIbadah = targetIbadah;
}
public String getEtTarget() {
return etTarget;
}
public void setEtTarget(String etTarget) {
this.etTarget = etTarget;
}
public String getEtCapaian() {
return etCapaian;
}
public void setEtCapaian(String etCapaian) {
this.etCapaian = etCapaian;
}
public String getDeskripsiIbadah() {
return deskripsiIbadah;
}
public void setDeskripsiIbadah(String deskripsiIbadah) {
this.deskripsiIbadah = deskripsiIbadah;
}
public int getIdIbadah() {
return idIbadah;
}
public void setIdIbadah(int idIbadah) {
this.idIbadah = idIbadah;
}
public String getNamaIbadah() {
return namaIbadah;
}
public void setNamaIbadah(String namaIbadah) {
this.namaIbadah = namaIbadah;
}
public boolean getStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
}
I hope, you can help me. Thank you very much & sorry for my bad english.
First you have to set your TextView and EditText invisible in your XML, by adding android:visibility="invisible" to the XML of your TextView and EditText.
Then you have to use setVisibility(View.VISIBLE) after you have set the checkbox, like this:
yourcheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b) {
//if checkbox is checked (b == true)
yourTextView.setVisibility(View.VISIBLE);
yourEditText.setVisibility(View.VISIBLE);
}
if (!b) {
//if checkbox is not checked (b == false)
yourTextView.setVisibility(View.INVISIBLE);
yourEditText.setVisibility(View.INVISIBLE);
}
}
});
If you first want to click a button and then check weather checkbox is checked, add this to your OnClickListenter:
if (yourcheckbox.isChecked) {
yourTextView.setVisibility(View.VISIBLE);
yourEditText.setVisibility(View.VISIBLE);
}

How to add JSON data to RecyclerView

This is my RecyclerAdapter code:
package com.example.sander.app;
import android.app.Fragment;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by Sander on 6-4-2017.
*/
public class RecycleAdapter extends RecyclerView.Adapter<RecycleAdapter.MyViewHolder> {
private String[] mDataset;
ArrayList<String> ArrayDataset;
public static class MyViewHolder extends RecyclerView.ViewHolder{
public CardView mCardView;
public TextView mTextView;
public MyViewHolder(View v){
super(v);
mCardView = (CardView) v.findViewById(R.id.card_view);
mTextView = (TextView) v.findViewById(R.id.tv_blah);
}
}
public RecycleAdapter(ArrayList<String> names){
ArrayDataset = names;
}
#Override
public RecycleAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_card_view, parent, false);
MyViewHolder vh = new MyViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position){
holder.mTextView.setText(ArrayDataset.get(position));
}
#Override
public int getItemCount() { return ArrayDataset.size(); }
}
And this is my Recycler Fragment code:
package com.example.sander.app;
import android.app.Fragment;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Sander on 6-4-2017.
*/
public class RecycleFrame extends Fragment {
ArrayList<String> names = new ArrayList<>();
GoogleMaps maps = new GoogleMaps();
public RecycleFrame() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RequestQueue rq = Volley.newRequestQueue(getActivity().getApplicationContext());
String url= "http://test.dontstealmywag.ga/api/parkgarage.php";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Do something with the response
try{
JSONObject o = new JSONObject(response);
JSONArray values=o.getJSONArray("parkgarage");
for ( int i=0; i< values.length(); i++) {
JSONObject jsonObject = values.getJSONObject(i);
names.add(jsonObject.getString("parkgarage_name"));
}
} catch (JSONException ex){}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Handle error
}
});
rq.add(stringRequest);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_recycle, container, false);
RecyclerView VRecyclerView = (RecyclerView) rootView.findViewById(R.id.rv_recycler_view);
VRecyclerView.setHasFixedSize(true);
RecycleAdapter adapter = new RecycleAdapter(names);
VRecyclerView.setAdapter(adapter);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
VRecyclerView.setLayoutManager(llm);
return rootView;
}
}
Now if I'm correct. My data from my API (link can be found in the code), will be added in an ArrayList called "names", but when I run my code my Recyclerview is empty. How do I add my JSON data to the RecyclerView and display it.
(For the record if I try it with String [] {"Example"} it will show a card with "Example")
Thanks in advance

String in Database and Drawable Image in drawable folder

How can I get String from my database and combine it with Image from my drawable folder. Help Please.
this is my main activity.
package com.apk.foodanalyzer.healthandnutrifactsanalyzer;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;
import com.apk.foodanalyzer.healthandnutrifactsanalyzer.goactivity.DatabaseHelper;
import com.apk.foodanalyzer.healthandnutrifactsanalyzer.goactivity.GoItem;
import com.apk.foodanalyzer.healthandnutrifactsanalyzer.goactivity.ListGoAdapter;
import com.apk.foodanalyzer.healthandnutrifactsanalyzer.growactivity.GrowDatabaseHelper;
import com.apk.foodanalyzer.healthandnutrifactsanalyzer.growactivity.GrowItem;
import com.apk.foodanalyzer.healthandnutrifactsanalyzer.growactivity.ListGrowAdapter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
/**
* Created by Pavilion on 11/18/2015.
*/
public class Grow extends AppCompatActivity {
private ListView listviewGrow;
private ListGrowAdapter adapter;
private List<GrowItem> mGrowItemList;
private GrowDatabaseHelper mDBHelper;
private SearchView searchtext;
Integer[] imgid = {R.drawable.carp,R.drawable.catfish, R.drawable.cavalla };
#Override
protected void onCreate(Bundle savedInstanceState) {
searchtext = (SearchView) findViewById(R.id.search_text);
super.onCreate(savedInstanceState);
setContentView(R.layout.grow_layout);
listviewGrow = (ListView)findViewById(R.id.listview_growtable);
mDBHelper = new GrowDatabaseHelper(this);
mGrowItemList = mDBHelper.getListGrow();
adapter = new ListGrowAdapter(imgid, this, mGrowItemList);
listviewGrow.setAdapter(adapter);
listviewGrow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View row, int position, long index) {
Toast.makeText(getApplicationContext(), "Position " + position, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Grow.this, GrowValueActivityContent.class);
intent.putExtra("RowId", position);
startActivity(intent);
}
});
}
This is my Adapter. I don't know what to revised this. Hope you would help me.
package com.apk.foodanalyzer.healthandnutrifactsanalyzer.growactivity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.apk.foodanalyzer.healthandnutrifactsanalyzer.R;
import com.apk.foodanalyzer.healthandnutrifactsanalyzer.goactivity.GoItem;
import java.util.List;
/**
* Created by Pavilion on 12/1/2015.
*/
public class ListGrowAdapter extends BaseAdapter {
private Context mContext;
private List<GrowItem> mGrowItemList;
private final Integer[] imgid;
public ListGrowAdapter(Integer[] imgid, Context mContext, List<GrowItem> mGrowItemList) {
this.imgid = imgid;
this.mContext = mContext;
this.mGrowItemList = mGrowItemList;
}
#Override
public int getCount() {
return mGrowItemList.size();
}
#Override
public GrowItem getItem(int position) {
return mGrowItemList.get(position);
}
#Override
public long getItemId(int position) {
return mGrowItemList.get(position).getRowId();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
GrowItem item = getItem(position);
View vv = View.inflate(mContext, R.layout.go_listview, null);
TextView tvFoodDescription = (TextView)vv.findViewById(R.id.txtvw_fooddescription);
ImageView imgFoodImage = (ImageView)vv.findViewById(R.id.food_image);
tvFoodDescription.setText(item.getFoodDescription());
imgFoodImage.setImageResource(imgid[position]);
return vv;
}
}

Categories