How to pass edit text value from adapter to activity? - java

I have a recycler view adapter which takes input from user in edittext. I want to pass those values as a list back to the activity in which the recycler view is present.
I need this list in activity to send as a parameter to api through retrofit.

Create an interface like this:
interface IList {
void addToList(String editTextValue);
}
Implement this interface in your Activity:
class MainActivity extends AppCompatActivity implements IList {
#Override
public void addToList(String editTextValue) {
//TODO("logic for adding to list and sending")
}
}
Add to Adapter's constructor Activity, that implementing IList interface, as paramert:
public Adapter(IList listener){
this.listener = listener;
}
Execute addToList method in your adapter:
#Override
public void onBindViewHolder(NewViewHolder holder, int position) {
holder.sendButton.setOnClickListener .setOnClickListener(v -> {
String newText = holder.editText.text.toString()
listener.addToList(newText)
});
}

There's a working sample.
MainActivity.java
```
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Adapter adapter = new Adapter();
RecyclerView recyclerView = findViewById(R.id.recyclerView);
recyclerView.setAdapter(adapter);
EditText editText = findViewById(R.id.editText);
editText.setOnEditorActionListener((textView, actionId, keyEvent) -> {
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_DONE) {
// add item
adapter.addItem(editText.getText().toString());
// clear text input
textView.setText("");
handled = true;
}
return handled;
});
}
}
```
activity_main.xml
```
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".MainActivity">
<EditText
android:id="#+id/editText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="Insert text.."
android:imeOptions="actionDone"
android:inputType="text"
app:layout_constraintBottom_toTopOf="#+id/recyclerView"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0"
app:layout_constraintVertical_chainStyle="packed" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/editText" />
</androidx.constraintlayout.widget.ConstraintLayout>
```
Adapter.java
```
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
private List<String> items = new ArrayList<>();
#NonNull
#Override
public Adapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(android.R.layout.test_list_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull Adapter.ViewHolder holder, int position) {
String currentItem = items.get(position);
holder.textView.setText(currentItem);
}
public void addItem(String item) {
// add at first position - replace with your desired index
int index = 0;
this.items.add(index, item);
notifyItemInserted(index);
}
#Override
public int getItemCount() {
return items.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
protected TextView textView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
textView = itemView.findViewById(android.R.id.text1);
}
}
}
You can use the "done" key on the keyboard to notify the adapter that an item has been added.
To display the "done" button in the xml it is necessary to use these two instructions in the edittext
android:imeOptions="actionDone"
android:inputType="text"

Related

size of recycler view item changes when user scrolls down and up

I am working on a chat functionality to implement in my app. The purpose is that when a message comes from another user, the message item will align parent's start and when the user sends a message, it will align to the end. The send button on upper left corner simulates the other user sending a message. The problem is that when items recycles, some of them mathes the width of parent layout. I do not really understand why this happens and how to fix it. Thanks in advance...
package com.example.messageapp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.Activity;
import android.content.Context;
import android.database.Observable;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
Button sendBtn;
Button otherSendBtn;
EditText editText;
RecyclerView recyclerView;
MessagesAdapter adapter;
List<ChatMessage> messageList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
messageList=new ArrayList<>();
sendBtn=findViewById(R.id.sendBtn);
otherSendBtn=findViewById(R.id.otherSendBtn);
editText=findViewById(R.id.editText);
recyclerView=findViewById(R.id.recyclerView);
adapter=new MessagesAdapter(this,messageList);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
for(int i=0; i<4; i++){
if(i%2==0){
messageList.add(new ChatMessage("from him","self"));
}else{
messageList.add(new ChatMessage("from me","other"));
}
adapter.notifyItemInserted(messageList.size()-1);
}
otherSendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
messageList.add(new ChatMessage("random","other"));
adapter.notifyItemInserted(messageList.size()-1);
}
});
sendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String txt=editText.getText().toString();
messageList.add(new ChatMessage(txt, "self"));
adapter.notifyItemInserted(messageList.size()-1);
editText.setText("");
hideKeyboardFrom(MainActivity.this, view);
}
});
}
public static void hideKeyboardFrom(Context context, View view) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
model class for messages
package com.example.messageapp;
public class ChatMessage {
public String text;
public String user;
public ChatMessage(String text, String user) {
this.text = text;
this.user = user;
}
}
recycler view adapter
package com.example.messageapp;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class MessagesAdapter extends RecyclerView.Adapter {
Context context;
List<ChatMessage> messages;
public void setMessages(List<ChatMessage> messages) {
this.messages = messages;
}
public MessagesAdapter(Context context, List<ChatMessage> messages) {
this.context = context;
this.messages = messages;
}
private static class MessageViewHolder extends RecyclerView.ViewHolder{
TextView textView;
RelativeLayout relativeLayout;
public MessageViewHolder(#NonNull View itemView) {
super(itemView);
textView=itemView.findViewById(R.id.messageTextView);
relativeLayout=itemView.findViewById(R.id.item_parent);
}
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v= LayoutInflater.from(context).inflate(R.layout.message_item,parent,false);
return new MessageViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
ChatMessage message=messages.get(position);
((MessageViewHolder) holder).textView.setText(message.text);
RelativeLayout.LayoutParams params= (RelativeLayout.LayoutParams) ((MessageViewHolder) holder).relativeLayout.getLayoutParams();
if(message.user.equals("self")){
params.addRule(RelativeLayout.ALIGN_PARENT_END);
((MessageViewHolder) holder).relativeLayout.setBackgroundColor(context.getResources().getColor(R.color.teal_200));
}else{
params.addRule(RelativeLayout.ALIGN_PARENT_START);
((MessageViewHolder) holder).relativeLayout.setBackgroundColor(context.getResources().getColor(R.color.purple_200));
}
((MessageViewHolder) holder).relativeLayout.setLayoutParams(params);
}
#Override
public int getItemCount() {
return messages.size();
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_margin="10dp">
<RelativeLayout
android:id="#+id/item_parent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/teal_700">
<TextView
android:padding="10dp"
android:id="#+id/messageTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="#+id/otherSendBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="send"
android:layout_centerHorizontal="true"/>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/otherSendBtn"
tools:listitem="#layout/message_item"/>
<RelativeLayout
android:id="#+id/linear"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="horizontal">
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toStartOf="#+id/sendBtn"
android:layout_marginEnd="5dp"/>
<Button
android:background="#drawable/ic_baseline_send_24"
android:id="#+id/sendBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"/>
</RelativeLayout>
</RelativeLayout>

Fit 2 textViews in an adapter , java , android

I am creating a note-taking app for myself, I created an adapter to show notes on the main screen with a title view and text view but the app crashes when I launch it
here is RecyclerViewAdapter.java.
I am using basic java, I don't have much experience so please try to explain simply so could I understand,
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.myViewHolder> {
String[] arr;
String[] arr2;
public RecyclerViewAdapter(String[] arr, String[] arr2) {
this.arr = arr;
this.arr2 = arr2;
}
#NonNull
#Override
public myViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_view, parent,
false);
return new myViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull myViewHolder holder, int position) {
holder.titleView.setText(position);
holder.textView.setText(position);
}
#Override
public int getItemCount() {
return arr.length;
}
public class myViewHolder extends RecyclerView.ViewHolder {
TextView titleView;
TextView textView;
public myViewHolder(#NonNull View itemView) {
super(itemView);
titleView = itemView.findViewById(R.id.text_title_view);
textView = itemView.findViewById(R.id.text_text_view);
}
}
}
Here is the XML code,
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/text_title_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:gravity="start"
android:text="Title" />
<TextView
android:id="#+id/text_text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:gravity="start"
android:text="Body will go here" />
</LinearLayout>
and here is my main activity
package com.example.keepnotes;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
public class MainActivity extends AppCompatActivity {
RecyclerView.LayoutManager layoutManager;
private RecyclerView recyclerView;
private Toolbar toolbar1;
RecyclerViewAdapter recyclerViewAdapter;
String []arr = {"First Heading ","Second Heading"};
String []arr2 = {"First body ","Second body"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setting up recycler view
recyclerView = findViewById(R.id.recycler_view);
layoutManager = new StaggeredGridLayoutManager(2, LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
recyclerViewAdapter= new RecyclerViewAdapter(arr, arr2);
recyclerView.setAdapter(recyclerViewAdapter);
}
}
please guide me that where I am mistaken.
update: Thanks to #stealthoust, App is running but can't find any view on the screen, what can I do about that.
Try to change this on onBindViewHolder
holder.titleView.setText(arr[position]); holder.textView.setText(arr2[position]);

How to change the font in recycler view?

I have a list of Button type TextViews like set in a horizontal RecyclerView and I'm trying to change the font of the text of these buttons and it's not working.
I've changed the font in the XML file of my item to exo, and tried to use many tips of view instead of the TextView but i can't change the font anyway.
is there any limitation about customization of the view when using RecyclerView or I'm doing it wrong?
p.s. I can't change the padding of the TextView either.
My RecyclerView item:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="32dp">
<TextView
android:id="#+id/rpgListBtn"
android:layout_width="130dp"
android:layout_height="32dp"
android:layout_weight="1"
android:background="#drawable/ic_rpg_list"
android:fontFamily="#font/exo_teste"
android:gravity="center"
android:includeFontPadding="true"
android:paddingLeft="8dp"
android:paddingRight="8dp"
android:text="D&D"
android:textAllCaps="false"
android:textColor="#000000"
android:textSize="13sp" />
</LinearLayout>
My RecyclerView:
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rpgListView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:clipToPadding="false"
android:paddingLeft="22dp"
android:paddingRight="8dp"
android:orientation="horizontal"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/escolha_um_" />
my adapter:
package com.example.rpglink.Adapters;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.rpglink.R;
import java.util.List;
public class RpgListAdapter extends RecyclerView.Adapter<RpgListAdapter.MyViewHolder> {
private List<String> titulos;
public RpgListAdapter(List<String> titulos) {
this.titulos = titulos;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemLista = LayoutInflater.from(parent.getContext()).inflate(R.layout.rps_list_view_holder,parent,false);
return new MyViewHolder(itemLista);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
String titulo = titulos.get(position);
holder.titulo.setText(titulo);
}
#Override
public int getItemCount() {
return titulos.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder{
TextView titulo;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
titulo = itemView.findViewById(R.id.rpgListBtn);
}
}
}
the implementation of recycler view in the activity:
package com.example.rpglink.Activitys;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import com.example.rpglink.Adapters.RpgListAdapter;
import com.example.rpglink.Helpers.HorizontalSpaceItemDecoration;
import com.example.rpglink.R;
import java.util.ArrayList;
import java.util.List;
public class HomeC extends AppCompatActivity {
private RecyclerView recyclerView;
private RpgListAdapter adapter;
private List<String> lista = new ArrayList<>();
public HomeC() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_c);
criarTitulos();
recyclerView = findViewById(R.id.rpgListView);
recyclerView.setHasFixedSize(false);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL, false);
recyclerView.setLayoutManager(layoutManager);
adapter = new RpgListAdapter(lista);
recyclerView.setAdapter(adapter);
recyclerView.addItemDecoration(new HorizontalSpaceItemDecoration(32));
}
public void criarTitulos(){
this.lista.add("D&D");
this.lista.add("CyberPunk");
this.lista.add("Call of Cthulhu");
this.lista.add("Tormenta");
}
}
You can set it in the ViewHolder constructor using Typeface.createFromAsset
public class MyViewHolder extends RecyclerView.ViewHolder{
TextView titulo;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
titulo = itemView.findViewById(R.id.rpgListBtn);
titulo.setTypeface(Typeface.createFromAsset(itemView.getContext().getAssets(),
"font/exo_teste"));
}
}

Recycle view in Android java

Recycler View is not iterating to the length of array.
Here is the code, what am i missing. i followed a guide describing the entire process, in that guide all items of the array is visible in the list view.
Here is the main activity file that host the recyclerView, below the adapter java class that filter through the array and pop out the list View. please help me
PickupActivity.java
package com.demo.driverconsole;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerViewAccessibilityDelegate;
import android.util.Log;
import android.widget.Adapter;
import android.widget.Toast;
import java.util.ArrayList;
public class pickupActivity extends AppCompatActivity {
private static final String TAG = "pickupActivity";
private RecyclerView studentList;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private ArrayList<String> myDataset = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pickup);
myDataset.add("John Doe");
myDataset.add("Jane Doe");
myDataset.add("Susan");
initRecycler();
}
public void initRecycler() {
Log.d(TAG, "Called");
RecyclerView recyclerView = findViewById(R.id.recyclerView);
StudentListAdapter adapter = new StudentListAdapter(myDataset);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
}
StudentListAdapter.java
package com.datastoneglobal.driverconsole;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.util.ArrayList;
public class StudentListAdapter extends RecyclerView.Adapter<StudentListAdapter.ViewHolder> {
private static final String TAG = "StudentListAdapter";
private ArrayList<String> names = new ArrayList<>();
public StudentListAdapter(ArrayList<String> names) {
Log.d(TAG, "StudentListAdapter: " + names);
this.names = names;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.student_item, parent, false);
ViewHolder vh = new ViewHolder(view);
return vh;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.text.setText(names.get(position));
}
#Override
public int getItemCount() {
return names.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView text;
RelativeLayout layout;
public ViewHolder(View itemView) {
super(itemView);
text = itemView.findViewById(R.id.textView);
}
}
}
ActivityPickup.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:layout_height="wrap_content" android:layout_width="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"></android.support.v7.widget.RecyclerView>
</RelativeLayout>
StudentItem.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:id="#+id/layout"
android:layout_height="match_parent">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="Loading ...">
</TextView>
</RelativeLayout>
The code looks right the only problem i find is the hight of your RelativeLayout in StudentItem.xml
Change the hight of your RelativeLayout to android:layout_height="wrap_content" in your StudentItem.xml
SAMPLE CODE
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:id="#+id/layout"
android:layout_height="wrap_content">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="Loading ...">
</TextView>
</RelativeLayout>
EDIT
Use this
private StudentListAdapter adapter;
Instead of this
private RecyclerView.Adapter adapter;
⬇ Remove this code ⬇
public class StudentListAdapter extends RecyclerView.Adapter<StudentListAdapter.ViewHolder>
{
// ....
}
⬇ use this code ⬇
public class StudentListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
{
// ....
}
because you extend :-
public class StudentListAdapter
extends RecyclerView.Adapter<StudentListAdapter.ViewHolder>
and you extend at here :- public class ViewHolder extends RecyclerView.ViewHolder

How to get value of a row in listview in android

I am new in android
The structure of my application consist of:
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.example.reyhane.myapplication.MainActivity">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.design.widget.CoordinatorLayout>
cell.xml
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layoutDirection="rtl">
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/nationalCode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="2"
android:layout_marginLeft="8dp"
android:textStyle="bold" />
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="2"
android:layout_marginLeft="8dp"
android:textStyle="bold" />
<TextView
android:id="#+id/lastName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="2"
android:layout_marginLeft="8dp"
android:textStyle="bold" />
<Button
android:id="#+id/delete_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="2"
android:text="حذف" />
</TableRow>
</TableLayout>
MainActivity.java
package com.example.reyhane.myapplication;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import java.util.ArrayList;
public class MainActivity extends Activity {
public ListView list;
public ArrayList<Person> countries = new ArrayList<Person>();
public ListAdapter adapter;
public void fillPerson(String nationalCode) {
Person person = new Person();
person.setNationalCode(nationalCode);
person.setName("reza");
person.setLastName("hghgh");
person.setPhone("231345");
countries.add(person);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
fillPerson("6768767");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.list);
adapter = new ListAdapter(this);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
Object o = list.getItemAtPosition(position);
Person person = (Person) o;
openAddPersonActivity(person.getNationalCode());
}
});
}
public void openAddPersonActivity(String nationalCode) {
Intent i = new Intent(MainActivity.this, AddPerson.class);
if (nationalCode != null)
i.putExtra("nationalCode", nationalCode);
startActivity(i);
}
}
ListAdapter.java
package com.example.reyhane.myapplication;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TableLayout;
import android.widget.TextView;
/**
* Created by reyhane on 11/24/16.
*/
public class ListAdapter extends BaseAdapter {
MainActivity mainActivity;
ListAdapter(MainActivity mainActivity) {
this.mainActivity = mainActivity;
}
#Override
public int getCount() {
return mainActivity.countries.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
static class ViewHolderItem {
TextView nationalCode;
TextView name;
TextView lastName;
TextView phone;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolderItem holder = new ViewHolderItem();
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mainActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.cell, null);
holder.nationalCode = (TextView) convertView.findViewById(R.id.nationalCode);
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.lastName = (TextView) convertView.findViewById(R.id.lastName);
convertView.setTag(holder);
} else {
holder = (ViewHolderItem) convertView.getTag();
}
Button deleteBtn = (Button) convertView.findViewById(R.id.delete_btn);
holder.nationalCode.setText(this.mainActivity.countries.get(position).getNationalCode());
holder.name.setText(this.mainActivity.countries.get(position).getName());
holder.lastName.setText(this.mainActivity.countries.get(position).getLastName());
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do something
mainActivity.countries.remove(position); //or some other task
notifyDataSetChanged();
}
});
return convertView;
}
}
My problem:
As you see in my application, i have list of person in listview.
In this form i add person and delete and edit it.
I can remove each record of listview but i can not get nationalCode value of person of each reacord in listview to fetch person from database by this nationalcode and edit it.
How do i do?
please help me
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View v, int arg2, long arg3)
{
String nationalcode = (String) ((TextView) v.findViewById(R.id.nationalcode)).getText();
Toast.makeText(getApplicationContext(), "NATIONAL CODE "+nationalcode, Toast.LENGTH_SHORT).show();
openAddPersonActivity(nationalcode);
}
});
Hope it helps.
try this :
openAddPersonActivity(countries.get(position).getNationalCode());
FYI, the list.setOnItemClick doesn't work
add this into your ListAdapter:
holder.nationalCode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(mainActivity,"Country Code = "+MainActivity.countries.get(position).getNationalCode(),Toast.LENGTH_SHORT).show();
Intent i = new Intent(mainActivity, AddPerson.class);
if (nationalCode != null)
i.putExtra("nationalCode", nationalCode);
startActivity(i);
}
});
and if you click country code in listview item then it will detected;
You have not set countries list to your Listview adaptor.
When you are setting the adaptor, pass the countries list to listview adaptor.
It work successfully:
holder.nationalCode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String nationalcode = (String) ((TextView) view.findViewById(R.id.nationalCode)).getText();
Toast.makeText(mainActivity, "NATIONAL CODE " + nationalcode, Toast.LENGTH_SHORT).show();
}
});
Try This
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
Person person = countries.get(position);
openAddPersonActivity(person.getNationalCode());
}

Categories