Change the layout of listview in custom array adapter - android

I am learning custom array adapter and i want to do something like if the listview row view is 0(the first row of the listview), i want to have a seperate layout, after that i want another comoon layout for the rest of the list. I have the custom adapter but don't quiet fully understand , how can it be done?. Thank you.
public class NewsFragment extends Fragment{
private ProgressDialog pDialog;// Progress Dialog
ListView newsList;
ArrayList<HashMap<String, String>> postList; //Declare Array
private static String url = "http://wangeltmg.com/GKN_ADMIN/GET_POSTS/get_news.php";
GetNews.CustomAdapter CA;
// JSON Node names
private static final String TAG_ID = "id";
private static final String POST_ALLPOSTS = "posts";
private static final String POST_ID = "ID";
private static final String POST_TITLE = "post_title";
private static final String POST_CONTENT = "post_content";
private static final String GUID = "guid";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.news, container, false);
newsList = (ListView) view.findViewById(R.id.newsListView);
TextView topic = (TextView) view.findViewById(R.id.topic);
postList = new ArrayList<HashMap<String, String>>();
//Get arguments
Bundle args = getArguments();
String mytopic = args.getString("Topic");
//Set topic
topic.setText(mytopic.toUpperCase());
//Execute getContacts
new GetNews().execute();
newsList.setOnItemClickListener(new newsListClick());
return view;
}
public class newsListClick implements ListView.OnItemClickListener{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("News List","Clicked " + id);
android.support.v4.app.FragmentManager fragmentManager = getFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
SinglePost singleFrag = new SinglePost();
fragmentTransaction.replace(R.id.content_frame, singleFrag);
fragmentTransaction.commit();
}
}
//Async Task
private class GetNews extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Strings","Checking Json");
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// contacts JSONArray
JSONArray posts = null;
// Getting JSON Array node
posts = jsonObj.getJSONArray(POST_ALLPOSTS);
// looping through All Contacts
for (int i = 0; i < posts.length(); i++) {
JSONObject c = posts.getJSONObject(i);
Log.d("Post->",posts.getJSONObject(i).toString());
String id = c.getString(POST_ID);
Log.d("Post->ID",id);
String post_title = c.getString(POST_TITLE);
String post_content = c.getString(POST_CONTENT);
String guid = c.getString(GUID);
Log.d("GUID->",guid);
//String gender = c.getString(TAG_GENDER);
// tmp hashmap for single post
HashMap<String, String> post = new HashMap<String, String>();
// adding each child node to HashMap key => value
post.put(POST_ID, id);
post.put(POST_TITLE, post_title);
post.put(POST_CONTENT, post_content);
post.put(GUID, guid);
// adding contact to contact list
postList.add(post);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
public void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
// Updating parsed JSON data into ListView
/*
ListAdapter adapter = new SimpleAdapter(getActivity(), postList, R.layout.list_item,
new String[] { POST_TITLE,POST_CONTENT, GUID },
new int[] {R.id.email, R.id.mobile, R.id.guid });
*/
CA = new CustomAdapter( getActivity(), R.layout.list_item, postList);
newsList.setAdapter(CA);
}
public class CustomAdapter extends ArrayAdapter<HashMap<String, String>>{
private final ArrayList<HashMap<String, String>> objects;
public CustomAdapter(Context context, int resource, ArrayList<HashMap<String, String>> objects) {
//something is wrong with super
super(context, resource, objects);
this.objects = objects;
}
public View getView(int position, View convertView, ViewGroup Parent){
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item,null);
}
TextView thisview = (TextView) convertView.findViewById(R.id.email);
String getListPos = String.valueOf(newsList.getFirstVisiblePosition());
if(getListPos == "0"){
thisview.setText(getListPos);
}else{
thisview.setText(objects.get(position).get(POST_TITLE));
}
//thisview.setText(getListPos);
return convertView;
}
}//
}
}

Can use getItemViewType to specify types of views list view can have.
Here is some sample example.

Try something like below:
public View getView(int position, View convertView, ViewGroup Parent){
if(position==0){
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.first_row_layout,null);
}
TextView thisview = (TextView) convertView.findViewById(R.id.email);
String getListPos = String.valueOf(newsList.getFirstVisiblePosition());
if(getListPos == "0"){
thisview.setText(getListPos);
}else{
thisview.setText(objects.get(position).get(POST_TITLE));
}
}else{
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.otherlayout_view,null);
}
TextView thisview = (TextView) convertView.findViewById(R.id.email);
String getListPos = String.valueOf(newsList.getFirstVisiblePosition());
if(getListPos == "0"){
thisview.setText(getListPos);
}else{
thisview.setText(objects.get(position).get(POST_TITLE));
}
}
//thisview.setText(getListPos);
return convertView;
}

I did something like this guys, is it right way to do it? It does the thing i want.
public View getView(int position, View convertView, ViewGroup Parent){
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item,null);
}
TextView thisview = (TextView) convertView.findViewById(R.id.email);
int getListPos = newsList.getFirstVisiblePosition();
//i set the count starting 0 and saved in the hashmap array
//to compare the first result with the first position of listview
int count = Integer.parseInt(objects.get(position).get("ListCount"));
if(getListPos == count) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item_header,null);
TextView HeaderText = (TextView) convertView.findViewById(R.id.headertext);
TextView HeaderContent = (TextView) convertView.findViewById(R.id.headercontent);
HeaderText.setText(objects.get(position).get(POST_TITLE));
HeaderContent.setText(objects.get(position).get(POST_CONTENT));
}else{
thisview.setText("Normal line");
}
return convertView;
}

Related

Whole listview gets duplicated

I've a listview which shows values from web service. Its fine when it loads the listview. But when I click on any item to open a new fragment (which shows details of the item) and get back to the same listview, its items doubles everytime. For example, if I have (in original) 5 items in total. Then when I get back from the fragment, the total count will be 10, then 15 and so on. It means the app is adding all items again and again. I searched for the solution and did what were the general solution like adapter.notifyDataSetChanged() but its still gets duplicated. If anyone can show me the problem, I would be grateful.
public class CustomListAdapter extends ArrayAdapter<Model> {
private Context mContext;
int resource;
private ArrayList<Model> mListData = new ArrayList<Model>();
public CustomListAdapter(Context mContext, int resource, ArrayList<Model> mListData) {
super(mContext, resource, mListData);
this.resource = resource;
this.mContext = mContext;
this.mListData = mListData;
}
public void setListData(ArrayList<Model> mListData) {
this.mListData = mListData;
notifyDataSetChanged();
}
#Override
public int getCount() {
return super.getCount();
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
View v = convertView;
final ViewHolder holder;
if (v == null) {
holder = new ViewHolder();
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
v = inflater.inflate(resource, parent, false);
holder.custname = (TextView) v.findViewById(R.id.cust_name);
holder.date = (TextView) v.findViewById(R.id.date);
holder.staffname = (TextView) v.findViewById(R.id.staff_name);
holder.time = (TextView) v.findViewById(R.id.time);
holder.service = (TextView) v.findViewById(R.id.service);
holder.refid = (TextView) v.findViewById(R.id.refid);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
final Model item = mListData.get(position);
holder.custname.setText(item.getCustname());
holder.date.setText(item.getDate());
holder.staffname.setText(item.getStaffname());
holder.time.setText(item.getTime());
holder.service.setText(item.getService());
holder.refid.setText(item.getRefid());
return v;
}
class ViewHolder {
TextView custname, date, staffname, time, service, refid;
}
}
public class ListFrag extends Fragment{
private SwipeMenuListView listView;
private CustomListAdapter adapter;
private CShowProgress cShowProgress;
private SQLiteHandler db;
private String uid, bookingId;
private ArrayList<Model> arrayList = new ArrayList<>();
private static final String BOOKED_LIST = "http://192.168.220.13/android/showbookinglist";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.listfrag, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
listView = (SwipeMenuListView)view.findViewById(R.id.list);
db = new SQLiteHandler(getActivity());
cShowProgress = CShowProgress.getInstance();
fetchDetails();
adapter = new CustomListAdapter(getActivity(), R.layout.listitem, arrayList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String a = arrayList.get(i).getCustname();
String b = arrayList.get(i).getStaffname();
String c = arrayList.get(i).getService();
String d = arrayList.get(i).getDate();
String e = arrayList.get(i).getTime();
String f = arrayList.get(i).getRefid();
String g = arrayList.get(i).getEmail();
String h = arrayList.get(i).getServprice();
String j = arrayList.get(i).getSpeclprice();
String k = arrayList.get(i).getStatus();
db.addDetails(a, b, c, d, e, f, g, h, j, k);
DetailsView details = new DetailsView();
((Bookings)getActivity()).replaceFragment(details);
}
});
}
private void fetchDetails() {
cShowProgress.showProgress(getActivity());
StringRequest stringRequest = new StringRequest(Request.Method.POST, BOOKED_LIST,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
cShowProgress.hideProgress();
try {
JSONArray jsonArray = new JSONArray(response);
for(int i=0; i<jsonArray.length(); i++){
JSONObject obj = jsonArray.getJSONObject(i);
Model model = new Model();
model.setCustname(obj.getString("customername"));
model.setDate(obj.getString("staffdate"));
model.setStaffname(obj.getString("staffname")+"(Staff)");
model.setTime(obj.getString("stafftime"));
model.setService(obj.getString("servicename"));
model.setRefid(obj.getString("booking_referenceid"));
model.setEmail(obj.getString("customeremail"));
model.setServprice(obj.getString("serviceprice"));
model.setSpeclprice(obj.getString("specialprice"));
model.setStatus(obj.getString("status"));
model.setBookid(obj.getString("bookingid"));
arrayList.add(model);
}
adapter.notifyDataSetChanged();
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getActivity(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "VolleyError" + error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("spaid", "145");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
}
try to change it as.. B'coz you are adding the elements in previously created list.. So you have to clear it.
private void fetchDetails() {
if(arrayList!=null )arrayList.clear(); // this line
cShowProgress.showProgress(getActivity());
The thing is that when you get back to the fragment it is recreated and onViewCreated is called again. From there you call again fetchDetails() and then your are adding the whole List for a second time to the adapter. So you can clear the list before fetchDetails() or just if you have to fetch them again.
change your try - catch block of onResponse method by below.
try {
JSONArray jsonArray = new JSONArray(response);
arrayList = new ArrayList<>();
for(int i=0; i<jsonArray.length(); i++)
{
JSONObject obj = jsonArray.getJSONObject(i);
Model model = new Model();
model.setCustname(obj.getString("customername"));
model.setDate(obj.getString("staffdate"));
model.setStaffname(obj.getString("staffname")+"(Staff)");
model.setTime(obj.getString("stafftime"));
model.setService(obj.getString("servicename"));
model.setRefid(obj.getString("booking_referenceid"));
model.setEmail(obj.getString("customeremail"));
model.setServprice(obj.getString("serviceprice"));
model.setSpeclprice(obj.getString("specialprice"));
model.setStatus(obj.getString("status"));
model.setBookid(obj.getString("bookingid"));
arrayList.add(model);
}
adapter.notifyDataSetChanged();
This is happening because you are not clearing the arrayList. Due to this every time that you construct the array and the adapter, you are adding the elements into an array that already has elements.
That why you have 5, then 10, then 15 and so on..
Clear the array before adding new elements
arrayList.clear();
Or program another strategy like:
Not populate the array every time you return to the fragment.
Check if he element existe before add it into the array.

Android List view with clickable button

Hi guys I am implementing a listview with a clickable button through this tutorial -> https://www.youtube.com/watch?v=ZEEYYvVwJGY
and I want to achieve the same output.
But I have a slight problem, since my list view is populated from mysql database but in the tutorial is not populated from mysql database so we have a different adapter.
Codes in the tutorial
public class MainActivity extends AppCompatActivity{
private ArrayList<String> data = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_attendance);
ListView lv = (ListView) findViewById(R.id.listview);
lv.setAdapter(new MyListAdapter(this, R.layout.list_item, data));
}
}
Then lets assume that this is the tutorials MyListAdapter
private class MyListAdapter extends ArrayAdapter<String>{
private int layout;
public MyListAdapter(Context context, int resource, List<String> objects) {
super(context, resource, objects);
layout = resource;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder mainViewHolder = null;
if (convertView == null){
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(layout, parent, false);
ViewHolder viewHolder = new ViewHolder();
viewHolder.tvid = (TextView) convertView.findViewById(R.id.studId);
viewHolder.tvname = (TextView) convertView.findViewById(R.id.studName);
viewHolder.btnP = (Button) convertView.findViewById(R.id.present);
viewHolder.btnA = (Button) convertView.findViewById(R.id.absent);
viewHolder.btnP.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(),"Button Clicked " + position, Toast.LENGTH_LONG).show();
}
});
convertView.setTag(viewHolder);
}
return convertView;
}
}
and my problem is in this part
the setAdapter
mylistView = (ListView) findViewById(R.id.list);
final ListAdapter adapter = new SimpleAdapter(Attendance.this,
studentList, R.layout.list_att, new String[]{
TAG_ID, TAG_NAME}, new int[]{
R.id.studId, R.id.studName});
mylistView.setAdapter(adapter);
what should I do? any help would be appreciated thanks in advance :)
this is my code
public class Attendance extends AppCompatActivity {
TextView Date;;
ListView mylistView;
private ArrayList<HashMap<String, String>> studentList = new ArrayList<HashMap<String, String>>();
TextView Name;
private static String url = "http://10.0.2.2/MobileClassRecord/getStudent.php";
private static final String TAG_STUDENTS = "students";
private static final String TAG_ID = "stud_id";
private static final String TAG_NAME = "stud_name";
JSONArray students = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_attendance);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Date = (TextView) findViewById(R.id.tvDate);
final Calendar calendar = Calendar.getInstance();
int dd = calendar.get(Calendar.DAY_OF_MONTH);
int mm = calendar.get(Calendar.MONTH);
int yy = calendar.get(Calendar.YEAR);
Date.setText(new StringBuilder().append(yy).append("-").append(mm + 1).append("-").append(dd));
new JSONParse().execute();
studentList = new ArrayList<HashMap<String, String>>();
}
private class JSONParse extends AsyncTask<String, String, JSONObject>{
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
Name =(TextView) findViewById(R.id.studName);
pDialog = new ProgressDialog(Attendance.this);
pDialog.setMessage("Getting Data from Database...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... params) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
pDialog.dismiss();
try {
students = jsonObject.getJSONArray(TAG_STUDENTS);
for (int i = 0; i < students.length(); i++){
JSONObject c =students.getJSONObject(i);
final String Id = c.getString(TAG_ID);
String Name = c.getString(TAG_NAME);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ID, Id);
map.put(TAG_NAME, Name);
studentList.add(map);
mylistView = (ListView) findViewById(R.id.list);
final ListAdapter adapter = new SimpleAdapter(Attendance.this,
studentList, R.layout.list_att, new String[]{
TAG_ID, TAG_NAME}, new int[]{
R.id.studId, R.id.studName});
mylistView.setAdapter(adapter);
mylistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String ID = ((TextView) (view.findViewById(R.id.studId))).getText().toString();
Toast.makeText(Attendance.this, "List Clicked " + ID, Toast.LENGTH_LONG).show();
SharedPreferences preferences = getSharedPreferences("MyApp", MODE_PRIVATE);
preferences.edit().putString("id", ID).commit();
}
});
}
}catch (JSONException e){
e.printStackTrace();
}
}
}
private class MyListAdapter extends ArrayAdapter<String>{
private int layout;
public MyListAdapter(Context context, int resource, List<String> objects) {
super(context, resource, objects);
layout = resource;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder mainViewHolder = null;
if (convertView == null){
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(layout, parent, false);
ViewHolder viewHolder = new ViewHolder();
viewHolder.tvid = (TextView) convertView.findViewById(R.id.studId);
viewHolder.tvname = (TextView) convertView.findViewById(R.id.studName);
viewHolder.btnP = (Button) convertView.findViewById(R.id.present);
viewHolder.btnA = (Button) convertView.findViewById(R.id.absent);
viewHolder.btnP.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(),"Button Clicked " + position, Toast.LENGTH_LONG).show();
}
});
convertView.setTag(viewHolder);
}
mainViewHolder = (ViewHolder) convertView.getTag();
mainViewHolder.tvid.setText(getItem(position));
return convertView;
}
}
public class ViewHolder{
TextView tvid, tvname;
Button btnP, btnA;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_attendance, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
Intent intent = new Intent(Attendance.this, SpecificClassRecord.class);
startActivity(intent);
return true;
case R.id.action_view_attendance:
Intent intent1 = new Intent(Attendance.this, ViewAttendance.class);
startActivity(intent1);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Sample Layout
like Udi said, more information would be nice.
One strange thing in your code is in the getView() method.
you have
if(convertView==null){
...
}else{
...
}
I think the else part is wrong. Just remove the else and the brackets (not the code insight of it).
The code in the else part is important, because without it the code will not change the TextView when the View is loaded for the first time. This mean, that your getView will do nothing
EDIT
The author has changed the code. You have now two different adapters there...
In my opinion the getView() Method should look like this
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder mainViewHolder = null;
if (convertView == null){
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(layout, parent, false);
ViewHolder viewHolder = new ViewHolder();
viewHolder.tvid = (TextView) convertView.findViewById(R.id.studId);
viewHolder.tvname = (TextView) convertView.findViewById(R.id.studName);
viewHolder.btnP = (Button) convertView.findViewById(R.id.present);
viewHolder.btnA = (Button) convertView.findViewById(R.id.absent);
viewHolder.btnP.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(),"Button Clicked " + position, Toast.LENGTH_LONG).show();
}
});
convertView.setTag(viewHolder);
}
mainViewHolder = (ViewHolder) convertView.getTag();
mainViewHolder.tvid.setText(getItem(position));
return convertView;
}
}
But for me it is still not clear where exactly the problem is. Is the App crashing or is there just a behavior you don't understand? If yes, what exactly?
If the App is crashing, when exactly?
EDIT 2:
mylistView = (ListView) findViewById(R.id.list);
final ListAdapter adapter = new MyListAdapter(Attendance.this,
R.layout.list_att, new String[]{
TAG_ID, TAG_NAME});
mylistView.setAdapter(adapter);
maybe this is all. I assume the layout of your rows is given by the layoutressource R.layout.list_att and that TAG_ID and TAG_Name are defined somewhere before.
I see your new Adapter needs a List of Strings. Insert the following before you set the adapter
List<String> test = new ArrayList<String>();
test.add("1");
test.add("2"):
test.add("3");
and then your adapter should look like this
final ListAdapter adapter = new MyListAdapter(Attendance.this,
R.layout.list_att, test);

How to fetch the image using JSON in ListFragment?

I am new to android development,I am parsing my data using JSON Parsing method,I extend my class with List Fragment and I want my data in list view but the problem is i am getting all the data perfectly except the images,i don't know how to solve it,my response looks like this
{"matching":[{"name":"Monic Dano","profile_id":"GM335695","image":"http://mywebsitename.com/images/Girlnoimage.jpg","cast":"","age":"24","location":"Ivory Coast"}]}
public class HomeFragment extends ListFragment {
//CustomAdapter adapter;
//private List<RowItem> rowItems;
private ProgressDialog pDialog;
//JSON parser class
JSONParser jsonParser = new JSONParser();
JSONArray matching=null;
ArrayList<HashMap<String,String>> aList;
private static String MATCH_URL = null;
private static final String TAG_MATCH="matching";
private static final String TAG_NAME="name";
private static final String TAG_PROFILE="profile_id";
private static final String TAG_IMAGE="image";
private static final String TAG_CAST="cast";
private static final String TAG_AGE="age";
private static final String TAG_LOCATION="location";
private ListView listview;
public HomeFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("user_login_id");
MATCH_URL = "http://mywebsitename.com/webservice/matching?version=apps&user_login_id="+strtext;
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
aList = new ArrayList<HashMap<String,String>>();
// rowItems = new ArrayList<RowItem>();
listview=(ListView)rootView.findViewById(android.R.id.list);
new LoadAlbums().execute();
return rootView;
}
class LoadAlbums extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(HomeFragment.this.getActivity());
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(MATCH_URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
matching = jsonObj.getJSONArray(TAG_MATCH);
// looping through All Contacts
for (int i = 0; i < matching.length(); i++) {
JSONObject c = matching.getJSONObject(i);
// Storing each json item values in variable
String user_name = c.getString(TAG_NAME);
String user_profile=c.getString(TAG_PROFILE);
String user_image=c.getString(TAG_IMAGE);
String user_cast=c.getString(TAG_CAST);
String user_age=c.getString(TAG_AGE);
String user_location=c.getString(TAG_LOCATION);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_NAME,user_name);
map.put(TAG_PROFILE, user_profile);
map.put(TAG_IMAGE, user_image);
map.put(TAG_CAST, user_cast);
map.put(TAG_AGE, user_age+" years");
map.put(TAG_LOCATION, user_location);
// adding HashList to ArrayList
aList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
protected void onPostExecute(String file_url) {
super.onPostExecute(file_url);
// dismiss the dialog after getting all albums
if (pDialog.isShowing())
pDialog.dismiss();
// updating UI from Background Thread
/**
* Updating parsed JSON data into ListView
* */
// updating listview
CustomAdapter adapter = new CustomAdapter(getActivity(),aList);
setListAdapter(adapter);
}
}
}
Try to AndroidQuery with custom adapter :
public class CustomAdapter extends BaseAdapter {
private Context context;
private ArrayList<HashMap<String,String>> listData;
private AQuery aQuery;
private static final String TAG_NAME="name";
private static final String TAG_PROFILE="profile_id";
private static final String TAG_IMAGE="image";
private static final String TAG_CAST="cast";
private static final String TAG_AGE="age";
private static final String TAG_LOCATION="location";
public CustomAdapter(Context context,ArrayList<HashMap<String,String>> listData) {
this.context = context;
this.listData=listData;
aQuery = new AQuery(this.context);
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.list_item, null);
holder.propic = (ImageView) convertView.findViewById(R.id.propic);
holder.txtproname = (TextView) convertView.findViewById(R.id.txtproname);
holder.txtproid = (TextView) convertView.findViewById(R.id.txtproid);
holder.txtprofilecast = (TextView) convertView.findViewById(R.id.txtprofilecast);
holder.txtprofileage = (TextView) convertView.findViewById(R.id.txtprofileage);
holder.txtprofileplace = (TextView) convertView.findViewById(R.id.txtprofileplace);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.txtproname.setText(listData.get(position).get(TAG_NAME));
holder.txtproid.setText(listData.get(position).get(TAG_PROFILE));
holder.txtprofilecast.setText(listData.get(position).get(TAG_CAST));
holder.txtprofileage.setText(listData.get(position).get(TAG_AGE));
holder.txtprofileplace.setText(listData.get(position).get(TAG_LOCATION));
aQuery.id(holder.propic).image(listData.get(position).get(TAG_IMAGE),true,true,0,R.drawable.ic_launcher);
// image parameter : 1 : memory cache,2:file cache,3:target width,4:fallback image
return convertView;
}
class ViewHolder{
ImageView propic;
TextView txtproname;
TextView txtproid;
TextView txtprofilecast;
TextView txtprofileage;
TextView txtprofileplace;
}
}
How to set adapter to ListView :
CustomAdapter adapter = new CustomAdapter(getActivity(),aList);
setListAdapter(adapter);
You can use universal image loader for viewing images from your server.Z
Just pass the image url and your view and you are good to go.
For your reference here is the link to Universal Image loader with all its documentation.
https://github.com/nostra13/Android-Universal-Image-Loader
Hop it helps you.
I am hardly suggest you to use Android Query for this. Its mind blowing api given by Android itself. You can download image, download bitmap or whatever you wanna do you can.
You can download the jar file from here :here Download the jar file and set jar to your Build Path.
AQuery androidAQuery=new AQuery(this);
As an example to load image directly from url:
androidAQuery.id(YOUR IMAGEVIEW).image(YOUR IMAGE TO LOAD, true, true, getDeviceWidth(), ANY DEFAULT IMAGE YOU WANT TO SHOW);
As an example to get Bitmap from url:
androidAQuery.ajax(YOUR IMAGE URL,Bitmap.class,0,new AjaxCallback<Bitmap>(){
#Override
public void callback(String url, Bitmap object, AjaxStatus status) {
super.callback(url, object, status);
//You will get Bitmap from object.
}
});
It's very fast and accurate, and using this you can find many more features like Animation when loading; getting a bitmap, if needed; etc.
//Declare adapter globally.
private EfficientAdapter adapter;
//Initialize it in onCreate() method
adapter = new EfficientAdapter(this);
//Set your adapter like
listview.setAdapter(adapter);
//Adapter class code
private class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private Context context;
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
this.context = context;
}
#Override
public int getCount() {
return aList.size();
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.YOUR ITEM LAYOUT, null);
holder = new ViewHolder();
holder.txtName = (TextView) convertView.findViewById(R.id.txtName);
holder.txtProfile = (TextView) convertView.findViewById(R.id.txtProfile);
holder.txtCast = (TextView) convertView.findViewById(R.id.txtCast);
holder.txtAge = (ImageView) convertView.findViewById(R.id.txtAge);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtName.setText(aList.get(position).get(TAG_NAME));
holder.txtProfile.setText(aList.get(position).get(TAG_PROFILE));
holder.txtCast.setText(aList.get(position).get(TAG_CAST));
holder.txtAge.setText(aList.get(position).get(TAG_AGE));
aQuery.id(holder.imgUser).image(data.get(position).get(TAG_IMAGE), true, true);
return convertView;
}
class ViewHolder {
TextView txtName;
TextView txtProfile;
TextView txtCast;
TextView txtAge;
ImageView imgUser;
}
}
In source code of SimpleAdapter:
private void bindView(int position, View view) {
final Map dataSet = mData.get(position);
if (dataSet == null) {
return;
}
final ViewBinder binder = mViewBinder;
final String[] from = mFrom;
final int[] to = mTo;
final int count = to.length;
for (int i = 0; i < count; i++) {
final View v = view.findViewById(to[i]);
if (v != null) {
final Object data = dataSet.get(from[i]);
String text = data == null ? "" : data.toString();
if (text == null) {
text = "";
}
boolean bound = false;
if (binder != null) {
bound = binder.setViewValue(v, data, text);
}
if (!bound) {
if (v instanceof Checkable) {
if (data instanceof Boolean) {
((Checkable) v).setChecked((Boolean) data);
} else if (v instanceof TextView) {
// Note: keep the instanceof TextView check at the bottom of these
// ifs since a lot of views are TextViews (e.g. CheckBoxes).
setViewText((TextView) v, text);
} else {
throw new IllegalStateException(v.getClass().getName() +
" should be bound to a Boolean, not a " +
(data == null ? "<unknown type>" : data.getClass()));
}
} else if (v instanceof TextView) {
// Note: keep the instanceof TextView check at the bottom of these
// ifs since a lot of views are TextViews (e.g. CheckBoxes).
setViewText((TextView) v, text);
} else if (v instanceof ImageView) {
if (data instanceof Integer) {
setViewImage((ImageView) v, (Integer) data);
} else {
setViewImage((ImageView) v, text);
}
} else {
throw new IllegalStateException(v.getClass().getName() + " is not a " +
" view that can be bounds by this SimpleAdapter");
}
}
}
}
}
You can see if your view is ImageView , the code will use the url String be the resId in
/**
* Called by bindView() to set the image for an ImageView but only if
* there is no existing ViewBinder or if the existing ViewBinder cannot
* handle binding to an ImageView.
*
* By default, the value will be treated as an image resource. If the
* value cannot be used as an image resource, the value is used as an
* image Uri.
*
* This method is called instead of {#link #setViewImage(ImageView, int)}
* if the supplied data is not an int or Integer.
*
* #param v ImageView to receive an image
* #param value the value retrieved from the data set
*
* #see #setViewImage(ImageView, int)
*/
public void setViewImage(ImageView v, String value) {
try {
v.setImageResource(Integer.parseInt(value));
} catch (NumberFormatException nfe) {
v.setImageURI(Uri.parse(value));
}
}
And your error is here , so you need Override the getView function of SimpleAdapter.Here is code:
Uri uri = Uri.parse("http://gujjumatch.com/images/Girlnoimage.jpg");
image.setImageURI(uri);
You need to create adapter and extend it to BaseAdapter and add all your items and call it in your AsyncTask's method and it will return your output as said by Haresh Chellana.

Restarting Asynctask in fragment after using replace transaction

I am using AsyncTask in my fragment for loading a list of data by Json. After clicking each list items this list fragment is replaced by details fragment containing details information. Then in new fragment (details fragment) user presses back button. Then again list fragment starts.
The problem is that Asynctask reloads again to fetch list items. I don't want this. I want to show previously loaded list. Here is the code:
public class MainList extends Fragment {
public MainList(){}
ArrayList<Country> countryList = new ArrayList<Country>();
Country country;
Button btnLoadMore;
ListView listView;
JSONParser jsonParser = new JSONParser();
public static String received_id;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
int current_page = 0;
int last_item;
int total_items = 32;
boolean continue_loading = true;
boolean loadingMore = false;
View footerView;
public ImageLoader_Json imageLoader;
int currentPosition = 0;
MyCustomAdapter dataAdapter = null;
private static String url_all_products_LoadMore = "http://www.hitel.ir/FarsiPlanet/Apps.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_RATE = "rate";
private static final String TAG_RATINGCOUNT = "ratingcount";
private static final String TAG_SHORT_DESCRIPTION = "short_description";
// products JSONArray
JSONArray products = null;
String Category;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.items_list, container, false);
Category = getArguments().getString("category");
footerView= ((LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.loading_footer, null,false);
listView = (ListView) rootView.findViewById(R.id.listView1);
listView.addFooterView(footerView);
imageLoader = new ImageLoader_Json(getActivity().getApplicationContext());
displayListView();
return rootView;
}
private void displayListView() {
//create an ArrayAdaptar from the String Array
dataAdapter = new MyCustomAdapter(getActivity(),
R.layout.country_info, countryList);
listView.setOnScrollListener(new OnScrollListener() {
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
}
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
int lastInScreen = firstVisibleItem + visibleItemCount;
if((lastInScreen == totalItemCount) && !(loadingMore)){
new loadMoreListView().execute();
}
}
});
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
final String pid = ((TextView) view.findViewById(R.id.pid)).getText().toString();
Bundle data = new Bundle();
data.putString(TAG_PID, pid);
data.putString("TAG_Category", Category);
Fragment fragment = new Details_Restaurant();
FragmentManager fm = getFragmentManager();
fragment.setArguments(data);
fm.beginTransaction().replace(R.id.frame_container, fragment).addToBackStack("f_02").commit();
}
});
listView.setAdapter(dataAdapter);
listView.setSelectionFromTop(currentPosition, 0);
}
private class MyCustomAdapter extends ArrayAdapter<Country> {
private ArrayList<Country> countryList;
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<Country> countryList) {
super(context, textViewResourceId, countryList);
this.countryList = new ArrayList<Country>();
this.countryList.addAll(countryList);
}
private class ViewHolder {
TextView code;
TextView name;
RatingBar rate;
TextView ratingcount;
TextView short_description;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
LayoutInflater vi = (LayoutInflater)getActivity().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.country_info, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.ratingcount = (TextView) convertView.findViewById(R.id.ratingCount);
holder.short_description = (TextView) convertView.findViewById(R.id.short_description);
holder.rate = (RatingBar) convertView.findViewById(R.id.ratingBar1);
holder.code = (TextView) convertView.findViewById(R.id.pid);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final Country country = countryList.get(position);
holder.name.setText(country.getName());
holder.ratingcount.setText(country.getRatingCount());
holder.short_description.setText(country.getShort_description());
holder.rate.setRating(country.getRate());
holder.code.setText(country.getCode());
return convertView;
}
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getActivity().getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
class loadMoreListView extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
/*
pDialog = new ProgressDialog(AllProductsActivity.this);
pDialog.setMessage("درحال دريافت اطلاعات...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show(); */
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
String firts_item = Integer.toString(current_page*10);
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("pid", firts_item));
params.add(new BasicNameValuePair("category", Category));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_all_products_LoadMore, "GET", params);
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
Float rate = (float) c.getInt(TAG_RATE);
String ratingcount = c.getString(TAG_RATINGCOUNT);
String short_description = c.getString(TAG_SHORT_DESCRIPTION);
country = new Country(id,name,rate,ratingcount,short_description,"","");
countryList.add(country);
}
}
else{
continue_loading = false;
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
current_page += 1;
if (continue_loading) {
currentPosition = listView.getFirstVisiblePosition();
dataAdapter.notifyDataSetChanged();
displayListView();
loadingMore = false;
} else {
listView.removeFooterView(footerView);
}
}
}
}
Here you need to include #Override before calling onScrollStateChanged and onScroll
listView.setOnScrollListener(new OnScrollListener() {
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
}
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
int lastInScreen = firstVisibleItem + visibleItemCount;
if((lastInScreen == totalItemCount) && !(loadingMore)){
new loadMoreListView().execute();
}
}
});
when you perform the replace() action on the fragment, you are removing the list fragment , thus when tapping back, you are replacing the details fragment with your listfragment which invokes onCreateView() as part of the fragments lifecycle.
I would try to either keep a static booelan set to true when the asynctask's onPostExecute() ends, so the next time the list fragment's onCreateView() will be invoked , you would check the value of the flag and if set to true will not execute the task, but just set the adapter with the old static data.

Listadapter duplicating items in listview after each time asynctask starts

I have a listview in fragment. It loads data from Json. After clicking list items a fragment transaction begins (replace). By pressing back button (in new fragment) again list fragment appears but the problem is that:
1: It loads again Asynctask (that I don't want it).
2. It adds new items on top of the former items in the list. You can say duplication in listview items happens. Each time I click listview item abd then return back to listview fragment it adds the same items to the end of the list. My code is this:
public class Followed extends Fragment {
public Followed(){}
ArrayList<Country> countryList = new ArrayList<Country>();
Country country;
ListView listView;
JSONParser jsonParser = new JSONParser();
public static String received_id;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
MyCustomAdapter dataAdapter = null;
ProgressDialog pDialog;
int success;
private static String url_all_followed = "http://www.hitel.ir/FarsiPlanet/Followed.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_RATE = "rate";
private static final String TAG_RATINGCOUNT = "ratingcount";
private static final String TAG_SHORT_DESCRIPTION = "short_description";
// products JSONArray
JSONArray products = null;
String Category;
String username;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.items_list, container, false);
loadSavedPreferences();
listView = (ListView) rootView.findViewById(R.id.listView1);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
final String pid = ((TextView) view.findViewById(R.id.pid)).getText().toString();
Bundle data = new Bundle();
data.putString(TAG_PID, pid);
data.putString("TAG_Category", "restaurant");
Fragment fragment = new Details_Restaurant();
FragmentManager fm = getFragmentManager();
fragment.setArguments(data);
fm.beginTransaction().replace(R.id.frame_container, fragment).addToBackStack("f_02asda").commit();
}
});
new loadMoreListView().execute();
return rootView;
}
private class MyCustomAdapter extends ArrayAdapter<Country> {
private ArrayList<Country> countryList;
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<Country> countryList) {
super(context, textViewResourceId, countryList);
this.countryList = new ArrayList<Country>();
this.countryList.addAll(countryList);
}
private class ViewHolder {
TextView code;
TextView name;
RatingBar rate;
TextView ratingcount;
TextView short_description;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
LayoutInflater vi = (LayoutInflater)getActivity().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.country_info, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.ratingcount = (TextView) convertView.findViewById(R.id.ratingCount);
holder.short_description = (TextView) convertView.findViewById(R.id.short_description);
holder.rate = (RatingBar) convertView.findViewById(R.id.ratingBar1);
holder.code = (TextView) convertView.findViewById(R.id.pid);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final Country country = countryList.get(position);
holder.name.setText(country.getName());
holder.ratingcount.setText(country.getRatingCount());
holder.short_description.setText(country.getShort_description());
holder.rate.setRating(country.getRate());
holder.code.setText(country.getCode());
return convertView;
}
}
class loadMoreListView extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("درحال دريافت اطلاعات...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", "sajad"));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_all_followed, "GET", params);
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
Float rate = (float) c.getInt(TAG_RATE);
String ratingcount = c.getString(TAG_RATINGCOUNT);
String short_description = c.getString(TAG_SHORT_DESCRIPTION);
country = new Country(id,name,rate,ratingcount,short_description,"","");
countryList.add(country);
}
}
else{
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
if (success == 0) {
Toast.makeText(getActivity(), "هیچ موردی یافت نشد!", Toast.LENGTH_SHORT).show();
}
pDialog.dismiss();
dataAdapter = new MyCustomAdapter(getActivity(),
R.layout.country_info, countryList);
listView.setAdapter(dataAdapter);
}
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getActivity().getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
private void loadSavedPreferences() {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(getActivity());
username = sharedPreferences.getString("username", "");
}
}
Alright. Found duplication problem. I just cleared adapter after clicking list items.
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
final String pid = ((TextView) view.findViewById(R.id.pid)).getText().toString();
Bundle data = new Bundle();
data.putString(TAG_PID, pid);
data.putString("TAG_Category", "restaurant");
Fragment fragment = new Details_Restaurant();
FragmentManager fm = getFragmentManager();
fragment.setArguments(data);
fm.beginTransaction().replace(R.id.frame_container, fragment).addToBackStack("f_02asda").commit();
dataAdapter.clear();
}
});

Categories

Resources