I have Activity and want to add edittext value to ArrayList useranswer. How I can do it? I reading some information from json file and add it in recyclerview.I also add Edittext in RecyclerView. It working, but i dont known how i can get infomation from edittext.Sorry about my english^^
TestText.java
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Objects;
public class TestText extends AppCompatActivity {
RecyclerView recyclerView;
ArrayList< String > id = new ArrayList<>();
ArrayList< String > question = new ArrayList<>();
ArrayList< String > possible_answer1 = new ArrayList<>();
ArrayList< String > possible_answer2 = new ArrayList<>();
ArrayList< String > possible_answer3 = new ArrayList<>();
ArrayList< String > answer = new ArrayList<>();
ArrayList<Integer> useranswer = new ArrayList<Integer>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_text);
recyclerView = findViewById(R.id.recyclerviewtest);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(linearLayoutManager);
Intent intent = getIntent();
Context context=this;
String fName = intent.getStringExtra("name");
setTitle(fName);
try {
JSONObject jsonObject = new JSONObject(JsonDataFromAsset("tests.json"));
JSONArray jsonArray = jsonObject.getJSONArray(fName);
for (int i=0;i<= jsonArray.length();i++){
JSONObject userData=jsonArray.getJSONObject(i);
id.add(userData.getString("id"));
question.add(userData.getString("question"));
possible_answer1.add(userData.getString("possible_answer1"));
possible_answer2.add(userData.getString("possible_answer2"));
possible_answer3.add(userData.getString("possible_answer3"));
answer.add(userData.getString("answer"));
}
} catch (JSONException e) {
e.printStackTrace();
}
HelperAdapterForTest helperAdapter = new HelperAdapterForTest(id,question,possible_answer1,possible_answer2,possible_answer3,answer,TestText.this);
recyclerView.setAdapter(helperAdapter);
Button but=findViewById(R.id.verify_button);
but.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Get edittext value in this place
}
});
}
public void GetThissheet(View view){
}
private String JsonDataFromAsset(String fileName) {
String json = null;
try {
InputStream inputStream = getAssets().open(fileName);
int sizeOfFile = inputStream.available();
byte[] bufferData = new byte[sizeOfFile];
inputStream.read(bufferData);
inputStream.close();
json = new String(bufferData, "UTF-8");
}catch (IOException e){
e.printStackTrace();
return null;
}
return json;
}
}
HelperAdapterForTest.java
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
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 androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class HelperAdapterForTest extends RecyclerView.Adapter<HelperAdapterForTest.MyViewClass>
{
ArrayList< String > id;
ArrayList< String > question;
ArrayList< String > possible_answer1;
ArrayList< String > possible_answer2;
ArrayList< String > possible_answer3;
ArrayList< String > answer;
Context context;
public HelperAdapterForTest(ArrayList< String > id,ArrayList< String > question, ArrayList< String > possible_answer1,ArrayList< String > possible_answer2,ArrayList< String > possible_answer3,ArrayList< String > answer,Context context) {
this.id = id;
this.question = question;
this.possible_answer1 = possible_answer1;
this.possible_answer2 = possible_answer2;
this.possible_answer3 = possible_answer3;
this.answer=answer;
this.context = context;
}
#NonNull
#Override
public HelperAdapterForTest.MyViewClass onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.test,parent,false);
HelperAdapterForTest.MyViewClass myViewClass=new HelperAdapterForTest.MyViewClass(view);
return myViewClass;
}
#Override
public void onBindViewHolder(#NonNull HelperAdapterForTest.MyViewClass holder, #SuppressLint("RecyclerView") int position) {
holder.id.setText(id.get(position));
holder.question.setText(question.get(position));
holder.possible_answer1.setText(possible_answer1.get(position));
holder.possible_answer2.setText(possible_answer2.get(position));
holder.possible_answer3.setText(possible_answer3.get(position));
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Intent intent = new Intent(context, TestText.class);
//intent.putExtra("name",question.get(position).toString());
//v.getContext().startActivity(intent);
//Toast.makeText(context,"Клик",Toast.LENGTH_LONG).show();
}
});
}
#Override
public int getItemCount() {
return id.size();
}
public class MyViewClass extends RecyclerView.ViewHolder{
TextView id;
TextView question;
TextView possible_answer1;
TextView possible_answer2;
TextView possible_answer3;
EditText answer;
public MyViewClass(#NonNull View itemView) {
super(itemView);
id = itemView.findViewById(R.id.questionid);
question=itemView.findViewById(R.id.question);
answer=itemView.findViewById(R.id.answer);
possible_answer1=itemView.findViewById(R.id.posibleanswer1);
possible_answer2=itemView.findViewById(R.id.posibleanswer2);
possible_answer3=itemView.findViewById(R.id.posibleanswer3);
}
}
}
activity_test_text.xml
<LinearLayout 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=".TestText"
android:orientation="vertical"
>
<ScrollView
android:id="#+id/scroll"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fillViewport="true"
android:layout_weight="1">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerviewtest"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</ScrollView>
<Button
android:id="#+id/verify_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:gravity="center_horizontal">
</Button>
</LinearLayout>
you need to add abutton to confirm action in viewholder
public class MyViewClass extends RecyclerView.ViewHolder{
TextView id;
.
.
EditText answer;
Button getAnswer;
public MyViewClass(#NonNull View itemView) {
super(itemView);
id = itemView.findViewById(R.id.questionid);
.
.
getAnswer=itemView.findViewById(R.id.getAnswer);
}
}
and in the onBindViewHolder add this
holder.getAnswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
answer.add(answer.getText().toString());
}
});
now the answere list will have a list of answers that get from edit text
use addTextChangedListener to your editText so that you can observe changes and add to your arrayList,
If you want to pass same value to Activity then you can create interface class and write a method which you can implement in Activity or you can use eventBus to pass value.
I find solution.I create setonclicklistener for this button and get data from edittext:)
but.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i=0;i<recyclerView.getAdapter().getItemCount();i++){
v=recyclerView.getChildAt(i);
EditText tutu=(EditText) v.findViewById(R.id.answer);
useranswer.add(i,tutu.getText().toString());
}
for (int i=0;i<useranswer.size();i++){
//Toast.makeText(TestText.this, useranswer.get(i)+","+answer.get(i), Toast.LENGTH_SHORT).show();
if (useranswer.get(i).equals(answer.get(i))){
v=recyclerView.getChildAt(i);
CardView card=v.findViewById(R.id.cardtest);
card.setCardBackgroundColor(Color.GREEN);
}else{
v=recyclerView.getChildAt(i);
CardView card=v.findViewById(R.id.cardtest);
card.setCardBackgroundColor(Color.RED);
}
}
}
});```
Related
i have a news app which i want when the news item (cardview) is clicked on, it should open another activity. unfortunately, nothing happens when the news item in the card view is clicked on, only when the background (recycler layout) is clicked on then the activity comes up.
i want when the news item on the cardview is clicked on, an activity should open and not when the background is clicked.
newsAdapter.java
package wami.ikechukwu.kanu;
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.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
public class newsAdapter extends RecyclerView.Adapter<newsAdapter.viewHolder> {
private ArrayList<dataModel> mDataModel;
private Context context;
private onclicklistener clicklistener;
public newsAdapter(Context context, ArrayList<dataModel> mDataModel, onclicklistener clicklistener) {
this.context = context;
this.mDataModel = mDataModel;
this.clicklistener = clicklistener;
}
#NonNull
#Override
public viewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view =
LayoutInflater.from(context).inflate(R.layout.recyclerview_layout,
viewGroup, false);
return new viewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final newsAdapter.viewHolder viewHolder, final int i) {
dataModel dataModel = mDataModel.get(i);
viewHolder.mTextView.setText(dataModel.getTitle());
viewHolder.mTextDescrip.setText(dataModel.getDescrip());
Glide.with(context).load(dataModel.getImage()).into(viewHolder.mImageView);
}
#Override
public int getItemCount() {
return mDataModel.size();
}
public interface onclicklistener {
void onItemClick(int position);
}
public class viewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView mTextView;
public ImageView mImageView;
public TextView mTextDescrip;
public viewHolder(#NonNull View itemView) {
super(itemView);
mTextView = itemView.findViewById(R.id.layout_text);
mImageView = itemView.findViewById(R.id.layout_image);
mTextDescrip = itemView.findViewById(R.id.layout_descrip);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int adapterposition = getAdapterPosition();
clicklistener.onItemClick(adapterposition);
}
}
}
MainActivity.java
package wami.ikechukwu.kanu;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.Toast;
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.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import dmax.dialog.SpotsDialog;
public class MainActivity extends AppCompatActivity implements newsAdapter.onclicklistener {
private final String KEY_AUTHOR = "author";
private final String KEY_TITLE = "title";
private final String KEY_DESCRIPTION = "description";
private final String KEY_URL = "url";
private final String KEY_URL_TO_IMAGE = "urlToImage";
private final String KEY_PUBLISHED_AT = "publishedAt";
//this string is appended to the url
String urlLink = "buhari";
ArrayList<dataModel> list;
private RecyclerView recyclerView;
private newsAdapter mAdapter;
private RecyclerView.LayoutManager mLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);
list = new ArrayList<>();
recyclerView = findViewById(R.id.recyclerView);
mAdapter = new newsAdapter(getApplicationContext(), list, this);
mLayout = new LinearLayoutManager(this);
recyclerView.setLayoutManager(mLayout);
recyclerView.setAdapter(mAdapter);
jsonParser();
}
private void jsonParser() {
final AlertDialog progressDialog = new SpotsDialog(this, R.style.customProgressDialog);
progressDialog.show();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "https://newsapi.org/v2/everything?q=" + urlLink + "&language=en&sortBy=publishedAt&pageSize=100&apiKey=655446a36e784e79b2b62adcad45be09", null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("articles");
//Using a for loop to get the object (data) in the JSON
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
dataModel dataModel = new dataModel();
dataModel.setTitle(jsonObject.getString(KEY_TITLE));
dataModel.setImage(jsonObject.getString(KEY_URL_TO_IMAGE));
dataModel.setDescrip(jsonObject.getString(KEY_DESCRIPTION));
list.add(dataModel);
}
} catch (JSONException e) {
e.printStackTrace();
}
mAdapter.notifyDataSetChanged();
progressDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", error.toString());
progressDialog.dismiss();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonObjectRequest);
}
#Override
public void onItemClick(int position) {
Toast.makeText(this, "it worked " + position, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this, news_detail.class);
startActivity(intent);
}
}
recyclerview_layout.xml
<?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"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:id="#+id/recyclerviewlayout"
android:layout_width="match_parent"
android:layout_height="250dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="10dp"
android:layout_marginRight="5dp"
android:clickable="true"
android:focusable="true"
app:cardCornerRadius="5dp"
app:cardElevation="10dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="250dp"
android:orientation="vertical">
<TextView
android:id="#+id/layout_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFFF"
android:ellipsize="end"
android:maxLines="1"
android:padding="5dp"
android:textColor="#F000"
android:textSize="17sp"
android:textStyle="bold" />
<ImageView
android:id="#+id/layout_image"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:contentDescription="#string/Recyclerview_ImageContent"
android:scaleType="centerCrop" />
<TextView
android:id="#+id/layout_descrip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFFF"
android:ellipsize="end"
android:maxLines="3"
android:padding="5dp"
android:textColor="#F000"
android:textSize="15sp" />
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:background="#color/colorPrimaryDark" />
</LinearLayout>
</android.support.v7.widget.CardView>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical">
</android.support.v7.widget.RecyclerView>
In order to set onclick listener in recycler view, you have to follow as below
inner class ViewHolderItem(itemView: View) : RecyclerView.ViewHolder(itemView) {
init {
itemView.setOnClickListener {
clicklistener.onItemClick(adapterposition)
}
}
}
OnclickListener will work in Init block
I think should add setOnClickListener method in an onBindViewHolder
And in that you should call another activity with passing your parameter.
Example :- (in onBindViewHolder)
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// call activity.
Intent intent = new Intent(activity, anotherActivityname.class);
// For passing values
intent.putExtra(key,value);
startActivity(intent);
}
});
You have to modify your viewHolder in newsAdapter like following.
public class viewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView mTextView;
public ImageView mImageView;
public TextView mTextDescrip;
public CardView yourCardView;
public viewHolder(#NonNull View itemView) {
super(itemView);
mTextView = itemView.findViewById(R.id.layout_text);
mImageView = itemView.findViewById(R.id.layout_image);
mTextDescrip = itemView.findViewById(R.id.layout_descrip);
yourCardView= itemView.findViewById(R.id.recyclerviewlayout);
// here you set on click listerner to your cardview.
yourCardView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int adapterposition = getAdapterPosition();
clicklistener.onItemClick(adapterposition);
}
}
Hope it helps you.
How to make a specific item respond to click in recyclerView?
So for this make your card view clickable false and make your new item(View inside cardview) clickable true:
<Cardview..
android:clickable="false">
...............
......
<View..
android:clickable="true"/>
</Cardview>
I am working on an Android Project to display Github repo details.
I am trying to first select org name for a particular company, like Amazon has orgs on Github like AWS, AMZN, AWSLABS etc.
For this I first create a List of clickable buttons via RecyclerView(which works).
Then when user clicks on a particular org_name, the App does a HTTP request to Github to fetch relevant info and display inside a fragment which uses another RecyclerView(not working RecyclerViewRepoAdapter.java).
This part does not work as onCreateViewHolder or onBindViewHolder is not called (getItemCount is called and returns correct length)
Tried some of the suggestions mentioned like in this link! but it didn't work.
Any help is appreciated!
OrganizationInfo.java // Driver program
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class OrganizationInfo extends AppCompatActivity {
private String companyName;
private String companyAddress;
private List<String> orgNames;
private TextView companyNameTV;
private TextView companyAddressTV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_organization_info);
getCompanyData();
companyNameTV = findViewById(R.id.companyNameTv);
companyAddressTV = findViewById(R.id.companyAddressTv);
companyNameTV.setText(companyName);
companyAddressTV.setText(companyAddress);
initRecyclerView();
}
private void getCompanyData() {
companyName = "amazon";
companyAddress = "207 Boren Ave N, Seattle, WA 98109";
orgNames = new ArrayList<>();
orgNames.add("amzn");
orgNames.add("aws");
orgNames.add("awslabs");
}
private void initRecyclerView(){
// Log.d(TAG, "initRecyclerView: init recyclerview");
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
RecyclerView recyclerView = findViewById(R.id.orgListRecyclerView);
recyclerView.setLayoutManager(layoutManager);
RecyclerViewOrgAdapter adapter = new RecyclerViewOrgAdapter(this, orgNames);
recyclerView.setAdapter(adapter);
}
}
GithubFragment.java
import android.os.AsyncTask;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* A simple {#link Fragment} subclass.
*/
public class GithubFragment extends Fragment {
private List<Repository> repositories = new ArrayList<>();
RecyclerView recyclerView;
RecyclerViewRepoAdapter listAdapter;
public GithubFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
assert getArguments() != null;
View v = inflater.inflate(R.layout.fragment_github, container, false);
recyclerView = v.findViewById(R.id.repo_recycler_view);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
listAdapter = new RecyclerViewRepoAdapter(getContext(), repositories); // List of Github repos to be display
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(listAdapter); // Called from here after response from cloud funtion
return v;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
if (getArguments() != null) {
String orgName = getArguments().getString("org_name");
GraphQLAsyncTask graphQLAsyncTask = new GraphQLAsyncTask();
graphQLAsyncTask.execute(orgName, "");
}
}
private class GraphQLAsyncTask extends AsyncTask<String, String, String> {
private String response;
private Reader in;
#Override
protected String doInBackground(String... body) {
Map<String, String> params = new HashMap<>();
params.put("company", body[0]);
params.put("language", body[1]);
StringBuilder postData = new StringBuilder();
try{
for (Map.Entry param : params.entrySet()) {
if (postData.length() != 0) postData.append('&');
postData.append(URLEncoder.encode(param.getKey().toString(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
String url = "https://****************/getOrgReposGraphQL";
URL urlObj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.getOutputStream().write(postDataBytes);
conn.connect();
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
StringBuilder sb = new StringBuilder();
for (int c; (c = in.read()) >= 0; )
sb.append((char) c);
response = sb.toString();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String response) {
ParseResponse parseResponse = new ParseResponse(response);
repositories.addAll(parseResponse.getRepositories());
listAdapter.notifyDataSetChanged();
}
}
}
RecyclerViewRepoAdapter.java // Problematic Adapter
package edu.neu.madcourse.goexplore;
import android.content.Context;
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.List;
public class RecyclerViewRepoAdapter extends RecyclerView.Adapter<RecyclerViewRepoAdapter.ListViewHolder> {
private List<Repository> mRepositories;
private Context mContext;
private int mCounter = 1;
public RecyclerViewRepoAdapter(Context context, List<Repository> repos) {
mRepositories = repos;
mContext = context;
}
#NonNull
#Override
public ListViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_repo, parent, false);
return new ListViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ListViewHolder holder, int position) {
Repository repo = mRepositories.get(position);
holder.repoTV.setText(repo.getNameWithOwner());
holder.repoLangugeTV.setText(repo.getPrimaryLanguage());
holder.repoStarsTV.setText(repo.getStargazers());
holder.repoCounter.setText(String.valueOf(mCounter++) + ".");
}
#Override
public int getItemCount() {
return mRepositories.size();
}
public class ListViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView repoTV;
TextView repoLangugeTV;
TextView repoStarsTV;
TextView repoCounter;
public ListViewHolder(View itemView) {
super(itemView);
repoTV = itemView.findViewById(R.id.repo_name_row);
repoLangugeTV = itemView.findViewById(R.id.repo_language_tv);
repoStarsTV = itemView.findViewById(R.id.repo_stars_tv);
repoCounter = itemView.findViewById(R.id.repo_list_number);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
}
}
}
RecyclerViewOrgAdapter.java
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class RecyclerViewOrgAdapter extends RecyclerView.Adapter<RecyclerViewOrgAdapter.ViewHolder> {
private static final String TAG = "RecyclerViewOrgAdapter";
private List<String> orgs;
private Context context;
public RecyclerViewOrgAdapter(Context context, List<String> orgs) {
this.orgs = orgs;
this.context = context;
}
#NonNull
#Override
public RecyclerViewOrgAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.organization_id_relative_layout, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final RecyclerViewOrgAdapter.ViewHolder holder, final int position) {
holder.orgIdBtn.setText(orgs.get(position));
holder.orgIdBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AppCompatActivity activity = (AppCompatActivity) v.getContext();
Fragment githubFragment = new GithubFragment();
Bundle bundle = new Bundle();
bundle.putString("org_name", orgs.get(position));
githubFragment.setArguments(bundle);
activity.getSupportFragmentManager().beginTransaction().replace(R.id.github_fragment, githubFragment).addToBackStack(null).commit();
}
});
}
#Override
public int getItemCount() {
return orgs.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
Button orgIdBtn;
public ViewHolder(View itemView) {
super(itemView);
orgIdBtn = itemView.findViewById(R.id.orgIdBtn);
}
}
}
list_item_repo.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/repo_list_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:text="1."
android:textSize="24sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/repo_name_row"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="24dp"
android:layout_marginTop="16dp"
android:text="Repo Name"
android:textSize="24sp"
app:layout_constraintStart_toEndOf="#+id/repo_list_number"
app:layout_constraintTop_toTopOf="parent" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="#+id/imageView2"
android:layout_width="42dp"
android:layout_height="33dp"
android:layout_marginTop="12dp"
app:layout_constraintStart_toStartOf="#+id/repo_name_row"
app:layout_constraintTop_toBottomOf="#+id/repo_name_row"
app:srcCompat="#mipmap/star_dark_round" />
<TextView
android:id="#+id/repo_stars_tv"
android:layout_width="42dp"
android:layout_height="33dp"
android:layout_marginStart="16dp"
android:text="1441"
app:layout_constraintBottom_toBottomOf="#+id/imageView2"
app:layout_constraintStart_toEndOf="#+id/imageView2"
app:layout_constraintTop_toTopOf="#+id/imageView2" />
<TextView
android:id="#+id/repo_language_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="24dp"
android:layout_marginTop="8dp"
android:text="Ruby"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="#+id/repo_stars_tv"
app:layout_constraintStart_toEndOf="#+id/repo_stars_tv"
app:layout_constraintTop_toTopOf="#+id/repo_stars_tv" />
</LinearLayout>
</LinearLayout>
fragment_github.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".GithubFragment">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/repo_recycler_view"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent" />
</LinearLayout>
You are attaching adapter after getting a response from the API
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
listAdapter = new RecyclerViewRepoAdapter(getContext(), repositories); // List of Github repos to be display
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(listAdapter); // Called from here after response from cloud funtion
Move this code in onCreateView
assert getArguments() != null;
View v = inflater.inflate(R.layout.fragment_github, container, false);
recyclerView = v.findViewById(R.id.repo_recycler_view);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
listAdapter = new RecyclerViewRepoAdapter(getContext(), repositories); // List of Github repos to be display
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(listAdapter); // Called from here after response from cloud funtion
return v;
And after getting a response from Api in AsyncTask onPostExecute() Method add data into list and notify adapter
ParseResponse parseResponse = new ParseResponse(response);
repositories = parseResponse.getRepositories();
listAdapter.notifyDataSetChanged();
I have a custom ListView with a TextView that get data from mysql. What I want to get the content from textview when the item is clicked.
I have tried this,
mList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String value = mList.getItemAtPosition(position).toString();
Toast.makeText(getBaseContext(), value, Toast.LENGTH_LONG).show();
}
});
but it returns com.wanto.sispaktriwanto.init.Penyakit#c05cb5c.
Can anyone help me to solve this?
Thanks.
This is model code:
package com.wanto.sispaktriwanto.init;
public class Penyakit {
private String penyakit_nama;
public String getpenyakit_nama() {
return penyakit_nama;
}
public void setpenyakit_nama(String penyakit_nama) {
this.penyakit_nama = penyakit_nama;
}
}
This is code for get data from mysql:
package com.wanto.sispaktriwanto.server;
import com.wanto.sispaktriwanto.init.HasilKonsul;
import com.wanto.sispaktriwanto.init.Penyakit;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
public class GetDetailPenyakit {
public static ArrayList<Penyakit> getDetail(String postvariable) {
String detail = "";
ArrayList<Penyakit> MyArraylist = new ArrayList<>();
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.0.2.2/android_sispak/getDetailPenyakit.php");
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("detail", postvariable));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
detail = EntityUtils.toString(httpResponse.getEntity());
JSONArray jsonArray = new JSONArray(detail);
for (int i = 0; i < jsonArray.length(); i++) {
Penyakit genres = new Penyakit();
JSONObject MyJsonObject = jsonArray.getJSONObject(i);
genres.setpenyakit_nama(MyJsonObject.getString("nama"));
MyArraylist.add(genres);
}
} catch (Exception e) {
e.printStackTrace();
}
return MyArraylist;
}
}
This is adapter code:
package com.wanto.sispaktriwanto.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import com.wanto.sispaktriwanto.R;
import com.wanto.sispaktriwanto.init.Penyakit;
import java.util.List;
public class PenyakitAdapter extends ArrayAdapter<Penyakit> {
private final List<Penyakit> list;
public PenyakitAdapter(Context context, int resource, List<Penyakit> list) {
super(context, resource, list);
this.list = list;
}
static class ViewHolder {
protected TextView penyakitNama;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
LayoutInflater inflator = LayoutInflater.from(getContext());
convertView = inflator.inflate(R.layout.row_penyakit, null);
viewHolder = new ViewHolder();
viewHolder.penyakitNama = (TextView) convertView.findViewById(R.id.row_namap);
convertView.setTag(viewHolder);
convertView.setTag(R.id.row_namap, viewHolder.penyakitNama);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.penyakitNama.setText(list.get(position).getpenyakit_nama());
return convertView;
}
}
This is activity code:
package com.wanto.sispaktriwanto;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.wanto.sispaktriwanto.adapter.PenyakitAdapter;
import com.wanto.sispaktriwanto.init.Penyakit;
import com.wanto.sispaktriwanto.server.GetDetailPenyakit;
import com.wanto.sispaktriwanto.server.PenyakitJsonParser;
import java.util.ArrayList;
public class DetailPenyakit extends AppCompatActivity {
Context context;
ArrayList<Penyakit> array_list;
GetDetailPenyakit JsonGetDetail;
ListView mList;
String konsultasiS;
static String detailresponse;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_penyakit);
Intent intent = getIntent();
detailresponse = intent.getExtras().getString("detail");
context = this;
new asyncTask_getPenyakit().execute();
}
public class asyncTask_getPenyakit extends AsyncTask<Void, Void, Void> {
ProgressDialog dialog = new ProgressDialog(context);
#Override
protected void onPreExecute() {
dialog.setTitle("Please wait...");
dialog.setMessage("Loading Info Penyakit!");
dialog.show();
array_list = new ArrayList<>();
JsonGetDetail = new GetDetailPenyakit();
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
array_list = JsonGetDetail.getDetail(detailresponse);
return null;
}
protected void onPostExecute(Void s) {
mList = (ListView) findViewById(R.id.detail_listView);
final PenyakitAdapter detailAdapter = new PenyakitAdapter(context, R.layout.row_penyakit, array_list);
mList.setAdapter(detailAdapter);
mList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String value = mList.getItemAtPosition(position).toString();
Toast.makeText(getBaseContext(), value, Toast.LENGTH_LONG).show();
}
});
super.onPostExecute(s);
dialog.dismiss();
}
}
}
This is activity xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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"
tools:context="com.wanto.sispaktriwanto.DetailPenyakit">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="100">
<ListView
android:id="#+id/detail_listView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:divider="#drawable/divider"
android:dividerHeight="1sp"
android:layout_weight="80"/>
</LinearLayout>
</android.support.constraint.ConstraintLayout>
and row xml:
<?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:layout_marginTop="10dp"
android:background="#ffffff"
android:orientation="vertical">
<TextView
android:id="#+id/row_namap"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_marginLeft="20dp"
android:maxLines="1"
android:text="sss"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceMedium"/>
</LinearLayout>
By using this code you can get the current value of the textview.
mList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String contactId = ((TextView) view.findViewById(R.id.row_namap)).getText().toString();
Toast.makeText(getBaseContext(), value, Toast.LENGTH_LONG).show();
}
});
one mistake is there,
You already have arraylist in your activity so try this,
mList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String value = array_list.get(position).getpenyakit_nama();
Toast.makeText(getBaseContext(), value, Toast.LENGTH_LONG).show();
}
});
Do let me know if this works or not
String value = mList.getItemAtPosition(position).toString();
it will be get Penyakit object.
if you want get penyakit_nama value, use below code.
String value = ((Penyakit)mList.getItemAtPosition(position)).getpenyakit_nama();
because generic type of your ArrayAdapter is <Penyakit>, getItemAtPosition() will return Penyakit object
I am new to android development. Here is a picture of my firebase database.
I am showing the name and an image of the movie in my android application in a custom list view.
Here is my ModelClass
public class ModelClass {
String name,imagelink;
public ModelClass() {
}
public ModelClass(String name, String imagelink) {
this.name = name;
this.imagelink = imagelink;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImagelink() {
return imagelink;
}
public void setImagelink(String imagelink) {
this.imagelink = imagelink;
}
}
Here is my Adapter Class
import android.app.Activity;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.List;
public class MyAdapter extends ArrayAdapter<ModelClass> {
private Activity context;
private int resource;
private List<ModelClass> listImage;
private DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("MovieDetails");
public MyAdapter(#NonNull Activity context, #LayoutRes int resource, #NonNull List<ModelClass> objects) {
super(context, resource, objects);
this.context = context;
this.resource = resource;
listImage = objects;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View v = inflater.inflate(resource, null);
TextView tvName = (TextView) v.findViewById(R.id.movie_name_view);
ImageView img = (ImageView) v.findViewById(R.id.movie_image_view);
tvName.setText(listImage.get(position).getName());
Glide.with(context).load(listImage.get(position).getImagelink()).into(img);
return v;
}
public void addElement(ModelClass element) {
listImage.add(element);
}
}
And This is my Activity
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.TextView;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class CheckMovieInfoActivity extends AppCompatActivity {
private DatabaseReference mDatabaseRef;
private List<ModelClass> imgList;
private ListView lv;
private MyAdapter myAdapter;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check_movie_info);
imgList = new ArrayList<>();
lv = (ListView) findViewById(R.id.messagelist);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Please wait loading Images...");
progressDialog.show();
mDatabaseRef = FirebaseDatabase.getInstance().getReference("MovieDetails");
myAdapter = new MyAdapter(CheckMovieInfoActivity.this, R.layout.customlistview, imgList);
lv.setAdapter(myAdapter);
mDatabaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
progressDialog.dismiss();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
ModelClass img = snapshot.getValue(ModelClass.class);
myAdapter.addElement(img);
}
myAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
progressDialog.dismiss();
}
});
}
}
And this is my Custom List View XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="6dp">
<ImageView
android:id="#+id/movie_image_view"
android:layout_width="140dp"
android:layout_height="140dp"
android:src="#drawable/upload_image_small"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="#+id/movie_name_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MOVIE NAME"
android:layout_gravity="center"
android:textSize="20dp"/>
</LinearLayout>
</LinearLayout>
<Button
android:layout_marginTop="8dp"
android:id="#+id/btndel"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Delete Movie"
android:background="#drawable/roundedbutton"/>
</LinearLayout>
I want to add a delete button in the custom listview to delete the data and also the image from the database.
I am not getting any errors I just want to add a delete button to delete the data. Thanks in advance.
I am new in android and I have read some tutos about custom ListView and I am doing an app to manipulate data I resume my problem with this litte app. the screen is this:
in this there are a listview and each item have a TextView and a EditText the one last control is for the user input a amount I need when the user press the button clear first save de amount info in the arraylist and then clear the fields. how I approach this
my code:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.rimacy.preguntalistview.MainActivity">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView1"
android:layout_weight="1"
android:focusable="false"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Clear"
android:id="#+id/btnClear"/>
</LinearLayout>
listview_item.xml
<?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="match_parent">
<TextView
android:layout_width="100dip"
android:layout_height="wrap_content"
android:text="item"
android:id="#+id/tv1" />
<EditText
android:layout_width="200dip"
android:layout_height="wrap_content"
android:hint="Input amount"
android:id="#+id/edit1"
android:layout_weight="1"
android:inputType="number"/>
</LinearLayout>
MainActivity.java
package com.rimacy.preguntalistview;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
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);
ArrayList<Inventory> data = new ArrayList<>();
data.add(new Inventory("candies",0));
data.add(new Inventory("milk",0));
data.add(new Inventory("soda",0));
data.add(new Inventory("paper",0));
data.add(new Inventory("bags",0));
//... the items are unknow in run time
MyAdapter adp = new MyAdapter(this,R.layout.listview_item,data);
ListView listView = (ListView)findViewById(R.id.listView1);
listView.setAdapter(adp);
Button btnClear = (Button) findViewById(R.id.btnClear);
btnClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// set de value of each EditText to "amount" field in each object in the ArrayList "data"
// perform a clear of all EditText in the listview
// set the focus in the firs EditText
}
});
}
class Inventory{
String name;
Integer amount;
public Inventory(String name, Integer amount) {
this.name = name;
this.amount = amount;
}
public String getName() {
return name;
}
}
class MyAdapter extends ArrayAdapter<Inventory>{
private ArrayList<Inventory> items;
public MyAdapter(Context context, int resource, ArrayList<Inventory> items) {
super(context, resource, items);
this.items = items;
}
public View getView(int position, final View convertView, ViewGroup parent) {
View v=convertView;
TextView editText;
if (v == null){
LayoutInflater inflater = LayoutInflater.from(getContext());
v = inflater.inflate(R.layout.listview_item, null);
}
editText = (TextView)v.findViewById(R.id.tv1);
editText.setText(items.get(position).getName());
return v;
}
}
}
update
I do this
**
package com.rimacy.preguntalistview;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends AppCompatActivity {
ArrayList<Inventory> data = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
data.add(new Inventory("candies",0));
data.add(new Inventory("milk",0));
data.add(new Inventory("soda",0));
data.add(new Inventory("paper",0));
data.add(new Inventory("bags",0));
//... the items are unknow in run time
final MyAdapter adp = new MyAdapter(this,R.layout.listview_item,data);
final ListView listView = (ListView)findViewById(R.id.listView1);
listView.setAdapter(adp);
adp.notifyDataSetChanged();
Button btnClear = (Button) findViewById(R.id.btnClear);
if (btnClear!= null){
btnClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// set de value of each EditText to "amount" field in each object in the ArrayList "data"
// perform a clear of all EditText in the listview
// set the focus in the firs EditText
for (Inventory i:data){
i.getTxt().setText("");
}
adp.notifyDataSetChanged();
}
});
}
}
class Inventory{
String name;
Integer amount;
EditText txt;
public void setName(String name) {
this.name = name;
}
public EditText getTxt() {
return txt;
}
public void setTxt(EditText txt) {
this.txt = txt;
}
public Inventory(String name, Integer amount) {
this.name = name;
this.amount = amount;
}
public String getName() {
return name;
}
}
class MyAdapter extends ArrayAdapter<Inventory>{
private ArrayList<Inventory> items;
public MyAdapter(Context context, int resource, ArrayList<Inventory> items1) {
super(context, resource, items1);
items = items1;
}
public View getView(int position, final View convertView, ViewGroup parent) {
View v=convertView;
TextView editText;
EditText txt;
if (v == null){
LayoutInflater inflater = LayoutInflater.from(getContext());
v = inflater.inflate(R.layout.listview_item, null);
}
txt = (EditText)v.findViewById(R.id.edit1);
editText = (TextView)v.findViewById(R.id.tv1);
items.get(position).setTxt(txt);
editText.setText(items.get(position).getName());
return v;
}
}
}
added a new member in the Inventory Class to store a reference of the editText wich is assigned in the getView event and with the getTxt methos recall this reference and call the setText method with empty string but it only works when I press the button for twice time why??