Custom Adapter not working for RecyclerView in a Fragment - android

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();

Related

Getting error while setting a data into recycler view

I am getting 2 data from firebase and setting them in a card view in recycler view they are
name
nodename
there is no problem with the "name" data but my "nodename" data is not being set in the text view
the error message that I am getting
No setter/field for node found on class com.Loopchat.com.Mychats_Model
my model class
package com.Loopchat.com;
public class Mychats_Model {
public Mychats_Model(String name, String nodename) {
this.name = name;
this.nodename = nodename;
}
Mychats_Model(){
}
String name, nodename;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNodename() {
return nodename;
}
public void setNodename(String nodename) {
this.nodename = nodename;
}
}
this is my Firebase data base structure
myAdapter Class
package com.Loopchat.com;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
public class Mychats_Adapter extends
FirebaseRecyclerAdapter<Mychats_Model,Mychats_Adapter.myViewHolder> {
private static final int MSG_TYPE_LEFT = 0;
private static final int MSG_TYPR_RIGHT = 1;
/**
* Initialize a {#link RecyclerView.Adapter} that listns to a Firebae query. See
* {#link FirebaseRecyclerOptions} for configuration options.
*
* #param options
*/
public Mychats_Adapter(#NonNull FirebaseRecyclerOptions<Mychats_Model> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull myViewHolder holder, int position, #NonNull Mychats_Model model) {
holder.name.setText(model.getName());
holder.node.setText(model.getNodename());
holder.name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(holder.node.getContext(),Chat2.class);
intent.putExtra("nodename",model.getNodename());
holder.node.getContext().startActivity(intent);
}
});
}
#NonNull
#Override
public myViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.mychats_item, parent, false);
return new myViewHolder(view);
// if (viewType == MSG_TYPE_LEFT) {
// View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.chat_left, parent, false);
// return new myViewHolder(view);
//} else {
// View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.chat_item, parent, false);
// return new myViewHolder(view);
//}
}
class myViewHolder extends RecyclerView.ViewHolder {
TextView name,node;
public myViewHolder(#NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.namedoc);
// node = itemView.findViewById(R.id.nodename);
node = itemView.findViewById(R.id.d);
}
}
}
XML of my item for my recycler view
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:cardCornerRadius="3dp"
app:cardUseCompatPadding="true"
android:elevation="6dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp">
<ImageView
android:layout_width="80dp"
android:layout_height="80dp"
android:id="#+id/imagedic"
android:src="#mipmap/ic_launcher"
android:layout_centerVertical="true">
</ImageView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/imagedic"
android:text="Username"
android:id="#+id/namedoc"
android:textSize="30dp"
android:layout_marginStart="20dp"
android:textStyle="bold"/>
<TextView
android:id="#+id/d"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/namedoc"
android:layout_marginStart="20dp"
android:layout_marginLeft="98dp"
android:layout_marginTop="4dp"
android:layout_toRightOf="#+id/imagedic"
android:text="Nodename"
android:textSize="15dp" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
my MainActivity
package com.Loopchat.com;
import static android.content.ContentValues.TAG;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.FirebaseDatabase;
public class MyChats extends AppCompatActivity {
RecyclerView rvc ;
Mychats_Adapter mychats_adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_chats);
SharedPreferences sharedPreferences = getSharedPreferences("MySharedPref",MODE_PRIVATE);
String myname = sharedPreferences.getString("username", "User");
Toast.makeText(this, myname, Toast.LENGTH_SHORT).show();
Log.d("TAG", "onCreate: "+myname+"Chats");
rvc = findViewById(R.id.rvc);
rvc.setLayoutManager(new LinearLayoutManager(this));
FirebaseRecyclerOptions<Mychats_Model> options =
new FirebaseRecyclerOptions.Builder<Mychats_Model>() .setQuery(FirebaseDatabase.getInstance().getReference().child(myname+"Chats"), Mychats_Model.class)
.build();
mychats_adapter = new Mychats_Adapter(options);
rvc.setAdapter(mychats_adapter);
}
#Override
protected void onStart() {
super.onStart();
mychats_adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
mychats_adapter.stopListening();
}
}

How to get EditText value from Recyclerview to ArrayList?

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);
}
}
}
});```

ViewPager2 Adapter is being called Twice

I am starting with Android java development and I am facing a issue on the ViewPager2 implementation.
On my app I have a ViewPager2 and I am inflate on it a layout which has a RecycleView.
The problem is, when I turn the ViewPager2 from page 0 to page 1, the adapter execulte onBindViewHolder twice, jumping from adapter position 0 to 1 and imediatelly from position 1 to 2. (ViewPager2 position stay on 1)
As I am populating the RecycleView with a Volley DB consult, this theard start only after the ViewPAger2 Adapter finish its works (after adapter execulte onBindViewHolder twice). So, only the ViewPager2 position 2 is populated (twice), ViewPager2 page 1 stay empty.
Thus, I kindly ask your help to avoid adapter execute onBindViewHolder twice once ViewPAger2 change. Or makes Volley executes its thread when the adapter position change from 0 to 1 and again when it change from 1 to 2.
Please help me since I have 5 days working around this problem without success.
See belwo my codes:
MY VIEWPAGER2 ADAPTER (Adapter_Department)
package br.com.portosaue.portosaueapp;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Adapter_Department extends RecyclerView.Adapter<Adapter_Department.UserViewHolder> {
Context mContext;
private RecyclerView rcv_products;
private RecyclerView.Adapter mAdapter;
private LinearLayoutManager mLayoutManager;
ViewPager2 vpg_productList;
List<Department> departmentList;
String Host_IP;
String ProductComment;
public MyAdapter(Context mContext, List<Department> departmentList) {
this.mContext = mContext;
this.departmentList = departmentList;
}
#NonNull
#Override
public UserViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
Host_IP = "192.168.0.100";
View view = LayoutInflater.from(mContext).inflate(R.layout.products_list, parent, false);
return new UserViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull UserViewHolder holder, int position) {
productsList(departmentList.get(position).getName());
}
#Override
public int getItemCount() {
return departmentList.size();
}
public class UserViewHolder extends RecyclerView.ViewHolder {
public UserViewHolder(#NonNull final View itemView) {
super(itemView);
rcv_products = itemView.findViewById(R.id.rcv_Products);
vpg_productList = ((Activity) mContext).findViewById(R.id.vpg_Products);
}
}
private void productsList(String department){
//SELECTING URL
String json_products;
switch (department) {
case "Salao":
json_products = "http://" + Host_IP + "/getSalon.php";
break;
case "Cozinha":
json_products = "http://" + Host_IP + "/getKitchen.php";
break;
case "Copa":
json_products = "http://" + Host_IP + "/getDrink.php";
break;
case "Churrasqueira":
json_products = "http://" + Host_IP + "/getBarbecue.php";
break;
case "Caixa":
json_products = "http://" + Host_IP + "/getCash.php";
break;
default:
json_products = "http://" + Host_IP + "/getProducts";
}
//VOLLEY / FETCH / JSONOBJECT
StringRequest stringRequest = new StringRequest(Request.Method.GET, json_products,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting the string to json array object
JSONArray array = new JSONArray(response);
ArrayList<Func_LoadProduct> loadproduct = new ArrayList<Func_LoadProduct>();
Func_LoadProduct p;
String ImagePath;
//traversing through all the object
for (int i = 0; i < array.length(); i++) {
//getting product object from json array
JSONObject product = array.getJSONObject(i);
//adding the product to product list
ImagePath = "http://" + Host_IP + "/PS APP Images/" + product.getString("Imagem");
p = new Func_LoadProduct(product.getInt("ID"),
product.getString("Nome"),
product.getDouble("Preco"),
ImagePath,
"");
loadproduct.add(p);
}
rcv_products=((Activity)mContext).findViewById(R.id.rcv_Products);
rcv_products.setHasFixedSize(true);
mLayoutManager=new LinearLayoutManager(mContext);
mAdapter=new Adapter_Products(loadproduct);
rcv_products.setLayoutManager(mLayoutManager);
rcv_products.setAdapter(mAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
Volley.newRequestQueue(mContext).add(stringRequest);
}
}
VIEWPAGER2 CLASS (Products)
package br.com.portosaue.portosaueapp;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.viewpager2.widget.ViewPager2;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Products extends AppCompatActivity {
ViewPager2 vpg_products;
List<Department> departmentList;
Adapter_Department adapterDepartment;
String TableNumb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_products);
vpg_products = findViewById(R.id.vpg_Products);
departmentList = new ArrayList<>();
departmentList.add(new Department("Salon"));
departmentList.add(new Department("Kitchen"));
departmentList.add(new Department("Bar"));
adapterDepartment = new Adapter_Department(this, departmentList);
vpg_products.setAdapter(adapterDepartment);
}
}
VIEWPAGER2 LAYOUT (activity_departments.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"
tools:context=".Products"
android:orientation="vertical">
<include
android:id="#+id/tbr_toobar"
layout = "#layout/toolbar"/>
<androidx.viewpager2.widget.ViewPager2
android:id="#+id/vpg_Products"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_below="#+id/tbr_toobar"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/tbr_toobar"
app:layout_constraintVertical_bias="1.0" />
</androidx.constraintlayout.widget.ConstraintLayout>
RECYCLEVIEW ADAPTER (Adapter_Products)
package br.com.portosaue.portosaueapp;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class Adapter_Products extends RecyclerView.Adapter<Adapter_Products.MyViewHolder>{
private ArrayList<Func_LoadProduct> mProductList;
public static class MyViewHolder extends RecyclerView.ViewHolder {
public ImageView img_ProductImage;
public TextView txv_ProductName;
public TextView txv_ProductPrice;
public TextView txv_ProductID;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
img_ProductImage = itemView.findViewById(R.id.imv_ProductImage);
txv_ProductName = itemView.findViewById(R.id.txv_ProductName);
txv_ProductPrice = itemView.findViewById(R.id.txv_ProductPrice);
txv_ProductID = itemView.findViewById(R.id.txv_ProcutID);
}
}
public Adapter_Products( ArrayList<Func_LoadProduct> productList){
this.mProductList=productList;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.product_line, parent, false);
MyViewHolder evh = new MyViewHolder(v);
return evh;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
Func_LoadProduct currentItem = mProductList.get(position);
Picasso.get().load(mProductList.get(position).getProductImageName()).into(holder.img_ProductImage);
holder.txv_ProductName.setText(currentItem.getProductName());
holder.txv_ProductPrice.setText("R$ " + Double.toString(currentItem.getProductPrice()));
holder.txv_ProductID.setText("ID: " + Integer.toString(currentItem.getProductID()));
}
#Override
public int getItemCount() {
return mProductList.size();
}
}
RECYCLEVIEW LAYOUT (product_list.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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rcv_Products"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="0dp"
android:layout_marginTop="0dp" />
</RelativeLayout>
ITEMS CLASS (Func_LoadProduct)
package br.com.portosaue.portosaueapp;
public class Func_LoadProduct {
private int ProductID;
private String ProductName;
private double ProductPrice;
private String ProductImageName;
private String ProductComment;
public Func_LoadProduct(int productID, String productName, double productPrice, String productImageName, String productComment){
this.ProductID = productID;
this.ProductName = productName;
this.ProductPrice = productPrice;
this.ProductImageName = productImageName;
this.ProductComment = productComment;
}
//SET
public void setProductID(int productID) {
this.ProductID = productID;
}
public void setProductName(String productName) {
this.ProductName = productName;
}
public void setProductPrice(double productPrice) {
this.ProductPrice = productPrice;
}
public void setProductImageName(String productImageName) { this.ProductImageName = productImageName; }
public void setProductComment(String productComment) { this.ProductComment = productComment; }
//GET
public int getProductID() {
return this.ProductID;
}
public String getProductName() {
return this.ProductName;
}
public double getProductPrice() {
return this.ProductPrice;
}
public String getProductImageName() { return this.ProductImageName; }
public String getProductComment() { return this.ProductComment; }
}
ITEMS LAYOUT (product_line.xml)
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
app:cardCornerRadius="4dp"
android:layout_marginTop="2dp"
android:layout_marginBottom="2dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="4dp">
<ImageView
android:id="#+id/imv_ProductImage"
android:layout_width="60dp"
android:layout_height="60dp"
android:padding="2dp"
android:scaleType="fitXY"
tools:srcCompat="#tools:sample/avatars"/>
<TextView
android:id="#+id/txv_ProductName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="64dp"
android:layout_marginTop="2dp"
android:textColor="#android:color/black"
android:textSize="20sp"
android:layout_weight="10"
android:text="Produto"
android:textAppearance="#style/TextAppearance.AppCompat.Large"/>
<TextView
android:id="#+id/txv_ProductPrice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/txv_ProductName"
android:layout_alignParentTop="true"
android:layout_marginStart="2dp"
android:layout_marginTop="31dp"
android:layout_weight="3"
android:text="Valor"
android:textSize="15sp" />
<TextView
android:id="#+id/txv_ProcutID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/txv_ProductPrice"
android:layout_alignParentStart="true"
android:layout_marginStart="347dp"
android:layout_marginBottom="0dp"
android:layout_weight="1"
android:text="ID"
android:textSize="15sp" />
</RelativeLayout>
</androidx.cardview.widget.CardView>

How to use onItemClick in listview that get data from mysql?

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

How To Set Image Resource To Android ImageView from Rest API

import android.content.Context;
import android.os.AsyncTask;
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.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.*******.******.app.R;
import com.*******.******.app.adapter.CustomAdapter;
import com.*******.******.app.adapter.CustomPromoAdapter;
import com.*******.******.app.pojo.Campaigns;
import com.*******.******.app.pojo.ConsumerProfile;
import org.springframework.web.client.RestTemplate;
import java.util.ArrayList;
public class Promo extends AppCompatActivity {
private ArrayList<String> imageurls = new ArrayList<>();
private ArrayList<String> imgnames = new ArrayList<>();
GridView gridview;
Context context;
ArrayList programName;
String campid,campImage,campName;
TextView name;
ImageView images;
// public static String[] programNameList = {"AppleMacBook", "HP_note_Book", "LG_NEXUS", "NokiaLumia", "SamsungRT", "SONY_BRAVIA", "Sansui"};
// public static int[] programImages = {R.drawable.apple, R.drawable.hp, R.drawable.nexus, R.drawable.lumia, R.drawable.fridge, R.drawable.tv, R.drawable.tv1};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_promo);
new HttpRequesrPromo().execute();
new HttpLocationPromo().execute();
gridview = (GridView) findViewById(R.id.gridView1);
//gv.setAdapter(new CustomPromoAdapter(this,programNameList,programImages));
CustomPromoAdapter adapter = new CustomPromoAdapter(this,imageurls,imgnames);
gridview.setAdapter(adapter);
name = (TextView) findViewById(R.id.textView1);
images = (ImageView) findViewById(R.id.imageView1);
}
private class HttpRequesrPromo extends AsyncTask<Void, Void, Campaigns> {
#Override
protected Campaigns doInBackground(Void... params) {
try {
final String url = "http://myurl";
RestTemplate restTemplate = new RestTemplate();
Campaigns campa = restTemplate.getForObject(url, Campaigns.class);
return campa;
} catch (Exception e) {
Log.e("MainActivity", e.getMessage(), e);
}
return null;
}
#Override
protected void onPostExecute(Campaigns campa) {
super.onPostExecute(campa);
campid = campa.getId();
Log.d("Campaign Idddddd~~~~~~~~", "onPostExecute: " + campid);
}
}
private class HttpLocationPromo extends AsyncTask<Void, Void, Campaigns> {
#Override
protected Campaigns doInBackground(Void... params) {
try {
final String url = "http://myurl";
RestTemplate restTemplate = new RestTemplate();
Campaigns locationcampa = restTemplate.getForObject(url, Campaigns.class);
return locationcampa;
} catch (Exception e) {
Log.e("MainActivity", e.getMessage(), e);
}
return null;
}
#Override
protected void onPostExecute(Campaigns locationcampa) {
super.onPostExecute(locationcampa);
campImage=locationcampa.getImage();
campName=locationcampa.getName();
imgnames.add(campName);
name.setText(campName);
Log.d("ImageUUURRRLLL", "onPostExecute: " + campImage);
Log.d("CampNNNAAMMEEE", "onPostExecute: " +campName);
imageurls.add(campImage);
}
}
}
This is my Activity Here I'm Getting Images From Rest Service and adding them in a list.
I have a GridView With CustomAdapter ImageView And TextView I want to set the Image Resource To Image View.
Below is My Adapter.......
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.app.R;
import com.app.activity.MainActivity;
import com.app.activity.Promo;
import java.util.ArrayList;
/**
* Created by ns2 on 2/4/16.
*/
public class CustomPromoAdapter extends BaseAdapter{
ImageView imageView;
TextView textView;
String [] result;
Context context;
int [] imageId;
private static LayoutInflater inflater=null;
public CustomPromoAdapter(Promo promo, ArrayList<String> imageurls, ArrayList<String> imgnames) {
// TODO Auto-generated constructor stub
//result=programNameList;
// context=promo;
// imageId=programImages;
inflater = ( LayoutInflater )context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return result.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view;
view=inflater.inflate(R.layout.promo_gridlist,null);
/* textView=(TextView)view.findViewById(R.id.textView1);
imageView=(ImageView)view.findViewById(R.id.imageView1);
imageView.setImageResource(imageId[position]);
textView.setText(imageId[position]);*/
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "You Clicked " + result[position], Toast.LENGTH_LONG).show();
}
});
return view;
}
}
This is my Adapter.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView1"
android:layout_gravity="center"
android:layout_width="88dp"
android:layout_height="88dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
/>
<TextView
android:id="#+id/textView1"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:text="TextView" />
</LinearLayout>
This is my Layout with ImageView And TextView.
<?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"
android:orientation="vertical"
tools:context=".activity.Promo" >
<GridView
android:id="#+id/gridView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"
android:numColumns="2" >
</GridView>
</RelativeLayout>
This is my Main layout.
I Have The Image Url's In a List now I want to Set those Url's to ImageView.
I'm new To Android Can Any One Help Me How To Solve This Problem.
Thankful To Them........
Best way to load images from server is
Glide.with(mContext)
.load(imageUrl)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.placeholder(R.drawable.default)
.error(R.drawable.default)
.override(400, 400)
.centerCrop()
.into(imageView);
For more follow this :
https://github.com/bumptech/glide
Best way to achieve this is use picasso library.
Picasso.with(context)
.load(url)
.placeholder(R.drawable.user_placeholder)
.error(R.drawable.user_placeholder_error)
.into(imageView);
for more details
Try this,
URL photoUrl = new URL(imageUrl);
mIcon = BitmapFactory.decodeStream(photoUrl.openConnection() .getInputStream());
imageView.setImageBitmap(mIcon);

Categories

Resources