in my android project I am using a custom listview where all the values are retrieved from the server and displayed in the listview. I have a button along with the textview in the listview entries, now I want to functionality of the button to be like when I click it will take the value from any textview of the same group and display it in the alert box. I retrieved the data and displayed successfully but I'm not able crack how to use the button to get the textview values of the list.. Thanks in advance for any help... My codes are posted below.
This is my contact adapter class:
package com.example.sohan.doctor;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Sohan on 6/9/2016.
*/
public class ContactAdapter extends ArrayAdapter {
notification nt = new notification();
List list = new ArrayList();
View row;
ContactHolder contactHolder;
public ContactAdapter(Context context, int resource) {
super(context, resource);
}
public void add(List<Contacts> updatedList) {
list.clear();
list.addAll(updatedList);
notifyDataSetChanged();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public int getCount() {
return list.size();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
row = convertView;
if(row==null){
LayoutInflater layoutInflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.view_symptom_layout,parent,false);
contactHolder = new ContactHolder();
contactHolder.Name =(TextView) row.findViewById(R.id.textView2);
contactHolder.Age =(TextView) row.findViewById(R.id.textView3);
contactHolder.Height =(TextView) row.findViewById(R.id.textView4);
contactHolder.Weight =(TextView) row.findViewById(R.id.textView5);
contactHolder.Symptom =(TextView) row.findViewById(R.id.textView6);
contactHolder.button = (Button) row.findViewById(R.id.button3);
contactHolder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name;
name = nt.newList.get(position).getName(); // This is where I'm stucked.
Toast.makeText(getContext().getApplicationContext(), name+" is served ", Toast.LENGTH_LONG).show();
}
});
row.setTag(contactHolder);
}
else{
contactHolder = (ContactHolder)row.getTag();
}
Contacts contacts = (Contacts)this.getItem(position);
contactHolder.Name.setText("Name: "+contacts.getName());
contactHolder.Age.setText("Age: "+contacts.getAge());
contactHolder.Height.setText("Height: "+contacts.getHeight());
contactHolder.Weight.setText("Weight: "+contacts.getWeight());
contactHolder.Symptom.setText("Symptoms: "+contacts.getSymptom());
return row;
}
static class ContactHolder{
TextView Name;
TextView Age;
TextView Height;
TextView Weight;
TextView Symptom;
Button button;
}
}
And this is the class where I retrieve all the values from server and store it in listview:
package com.example.sohan.doctor;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Sohan on 6/25/2016.
*/
public class notification extends Fragment implements AdapterView.OnItemSelectedListener{
public final static String Message = "Sohan";
View myView;
String selectedCity;
Context myContext;
String jsonResult;
JSONObject jsonObject;
JSONArray jsonArray;
String JSON_String;
ContactAdapter contactAdapter;
ListView listView;
List<Contacts> newList;
Button button;
String send;
public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.notification, container, false);
myContext = inflater.getContext();
contactAdapter = new ContactAdapter(myContext, R.layout.view_symptom_layout);
listView = (ListView)myView.findViewById(R.id.listView);
listView.setAdapter(contactAdapter);
retrieveInfo ri = new retrieveInfo();
ri.execute();
return myView;
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
class retrieveInfo extends AsyncTask<Void, Void, String> { // send data to server
String myUrl;
protected void onPreExecute() {
myUrl ="httP://myserver.com"; // change php script
}
protected String doInBackground(Void... args) {
String city;
String result = null;
JSONArray jsonArray = null;
try{
URL url = new URL(myUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
// String data_to_send = URLEncoder.encode("city", "UTF-8")+"="+URLEncoder.encode(city,"UTF-8");
//bufferedWriter.write(data_to_send);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream is = httpURLConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
while ((JSON_String = reader.readLine()) != null)
{
sb.append(JSON_String+"\n");
}
reader.close();
httpURLConnection.disconnect();
is.close();
return sb.toString().trim();
}catch(MalformedURLException e){
e.printStackTrace();
}catch(IOException f){
f.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
jsonResult = result;
parseJSON(jsonResult);
}
}
public void parseJSON(String json){
Contacts contacts=null;
try {
jsonObject = new JSONObject(json);
jsonArray = jsonObject.getJSONArray("patient");
int count = 0;
String name,age,height,weight,symptom;
newList = new ArrayList<Contacts>();
while (count < jsonArray.length()) {
JSONObject jo = jsonArray.getJSONObject(count);
name = jo.getString("Name"); // data's are send to store in and print in listview
age = jo.getString("Age");
height = jo.getString("Height");
weight = jo.getString("Weight");
symptom = jo.getString("Symptom");
contacts = new Contacts(name,age,height,weight,symptom);
newList.add(contacts); // data are stored in the newlist array
count++;
}
contactAdapter.add(newList); // the newlist array are send to add in the listview
} catch (Exception e) {
e.printStackTrace();
}
}
}
You can make some more changes like following.
ContactAdapter extends ArrayAdapter<Contacts>
List<Contacts> list = new ArrayList<Contacts>();
And this line:
String name,age,height,weight,symptom;
You should put in while loop with initialize as null ""
name = nt.newList.get(position).getName();
I think it should be:
name = list.get(position).getName();
You cam also read this article:
ListView with Add and Delete Buttons in each Row in android
Related
my name ari.. i am newbie in Android development. maybe you can help me to answer my problem. I want to display data from the listview adapter, but when i click the data. my app force close.
i have a adapter for show data in listview like :
ListAdapter.java
package com.santosa.sapasantosa.components;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.santosa.sapasantosa.R;
import java.util.ArrayList;
/**
* Created by muhammadaa on 10/14/2017.
*/
public class ListAdapter extends BaseAdapter {
private Activity activity;
private static ArrayList nik;
private static ArrayList nama;
private static ArrayList email;
private static ArrayList phone;
private static ArrayList jabatan;
private static ArrayList departement;
private static ArrayList gender;
private static ArrayList status;
private static ArrayList label;
private static LayoutInflater inflater = null;
public ListAdapter(Activity a, ArrayList b, ArrayList c, ArrayList d, ArrayList e, ArrayList f, ArrayList g, ArrayList h, ArrayList i, ArrayList j) {
activity = a;
this.nik = b;
this.nama = c;
this.email = d;
this.gender = e;
this.status = f;
this.label = g;
this.phone = h;
this.jabatan = i;
this.departement = j;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return nik.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.listview_data_profile, null);
TextView nik2 = (TextView) vi.findViewById(R.id.profNik); // nik
String ambilNik = nik.get(position).toString();
nik2.setText(ambilNik);
TextView nama2 = (TextView) vi.findViewById(R.id.profNama); // nama
String ambilNama = nama.get(position).toString();
nama2.setText(ambilNama);
TextView email2 = (TextView) vi.findViewById(R.id.profEmail); // email
String ambilEmail = email.get(position).toString();
email2.setText(ambilEmail);
TextView phone2 = (TextView) vi.findViewById(R.id.profPhone); // phone
String ambilPhone = phone.get(position).toString();
phone2.setText(ambilPhone);
TextView gender2 = (TextView) vi.findViewById(R.id.profGender); // gender
String ambilGender = gender.get(position).toString();
gender2.setText(ambilGender);
TextView bagian = (TextView) vi.findViewById(R.id.profBagian); // Bagian
String ambilJabatan = jabatan.get(position).toString();
String ambilDepartement = departement.get(position).toString();
bagian.setText(ambilJabatan+"/"+ambilDepartement);
TextView status2 = (TextView) vi.findViewById(R.id.profStatus); // status
String ambilStatus = status.get(position).toString();
status2.setText(ambilStatus);
TextView label2 = (TextView) vi.findViewById(R.id.countNumber); // label
String ambilLabel = label.get(position).toString();
label2.setText(ambilLabel);
return vi;
}
}
And this class fragment for using adapter
AdminHomeFragment
package com.santosa.sapasantosa.view.admin;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.StringDef;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import com.santosa.sapasantosa.R;
import com.santosa.sapasantosa.components.ListAdapter;
import com.santosa.sapasantosa.components.RequestHandler;
import com.santosa.sapasantosa.components.SharedPrefManager;
import com.santosa.sapasantosa.configs.Constrant;
import com.santosa.sapasantosa.models.Employee;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import static android.provider.AlarmClock.EXTRA_MESSAGE;
/**
* A simple {#link Fragment} subclass.
*/
public class AdminHomeFragment extends Fragment {
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
ArrayList<String> nik_array = new ArrayList<String>();
ArrayList<String> nama_array = new ArrayList<String>();
ArrayList<String> email_array = new ArrayList<String>();
ArrayList<String> phone_array = new ArrayList<String>();
ArrayList<String> gender_array = new ArrayList<String>();
ArrayList<String> jabatan_array = new ArrayList<String>();
ArrayList<String> departement_array = new ArrayList<String>();
ArrayList<String> status_array = new ArrayList<String>();
ArrayList<Integer> label_array = new ArrayList<>();
com.santosa.sapasantosa.components.ListAdapter adapter;
ListView listPeg;
public AdminHomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_admin_home, container, false);
listPeg = (ListView) view.findViewById(R.id.pegListView);
listPeg.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(getActivity(),ProfileEmployeeActivity.class);
HashMap<String,String> map = (HashMap) parent.getItemAtPosition(position);
Log.e("","adad "+map);
String empId = map.get("nik");
i.putExtra("nik",empId);
startActivity(i);
}
});
loadDataPegawai();
return view;
}
private void loadDataPegawai() {
// get parameter
final String users = SharedPrefManager.getInstance(getContext()).getUserEmployee().getNik();
class LoadPegawai extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... voids) {
//creating request handler object
RequestHandler requestHandler = new RequestHandler();
//creating request parameters
HashMap<String, String> params = new HashMap<>();
params.put("username", users);
//returing the response
return requestHandler.sendPostRequest(Constrant.URL_PROFIL, params);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
int n = 1;
try {
JSONObject obj = new JSONObject(s);
if (!obj.getBoolean("error")) {
// get data user dari respone
JSONArray userJson = obj.getJSONArray("user");
for (int i = 0, count = userJson.length(); i < count; i++) {
try {
JSONObject jsonObject = userJson.getJSONObject(i);
if (jsonObject.getString("employeeStatus").toString().equals("0")) {
nik_array.add(jsonObject.getString("employeeID").toString());
nama_array.add(jsonObject.getString("employeeNama").toString());
email_array.add(jsonObject.getString("employeeEmail").toString());
gender_array.add(jsonObject.getString("employeeGender").toString());
status_array.add(jsonObject.getString("employeeStatus").toString());
phone_array.add(jsonObject.getString("employeePhone").toString());
jabatan_array.add(jsonObject.getString("employeeJabatan").toString());
departement_array.add(jsonObject.getString("employeeDepartement").toString());
label_array.add(n++);
String id = jsonObject.getString("employeeID").toString();
// adding to hashmap
HashMap<String,String> employees = new HashMap<>();
employees.put("nik",id);
list.add(employees);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
/* Set data to listview */
adapter = new com.santosa.sapasantosa.components.ListAdapter( getActivity(),
nik_array,
nama_array,
email_array,
gender_array,
status_array,
label_array,
phone_array,
jabatan_array,
departement_array);
listPeg.setAdapter(adapter);
listPeg.setTextFilterEnabled(true);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
//executing the async task
LoadPegawai ru = new LoadPegawai();
ru.execute();
}
}
when i clik data adapter in ListView, i have a Error like:
Can you help me for resolve the error. I say very very thanks you for your help...
Seems you're trying to display all employees as a ListView... If my understanding is't wrong, you should :
Create an EmployeeBean
Put all your employee into a collection...maybe ArrayList.
After that, when you click an item on ListView, the integer you get is the index of EmployeeBean in your collection, so that you can access it from your collection.
Here is my code of the populated listview adapter that I have
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;
public class ListViewAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Contact> DataList;
public ListViewAdapter(Activity activity, List<Contact> dataitem) {
this.activity = activity;
this.DataList = dataitem;
}
#Override
public int getCount() {
return DataList.size();
}
#Override
public Object getItem(int location) {
return DataList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list, null);
TextView name = (TextView) convertView.findViewById(R.id.name);
TextView companyName = (TextView) convertView.findViewById(R.id.companyName);
Contact m = DataList.get(position);
name.setText(m.getName());
companyName.setText(String.valueOf(m.getCompanyName()));
return convertView;
}
}
And here is my main
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
private static final String url = "https://s3.amazonaws.com/technical-challenge/v3/contacts.json";
private List<Contact> l = new ArrayList<Contact>();
private ListView listView;
private ListViewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list);
adapter = new ListViewAdapter(this, l);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(MainActivity.this, ContactDetail.class);
startActivity(i);
}
});
JsonArrayRequest jsonreq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Contact dataSet = new Contact();
dataSet.setName(obj.getString("name"));
dataSet.setCompanyName(obj.getString("companyName"));
l.add(dataSet);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
AlertDialog.Builder add = new AlertDialog.Builder(MainActivity.this);
add.setMessage(error.getMessage()).setCancelable(true);
AlertDialog alert = add.create();
alert.setTitle("Error!!!");
alert.show();
}
});
Controller.getInstance(this).addToRequestQueue(jsonreq);
}
}
}
this code works properly and populates my listview, however, when I click on an item in the listview I have another listview populating that displays all contact items...I just want ONE contact item to display.
import android.app.Activity;
import android.content.Context;
import android.net.Uri;
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 java.util.List;
public class ListViewContactAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Contact> DataList;
public ListViewContactAdapter(Activity activity, List<Contact> dataitem) {
this.activity = activity;
this.DataList = dataitem;
}
#Override
public int getCount() {
return DataList.size();
}
#Override
public Object getItem(int location) {
return DataList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.contactlistinfo, null);
ImageView i = (ImageView) convertView.findViewById(R.id.imageView2);
TextView tv2 = (TextView) convertView.findViewById(R.id.textView2);
TextView tv4 = (TextView) convertView.findViewById(R.id.textView4);
TextView tv6 = (TextView) convertView.findViewById(R.id.textView6);
TextView tv8 = (TextView) convertView.findViewById(R.id.textView8);
TextView tv17 = (TextView) convertView.findViewById(R.id.textView17);
TextView tv18 = (TextView) convertView.findViewById(R.id.textView18);
TextView tv19 = (TextView) convertView.findViewById(R.id.textView19);
TextView tv20 = (TextView) convertView.findViewById(R.id.textView20);
TextView tv10 = (TextView) convertView.findViewById(R.id.textView10);
TextView tv12 = (TextView) convertView.findViewById(R.id.textView12);
TextView tv14 = (TextView) convertView.findViewById(R.id.textView14);
TextView tv16 = (TextView) convertView.findViewById(R.id.textView16);
Contact m = DataList.get(position);
tv2.setText(m.getName());
tv4.setText(m.getCompanyName());
tv6.setText(m.getHome());
tv12.setText(m.getMobile());
tv14.setText(m.getWork());
tv8.setText(m.getStreet());
tv18.setText(m.getCity());
tv17.setText(m.getState());
tv19.setText(m.getZipCode());
tv20.setText(m.getCountry());
tv10.setText(m.getBirthdate());
tv16.setText(m.getEmail());
i.setImageURI(Uri.parse("https://s3.amazonaws.com/technical-challenge/v3/images/elmer-fudd-small.jpg"));
return convertView;
}
}
Now here is where I have it being populated. But why does it display as another list listview? I want only ONE item.
import android.app.AlertDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class ContactDetail extends AppCompatActivity {
private static final String url = "https://s3.amazonaws.com/technical-challenge/v3/contacts.json";
private List<Contact> l = new ArrayList<Contact>();
private ListView listView;
private ListViewContactAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_detail);
listView = (ListView) findViewById(R.id.list2);
adapter = new ListViewContactAdapter(this, l);
listView.setAdapter(adapter);
JsonArrayRequest jsonreq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++)
try {
JSONObject obj = response.getJSONObject(i);
// Phone
JSONObject phone = obj.getJSONObject("phone");
String home = phone.getString("home");
String mobile = phone.getString("mobile");
String work = phone.getString("work");
//Address
JSONObject address = obj.getJSONObject("address");
String street = address.getString("street");
String city= address.getString("city");
String state= address.getString("state");
String country= address.getString("country");
String zipCode= address.getString("zipCode");
Contact dataSet = new Contact();
dataSet.setName(obj.getString("name"));
dataSet.setCompanyName(obj.getString("companyName"));
dataSet.setBirthdate(obj.getString("birthdate"));
dataSet.setEmail(obj.getString("emailAddress"));
dataSet.setHome(home);
dataSet.setMobile(mobile);
dataSet.setWork(work);
dataSet.setStreet(street);
dataSet.setState(state);
dataSet.setCity(city);
dataSet.setZipCode(zipCode);
dataSet.setCountry(country);
dataSet.setImage(obj.getString("largeImageURL"));
l.add(dataSet);
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
AlertDialog.Builder add = new AlertDialog.Builder(ContactDetail.this);
add.setMessage(error.getMessage()).setCancelable(true);
AlertDialog alert = add.create();
alert.setTitle("Error!!!");
alert.show();
}
});
Controller.getInstance(this).addToRequestQueue(jsonreq);
}
}
I guess your ContactDetail activity is getting the list again. And why do you need to show a listview again if you only need one item upon clicking of one item in your first activity.
Anyway, if you still want to use listview in your ContactDetail then do this..
in your listview.setOnItemClickListener on MainActivity
Intent intent = new Intent(MainActivity.this, ContactDetail.this);
intent.putExtra("contact", l.get(position));
startActivity(intent);
in your ContactDetails activity, replace it with this.. remove that JsonArrayRequest
listView = (ListView) findViewById(R.id.list2);
Contact contact = getIntent().getSerializableExtra("contact");
l.add(contact);
adapter = new ListViewContactAdapter(this, l);
listView.setAdapter(adapter);
and also make sure that your Contact object implements Serializable
I have been working on an android project where I need to fetch data from server and display in a listview. The first retrieval is done successfully but from second retrieval onwards the fetched data's are placed below the previously fetched data. How can I refresh the listview to view the fetched data in the listview? The codes I used are given below.
package com.example.sohan.patient;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Sohan on 5/20/2016.
*/
public class Doctors_layout extends Fragment implements AdapterView.OnItemSelectedListener{
View myView;
Spinner spinner;
String selectedCity;
Context myContext;
String jsonResult;
JSONObject jsonObject;
JSONArray jsonArray;
ContactAdapter contactAdapter;
String JSON_String;
ListView listView;
Button button;
int check=0;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.doctors_directory, container, false);
myContext = inflater.getContext();
contactAdapter = new ContactAdapter(myContext, R.layout.row_layout);
spinner = (Spinner)myView.findViewById(R.id.spinner);
listView = (ListView)myView.findViewById(R.id.listView);
listView.setAdapter(contactAdapter);
spinner.setOnItemSelectedListener(this);
List<String> city = new ArrayList<String>();
city.add("Choose a City");
city.add("Chittagong");
city.add("Dhaka");
ArrayAdapter<String> aAdapter = new ArrayAdapter<String>(myContext, android.R.layout.simple_spinner_item ,city);
aAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(aAdapter);
return myView;
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//contactAdapter.notifyDataSetChanged();
if(check==0) {
((TextView) parent.getChildAt(0)).setTextSize(21);
if (position == 0) {
nothing();
} else {
check++;
selectedCity = parent.getItemAtPosition(position).toString();
Toast.makeText(myContext, "Check value: "+check, Toast.LENGTH_LONG).show();
retrieveInfo ri = new retrieveInfo();
ri.execute(selectedCity); // notifydata
}
}
else{
contactAdapter.notifyDataSetChanged();
selectedCity = parent.getItemAtPosition(position).toString();
retrieveInfo ri = new retrieveInfo();
ri.execute(selectedCity);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public void nothing(){
//Toast.makeText(myContext, "Default position 0", Toast.LENGTH_LONG).show();
}
class retrieveInfo extends AsyncTask<String, Void, String> { // send data to server
String myUrl;
protected void onPreExecute() {
myUrl ="http://bdpricelist.com/patient/retrieveMedicalName.php"; // change php script
}
protected String doInBackground(String... args) {
String city;
String result = null;
city = args[0];
JSONArray jsonArray = null;
try{
URL url = new URL(myUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String data_to_send = URLEncoder.encode("city", "UTF-8")+"="+URLEncoder.encode(city,"UTF-8");
bufferedWriter.write(data_to_send);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream is = httpURLConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
while ((JSON_String = reader.readLine()) != null)
{
sb.append(JSON_String+"\n");
}
reader.close();
httpURLConnection.disconnect();
is.close();
return sb.toString().trim();
}catch(MalformedURLException e){
e.printStackTrace();
}catch(IOException f){
f.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
jsonResult = result;
parseJSON(jsonResult);
//jsonResult="";
}
}
public void delete(String city) {
Fragment Dl = new Doctors_layout();
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.content_frame, Dl);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
public void parseJSON(String json){
Contacts contacts=null;
try {
jsonObject = new JSONObject(json);
jsonArray = jsonObject.getJSONArray("patient");
int count = 0;
String name;
while (count < jsonArray.length()) {
JSONObject jo = jsonArray.getJSONObject(count);
name = jo.getString("Medical"); // data's are send to store in and print in listview
contacts = new Contacts(name);
contactAdapter.add(contacts);
count++;
}
//contactAdapter.add(contacts.getMedicalName());
} catch (Exception e) {
e.printStackTrace();
}
}
}
And my adapter class is given below
package com.example.sohan.patient;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Sohan on 6/9/2016.
*/
public class ContactAdapter extends ArrayAdapter {
//ContactHolder contactHolder;
List list = new ArrayList();
ContactAdapter contactAdapter;
List receivedList = new ArrayList();
View row;
ContactHolder contactHolder;
int count =0;
public ContactAdapter(Context context, int resource) {
super(context, resource);
}
public void add(Contacts object) {
// list.clear();
super.add(object);
list.add(object);
//notifyDataSetChanged();
Toast.makeText(getContext().getApplicationContext(), "Entry without delete ", Toast.LENGTH_SHORT).show();
}
#Override
public int getCount() {
return list.size();
}
#Override
public void clear() {
super.clear();
}
#Override
public boolean isEmpty() {
return super.isEmpty();
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
public void deleteEntry(){
list.clear();
Toast.makeText(getContext().getApplicationContext(), "List cleared before entry ", Toast.LENGTH_SHORT).show();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//count++;
row = convertView;
if(row==null){
LayoutInflater layoutInflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.row_layout,parent,false);
contactHolder = new ContactHolder();
contactHolder.MedicalName =(TextView) row.findViewById(R.id.textView5);
row.setTag(contactHolder);
}
else{
contactHolder = (ContactHolder)row.getTag();
}
contactHolder = new ContactHolder();
contactHolder.MedicalName =(TextView) row.findViewById(R.id.textView5);
Contacts contacts = (Contacts)this.getItem(position);
contactHolder.MedicalName.setText(contacts.getMedicalName());
return row;
}
static class ContactHolder{
TextView MedicalName;
}
}
Instead of having add(Contacts object) in your adapter, have a method where you clear the current items in the list and update with the newly retrieved items.
private void updateContactList(List<Contacts> updatedList) {
list.clear();
list.addAll(updatedList);
notifyDataSetChanged();
}
and inside parseJSON(String json)
List<Contacts> newList = new ArrayList<>();
while (count < jsonArray.length()) {
JSONObject jo = jsonArray.getJSONObject(count);
name = jo.getString("Medical");
contacts = new Contacts(name);
newList.add(contacts);
count++;
}
contactAdapter.updateContactList(newList);
The new data is being shown after the old data because you are adding new data to the existing one in parseJSON().
If you want to replace the old data with new one then remove these lines from onCreateView and add inside parseJSON(), right after while loop.
contactAdapter = new ContactAdapter(myContext, R.layout.row_layout);
listView.setAdapter(contactAdapter);
I receive a JSON array from the server that looks like this,
[{"id":"3","name":"Spanish 101","uid":"54f22e5c87cbd3.52439435","did":"fba6a04d1d6375fbdbb102953e984002"},
{"id":"4","name":"Calc","uid":"54f22e5c87cbd3.52439435","did":"fb7f4ba1eae22eb396dc7cbd465a10b4"},
{"id":"5","name":"Stats 250","uid":"54f22e5c87cbd3.52439435","did":"f6adca44250056c17fec56530faee7c9"}]
I want to take this information and put it into a listview
This is my code that is suppose to process this JSON aray and put it into a listview
package com.example.library;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
public class FetchDataTask extends AsyncTask<String, Void, String>{
private final FetchDataListener listener;
private String msg;
public FetchDataTask(FetchDataListener listener) {
this.listener = listener;
}
#Override
protected String doInBackground(String... params) {
if(params == null) return null;
// get url from params
String url = params[0];
try {
// create http connection
HttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
// connect
HttpResponse response = client.execute(httpget);
// get response
HttpEntity entity = response.getEntity();
if(entity == null) {
msg = "No response from server";
return null;
}
// get response content and convert it to json string
InputStream is = entity.getContent();
return streamToString(is);
}
catch(IOException e){
msg = "No Network Connection";
}
return null;
}
#Override
protected void onPostExecute(String sJson) {
if(sJson == null) {
if(listener != null) listener.onFetchFailure(msg);
return;
}
try {
// convert json string to json array
JSONArray aJson = new JSONArray(sJson);
// create apps list
List<Application> apps = new ArrayList<Application>();
for(int i=0; i<aJson.length(); i++) {
JSONObject json = aJson.getJSONObject(i);
Application app = new Application();
app.setTitle(json.getString("name"));
// add the app to apps list
apps.add(app);
}
//notify the activity that fetch data has been complete
if(listener != null) listener.onFetchComplete(apps);
} catch (JSONException e) {
msg = "Invalid response";
if(listener != null) listener.onFetchFailure(msg);
return;
}
}
/**
* This function will convert response stream into json string
* #param is respons string
* #return json string
* #throws IOException
*/
public String streamToString(final InputStream is) throws IOException{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
}
catch (IOException e) {
throw e;
}
finally {
try {
is.close();
}
catch (IOException e) {
throw e;
}
}
return sb.toString();
}
}
FetchDataListener
package com.example.library;
import java.util.List;
public interface FetchDataListener {
public void onFetchComplete(List<Application> data);
public void onFetchFailure(String msg);
}
I am currently only trying to place the name into the listview, when I run this code what happens is only the first array gets put into the listview. So there is only one list item and it has the name Spanish 101.
Why aren't the other array names being put into the listview?
Application Adapter
package com.example.library;
import java.text.NumberFormat;
import java.util.List;
import android.content.Context;
import android.content.res.Resources;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.example.R;
public class ApplicationAdapter extends ArrayAdapter<Application>{
private List<Application> items;
public ApplicationAdapter(Context context, List<Application> items) {
super(context, R.layout.app_custom_list, items);
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if(v == null) {
LayoutInflater li = LayoutInflater.from(getContext());
v = li.inflate(R.layout.app_custom_list, null);
}
Application app = items.get(position);
if(app != null) {
TextView titleText = (TextView)v.findViewById(R.id.titleTxt);
if(titleText != null) titleText.setText(app.getTitle());
}
return v;
}
}
Get and Set
package com.example.library;
public class Application {
private String title;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
MainActivity that has ListView
package com.example;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.example.R;
import com.example.library.Application;
import com.example.library.ApplicationAdapter;
import com.example.library.DatabaseHandler;
import com.example.library.FetchDataListener;
import com.example.library.FetchDataTask;
import com.example.library.UserFunctions;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends ListActivity implements FetchDataListener {
private ProgressDialog dialog;
ProgressDialog nDialog;
AlertDialog.Builder dlgAlert;
ListView listView ;
TextView tv;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
tv = (TextView) findViewById(R.id.tv);
nDialog = new ProgressDialog(MainActivity.this);
//Action bar information
android.app.ActionBar mActionBar = getActionBar();
assert mActionBar != null;
mActionBar.setDisplayShowHomeEnabled(false);
mActionBar.setDisplayShowTitleEnabled(false);
LayoutInflater mInflater = LayoutInflater.from(this);
View mCustomView = mInflater.inflate(R.layout.custom_actionbar, null);
//FIX THISSSSS TO LOGOUT BUTTON
RelativeLayout settingButton = (RelativeLayout) mCustomView
.findViewById(R.id.settingButton);
settingButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
UserFunctions logout = new UserFunctions();
logout.logoutUser(getApplicationContext());
Intent startup = new Intent(getApplicationContext(), StartUp.class);
startup.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(startup);
finish();
}
});
mActionBar.setCustomView(mCustomView);
mActionBar.setDisplayShowCustomEnabled(true);
//End action bar information
}//End onCreate
private void initView() {
// show progress dialog
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
HashMap user = new HashMap();
user = db.getUserDetails();
String uid = user.get("unique_id").toString();
dialog = ProgressDialog.show(this, "", "Loading...");
String url = "www.example.com";
FetchDataTask task = new FetchDataTask(this);
task.execute(url);
}
#Override
public void onFetchComplete(List<Application> data) {
// dismiss the progress dialog
if(dialog != null) dialog.dismiss();
// create new adapter
ApplicationAdapter adapter = new ApplicationAdapter(this, data);
// set the adapter to list
setListAdapter(adapter);
}
#Override
public void onFetchFailure(String msg) {
// dismiss the progress dialog
if(dialog != null) dialog.dismiss();
// show failure message
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
}//End Activity
This is how i deal with ListView and CustomAdapter
in onCreate() of Activity
//Photos Model List
photoList = new ArrayList<Photos>();
//ListView
lvGalleryPhotos = (ListView) parentView.findViewById(R.id.lvGalleryPhotos);
//My CustomAdapter
pgAdapter = new PhotoGalleryAdapter(photoList, getSherlockActivity());
//Setting adapter to GridView
lvGalleryPhotos.setAdapter(pgAdapter);
//Parsing JSON
for(int i=0;i<10;i++){
//each result contains details about a image
JSONObject result = results.getJSONObject(i);
//Real Parsing
int width = result.getInt("width");
int height = result.getInt("height");
String title = result.getString("titleNoFormatting");
String url = result.getString("unescapedUrl");
//Make it workable so replace \u003d with =
String tbUrl = result.getString("tbUrl").replace("\u003d", "=");
//Creating photo object and inserting all collected information into it.
Photos photo = new Photos();
photo.setHeight(height);
photo.setWidth(width);
photo.setTitle(title);
photo.setURL(url);
photo.setTbUrl(tbUrl);
//Adding each Photo Object to PhotoList
photoList.add(photo);
}
//Informing that data has changed
pgAdapter.notifyDataSetChanged();
My Custom Adapter
public class PhotoGalleryAdapter extends BaseAdapter {
ImageLoader mImageLoader;
List<Photos> photoList;
Context mContext;
BlowIt blw;
LayoutInflater mLInflater;
public PhotoGalleryAdapter(List<Photos> photoList,Context mContext){
this.photoList = photoList;
this.mContext = mContext;
blw = new BlowIt(mContext);
}
#Override
public int getCount() {
return photoList.size();
}
#Override
public Object getItem(int position) {
return photoList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//Creating layout inflater
if(mLInflater==null){
mLInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
//Inflating Layout
if(convertView==null){
convertView = mLInflater.inflate(R.layout.gallery_single_photo,parent,false);
}
//Getting Object
final Photos photo = photoList.get(position);
//Single Image
NetworkImageView nivGalleryPhoto = (NetworkImageView) convertView.findViewById(R.id.nivGalleryPhoto);
TextView tvPhotoName = (TextView) convertView.findViewById(R.id.tvPhotoName);
TextView tvPhotoDesc = (TextView) convertView.findViewById(R.id.tvPhotoDesc);
final String photoDescr = photo.getHeight()+"x"+photo.getWidth();
nivGalleryPhoto.setImageUrl(photo.getTbUrl(), mImageLoader);
tvPhotoName.setText(photo.getTitle());
tvPhotoDesc.setText(photoDescr);
convertView.setTag(photo);
convertView.setId(position);
//This will trigger when ever the user clicks on a specific image
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//This will prompt automatically context menu
v.showContextMenu();
}
});
return convertView;
}
}
and the layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/llPhotosFragmentRoot"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/lvGalleryPhotos"
android:layout_height="wrap_content"
android:layout_width="match_parent"
></ListView>
</LinearLayout>
and the gallery_single_photo.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:padding="10dp"
android:layout_height="wrap_content" >
<!-- <com.android.volley.toolbox.NetworkImageView -->
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/nivGalleryPhoto"
android:layout_height="90dp"
android:scaleType="centerCrop"
android:layout_width="75dp"
android:contentDescription="#string/dummy_desc"
/>
<TextView
android:id="#+id/tvPhotoName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
android:textStyle="bold"
android:layout_alignTop="#+id/nivGalleryPhoto"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#+id/nivGalleryPhoto"
android:text="Large Text"/>
<TextView
android:id="#+id/tvPhotoDesc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/tvPhotoName"
android:layout_below="#+id/tvPhotoName"
android:text="Medium Text"
android:textSize="13sp"
android:textColor="#color/border_black" />
</RelativeLayout>
and all the above codes can make a listView with items like this
Use ViewHolder design pattern in your getView(...):
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder holder;
if(v == null) {
LayoutInflater li = LayoutInflater.from(getContext());
v = li.inflate(R.layout.app_custom_list, null);
holder = new ViewHolder();
holder.titleText = (TextView)v.findViewById(R.id.titleTxt);
v.setTag(holder);
}
else
holder = (ViewHolder) v.getTag()
Application app = items.get(position);
if(app != null) {
if(titleText != null)
holder.titleText.setText(app.getTitle());
}
return v;
}
static class ViewHolder {
TextView titleText;
}
I am working on an android application in which i have implemented CustomListView having some images and texts. i am feeding data in listview after a webservice call it takes some time to render list and when i scroll the list it's not scrolling smoothly.
here is the code of my List Adapter:
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import com.tv.makamaka.Constant;
import com.tv.makamaka.R;
import com.tv.makamaka.comment.SmileyCommentDialogActivity;
public class MakaMakaProfileListAdapter extends BaseAdapter implements Filterable {
private LayoutInflater mInflater;
private ArrayList<Object> itemList;
private Activity _activity;
String caption="";
String photoPath="";
String comments="";
String commentImage="";
String commentUserId="";
String likersImage="";
String likersType="";
String likersUserId="";
String mediaid="";
String mediaImageUrl="";
String mediaString="";
String mediaStringImage="";
String mediaStringUserId="";
String mediaType="";
String rating="";
String requestCount="";
String userid="";
String userProileImage="";
String withfriends="";
int index,index1,index2;
public MakaMakaProfileListAdapter(Activity activity, ArrayList<Object> itemList) {
this._activity = activity;
this.itemList = itemList;
mInflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return itemList.size();
}
public Object getItem(int position) {
return itemList.get(position);
}
public Filter getFilter() {
return null;
}
public long getItemId(int position) {
return 0;
}
static class ViewHolder {
TextView _commentTxt;
ImageView _userImage;
ImageView _smallUserImage;
ImageView _smallPostedUserImage;
ImageView _transparentImage;
}
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.makamaka_profile_listrow, null);
holder = new ViewHolder();
holder._userImage=(ImageView)convertView.findViewById(R.id.posted_userimage);
holder._smallUserImage=(ImageView)convertView.findViewById(R.id.small_userimage);
holder._smallPostedUserImage=(ImageView)convertView.findViewById(R.id.small_posted_userimage);
holder._transparentImage=(ImageView)convertView.findViewById(R.id.transparent_smiley_image);
holder._commentTxt = (TextView) convertView.findViewById(R.id.comment_txt);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder._commentTxt.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
}
});
holder._transparentImage.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent=new Intent(_activity,SmileyCommentDialogActivity.class);
_activity.startActivity(intent);
}
});
//////////////////SET VALUES ON LIST VIEW///////////////////////////
MakaMakaProfileBean makaMakaProfileBean=(MakaMakaProfileBean)itemList.get(position);
////////////////PARSE CAPTION///////////
caption=makaMakaProfileBean.getCaption();
ArrayList<String> captionList = new ArrayList<String>(Arrays.asList(caption.split(" , ")));
/*int index=caption.indexOf(",");
String caption1=caption.substring(0,index);
int index1=caption.indexOf(",", index+1);
String userName=caption.substring(index,index1+1);
String timeAgo=caption.substring(index1+1);*/
////////////////////////////////////////
////////////////PARSE COMMENTS////////////
comments=makaMakaProfileBean.getComments();
ArrayList<String> commentList = new ArrayList<String>(Arrays.asList(comments.split(" , ")));
//////////////////////////////////////////
////////////////PARSE COMMENT IMAGES//////
commentImage=makaMakaProfileBean.getCommentImage();
ArrayList<String> commentImageList = new ArrayList<String>(Arrays.asList(commentImage.split(" , ")));
//////////////////////////////////////////
////////////////PARSE COMMENT USER ID//////
commentUserId=makaMakaProfileBean.getCommentId();
ArrayList<String> commentUserIdList = new ArrayList<String>(Arrays.asList(commentUserId.split(" , ")));
//////////////////////////////////////////
////////////////PARSE LIKER IMAGES//////
likersImage=makaMakaProfileBean.getlikersImage();
ArrayList<String> likersImageList = new ArrayList<String>(Arrays.asList(likersImage.split(" , ")));
//////////////////////////////////////////
////////////////PARSE LIKER TYPE//////
likersType=makaMakaProfileBean.getComments();
ArrayList<String> likerTypeList = new ArrayList<String>(Arrays.asList(likersType.split(" , ")));
//////////////////////////////////////////
////////////////PARSE LIKER USER ID//////
likersUserId=makaMakaProfileBean.getComments();
ArrayList<String> likerUserIdList = new ArrayList<String>(Arrays.asList(likersUserId.split(" , ")));
//////////////////////////////////////////
////////////////PARSE OTHER PARAS//////
mediaid=makaMakaProfileBean.getmediaId();
mediaImageUrl=makaMakaProfileBean.getMediaImageUrl();
mediaString=makaMakaProfileBean.getMediaString();
mediaStringImage=makaMakaProfileBean.getMediaStringImage();
//mediaStringUserId=makaMakaProfileBean.
mediaType=makaMakaProfileBean.getMediaType();
rating=makaMakaProfileBean.getRating();
requestCount=makaMakaProfileBean.getRequestCount();
userid=makaMakaProfileBean.getUserId();
//userProileImage=makaMakaProfileBean.getUserProfileImage();
withfriends=makaMakaProfileBean.getWithFriends();
//////////////////////////////////////////
photoPath=makaMakaProfileBean.getUserProfileImage();
if(photoPath!=null){
URL url;
try {
url = new URL(photoPath);
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
holder._userImage.setImageBitmap(bmp);
} catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
int i=0;
while(i<captionList.size()){
if(i==0){
holder._commentTxt.setText((String)captionList.get(i));
}else if(i==1){
holder._commentTxt.setText(Html.fromHtml((String)captionList.get(i)));
}else if(i==2){
holder._commentTxt.setText(Html.fromHtml((String)captionList.get(i)));
}
i++;
}
return convertView;
/////////////////////////////////////////////////////////////////////
}
private Handler _handler = new Handler() {
public void dispatchMessage(Message msg) {
switch (msg.arg1) {
case 123:
break;
default:
break;
}
}
};
public void serverResponse(String response, int processid) {
Message msg = new Message();
msg.arg1 = processid;
msg.obj = response;
_handler.dispatchMessage(msg);
}
//SEND EMAIL TO INVITE FRIEND
public void sendEmail(String emailId){
Intent intent = new Intent(Intent.ACTION_SEND);
//intent.setType("text/plain");
intent.setType("message/rfc822");
intent.putExtra(Intent.EXTRA_EMAIL, emailId);
intent.putExtra(Intent.EXTRA_SUBJECT,Constant.EMAIL_SUBJECT);
intent.putExtra(Intent.EXTRA_TEXT, Constant.EMAIL_CONTENT);
_activity.startActivity(Intent.createChooser(intent, "Send Email"));
}
}
Output:
Is there any way to make list with smooth scroll.
You're decoding the image in getView. That's an expensive call, and you're going to be doing it a lot while scrolling. Use an LRUCache to cache images, so you can reuse the results of previous decodes if they exist. Only decode it in getView if its not in the cache.