How to add elements to a list from another class? - java

So i have my a list on my main activity that i want to be able to access in another class. The second class is supposed to add more records to the list based on the users input but i don't know how to access it. Can anybody help?
Contactos.java:
This is my main class and its also where the list is kept, i did a test run on it so that's why the constructor is filled with numbers. I want to be able to add to the list from another class.
public class Contactos extends AppCompatActivity {
private Button btnReciente;
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnReciente = (Button) findViewById(R.id.Reciente);
listView = (ListView) findViewById(R.id.list1);
List<contactosLista> list1 = new ArrayList<contactosLista>();
list1.add(new contactosLista("1","2","3","4","5","6"));
ContactosAdapter adapter = new ContactosAdapter(this,list1);
listView.setAdapter(adapter);
ContactosAdapter.java: This is where i inflate the list, i use it so i can use a .xml file to better display the values in the list.
public class ContactosAdapter extends BaseAdapter
{
private Context mContext;
private List<contactosLista>mListaContactos;
public ContactosAdapter(Context context, List<contactosLista> list)
{
mContext = context;
mListaContactos = list;
}
#Override
public int getCount() {
return mListaContactos.size();
}
#Override
public Object getItem(int position) {
return mListaContactos.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
contactosLista entrada = mListaContactos.get(position);
if(convertView == null)
{
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(R.layout.contactos_row,null);
}
TextView Contact = (TextView) convertView.findViewById(R.id.Contacto);
Contact.setText(entrada.getmName() + " -- " + entrada.getmEmpresa());
return convertView;
}
}
contactosLista.java: This the class that defines the elements that the list needs. i made a constructor that accommodates all the strings and made all the setters & getters
public class contactosLista
{
private String mName;
private String mEmpresa;
private String mRazon;
private String mDireccion;
private String mEstatus;
private String mPaquete;
public contactosLista(String mName, String mEmpresa, String mRazon, String mDireccion, String mEstatus, String mPaquete)
{
this.mName = mName;
this.mEmpresa = mEmpresa;
this.mRazon = mRazon;
this.mDireccion = mDireccion;
this.mEstatus = mEstatus;
this.mPaquete = mPaquete;
}
public String getmName() {
return mName;
}
public void setmName(String mName) {
this.mName = mName;
}
public String getmEmpresa() {
return mEmpresa;
}
public void setmEmpresa(String mEmpresa) {
this.mEmpresa = mEmpresa;
}
public String getmRazon() {
return mRazon;
}
public void setmRazon(String mRazon) {
this.mRazon = mRazon;
}
public String getmDireccion() {
return mDireccion;
}
public void setmDireccion(String mDireccion) {
this.mDireccion = mDireccion;
}
public String getmEstatus() {
return mEstatus;
}
public void setmEstatus(String mEstatus) {
this.mEstatus = mEstatus;
}
public String getmPaquete() {
return mPaquete;
}
public void setmPaquete(String mPaquete) {
this.mPaquete = mPaquete;
}
}
createContact.java: finally this is the class where i want to be able to access the list from Contactos.java, I have a layout file that has a bunch of Edit text so that i can record input from the user. When the user clicks on the button to save i want my void "GuardarCon" to save the input from the user to strings and then i want to use those strings as parameters for my list. This is where the problem arises, i don't know how to call the list. PLS help.
public class createContact extends AppCompatActivity
{
EditText nombre;
EditText empresa;
EditText razon;
EditText direccion;
EditText estatus;
EditText paquete;
String snombre;
String sempresa;
String srazon;
String sdireccion;
String sestatus;
String spaquete;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_contact);
nombre = (EditText) findViewById(R.id.nombreT);
empresa = (EditText) findViewById(R.id.empresaT);
razon = (EditText) findViewById(R.id.razonSocialT);
direccion = (EditText) findViewById(R.id.direccionT);
estatus = (EditText) findViewById(R.id.EstatusT);
paquete = (EditText) findViewById(R.id.paqueteT);
}
public void GuardarCon(View view)
{
snombre = nombre.getText().toString();
sempresa = empresa.getText().toString();
srazon = razon.getText().toString();
sdireccion = direccion.getText().toString();
sestatus = estatus.getText().toString();
spaquete = paquete.getText().toString();
}

Create a singleton class and access and modify data as you want !
public class DataHolder{
public static final DataHolder instance = new DataHolder();
private List<Your_Data_Type> data;
//Your methods goes here...
}

You could use startActivityForResult method to start createContact from Contactos activity and after the addition process is done use setResult method to return the added item to the Contactos activity and handle adding the item to the list in onActivityResult.
take a look at this link for further info:
https://developer.android.com/training/basics/intents/result

Related

Using button to delete selected item in Listview w/ ArrayAdapter

I've been working with Java for a few months but new to Android. This is a recipe holder app.
I have an ArrayAdapter set on a ListView and am needing to select an item in the ListView and delete it with a Button (I've already successfully set up adding of Strings to the Listview). I'm using an ArrayList for the list used to store Ingredient objects rather than a regular array. I'm attempting to use AdapterView.onSelectedItemListener to identify a user selection in the ListView and then use the Button to delete the selected item. For the Button, I'm implementing Button.onClickItemListener.
To get the list items into the ListView I'm using a dialog. I'm using an interface to send the string input from the dialog to the ListView in RecipeFragmentNew. I haven't been having issues getting the Strings from the dialog to RecipeFragmentNew, so I haven't included any of that code.
Problem: Button is deleting list items but it is deleting the first item in the list, not the item that is being selected.
Recipe.java
public class Recipe {
private UUID mID;
private String mName;
private Date mDate;
private boolean mIsFavorite;
private final ArrayList<Ingredient> ingredients;
public final ArrayList<Instruction> instructions;
public Recipe() {
mID = UUID.randomUUID();
mDate = new Date();
this.ingredients = new ArrayList<>();
this.instructions = new ArrayList<>();
}
public UUID getID() {
return mID;
}
public String getName() {
return mName;
}
public void setName(String name) {
mName = name;
}
public Date getDate() {
return mDate;
}
public void setDate(Date date) {
mDate = date;
}
public boolean isFavorite() {
return mIsFavorite;
}
public void setFavorite(boolean favorite) {
mIsFavorite = favorite;
}
public ArrayList<Ingredient> getIngredients() {
return ingredients;
}
public ArrayList<Instruction> getInstructions() {
return instructions;
}
}
Ingredient.java
public class Ingredient {
private String name;
private String amount;
public Ingredient(String name, String amount) {
this.name = name;
this.amount = amount;
}
public String getName() {
return name;
}
public String getAmount() {
return amount;
}
#Override
public String toString() {
return this.name + " " + this.amount;
}
}
The arrayList is retreived from Recipe class using mRecipe.getIngredients().
The ListView is mIngredientWindow.
RecipeFragmentNew.java
public class RecipeFragmentNew extends Fragment implements IngredientListDialog.OnInputSelected {
public static final String TAG = "RecipeFragmentNew";
public static final String DIALOG_INGREDIENTS = "DialogIngredients";
private Recipe mRecipe;
private EditText mNameField;
private Button mIngredientAdd;
private Button mIngredientDelete;
private ListView mIngredientWindow;
private int listViewPosition;
private ArrayAdapter<Ingredient> listAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
UUID recipeId = (UUID) getArguments().getSerializable(ARG_RECIPE_ID);
mRecipe = RecipeQueue.get(getActivity()).getRecipe(recipeId);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.lists_detail_view, container, false);
mIngredientDelete = v.findViewById(R.id.delete_ingredient_button);
mIngredientDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < mRecipe.getIngredients().size(); i++) {
if (i == listViewPosition) {
mRecipe.getIngredients().remove(i);
}
listAdapter.notifyDataSetChanged();
}
}
});
listAdapter = new ArrayAdapter<Ingredient>(
getActivity(),
android.R.layout.simple_list_item_1,
mRecipe.getIngredients()
);
mIngredientWindow = v.findViewById(R.id.ingredients_window);
mIngredientWindow.setAdapter(listAdapter);
AdapterView.OnItemSelectedListener itemSelectedListener = new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
listViewPosition = position;
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
};
Button is deleting list items but it is deleting the first item in
the list, not the item that is being selected.
The variable listViewPosition is always 0 because the setOnItemSelectedListener is not called. please check this answer
So you can replace this method with setOnItemClicklistener like the below code:
mIngredientWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//mIngredientWindow.setSelection(position);
listViewPosition = position;
}
});
Simple
the listViewPosition variable always equals 0
Here's Why, You have defined an object from AdapterView.OnItemSelectedListener but you never attache it to the listview
all you need to do is add
mIngredientWindow.setOnItemSelectedListener (itemSelectedListener );

Android: Passing variables that allows recyclerview to be populated by specific strings

I'm trying to create a code saying "Where the username that is logged in matches the username of a created recipe, only show these database entries in the recyclerview on my MyRecipes.java activity". I'm having trouble working out where to put this potential statement. Looking at my code, where would you put that statement, if or otherwise?
The userLoggedIn and loggedUser is the variable for the currently logged in user.
The thisUser is what I've set as the users pulled from the database when the recyclerview is populating in the recyclerview.java class.
Any help would be greatly appreciated!
RecyclerView.java class
private static String thisUser;
String userLoggedIn = HomeActivity.getUserLogged();
private Context mContext;
private RecipesAdapter mRecipeAdapter;
public void setConfig (RecyclerView recyclerView, Context context, List<Recipes> recipes, List<String> keys){
mContext = context;
mRecipeAdapter = new RecipesAdapter(recipes, keys);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
recyclerView.setAdapter(mRecipeAdapter);
}
class RecipeItemView extends RecyclerView.ViewHolder{
private TextView mTitle;
private TextView mIngredients;
private TextView mMethod;
private TextView mUser;
private String key;
public RecipeItemView(ViewGroup parent){
super(LayoutInflater.from(mContext).inflate(R.layout.recipe_list_item, parent,false));
mTitle = (TextView) itemView.findViewById(R.id.tvTitle);
mMethod = (TextView) itemView.findViewById(R.id.tvMethod);
mIngredients = (TextView) itemView.findViewById(R.id.tvIngredients);
mUser = (TextView) itemView.findViewById(R.id.tvUser);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, RecipeDetails.class);
intent.putExtra("key", key);
intent.putExtra("title", mTitle.getText().toString());
intent.putExtra("ingredients", mIngredients.getText().toString());
intent.putExtra("method", mMethod.getText().toString());
mContext.startActivity(intent);
}
});
}
public void bind(Recipes recipes, String key) {
mTitle.setText(recipes.getTitle());
mIngredients.setText(recipes.getIngredients());
mMethod.setText(recipes.getMethod());
mUser.setText(recipes.getCreatedUser());
thisUser = mUser.getText().toString().trim();
this.key = key;
}
}
public static String getUserLoggedIn(){
return thisUser;
}
class RecipesAdapter extends RecyclerView.Adapter<RecipeItemView> {
private List<Recipes> mRecipeList;
private List<String> mKeys;
public RecipesAdapter(List<Recipes> mRecipeList, List<String> mKeys) {
this.mRecipeList = mRecipeList;
this.mKeys = mKeys;
}
#NonNull
#Override
public RecipeItemView onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new RecipeItemView(parent);
}
#Override
public void onBindViewHolder(#NonNull RecipeItemView holder, int position) {
holder.bind(mRecipeList.get(position), mKeys.get(position));
}
#Override
public int getItemCount() {
return mRecipeList.size();
}
}
}
MyRecipes.java (Where the recycler view populates and shows all the recipes)
String loggedUser = HomeActivity.getUserLogged();
String thisUser = RecyclerViewConfig.getUserLoggedIn();
Button addRecipes;
private RecyclerView mRecyclerView;
private String passedUsername;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_recipes);
passedUsername = getIntent().getStringExtra("loggedUsername1");
mRecyclerView = (RecyclerView) findViewById(R.id.rvRecipes);
new FirebaseDatabaseHelper().readRecipes(new FirebaseDatabaseHelper.DataStatus() {
#Override
public void DataIsLoaded(List<Recipes> recipes, List<String> keys) {
new RecyclerViewConfig().setConfig(mRecyclerView, MyRecipesActivity.this, recipes, keys);
}
#Override
public void DataIsInserted() {
}
#Override
public void DataIsUpdated() {
}
#Override
public void DataIsDeleted() {
}
});
addRecipes = findViewById(R.id.btnAddNewRecipe);
addRecipes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent addrecipe = new Intent(MyRecipesActivity.this, AddRecipes.class);
addrecipe.putExtra("loggedUsername2", passedUsername);
startActivity(addrecipe);
}
});
}
}
If i understand correctly, you need to show the recipes to the user only if he/she is the one who created it? Assuming that, below change in the code will do the trick.
Change your bind() method as follows.
public void bind(Recipes recipes, String key) {
thisUser = mUser.getText().toString().trim();
if(thisUser.equals(recipes.getCreatedUser)) {
mTitle.setText(recipes.getTitle());
mIngredients.setText(recipes.getIngredients());
mMethod.setText(recipes.getMethod());
mUser.setText(recipes.getCreatedUser());
this.key = key;
}
}
Though that is a naive approach, a better approach would be to filter the recipes list with created user when you load data from Firebase with readRecipes() method itself. To do that a query can be used as below(the exact query below might not work for you depending on your DB structure. Change it as needed)
Query query = reference.child("Recipes").orderByChild("userCreated").equalTo(thisUser);

Androidx RecycleView Not showing items with parse server

This is my adapter for recycle view
CategoryAdapter Class
public class CategoryRAdapter extends RecyclerView.Adapter<CategoryRAdapter.MyViewHolder> {
private Context mcontext;
private List<Food> mData;
RequestOptions option;
public CategoryRAdapter(Context mcontext, List<Food> mData) {
this.mcontext = mcontext;
this.mData = mData;
option = new RequestOptions().centerCrop().placeholder(R.drawable.loading_shape).error(R.drawable.loading_shape);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.food_row, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Food current = mData.get(position);
holder.tv_Name.setText(current.getName());
holder.tv_Rating.setText(current.getRating());
holder.tv_Descip.setText(current.getDescrip());
holder.tv_Category.setText(current.getCateg());
Glide.with(mcontext).load(mData.get(position).getImages()).apply(option).into(holder.img_Thumbnail);
}
#Override
public int getItemCount() {
return mData.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView tv_Name;
TextView tv_Rating;
TextView tv_Descip;
TextView tv_Category;
ImageView img_Thumbnail;
public MyViewHolder(View itemView) {
super(itemView);
tv_Name = itemView.findViewById(R.id.food_name);
tv_Rating = itemView.findViewById(R.id.rating);
tv_Descip = itemView.findViewById(R.id.desc);
tv_Category = itemView.findViewById(R.id.category);
img_Thumbnail = itemView.findViewById(R.id.thumbnail);
}
}
}
This is my model
Food Class
public class Food {
String Name;
String Images;
String Descrip;
String Rating;
String Categ;
public Food() {
}
public Food(String name, String images, String descrip, String rating, String categ) {
this.Name = name;
this.Images = images;
this.Descrip = descrip;
this.Rating = rating;
this.Categ = categ;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getImages() {
return Images;
}
public void setImages(String images) {
Images = images;
}
public String getDescrip() {
return Descrip;
}
public void setDescrip(String descrip) {
Descrip = descrip;
}
public String getRating() {
return Rating;
}
public void setRating(String rating) {
Rating = rating;
}
public String getCateg() {
return Categ;
}
public void setCateg(String categ) {
Categ = categ;
}
}
My mian activity
CategoryActivity Class
public class CategoriaActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private List<Food> dbObjects;
private RecyclerView.Adapter adapter;
private AlertDialog.Builder dialogBuilder;
private AlertDialog dialog;
TextView l_nombre,l_precio;
Button l_finalizar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_categoria);
recyclerView = findViewById(R.id.recycle_id);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
dbObjects = new ArrayList<>();
ParseQuery<ParseObject> query = ParseQuery.getQuery("Category");
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> objList, ParseException e) {
if (e == null) {
for (ParseObject obj : objList) {
Food food = new Food();
food.setName(obj.getString("Name"));
food.setDescrip(obj.getString("Descrip"));
food.setRating(obj.getString("Rating"));
food.setCateg(obj.getString("Categ"));
food.setImages(obj.getString("Images"));
dbObjects.add(food);
}
} else {
FancyToast.makeText(CategoriaActivity.this, "Error: " + e.getMessage(), FancyToast.LENGTH_SHORT, FancyToast.ERROR, true).show();
}
}
});
adapter = new CategoryRAdapter(this, dbObjects);
recyclerView.setAdapter(adapter);
FloatingActionButton fab = findViewById(R.id.shoppingFlot);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
carritopop();
}
});
}
private void carritopop() {
dialogBuilder = new AlertDialog.Builder(this);
View view = getLayoutInflater().inflate(R.layout.pop_cart,null);
l_finalizar = view.findViewById(R.id.l_finalizar);
l_finalizar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pago();
}
});
dialogBuilder.setView(view);
dialog = dialogBuilder.create();
dialog.show();
}
private void pago() {
Intent intent = new Intent(CategoriaActivity.this, PagoActivity.class);
startActivity(intent);
}
}
I dont know whats wrong with the code, the recycle view aint working, it aint showing any items, i would really appreciate if someone could help me out and notice something wrong in my code
Call adapter.notifyDataSetChanged() in your query done callback, this will notify the adapter that the list has changed. This is happening because when you set the adapter, the list was empty as the query was running in background. Once it completes, you have to tell the adapter that new data has been added to list:
if (e == null) {
for (ParseObject obj : objList) {
...
}
adapter.notifyDataSetChanged();
}
Also, create your adapter before you send the query otherwise it may result in NullPointerException in case data is loaded before the next statement executes (highly unlikely but never hurts to be safe).
dbObjects = new ArrayList<>();
adapter = new CategoryRAdapter(this, dbObjects);
ParseQuery<ParseObject> query = ParseQuery.getQuery("Category");
I recommend you to use RxJava2 to user asynchronous methods, it's awesome... And about the problem, maybe your data is not ready when you're already creating the adapter with the ArrayList.
Try to move the recyclerView.setAdapter() to inside the FindCallback after create the Food Objects.

add object to arraylist from another class

I got a problem. I want to add an object named Transactions which is this one:
public class Transaction {
private float value;
private int transaction_date;
private String description;
public Transaction(float value, int transaction_date, String description){
super();
this.value = value;
this.transaction_date = transaction_date;
this.description = description;
}
public float getValue(){
return value;
}
public int getTransaction_date(){
return transaction_date;
}
public String getDescription(){
return description;
}
to an ArrayList in my main activity.
Okay as far not that much of a problem. But how can I do this from another activity where I want to set the required variables (in my case the value, transaction_date and description)?
Here is my Activity where I want to set the values (yes I know that there are no variable inputs yet):
public class AddMoneyTransaction extends AppCompatActivity {
EditText depositInputSix;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_money_transaction);
//transaction list
populateTransactionList();
populateListView();
//setup the button
Button addDepositButton;
addDepositButton = (Button)findViewById(R.id.addDepositButton);
//make it work
addDepositButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view) {
}
});
}
//populated transaction list
protected void populateTransactionList() {
myTransactions.add(new Transaction(1,19,"monday"));
myTransactions.add(new Transaction(2,20,"tuesday"));
myTransactions.add(new Transaction(3,21,"wednesday"));
}
//populated list view
private void populateListView() {
ArrayAdapter<Transaction> adapter = new AssetsOverview.LastTransactionsListAdapter();
ListView list = (ListView) findViewById(R.id.last_transactions_listView);
list.setAdapter(adapter);
}
private class LastTransactionsListAdapter extends ArrayAdapter<Transaction>{
public LastTransactionsListAdapter(){
super(AddMoneyTransaction.this, R.layout.transaction_list_view, myTransactions);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
//make sure there is a view to work with (maybe null)
View itemView = convertView;
if (itemView == null){
itemView = getLayoutInflater().inflate(R.layout.transaction_list_view, parent, false);
}
//find a transaction to work with
Transaction currentTransaction = myTransactions.get(position);
// fill the view:
// value
TextView valueView = (TextView) itemView.findViewById(R.id.transactionValueView);
valueView.setText(currentTransaction.getValue() + "$");
// date
TextView dateView = (TextView) itemView.findViewById(R.id.transactionDateView);
dateView.setText(currentTransaction.getTransaction_date() + "");
// description
TextView descriptionView = (TextView) itemView.findViewById(R.id.transactionDesciptionView);
descriptionView.setText(currentTransaction.getDescription());
return itemView;
}
}
I hope someone can please help me with this since I did not find anything helpful. Please tell me if you need more information...
I assume your myTransactions list is defined inside parent class AppCompatActivity. The problem in
addDepositButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
}
});
seems to be that myTransactions is not defined as a final variable.
When you create a new anonymous OnClickListener, what the compiler does is it provides to OnClickListener constructor a reference to your myTransactions, if myTransactions is used inside the onClick method. This myTransactions cannot be changed later and must therefore be final.
So for the solution, I would try adding final keyword in the definition of myTransactions.

Empty listview with retrofit 2.0

I have listview that have to fill from JSON file but until now after running app I see nothing and I don't know if the problem from java codes or JSON file??
also I notice that I can't add file extensions inside #Path ,,
MainActivity.java
public class MainActivity extends AppCompatActivity {
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
final Retrofit retrofit = new Retrofit.Builder().baseUrl("http://10.0.2.2").addConverterFactory(GsonConverterFactory.create()).build();
TelService service = retrofit.create(TelService.class);
final retrofit.Call<List<tel_list>> calls = service.getphones("telephones");
calls.enqueue(new Callback<List<tel_list>>() {
#Override
public void onResponse(Response<List<tel_list>> response, Retrofit retrofit) {
if (!response.isSuccess()) {
//TODO
return;
}
List<tel_list> telephones = response.body();
TelAdapter adapter = new TelAdapter (MainActivity.this, telephones);
listView.setAdapter(adapter);
}
#Override
public void onFailure(Throwable t) {
}
});
}
}
TelService.java
public interface TelService {
#GET("/alruthea/{getphones_1}.php")
retrofit.Call<List<tel_list>> getphones(#Path("getphones_1")String telephones);
}
TelAdapter.java
public class TelAdapter extends ArrayAdapter<tel_list> {
private Context context;
private List<tel_list> telephones;
public TelAdapter(Context context, List<tel_list> data) {
super(context, R.layout.list_item, data);
telephones = data;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(getContext());
View item = inflater.inflate(R.layout.list_item, null);
TextView name = (TextView) item.findViewById(R.id.names);
name.setText(telephones.get(position).getName());
TextView number = (TextView) item.findViewById(R.id.numbers);
number.setText(telephones.get(position).getNumber());
return item;
}
}
tel_list.java
public class tel_list {
private String name;
private String number;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}

Categories

Resources