2012-03-08 101 views
2

我有一个列表视图,显示从网页检索到的项目。列表视图中的每个项目都有一个facebook分享按钮,允许用户共享信息。但是,当我点击分享按钮时,显示的信息与我点击的项目不同。无论我点击哪个项目,它都会获得前几项的信息。Android - 从列表视图中的项目检索到不正确的数据

例如,点击项目#6将显示项目#2的信息。换句话说,无论我点击哪个项目,它都会显示错误的信息。我在这里做错了什么?

** listview以正确无误的方式显示项目。

MyActivity.java

public class MyActivity extends Activity { 

private static final String targetURL ="http://www.google.com/image/myself"; 
ListView list; 
private Handler mRunOnUi = new Handler(); 
private ProgressDialog mProgress; 
ProgressDialog dialog; 
private String[] mStrings = {}; 
private String[] dStrings = {}; 
private String date; 

private String messageToPost; 
Facebook facebook = new Facebook("110928043842377"); 
private SharedPreferences mPrefs; 

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.cats); 

    new TheTask().execute(); 
    list=(ListView)findViewById(R.id.list);     
} 

protected class TheTask extends AsyncTask<Void, Void, MyResultClass >{ 

    protected void onPreExecute() { 
     dialog = ProgressDialog.show(MyActivity.this, "Retrieving Information", "Please wait for a few seconds...", true, false); 
     dialog.setCancelable(true); 
    } 

    protected MyResultClass doInBackground(Void... params) { 
     searchContent(); 
     MyResultClass result = new MyResultClass(); 
     result.mStrings = mStrings; 
     result.dStrings = dStrings; 
     result.date = date; 
     return result;   
    } 

    protected void onPostExecute(MyResultClass result) {    
     dStrings = result.dStrings; 
     mStrings = result.mStrings; 
     date = result.date; 
     LazyAdapter adapter = new LazyAdapter(MyActivity.this, mStrings, dStrings); 
     list.setAdapter(adapter); 

     adapter.setTaskListener(new FBookTaskListener(){ 
      public void doAuthentication() 
      { 
        // here all your FB authentication related stuff. 

       mPrefs = getPreferences(MODE_PRIVATE); 
       String access_token = mPrefs.getString("access_token", null); 
       long expires = mPrefs.getLong("access_expires", 0); 
       if(access_token != null) { 
        facebook.setAccessToken(access_token); 
       } 
       if(expires != 0) { 
        facebook.setAccessExpires(expires); 
       } 

       /* 
       * Only call authorize if the access_token has expired. 
       */ 
       if(!facebook.isSessionValid()) { 

       facebook.authorize(Myactivity.this, new String[] { "publish_stream", "read_stream", "publish_checkins"}, new DialogListener() { 
        @Override 
        public void onComplete(Bundle values) 
        { 
         SharedPreferences.Editor editor = mPrefs.edit(); 
         editor.putString("access_token", facebook.getAccessToken()); 
         editor.putLong("access_expires", facebook.getAccessExpires()); 
         editor.commit(); 
        } 

        @Override 
        public void onFacebookError(FacebookError error) {} 

        @Override 
        public void onError(DialogError e) {} 

        @Override 
        public void onCancel() {} 
       }); 
      } 

       Log.d("Test", "Authorizing completed"); 
      } 
      public void postToWall(String data) 
      { 
       Log.d("Test", "Start of postToWall"); 
       postToFacebook(messageToPost); 
       System.out.println("postToWall complete"); 
      } 
     }); 

     dialog.dismiss(); 
    }  
} 

    class MyResultClass 
    { 
     public String[] mStrings; 
     public String[] dStrings; 
     public String date; 
    } 

    public void onActivityResult(int requestCode, int resultCode, Intent data) { 
     super.onActivityResult(requestCode, resultCode, data); 

     facebook.authorizeCallback(requestCode, resultCode, data); 
    } 

    private void postToFacebook(String message) { 

     Bundle params = new Bundle(); 

     params.putString("name", "Pinky"); 
     params.putString("caption", "google.com"); 
     params.putString("link", "http://www.google.com"); 
     params.putString("description", "Visit "); 
     params.putString("picture", data); 

     facebook.dialog(this, "feed", params, new PostDialogListener()); 

    }//close posttofacebook 

    private final class WallPostListener extends BaseRequestListener { 
     public void onComplete(final String response) { 
      mRunOnUi.post(new Runnable() { 
       @Override 
       public void run() { 
        mProgress.cancel(); 

        Toast.makeText(MyActivity.this, "Posted to Facebook", Toast.LENGTH_SHORT).show(); 
       } 
      }); 
     }//close oncomplete 
    }//close wallpostlistener 

public void searchContent() 
{ 
    String imageC = ""; 
    String textC = ""; 

    try { 

     URL url = new URL(targetURL); 

     // Make the connection 
     URLConnection conn = url.openConnection(); 
     BufferedReader reader = new BufferedReader(
     new InputStreamReader(conn.getInputStream())); 

     String line = reader.readLine(); 
     Pattern sChar = Pattern.compile("&.*?;"); 
     line.replaceAll("\\<.*?\\>", ""); 
     Matcher msChar = sChar.matcher(line); 
     while (msChar.find()) line = msChar.replaceAll(""); 

     while (line != null) { 

      if(line.contains("../../")) 
      { 

       int startIndex = line.indexOf("../../") + 6; 
       int endIndex = line.indexOf(">", startIndex + 1); 
       String abc = "http://www.google.com/image/myself"; 
       String imageSrc = line.substring(startIndex,endIndex); 
       //complete full url 
       String xyz = abc +imageSrc; 
       xyz = xyz.substring(0,xyz.indexOf('"')); 
       xyz = xyz +";"; 
       xyz = xyz.replaceAll(" ", "%20"); 
       imageC += xyz;     
       mStrings = imageC.split(";"); 
       line = reader.readLine(); 
      } 

      if(line.contains("../../") == false) 
      { 
       line = reader.readLine(); 
      } 

      if (line.contains("Gnametag")) 
      { 
       int startIndex = line.indexOf("Gnametag") + 10; 
       int endIndex = line.indexOf("<", startIndex + 1); 
       String gname = line.substring(startIndex,endIndex); 
       textC = textC.replaceAll("</span>", ""); 
       textC += "Name: "+gname+ "\n"; 
      } 


       if (line.contains("Age")) 
       { 
        textC += "Age: "+reader.readLine() + "\n" + ";"; 
        textC = textC.replaceAll("     ", ""); 
        dStrings = textC.split(";"); 
       } 

      if (line.contains("Last Update")) 
      { 
       int startIndex = line.indexOf("Last Update") + 16; 
       int endIndex = line.indexOf("</td>", startIndex + 1); 
       date = line.substring(startIndex,endIndex); 
       reader.close(); 
      }        
     }   

     // Close the reader 
     reader.close(); 

    } catch (Exception ex) { 
     ex.printStackTrace();   
    }  
}  

public class PostDialogListener extends BaseDialogListener { 
    @Override 
    public void onComplete(Bundle values) { 
     final String postId = values.getString("post_id"); 
     if (postId != null) { 
     } else { 
     } 
    } 
}  
} 

Adapter.java

public class LazyAdapter extends BaseAdapter { 
FBookTaskListener taskListener; 
Facebook facebook = new Facebook("110928043842377"); 
private Activity activity; 
private String[] data; 
private String[] text; 
private static LayoutInflater inflater=null; 
public ImageLoader imageLoader; 

private ProgressDialog mProgress; 
private Handler mRunOnUi = new Handler(); 

String FILENAME = "AndroidSSO_data"; 
private SharedPreferences mPrefs; 

public void setTaskListener(FBookTaskListener listener) 
{ 
    this.taskListener = listener; 
} 

public LazyAdapter(Activity a, String[] d, String[] t) { 
    activity = a; 
    data=d; 
    text = t; 
    inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    imageLoader=new ImageLoader(activity.getApplicationContext());   

} 

public int getCount() { 
    return data.length; 
}  

public Object getItem(int position) { 
    return position; 
} 

public long getItemId(int position) { 
    return position; 
} 

public static class ViewHolder{ 
    public TextView text; 
    public ImageView image; 
} 

public View getView(final int position, View convertView, ViewGroup parent) { 
    View vi=convertView; 
    ViewHolder holder; 
    if(convertView==null){ 
     vi = inflater.inflate(R.layout.item, null); 
     holder=new ViewHolder(); 
     holder.text=(TextView)vi.findViewById(R.id.text);; 
     holder.image=(ImageView)vi.findViewById(R.id.image); 
     vi.setTag(holder); 

     ImageButton fbBtn = (ImageButton) vi.findViewById(R.id.fb); 

     fbBtn.setOnClickListener(
       new Button.OnClickListener() { 
        public void onClick(View v) 
        { 
         taskListener.doAuthentication(); 
          taskListener.postToWall();}} 
      ); 

    } 
    else 
    holder=(ViewHolder)vi.getTag(); 

    holder.text.setText(text[position]); 
    holder.image.setTag(data[position]); 
    imageLoader.DisplayImage(data[position], activity, holder.image); 
    return vi;   
}//close getView 

public static interface FBookTaskListener{ 
    public void doAuthentication(); //paramas may be added if needed 
    public void postToWall(String data); //paramas may be added if needed 
} 

} 
+0

哪里是听众...?不能在这里看到..你应该使用** onItemSelectedListener **一些地方,张贴代码太.. – ngesh 2012-03-08 03:59:56

+0

我的facebook按钮在适配器类。使用'fbBtn.setOnClickListener' – Hend 2012-03-08 04:14:03

回答

5

这里的问题是.. ListView中..的getView( )每次生成列表的单行时被调用。

比方说,你的屏幕一次可以显示4个项目(1-4)(在滚动中休息)。当您向下滚动时,项目2-5将显示,并且row5再次调用getView()。

你在这里遇到的麻烦是,你的onclick听众属于说第5项。将被分配到屏幕上的row2-5 ..我解决了类似的问题在我的情况下使用view.setTag()在适配器和单个onclick监听器,我检索视图的标记。并根据行执行我的onclick任务(由标记对象标识)。

按照这种方法,你将能够解决的任务然后..如果有任何进一步的疑问..post它的一些细节,如 - 我havin小律麻烦识别你的onclick听众如何工作..如何区分ROWS in/onclick事件..实际上那些行是什么..

+0

我想我已经有了'view.setTag(holder)'在我的适配器中。所以我在适配器中的onClick事件中添加了'v.getTag()'行。 – Hend 2012-03-12 02:30:38

+0

不同的行在这里对应什么......?什么不同的行动ntaskListenereed发生每行...从您的代码即时看到每个图像按钮在每一行.. FB认证和张贴到墙壁被称为... – 2012-03-12 04:41:36

+0

来标识在听众中的行,你需要有,...'taskListener.doAuthentication(vi);'并将调用修改为'doAuthentication(View v)',其中u可以通过在v.getTag()方法内部识别行... – 2012-03-12 04:43:15

1

让我们检查两个以下方法,这是奇怪的:

public Object getItem(int position) { 
    return position; 
} 

public long getItemId(int position) { 
    return position; 
} 
+0

我不确定它,但至少这是正确显示列表视图项目。 – Hend 2012-03-09 12:54:27

相关问题