How to get id onclick listview using android - android

I am working on listview example, I want tid from mysql database onclick selected listview .how to do it please help me , I am working from long time on that but can not found any solution.
ListTask Activity
public class ListTask extends Activity {
Task task_;
ListView listCollege;
ProgressBar proCollageList;
TextView GetTaskName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_task);
listCollege = (ListView)findViewById(R.id.tasklist);
proCollageList = (ProgressBar)findViewById(R.id.proCollageList);
GetTaskName = (TextView) findViewById(R.id.taskname);
new GetHttpResponse(this).execute();
}
private class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
private Context context;
String result;
List<Task> Task_;
public GetHttpResponse(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
HttpService httpService = new HttpService("http://192.168.0.103/GroupBuilder/GetListTask.php");
try
{
httpService.ExecutePostRequest();
if(httpService.getResponseCode() == 200)
{
result = httpService.getResponse();
System.out.println("Result . . . "+result);
Log.d("Result", result);
if(result != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(result);
JSONObject object;
JSONArray array;
// cources college;
Task_ = new ArrayList<Task>();
for(int i=0; i<jsonArray.length(); i++)
{
task_ = new Task();
object = jsonArray.getJSONObject(i);
task_.taskname = object.getString("taskname");
task_.tid = object.getString("tid");
System.out.println("Taask Tid "+task_.tid);
Task_.add(task_);
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else
{
Toast.makeText(context, httpService.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
ListAdapter class
public class ListTaskAdapter extends BaseAdapter {
Context context;
List<Task> taskList;
Task task_;
public ListTaskAdapter(List<Task> listValue, Context context)
{
this.context = context;
this.taskList = listValue;
}
#Override
public int getCount() {
return this.taskList.size();
}
#Override
public Object getItem(int position) {
return this.taskList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, final ViewGroup viewGroup) {
ViewTaskName viewtaskname = null;
if(convertView == null)
{
viewtaskname = new ViewTaskName();
LayoutInflater layoutInfiater = (LayoutInflater)this.context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
//LayoutInflater layoutInfiater = LayoutInflater.from(context);
convertView = layoutInfiater.inflate(R.layout.listtaskadapter, null);
viewtaskname.task_name = (TextView)convertView.findViewById(R.id.taskname);
final String str = viewtaskname.task_name.getText().toString();
convertView.setTag(viewtaskname);
}
else
{
viewtaskname = (ViewTaskName) convertView.getTag();
}
viewtaskname.task_name.setText(taskList.get(position).taskname);
return convertView;
}
}
class ViewTaskName
{
TextView task_name;
}
class Task{
public String taskname;
public String tid;
}
activity_list_task.xml code
<ListView
android:id="#+id/tasklist"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="visible"
android:background="#38a2ed"
android:layout_marginTop="35dp" >
</ListView>
listadaper code
<TextView
android:id="#+id/taskname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="TaskName"
android:textColor="#000000"
android:textSize="18sp"
/>
I am not getting any solution please help me and update my code , Thanks

You should use setOnItemClickListener
Register a callback to be invoked when an item in this AdapterView has
been clicked.
Create a TextView which hold ID like Name .
<TextView
android:id="#+id/taskID"
android:layout_width="0dp"
android:layout_height="0dp"
/>
Then
listCollege.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id)
{
TextView taskIDOBJ=(TextView)view.findViewById(R.id.taskID);
String item = tasknameOBJ.getText().toString();
Toast.makeText(this,"You selected : " + item,Toast.LENGTH_SHORT).show();
}
});
Simple way
String str_ID = Task_.get(position).tid;
Code
listCollege.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id)
{
String str_ID = Task_.get(position).tid;
Toast.makeText(this,"You selected : " + str_ID ,Toast.LENGTH_SHORT).show();
}
});

try this
//declare global use this array list in AsyncTask response to add
List<Tast> taskList = new ArrayList<>();
listCollege.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String tid = taskList.get(position).tid;
}
});

use setOnItemClickListener method and get id from sqllite , this method gives you a position , on the bases of position you got your id from bean class . follow this link .
Get Id from database in a listview onclick

view.setTag(id);
view.getTag();

Related

EditText AutoCompleteTextView When Typing Using Custom Adapter Json Fragment

I want EditText become AutoComplete when user start typing in the EditText field. I have create this code
public class PegawaiFragment extends Fragment {
public static PegawaiFragment newInstance() {
PegawaiFragment fragment = new PegawaiFragment();
return fragment;
}
String namapegawai;
AutoCompleteTextView textAutoComplete;
ListView StudentListView;
ProgressBar progressBar;
String HttpUrl = "http://192.168.43.241/Android/MyKoperasi/PegawaiDashboard.php";
List<String> IdList = new ArrayList<>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_pegawai, container, false);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
namapegawai = prefs.getString(MainActivity.UserName,MainActivity.UserName);
TextView NamaPegawai = v.findViewById(R.id.TextViewNamaPegawai);
NamaPegawai.setText(namapegawai);
textAutoComplete = v.findViewById(R.id.autoCompleteTextView1);
ArrayAdapter adapter = new ArrayAdapter(getActivity(),android.R.layout.simple_list_item_1);
textAutoComplete.setAdapter(adapter);
textAutoComplete.setThreshold(1);
StudentListView = v.findViewById(R.id.listview2);
progressBar = v.findViewById(R.id.progressBar1);
new GetHttpResponse(getActivity()).execute();
//Adding ListView Item click Listener.
StudentListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
//Intent intentSemuaMemberLihat = new Intent(getActivity(),SemuaMemberLihat.class);
// Sending ListView clicked value using intent.
//intentSemuaMemberLihat.putExtra("ListViewValue", IdList.get(position).toString());
//startActivity(intentSemuaMemberLihat);
}
});
return v;
}
// JSON parse class started from here.
class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
public Context context;
String JSonResult;
List<Member> studentList;
public GetHttpResponse(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
// Passing HTTP URL to HttpServicesClass Class.
HttpServicesClass httpServicesClass = new HttpServicesClass(HttpUrl);
try
{
httpServicesClass.ExecutePostRequest();
if(httpServicesClass.getResponseCode() == 200)
{
JSonResult = httpServicesClass.getResponse();
if(JSonResult != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(JSonResult);
JSONObject jsonObject;
Member member;
studentList = new ArrayList<Member>();
for(int i=0; i<jsonArray.length(); i++)
{
member = new Member();
jsonObject = jsonArray.getJSONObject(i);
// Adding Student Id TO IdList Array.
IdList.add(jsonObject.getString("id").toString());
//Adding Student Name.
member.nama = jsonObject.getString("nama").toString();
//member.nrp = jsonObject.getString("nrp").toString();
studentList.add(member);
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else
{
Toast.makeText(context, httpServicesClass.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
progressBar.setVisibility(View.GONE);
StudentListView.setVisibility(View.VISIBLE);
if(studentList != null) {
ListAdapterClass adapter = new ListAdapterClass(studentList, context);
StudentListView.setAdapter(adapter);
}else
{
Toast.makeText(context, "Tidak ada data ditampilkan", Toast.LENGTH_SHORT).show();
}
}
}
}
This code shows perfect, but when I start typing in EditText which in autoCompleteTextView1, no suggestion name come out. I think this is in here
textAutoComplete = v.findViewById(R.id.autoCompleteTextView1);
ArrayAdapter adapter = new ArrayAdapter(getActivity(),android.R.layout.simple_list_item_1);
textAutoComplete.setAdapter(adapter);
textAutoComplete.setThreshold(1);
But why the EditText doesn't show the suggestions? instead, my ListView works perfect there.
Here is my XML code
<FrameLayout 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="com.network.poeja.mykoperasi.PegawaiFragment">
<TextView
android:id="#+id/TextViewNamaPegawai"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<AutoCompleteTextView
android:layout_weight="1"
android:id="#+id/autoCompleteTextView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Text Auto Complete"
android:layout_below="#+id/TextViewNamaPegawai">
<requestFocus />
</AutoCompleteTextView>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="50dp"
android:layout_below="#+id/autoCompleteTextView1">
<!-- TODO: Update blank fragment layout -->
<ListView
android:id="#+id/listview2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_below="#+id/logos"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dip"/>
<ProgressBar
android:id="#+id/progressBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="visible" />
</RelativeLayout>
</FrameLayout>
===============ADAPTER CLASS
public class ListAdapterClass extends BaseAdapter {
Context context;
List<Member> valueList;
public ListAdapterClass(List<Member> listValue, Context context)
{
this.context = context;
this.valueList = listValue;
}
#Override
public int getCount()
{
return this.valueList.size();
}
#Override
public Object getItem(int position)
{
return this.valueList.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewItem viewItem = null;
if(convertView == null)
{
viewItem = new ViewItem();
LayoutInflater layoutInfiater = (LayoutInflater)this.context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = layoutInfiater.inflate(R.layout.listview_item, null);
viewItem.TextViewNama = convertView.findViewById(R.id.textViewNama);
viewItem.TextViewNrp = convertView.findViewById(R.id.textViewNrp);
convertView.setTag(viewItem);
}
else
{
viewItem = (ViewItem) convertView.getTag();
}
viewItem.TextViewNama.setText(valueList.get(position).nama);
viewItem.TextViewNrp.setText(valueList.get(position).nrp);
return convertView;
}
}
class ViewItem
{
TextView TextViewNama, TextViewNrp;
}
You need to provide Array containing data on ArrayAdapter. Its the source of data where adapter will search. Here is an example how to use ArrayAdapter and AutoCompleteTextView -
public class MainActivity extends Activity {
String[] data = {"Apple", "Banana", "Cherry", "Date", "Grape", "Kiwi", "Mango", "Pear"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Creating the instance of ArrayAdapter containing list of fruit names
ArrayAdapter<String> adapter = new ArrayAdapter<String>
(this, android.R.layout.simple_list_item_1, data);
//Getting the instance of AutoCompleteTextView
AutoCompleteTextView actv = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
actv.setThreshold(1);//will start working from first character
actv.setAdapter(adapter);//setting the adapter data into the AutoCompleteTextView
actv.setTextColor(Color.RED);
}
}
Based on your code of AutoCompleteTextView. I made a solution.
String[] data = {"Apple", "Banana", "Cherry", "Date", "Grape", "Kiwi", "Mango", "Pear"};
GetHttpResponse getHttpResponse = new GetHttpResponse(getActivity());
getHttpResponse.execute();
textAutoComplete = v.findViewById(R.id.autoCompleteTextView1);
List<Member> studentList = getHttpResponse.getStudentList();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, studentList.toArray(new String[studentList.size()]));
textAutoComplete.setAdapter(adapter);
textAutoComplete.setThreshold(1);
Add a method to get studentList from GetHttpResponse class -
// JSON parse class started from here.
class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
public Context context;
String JSonResult;
List<Member> studentList;
public GetHttpResponse(Context context)
{
this.context = context;
}
public ArrayList<Member> getStudentList(){
return this.studentList;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
// Passing HTTP URL to HttpServicesClass Class.
HttpServicesClass httpServicesClass = new HttpServicesClass(HttpUrl);
try
{
httpServicesClass.ExecutePostRequest();
if(httpServicesClass.getResponseCode() == 200)
{
JSonResult = httpServicesClass.getResponse();
if(JSonResult != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(JSonResult);
JSONObject jsonObject;
Member member;
studentList = new ArrayList<Member>();
for(int i=0; i<jsonArray.length(); i++)
{
member = new Member();
jsonObject = jsonArray.getJSONObject(i);
// Adding Student Id TO IdList Array.
IdList.add(jsonObject.getString("id").toString());
//Adding Student Name.
member.nama = jsonObject.getString("nama").toString();
//member.nrp = jsonObject.getString("nrp").toString();
studentList.add(member);
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else
{
Toast.makeText(context, httpServicesClass.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
progressBar.setVisibility(View.GONE);
StudentListView.setVisibility(View.VISIBLE);
if(studentList != null) {
ListAdapterClass adapter = new ListAdapterClass(studentList, context);
StudentListView.setAdapter(adapter);
}else
{
Toast.makeText(context, "Tidak ada data ditampilkan", Toast.LENGTH_SHORT).show();
}
}
}

Choose a specific row of a recyclerview for sharing intent

Is there a way to choose a specific row of my RecyclerView (maybe by getting the index of the row) and then use it to create an intent.
I tried some things by getting the specific row information but that was not even close. My recycler is populated with data from a database.
To choose a specific row of my recycler, you can add setOnItemClickListener code like this one to your onCreate function:
listView_search.setOnItemClickListener(
new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id){
//Here I'm getting store_id and store_name
TextView store_search_id =(TextView) v.findViewById(R.id.store_search_id);
TextView store_search_name =(TextView) v.findViewById(R.id.store_search_name);
String store_name = store_search_name.getText().toString();
String store_id = store_search_id.getText().toString();
//Then I'm sending theses variables to a shared Intent
Intent myIntent = new Intent(getApplicationContext(), StoresShowActivity.class);
myIntent.putExtra("STORE_ID", store_id);
myIntent.putExtra("STORE_NAME", store_name);
startActivity(myIntent);
}
}
);
You may also want to follow these steps:
A. Add a layout for the Recycle view:
<?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:id="#+id/activity_stores_search"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="ksa.ikp.activities.StoresSearchActivity">
<SearchView
android:id="#+id/SearchView_store"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:iconifiedByDefault="false">
<requestFocus />
</SearchView>
<ListView
android:id="#+id/listView_search"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/SearchView_store" />
</RelativeLayout >
B. Add a layout for the recycleview item
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:padding="10dp">
<TextView
android:id="#+id/store_search_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="invisible" />
<TextView
android:id="#+id/store_search_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/store_search_category"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
C. Use adapter like this one and you can modify it based on your need
public class StoresSearchAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<Store> myList = null;
private ArrayList<Store> myArrayList;
public StoresSearchAdapter(Context context, List<Store> myList) {
mContext = context;
this.myList = myList;
inflater = LayoutInflater.from(mContext);
this.myArrayList = new ArrayList<Store>();
this.myArrayList.addAll(myList);
}
public class ViewHolder {
TextView store_search_id;
TextView store_search_name;
TextView store_search_category;
}
#Override
public int getCount() {
return myList.size();
}
#Override
public Store getItem(int position) {
return myList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.activity_stores_search_item, null);
// Locate the TextViews in activity_stores_search_item.xml
holder.store_search_id = (TextView) view.findViewById(R.id.store_search_id);
holder.store_search_name = (TextView) view.findViewById(R.id.store_search_name);
holder.store_search_category = (TextView) view.findViewById(R.id.store_search_category);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
holder.store_search_id.setText(myList.get(position).getStr_id()+"");
holder.store_search_name.setText(myList.get(position).getStr_name());
String s = SplashActivity.db.getNameById(myList.get(position).getStr_cat_id()+"",SplashActivity.db.TABLE_CATEGORY,SplashActivity.db.COLUMN_CAT_NAME,SplashActivity.db.COLUMN_CAT_ID);
s = " in ("+ s + ")";
holder.store_search_category.setText(s);
return view;
}
// Filter Class
public void filter(String s) {
s = s.toLowerCase(Locale.getDefault());
myList.clear();
if (s.length() == 0) {
myList.addAll(myArrayList);
} else {
myList.addAll(SplashActivity.db.getAllStoresFiltered(s));
}
notifyDataSetChanged();
}
}
Finally your final output will be something like this one:
screenshot
This is my recyclerbackgroundtask
public class RecycleBackgroundTask extends AsyncTask{
Context ctx;
Activity activity;
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
RecyclerView.LayoutManager layoutManager;
ArrayList<Post> arrayList = new ArrayList<>();
public RecycleBackgroundTask(Context ctx){
this.ctx = ctx;
activity = (Activity)ctx;
}
String json_string = "http://192.168.2.110/app/post.php";
#Override
public void onPreExecute() {
recyclerView = (RecyclerView)activity.findViewById(R.id.recyclerView);
layoutManager = new LinearLayoutManager(ctx);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
adapter = new RecyclerAdapter(arrayList);
recyclerView.setAdapter(adapter);
}
#Override
public Void doInBackground(Void... params) {
try {
URL url = new URL(json_string);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line=bufferedReader.readLine())!=null) {
stringBuilder.append(line+"\n");
}
httpURLConnection.disconnect();
String json_string = stringBuilder.toString().trim();
JSONObject jsonObject = new JSONObject(json_string);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
while(count<jsonArray.length()){
JSONObject JO = jsonArray.getJSONObject(count);
count++;
Post post = new Post(JO.getString("headline"),JO.getString("source"),JO.getString("url"));
publishProgress(post);
}
Log.d("JSON STRING",json_string);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
public void onProgressUpdate(Post... values) {
arrayList.add(values[0]);
adapter.notifyDataSetChanged();
}
And my RecyclerAdapter
public class RecyclerAdapter extends RecyclerView.Adapter {
private static final int TYPE_HEAD = 0;
private static final int TYPE_LIST = 1;
ArrayList<Post> arrayList = new ArrayList<>();
public RecyclerAdapter (ArrayList<Post> arrayList){
this.arrayList = arrayList;
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if(viewType == TYPE_HEAD){
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_recycler,parent,false); // instead of row_recycler ,header_layout.
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(view,viewType);
return recyclerViewHolder;
}
if(viewType == TYPE_LIST){
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_recycler,parent,false);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(view,viewType);
return recyclerViewHolder;
}
return null;
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
if(holder.viewType == TYPE_LIST) {
Post post = arrayList.get(position-1);
holder.Headline.setText(post.getHeadline());
holder.Source.setText(post.getSource());
//holder.Url.setText(post.getUrl());
}
}
#Override
public int getItemCount() {
return arrayList.size()+1;
}
public static class RecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView Headline,Source;//,Url;
int viewType;
public RecyclerViewHolder(View view,int viewType){
super(view);
if(viewType == TYPE_LIST) {
Headline = (TextView) view.findViewById(R.id.headline);
Source = (TextView) view.findViewById(R.id.source);
Headline.setOnClickListener(this);
Source.setOnClickListener(this);
// Url = (TextView) view.findViewById(R.id.url);
this.viewType = TYPE_LIST;
}else if (viewType == TYPE_HEAD){
this.viewType = TYPE_HEAD;
}
}
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "ITEM PRESSED = " + String.valueOf(getAdapterPosition()), Toast.LENGTH_SHORT).show();
}
}
#Override
public int getItemViewType(int position){
if(position==0)
return TYPE_HEAD;
return TYPE_LIST;
}
public void setFilter(ArrayList<Post> newList){
arrayList = new ArrayList<>();
arrayList.addAll(newList);
notifyDataSetChanged();
}
}
Maybe that helps. i already set up a simple onclicklistener with a toast btw

setting onClickListener on listView that is populated with json

i have implemented a multi colum list view that is populated from json data. i also have set an onClickListener to it. but on running the app when i click the listView i am only able to fetch the first item of the list.
what i want to acheive is when i click on any item in the listView i should be able to get the row item. the code that i used is as follows
Adapter.java
private Activity activity;
private static ArrayList prefrenceid,partnerid;
private static LayoutInflater inflater = null;
public CompanyRegistrationAdapter(Activity a, ArrayList pref, ArrayList part) {
activity = a;
this.prefrenceid = pref;
this.partnerid=part;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return prefrenceid.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.company_registation_adapter, null);
TextView preferences = (TextView) vi.findViewById(R.id.textView20);
String song = prefrenceid.get(position).toString();
preferences.setText(song);
TextView partner = (TextView) vi.findViewById(R.id.textView21);
String song2 = partnerid.get(position).toString();
partner.setText(song2);
return vi;
}
MainActivity.java
AsyncHttpClient usercheck = new AsyncHttpClient();
usercheck.get("REST URL", new AsyncHttpResponseHandler() {
public void onSuccess(String response) {
try {
progressDialog.hide();
JSONObject obj3 = new JSONObject(response);
final JSONArray jsonArray3 = obj3.getJSONArray("REST Method");
int length3 = jsonArray3.length();
if (length3 != 0) {
for (int i = 0; i < length3; i++) {
JSONObject user3 = jsonArray3.getJSONObject(i);
preference_array.add(user3.getString("GCP_NUMBER").toString());
partner_array.add(user3.getString("COMPANY_NAME").toString());
}
adapter = new CompanyRegistrationAdapter(CompanyRegistrationResult.this, preference_array, partner_array);
fav.setAdapter(adapter);
fav.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
try {
String iPartnerID = jsonArray3.getJSONObject(position).getString("ID");
Toast.makeText(getApplicationContext(),iPartnerID,Toast.LENGTH_SHORT).show();
Intent compRegister=new Intent(getApplicationContext(),CompanyRegistration.class);
compRegister.putExtra("gcp", gcp);
compRegister.putExtra("compName", compName);
startActivity(compRegister);
} catch (JSONException e) {
e.printStackTrace();
}
String gcp=((TextView) findViewById(R.id.textView20)).getText().toString();
String compName=((TextView) findViewById(R.id.textView21)).getText().toString();
}
});
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Custom adapter never empty

I've custom adapter that populates custom listview with data fetched from server. What I want is check if adapter is empty and append data to listview if it is empty else fill the listview with data and notifyDataSetChanged. I'm implementing OnScrollListener to load more data from server. But adapter never is empty and always notifyDataSetChanged is called.
My List Activity
public class ListResultActivity extends Activity implements OnScrollListener{
private ArrayList<BusinessListData> businesses;
private ListView businessList;
private LayoutInflater layoutInflator;
private BusinessListIconTask imgFetcher;
BusinessListDataAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.businesslist);
this.businessList = (ListView) findViewById(R.id.lvBusinesslist);
this.adapter= new BusinessListDataAdapter(this,
this.imgFetcher, this.layoutInflator, this.businesses);
getData();
businessList.setOnScrollListener(this);
}
#Override
public Object onRetainNonConfigurationInstance() {
Object[] myStuff = new Object[2];
myStuff[0] = this.businesses;
myStuff[1] = this.imgFetcher;
return myStuff;
}
/**
* Bundle to hold refs to row items views.
*
*/
public static class MyViewHolder {
public TextView businessName, businessAddress, phoneNo;
public Button btnProfile;
public ImageView icon;
public BusinessListData business;
}
public void setBusinesses(ArrayList<BusinessListData> businesses) {
this.imgFetcher = new BusinessListIconTask(this);
this.layoutInflator = LayoutInflater.from(this);
this.businesses = businesses;
if(adapter !=null){
this.adapter.notifyDataSetChanged();
}else{
this.adapter= new BusinessListDataAdapter(this,
this.imgFetcher, this.layoutInflator, this.businesses);
businessList.setAdapter(adapter);
}
}
private void getData() {
// TODO Auto-generated method stub
Intent myIntent = getIntent();
// gets the arguments from previously created intent
String metroTxt = myIntent.getStringExtra("key");
String metroLoc = myIntent.getStringExtra("loc");
String metroId = myIntent.getStringExtra("qt");
BusinessListApiTask spTask = new BusinessListApiTask(
ListResultActivity.this);
try {
spTask.execute(metroTxt, metroLoc, metroId);
} catch (Exception e) {
spTask.cancel(true);
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
if (businessList.getLastVisiblePosition() == totalItemCount - 1) {
getData();
adapter.notifyDataSetChanged();
Log.d("test count", "abc"+totalItemCount);
}
}
}
Class to fetch data from server and set to adapter
public class BusinessListApiTask extends AsyncTask<String, Integer, String> {
private ProgressDialog progDialog;
private Context context;
private ListResultActivity activity;
private static final String debugTag = "sodhpuch";
HashMap<String, String> queryValues;
/**
* Construct a task
*
* #param activity
*/
public BusinessListApiTask(ListResultActivity activity) {
// TODO Auto-generated constructor stub
super();
this.activity = activity;
this.context = this.activity.getApplicationContext();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progDialog = ProgressDialog.show(this.activity, "Search", this.context
.getResources().getString(R.string.looking_for_business), true,
false);
}
#Override
protected String doInBackground(String... params) {
try {
// Log.d(debugTag, "Background:" +
// Thread.currentThread().getName());
String result = BusinessListHelper.downloadFromServer(params);
// try {
//
// updateSQLite(result);
//
// } catch (Exception e) {
// return result;
// }
Log.d("result", result);
return result;
} catch (Exception e) {
return new String();
}
}
#Override
protected void onPostExecute(String result) {
ArrayList<BusinessListData> businessData = new ArrayList<BusinessListData>();
progDialog.dismiss();
try {
JSONObject respObj = new JSONObject(result);
int success = respObj.getInt("success");
Log.d("Success", "abc"+success);
if (success == 1) {
JSONArray tracks = respObj.getJSONArray("idioms");
for (int i = 0; i < tracks.length(); i++) {
JSONObject track = tracks.getJSONObject(i);
String businessName = track.getString("name");
String businessAddress = track.getString("address");
String phone = track.getString("phone");
String id = track.getString("id");
String deals_in = track.getString("deals_in");
businessData.add(new BusinessListData(businessName,
businessAddress, id, phone, deals_in));
}
} else {
Log.d("Success", "first"+success);
// Log.d(debugTag, "Background:" + result);
// DBController controller = new DBController(context);
// businessData = controller.getBusinessList();
return ;
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// }
this.activity.setBusinesses(businessData);
}
My Adapter
public class BusinessListDataAdapter extends BaseAdapter implements
OnClickListener {
private static final String debugTag = "BusinessListDataAdapter";
private ListResultActivity activity;
private BusinessListIconTask imgFetcher;
private LayoutInflater layoutInflater;
private ArrayList<BusinessListData> businesses;
BusinessListData business;
public BusinessListDataAdapter(ListResultActivity a,
BusinessListIconTask i, LayoutInflater l,
ArrayList<BusinessListData> data) {
this.activity = a;
this.imgFetcher = i;
this.layoutInflater = l;
this.businesses = data;
}
#Override
public int getCount() {
return this.businesses.size();
}
public void clear()
{
businesses.clear();
notifyDataSetChanged();
}
#Override
public boolean areAllItemsEnabled() {
return true;
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int pos) {
return pos;
}
#Override
public View getView(int pos, View convertView, ViewGroup parent) {
MyViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.trackrow, parent,
false);
holder = new MyViewHolder();
holder.businessName = (TextView) convertView
.findViewById(R.id.tvBusinessName);
holder.businessAddress = (TextView) convertView
.findViewById(R.id.tvAddress);
holder.phoneNo = (TextView) convertView.findViewById(R.id.tvPhone);
holder.icon = (ImageView) convertView.findViewById(R.id.album_icon);
holder.btnProfile = (Button) convertView
.findViewById(R.id.btnProfile);
holder.btnProfile.setTag(holder);
convertView.setTag(holder);
} else {
holder = (MyViewHolder) convertView.getTag();
}
convertView.setOnClickListener(this);
business= businesses.get(pos);
holder.business = business;
holder.businessName.setText(business.getName());
holder.businessAddress.setText(business.getAddress());
holder.phoneNo.setText(business.getPhone());
holder.btnProfile.setOnClickListener(this);
// if(track.getImageUrl() != null) {
// holder.icon.setTag(track.getImageUrl());
// Drawable dr = imgFetcher.loadImage(this, holder.icon);
// if(dr != null) {
// holder.icon.setImageDrawable(dr);
// }
// } else {
holder.icon.setImageResource(R.drawable.filler_icon);
// }
return convertView;
}
#Override
public void onClick(View v) {
String deals_in = business.getDeals().toString();
Log.d("name", deals_in);
MyViewHolder holder = (MyViewHolder) v.getTag();
if (v instanceof Button) {
Intent profile = new Intent(activity,
ProfileActivity.class);
profile.putExtra("deals_in", deals_in);
profile.putExtra("phone", holder.business.getPhone());
profile.putExtra("address", holder.business.getAddress());
profile.putExtra("name", holder.business.getName());
this.activity.startActivity(profile);
} else if (v instanceof View) {
Log.d("test","call testing");
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" +holder.business.getPhone()));
this.activity.startActivity(intent);
}
Log.d(debugTag, "OnClick pressed.");
}
}
Try this way,hope this will help you to solve your problem.
public void setBusinesses(ArrayList<BusinessListData> businesses) {
imgFetcher = new BusinessListIconTask(this);
layoutInflator = LayoutInflater.from(this);
if(this.businesses == null || adapter==null){
this.businesses = new ArrayList<BusinessListData>();
adapter= new BusinessListDataAdapter(this,imgFetcher,layoutInflator,this.businesses);
businessList.setAdapter(adapter);
}
this.businesses.addAll(businesses);
adapter.notifyDataSetChanged();
}
You have the adapter object in your setBusinesses Method. You just need to check the size of the adapter too as follows which is solve your problem.
if(adapter !=null && adapter.getCount()>0)
{
this.adapter.notifyDataSetChanged();
}
else
{
this.adapter= new BusinessListDataAdapter(this,
this.imgFetcher, this.layoutInflator, this.businesses);
businessList.setAdapter(adapter);
}
this will check the size of your BusinessListData object in the adapter and this will not initialize the adapter again and again.
Hope this Solves your problem.
Thank You!
Change use of OnScrollListener. Use Asynctask class and onPreExecute() set adapter as null. Load data in doInBackground() method and call custom adapter in onPostExecute(). I hope it 'll work fine.

OnItemClickListener getting data from model

I am fairly new to Android development and I am trying to build a ListView which get data from web service using gson. I have a model class, a list class, an adapter class and the activity class.
The list works fine and it got the data, and now I want to integrate the OnItemClickListener to it and pass the data to the 2nd activity. And I'd like to get the item id (DistrictId) and pass it to the next Activity(listView) instead of the row id. It would be great if someone could show me the light... as the documentation is not as clear to understand and because I am new.
Below is my code.
The model class
package com.sample.myapp;
public class DistrictModel {
private String id;
private String districtName;
public String getDistrictId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDistrictName(){
return districtName;
}
public void setDistrictEN(String districtName){
this.districtName = districtName;
}
}
The List class
public class DistrictList {
private List<DistrictModel> districts;
public List<DistrictModel> getDistricts(){
return districts;
}
public void setDistrictList(List<DistrictModel> districts){
this.districts = districts;
}
}
The Adapter class
public class DistrictAdapter extends ArrayAdapter<DistrictModel>{
int resource;
String response;
Context context;
private LayoutInflater dInflater;
public DistrictAdapter(Context context, int resource, List<DistrictModel> objects) {
super(context, resource, objects);
this.resource = resource;
dInflater = LayoutInflater.from(context);
}
static class ViewHolder {
TextView title;
}
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder;
//Get the current location object
DistrictModel lm = (DistrictModel) getItem(position);
//Inflate the view
if(convertView==null)
{
convertView = dInflater.inflate(R.layout.item_district, null);
holder = new ViewHolder();
holder.title = (TextView) convertView
.findViewById(R.id.district_name);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.title.setText(lm.getDistrictName());
return convertView;
}
}
The activity class
public class DistrictListActivity extends Activity{
LocationManager lm;
ArrayList<DistrictModel> districtArray = null;
DistrictAdapter districtAdapter;
DistrictList list;
ListView lv;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.districtlist_layout);
lv = (ListView) findViewById(R.id.list_district);
districtArray = new ArrayList<DistrictModel>();
districtAdapter = new DistrictAdapter(DistrictListActivity.this, R.layout.item_district, districtArray);
lv.setTextFilterEnabled(true);
lv.setAdapter(districtAdapter);
try {
new DistrictSync().execute("http://aws.something.com/service");
} catch(Exception e) {}
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View convertView, int position, long id) {
AlertDialog.Builder adb=new AlertDialog.Builder(DistrictListActivity.this);
adb.setTitle("LVSelectedItemExample");
adb.setMessage("Selected Item is = "+(lv.getItemIdAtPosition(position)));
adb.setPositiveButton("Ok", null);
adb.show();
}
}); **//i'd like to get the DistrictId from the json data.**
}
private class DistrictSync extends AsyncTask<String, Integer, DistrictList> {
protected DistrictList doInBackground(String... urls) {
DistrictList list = null;
int count = urls.length;
for (int i = 0; i < count; i++) {
try {
// ntar diganti service
RestClient client = new RestClient(urls[i]);
try {
client.Execute(RequestMethod.GET);
} catch (Exception e) {
e.printStackTrace();
}
String json = client.getResponse();
list = new Gson().fromJson(json, DistrictList.class);
//
} catch(Exception e) {}
}
return list;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(DistrictList dislist) {
for(DistrictModel lm : dislist.getDistricts())
{
districtArray.add(lm);
}
districtAdapter.notifyDataSetChanged();
}
}
}
For testing purpose, now I click the row it will show me the row id, so I know the onclick listener works, but I just want it to grab me the DistrictId so I can use it to pass to the next activity.
Thank you so much.
(out of my head) Try this:
((DistrictModel)lv.getAdapter().getItem(position)).getDistrictId();
Generally when you want to pass data from one Activity to another, you just place it into the Intent that you use to create the new Activity.
For example (and here are some additional examples):
Intent i = new Intent(context, MyNewActivity.class);
i.putExtra("MyCurrentHealth", mCurrentHealth);
context.startActivity(i);
To retrieve the data do this:
Bundle extras = getIntent().getExtras();
if (extra != null) {
... // Do stuff with extras
}

Categories

Resources