android helper android helper - 6 months ago 15
Java Question

How to avoid repeated listview litems in Android?

Here is my some Item repeated, so what should i do to avoid it?
here is Tipster_adapter.java class.

import java.util.ArrayList;

// Import goes here

public class Tipster_adapter extends BaseAdapter {
Context context;
ArrayList<Tipster_list>tipslist;

public Tipster_adapter(Context context, ArrayList<Tipster_list> tipslist) {
super();
this.context = context;
this.tipslist = tipslist;
}

@Override
public int getCount() {
// TODO Auto-generated method stub
return tipslist.size();
}

@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}

@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null){

LayoutInflater inflater=(LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
convertView=inflater.inflate(R.layout.activity_tipster_adapter,null);
ImageView icon=(ImageView)convertView.findViewById(R.id.icon_tipsterIconID);
TextView name=(TextView) convertView.findViewById(R.id.txt_name_tipsterID);
TextView total=(TextView) convertView.findViewById(R.id.txt_total_tipsterID);
final TextView proofingLink=(TextView) convertView.findViewById(R.id.txt_proofinglink_tipsterID);
proofingLink.setFocusable(true);
//proofingLink.setOnClickListener(this);
proofingLink.requestFocus();

TextView siteLink=(TextView) convertView.findViewById(R.id.txt_sitelink_tipsterID);

Tipster_list services=tipslist.get(position);
Picasso.with(context).load(services.getImage()).into(icon);
Log.d("Url",services.getImage());
name.setText(services.getName());
total.setText(services.getTotal());
//proofingLink.setText(services.getProofinglink());
//siteLink.setText(services.getSitelink());


convertView.setTag(position);
final String getproofing=services.getProofinglink();
final String getsite=services.getSitelink();
proofingLink.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context, Tipster_webview.class);
intent.putExtra("gettproofing_URl",getproofing);
context.startActivity(intent);
//Toast.makeText(context, "proofing...", Toast.LENGTH_SHORT).show();

}
});
proofingLink.setOnTouchListener(new View.OnTouchListener() {

@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub

switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
((TextView)v).setTextColor(Color.parseColor("#A2B4BA")); //dark
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
((TextView)v).setTextColor(Color.parseColor("#219BCC")); //Light-blue
break;
}


return false;
}
});

siteLink.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context, Tipster_webview.class);
intent.putExtra("site",getsite);
context.startActivity(intent);
}
});

siteLink.setOnTouchListener(new View.OnTouchListener() {

@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub

switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
((TextView)v).setTextColor(Color.parseColor("#A2B4BA")); //dark
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
((TextView)v).setTextColor(Color.parseColor("#219BCC")); //Light-blue
break;
}


return false;
}
});

}
return convertView;
}

}


And here is XML

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout_mainID"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="tipster.Tipster_adapter" >

<ImageView
android:id="@+id/icon_tipsterIconID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" />

<LinearLayout
android:id="@+id/llot1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:orientation="vertical" >

<TextView
android:id="@+id/txt_name_tipsterID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/str_text11" />

<TextView
android:id="@+id/txt_total_tipsterID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />

<TextView
android:id="@+id/txt_proofinglink_tipsterID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="View Proofing"
android:textColor="#219BCC"
android:textColorLink="#6D7578" />

<TextView
android:id="@+id/txt_sitelink_tipsterID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get More Detail"
android:textColor="#219BCC" />

</LinearLayout>




please anyone help me what i am missing in my code? or what i should do to avoid repeating item in listview

Here is my list_adapter.java

package tipster;

public class Tipster_list {
private String image;
private String name;
private String total;
private String proofinglink;
private String sitelink;

public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTotal() {
return total;
}
public void setTotal(String total) {
this.total = total;
}
public String getProofinglink() {
return proofinglink;
}
public void setProofinglink(String proofinglink) {
this.proofinglink = proofinglink;
}
public String getSitelink() {
return sitelink;
}
public void setSitelink(String sitelink) {
this.sitelink = sitelink;
}
public Tipster_list(String image, String name, String total,
String proofinglink, String sitelink) {
super();
this.image = image;
this.name = name;
this.total = total;
this.proofinglink = proofinglink;
this.sitelink = sitelink;
}


}


here is my tipster.java class

public class Tipster extends Activity {
ListView lv;
ArrayList<Tipster_list>listitem;
String title;
String serviceUrl;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tipster);

if (isNetworkAvailable()) {
execute();

title="Free Tip - Betfans";

lv=(ListView) findViewById(R.id.listView_tipsterID);

listitem=new ArrayList<Tipster_list>();
}

else {
// Error message here if network is unavailable.
Toast.makeText(this, "Network is unavailable!", Toast.LENGTH_LONG).show();
}

}

private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();

boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}

private void execute() {

serviceUrl ="http://union.com/api/?action=top&type=default&key=MEu07MgghiuWgXwJOo7Oe1aHL0yM8VvP";

class LoginAsync extends AsyncTask<String, Void, String>{

private Dialog loadingDialog;

@Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(Tipster.this, "Please while wait", "Loading...");
}

@Override
protected String doInBackground(String... params) {

JSONObject jsonObject = new JSONObject();

String dataString = jsonObject.toString();

InputStream is = null;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("data", dataString));

String result = null;

try{

HttpClient httpClient = new DefaultHttpClient();
HttpGet httpRequest = new HttpGet();

URI apiurl = new URI(serviceUrl);

httpRequest.setURI(apiurl);

HttpResponse response = httpClient.execute(httpRequest);

HttpEntity entity = response.getEntity();

is = entity.getContent();

BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();

String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}

protected void onPostExecute(String result){
String s = result.trim();

loadingDialog.dismiss();

JSONObject respObject;
try {
respObject = new JSONObject(s);
String active = respObject.getString("status_message");

//boolean status = respObject.getBoolean("status_message");

if(active.equalsIgnoreCase("success")){
JSONArray array = respObject.getJSONArray("response");
for (int i =0; i<array.length();i++){

JSONObject jsonObject = array.getJSONObject(i);
String icon= jsonObject.getString("image");
String name = jsonObject.getString("name");
String total = jsonObject.getString("total");
String proofinglink = jsonObject.getString("proofinglink");
String sitelink = jsonObject.getString("sitelink");

listitem.add(new Tipster_list(icon,name,"+"+total,proofinglink,sitelink));

}
lv.setAdapter(new Tipster_adapter(Tipster.this, listitem));

}else {
Toast.makeText(Tipster.this, "tipster received Fail", Toast.LENGTH_LONG).show();

}


} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

LoginAsync la = new LoginAsync();
la.execute();

}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.tipster, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

Answer

The best way is to use a ViewHolder:

private class ViewHolder {
    public ImageView icon;
    public TextView name;
    public TextView total;
    public TextView proofingLink;
    public TextView siteLink;
}   

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;

    if(convertView==null){
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.activity_tipster_adapter,null);
        holder = new ViewHolder();
        holder.icon = (ImageView) convertView.findViewById(R.id.icon_tipsterIconID);
        holder.name = (TextView) convertView.findViewById(R.id.txt_name_tipsterID);
        holder.total = (TextView) convertView.findViewById(R.id.txt_total_tipsterID);
        holder.proofingLink = (TextView) convertView.findViewById(R.id.txt_proofinglink_tipsterID);
        holder.proofingLink.setFocusable(true);
        holder.proofingLink.requestFocus();
        holder.siteLink = (TextView) convertView.findViewById(R.id.txt_sitelink_tipsterID);
        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    Tipster_list services=tipslist.get(position);
    Picasso.with(context).load(services.getImage()).into(holder.icon);
    Log.d("Url",services.getImage());
    holder.name.setText(services.getName());
    holder.total.setText(services.getTotal());

    final String getproofing=services.getProofinglink();
    final String getsite=services.getSitelink();
    holder.proofingLink.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(context, Tipster_webview.class);
             intent.putExtra("gettproofing_URl",getproofing);
            context.startActivity(intent);
            //Toast.makeText(context, "proofing...", Toast.LENGTH_SHORT).show();

        }
    });
    holder.proofingLink.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // TODO Auto-generated method stub

            switch(event.getAction()){            
            case MotionEvent.ACTION_DOWN:
            ((TextView)v).setTextColor(Color.parseColor("#A2B4BA")); //dark
                break;          
            case MotionEvent.ACTION_CANCEL:             
            case MotionEvent.ACTION_UP:
            ((TextView)v).setTextColor(Color.parseColor("#219BCC")); //Light-blue
                break;
            } 
            return false;
        }
    });

    holder.siteLink.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        Intent intent = new Intent(context, Tipster_webview.class);
                         intent.putExtra("site",getsite);
                        context.startActivity(intent);
                    }
                });

    holder.siteLink.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // TODO Auto-generated method stub

            switch(event.getAction()){            
            case MotionEvent.ACTION_DOWN:
            ((TextView)v).setTextColor(Color.parseColor("#A2B4BA")); //dark
                break;          
            case MotionEvent.ACTION_CANCEL:             
            case MotionEvent.ACTION_UP:
            ((TextView)v).setTextColor(Color.parseColor("#219BCC")); //Light-blue
                break;
            } 
            return false;
        }
    });

    }
    return convertView;
}