0

我制作了一个gridview,我试图在该网格中添加下一个功能。当有人单击“下一步”时,网格会加载新的一堆图像。

我制定了一个逻辑,不知何故它正在工作,但它并不稳定。应用程序有时会停止,有时单击“下一步”会跳过下一页(假设当前我在第 0 页,当我单击“下一个”时,网格会刷新并且显示第 2 页而不是第 1 页)

我正在做的是我做了一个异步任务,它将 http 请求发送到 php 服务器以获取新的图像 url。然后我刷新 gridview 并显示来自新图像 url 的新图像。

代码

public class UserPage extends Activity {


ImageAdapter ia = new ImageAdapter(this);
GetResponse task = new GetResponse(0);
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.userpage);

    final GridView gridview = (GridView) findViewById(R.id.gridview);

    gridview.setAdapter(ia);
    gridview.setStretchMode(GridView.STRETCH_COLUMN_WIDTH);

    Button nxt = (Button) findViewById(R.id.nextbuttongrid);
    nxt.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // next page
            int i = Integer.parseInt(GetResponse.counter);
            i=i+1;
            GetResponse.counter = Integer.toString(i);
            String x = GetResponse.response;
            task.execute();
        //this is done so that the thread sleeps until the response variable value is updated  
            while(x.equals(GetResponse.response)==true){
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    System.out.println("Here in sleep..incre");
                } }
            change(gridview);
        }
    });

    Button pre = (Button) findViewById(R.id.previousbuttongrid);
    pre.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // previous page
            int i = Integer.parseInt(GetResponse.counter);
            i=i-1;
            GetResponse.counter = Integer.toString(i);
            String x = GetResponse.response;
            task.execute();
           //this is done so that the thread sleeps until the response variable value is updated  
            while(x.equals(GetResponse.response)==true){
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                System.out.println("Here in sleep.. decre");
            } }
            change(gridview);

        }
    });

    /**
     * On Click event for Single Gridview Item
     * */
     gridview.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View v,
                int position, long id) {

            // Sending image id to FullImage.java
            Intent i = new Intent(getApplicationContext(), FullImage.class);
            i.putExtra("id", position);
            startActivity(i);
        }
    });
}

void change(GridView gridview) {
    ia = new ImageAdapter(this);
    gridview.invalidateViews();
    gridview.setAdapter(ia);
}
}
public class GetResponse extends AsyncTask<Void, Void, Void> {

  public static String counter = "0";

  HttpPost httppost;
  StringBuffer buffer;
  HttpResponse response1;
  HttpClient httpclient;
  List<NameValuePair> nameValuePairs;

  public static String response;


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

try {
    Log.d("response's Value == >", "Response previous " + response);
    httpclient=new DefaultHttpClient();
    httppost= new HttpPost(ServerAdressHere); 
    //add your data
    nameValuePairs = new ArrayList<NameValuePair>(3);

    nameValuePairs.add(new BasicNameValuePair("username",AndroidPHPConnectionDemo.userName)); 
    nameValuePairs.add(new BasicNameValuePair("password",AndroidPHPConnectionDemo.passWord));
    nameValuePairs.add(new BasicNameValuePair("count",counter));
    Log.d("Counter's Value == >", "Counter " + counter);
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    //Execute HTTP Post Request
    response1=httpclient.execute(httppost);
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    response = httpclient.execute(httppost, responseHandler);
    Log.d("response's Value == >", "Response after " + response);
}
    catch(Exception e){
        System.out.println("Exception Here"+e);
    }
  return null;

    }
   }
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private TextView txtUrl;
private String response;
public ImageView imageView;
public static String[] mThumbIds;

  public ImageAdapter(Context c) {
    mContext = c;
    this.response = GetResponse.response.trim();
    mThumbIds = response.split(",");
    }

private final Downloader imageDownloader = new Downloader(mContext);


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

public Object getItem(int position) {
    return mThumbIds[position];
}

public long getItemId(int position) {
    return mThumbIds[position].hashCode();
}

// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {

    if(convertView==null) {
        imageView = new ImageView(mContext);
        imageView.setLayoutParams(new GridView.LayoutParams(LayoutParams.MATCH_PARENT, 195));
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setPadding(10, 10, 10, 10);
    }

    else {
         imageView = (ImageView) convertView;
         }

    imageDownloader.DisplayImage(mThumbIds[position], (ImageView) imageView);

    return imageView;
}

public Downloader getImageDownloader() {
    return imageDownloader;
}
}

“计数器”变量(静态和字符串类型)在请求中发送,它将下一个 gridview 的页码告诉 php 服务器。因此,服务器将发送与该页码相关的图像 url。

我面临的问题是网格在异步任务类更新“响应”变量之前被刷新。所以这就是为什么我使用 System.sleep() 来获得两行代码的时间间隔 b/w 执行。

“响应”变量(静态和整数类型)包含图像 url。

请帮忙 !如果需要更多细节,请询问。

4

1 回答 1

0

首先,onClick 方法中的循环中的 Thread.sleep 不是这样做的正确方法。asynctask 的重点是避免锁定主线程,而 Thread.sleep 就是这样做的。

请改用您的 asynctask 的 onPostExecute 。

但是,到目前为止,这显然有效(您的服务器和连接足够快,否则您会遇到 ANR),即使您的 ui 可能会冻结几秒钟。

在那之后,还有图像下载的问题。调用 setAdapter(new Adapter...) 似乎是一个足够好的方法。

一步一步调试你走了多远?

  • 您是否收到在线的图像 ID 列表Log.d("response's Value == >", "Response after " + response);
  • 您是否到达 getView,如果是,您是否使用正确的 url/id/string 到达那里,无论 mThumbIds[position] 应该是什么?
  • 如果是这样,什么是下载器,它是如何工作的?

出于好奇,你为什么要执行两次请求?( response1=httpclient.execute(httppost);)

编辑

我真的不敢相信你没有,尽管提到你的应用程序实际上正在崩溃很有趣,这与“网格没有刷新”完全不同。

你必须

A/ 阅读你的堆栈跟踪。

B/如果不清楚,谷歌它。

C/我不知道还能添加什么(a task can be executed only once)

于 2013-04-08T16:18:48.413 回答