1

我正在开发一个需要在列表视图上显示数据的应用程序。要在列表视图上显示的数据需要经常更新,所以我创建了一个同步适配器,它将触发我来自 gcm 的广播消息。当发生这种情况时,我的 AsyncTask loader.onContentChanged 被调用,它调用 loadinbackground 方法,所有这些都正常工作。我遇到的问题是在列表视图上显示新数据而不重新启动活动。我正试图让它像 facebook 新闻提要列表视图一样工作。

请帮我

我的代码如下

同步适配器

@Override
public void onPerformSync(Account account, Bundle extras, String authority,
        ContentProviderClient provider, SyncResult syncResult) {
    // TODO Auto-generated method stub
    Log.d(TAG, "onPerformSync for account[" + account.name + "]");
    String theValue = mAccountManager.getUserData(account, "User_ID");
    mContentResolver = mContext.getContentResolver();
    final RoomListLoader mLoader = new RoomListLoader(mContext, theValue);
    mLoader.onContentChanged();


}

装载机

  public class RoomListLoader extends AsyncTaskLoader<List<RoomList>> {
 private static String url = "********************";
 int success;
 private static final String TAG_SUCCESS = "success";
 private static final String TAG_ROOMS = "room";
String room_id = null, roomTitle, created_at, user_id, room_ids,
        clickedOnRoomId, retrievedRoomId, username;
String room_title, reward, numOfComments, filePath;
JSONParser jsonParser = new JSONParser();
JSONObject json;
JSONArray rooms = null;
JSONArray ids = null;
int i = 0, c = 0, tryme = 0, tryme2 = 0;
int co = 0, counterOnGetRooms = 0;
RoomList details;
public static List<RoomList> mRoomList = new ArrayList<RoomList>();

Context mContext;
//private final Handler observerHandler;

public RoomListLoader(Context context,String nuser_id) {
    super(context);
    // TODO Auto-generated constructor stub
    //mRoomList = nRoomList;
    this.user_id = nuser_id; 

    this.mContext = context;
    //observerHandler = new Handler();
}

@Override
public List<RoomList> loadInBackground() {
    // TODO Auto-generated method stub
    mRoomList.clear();
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("user_id", user_id));

    json = jsonParser.makeHttpRequest(url, "POST", params);
    // final Context context = getContext();

    try {
        success = json.getInt(TAG_SUCCESS);
        if (success == 1) {

            rooms = json.getJSONArray(TAG_ROOMS);
            // counter = json.getInt("counter");
            counterOnGetRooms = json.getInt("count");
            Log.d("counterOnGetRooms", "" + counterOnGetRooms);
            // Log.v("counter", "" + counter);

            for (int i = 0; i < rooms.length(); i++) {
                tryme2++;
                JSONObject c = rooms.getJSONObject(i);
                // get room titles
                roomTitle = c.getString("room_title");
                retrievedRoomId = c.getString("room_id");
                created_at = c.getString("created_at");
                username = c.getString("username");
                numOfComments = c.getString("counters");
                filePath = c.getString("filePath");
                Log.i("filePath", filePath);
                details = new RoomList(retrievedRoomId, roomTitle,
                        created_at, username, numOfComments, filePath);
                mRoomList.add(details);
            }
        }
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    //MostRecentRooms Room;

    //deliverResult(mRoomList);
    return mRoomList;
}

@Override
public void onContentChanged() {
    // TODO Auto-generated method stub
    super.onContentChanged();
    loadInBackground();

    //deliverResult(mRoomList);

}

@Override
public void onCanceled(List<RoomList> data) {
    // TODO Auto-generated method stub
    super.onCanceled(data);
}

@Override
public void deliverResult(List<RoomList> data) {
    // TODO Auto-generated method stub
    Log.d("Deliver Result",""+data.size());
    super.deliverResult(data);

}


@Override
protected void onReset() {
    // TODO Auto-generated method stub
    super.onReset();
    onStopLoading();
}



@Override
protected void onStartLoading() {
    // TODO Auto-generated method stub
    if (mRoomList != null) {
        //deliverResult(mRoomList);
    }
    super.onStartLoading();
}

@Override
protected void onStopLoading() {
    // TODO Auto-generated method stub
    cancelLoad();
}



}

活动

public class MostRecentRooms extends ListActivity implements   LoaderManager.LoaderCallbacks<List<RoomList>> {

// progress dialog
ProgressDialog pDialog;
// json parser object
JSONParser jsonParser = new JSONParser();
int decrement = 0;
int success;
int s = 0;
Activity mActivity;

// url to view most recent rooms
private static String url = "************8";
// url to load more rooms
private static String url3 = "***************";
// url to check status of user
private static String url2 = "*****************";
// url to get profile images
private static String url4 = "****************88";

private static final String TAG_SUCCESS = "success";
private static final String TAG_ROOMS = "room";
int Loader_ID =0x3;
int counter = 0;

HashMap<String, String> map;
public static List<RoomList> mRoomList = new ArrayList<RoomList>(); 
RoomList details;
ListAdapter adapter;
public static RoomListAdapter mAdapter;
public static LoaderManager mLoadManager;

// json arrays
JSONArray rooms = null;
JSONArray ids = null;
int i = 0, c = 0, tryme = 0, tryme2 = 0;
int co = 0, counterOnGetRooms = 0;
// Array list to hold room titles
ArrayList<HashMap<String, String>> allRooms;
// ArrayList<String> allRooms;

// List view to show room titles of an arraylist
public ListView lv;
// json Object
JSONObject json;
int limit = 20;

// strings
String room_id = null, roomTitle, created_at, user_id, room_ids,
        clickedOnRoomId, retrievedRoomId, username;
String room_title, reward, numOfComments, filePath;

// buttons
Button back, loadMore, refresh;

Bitmap img_bitmap;



@Override
protected void onResume() {
    // TODO Auto-generated method stub
     super.onResume();
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);

}


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_most_recent_rooms);
    mLoadManager = getLoaderManager();
    mAdapter = new RoomListAdapter(this, getApplicationContext());
    lv= getListView();
    lv.setAdapter(mAdapter);



    // back button
    back = (Button) findViewById(R.id.backToMainMenu);
    back.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            finish();
        }
    });
    // end back button

    // get user id from View rooms class
    if (getIntent().getExtras().getString("user_id_value") != null)
        user_id = getIntent().getExtras().getString("user_id_value");
    else
        Log.e("Error", "Missing user_id");




    mLoadManager.initLoader(Loader_ID,null,MostRecentRooms.this);

    //allRooms = new ArrayList<HashMap<String, String>>();
    // allRooms = new ArrayList<String>();

    // call class GetAllRooms
    //new GetAllRooms().execute();

    // get room_id
    if (getIntent().getExtras().getString("room_id_to_send") != null)
        room_id = getIntent().getExtras().getString("room_id_to_send");
    else
        Log.e("Error", "Missing room id");

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

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            //new LoadMoreRooms().execute();
            // counter -= 5;
        }
    });
    refresh = (Button) findViewById(R.id.refresh);
    refresh.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            mRoomList.clear();
            allRooms.clear();
            limit = 20;
            tryme = 0;
            img_bitmap.recycle();
            //new GetAllRooms().execute();
        }
    });

}




/**
 * This class get users status whether deleted or not
 */

class GetUserStatus extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... args) {
        // TODO Auto-generated method stub
        backGroundProcess(user_id);
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        Log.e("i is", "" + i);
        if (i == 2) {
            // decativatedPage();
            Toast.makeText(getApplicationContext(), "noooo",
                    Toast.LENGTH_SHORT).show();
        } else {
            Intent i = new Intent(getApplicationContext(), RoomPage.class);
            i.putExtra("room_id_to_send", clickedOnRoomId);
            i.putExtra("user_id_value", user_id);
            startActivity(i);
        }
    }

}// end class

private void backGroundProcess(String string) {
    // build parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("user_id", string));

    json = jsonParser.makeHttpRequest(url2, "POST", params);
    int success;
    try {
        success = json.getInt("success");
        if (success == 1) {
            i = 1;
            Log.i("status", json.getString("message").toString());
        } else if (success == 2) {
            i = 2;
        } else {
            Log.d("Error", "Something went wrong");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

@Override
public Loader<List<RoomList>> onCreateLoader(int id, Bundle args) {
    // TODO Auto-generated method stub
    Log.d("Tsg", "here");
    RoomListLoader mRoomloader = new RoomListLoader(getApplicationContext(), user_id);
    mRoomloader.forceLoad();
    return mRoomloader ;
}

@Override
public void onLoadFinished(Loader<List<RoomList>> arg0, List<RoomList> data) {
    // TODO Auto-generated method stub
    Log.i("tag","list loaded");
    if(data != null){
        mAdapter.SetData(data);
        mAdapter.notifyDataSetChanged();
    }
    //mAdapter.SetData(data);
    Log.i("Tag",""+data.size());
    //lv.setAdapter(mAdapter);

}

@Override
public void onLoaderReset(Loader<List<RoomList>> arg0) {
    // TODO Auto-generated method stub
    Log.d("Loader", "Loader Reset");
    mAdapter.SetData(null);

}


 }

适配器

public class RoomListAdapter extends ArrayAdapter<RoomList> {
ImageLoader imageLoader = null;
private Activity activity;
String TAG = "RoomListAdapter";
private final LayoutInflater mInflator;
List<RoomList> nRoomList;

public RoomListAdapter(Activity a, Context context) {
    // TODO Auto-generated constructor stub
    super(context, R.layout.viewroom_layout);
    activity = a;
    mInflator = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    imageLoader = new ImageLoader(a.getApplicationContext());
    //nRoomList = mRoomList;
    //SetData(nRoomList);
}

public void SetData(List<RoomList> data) {
    clear();
    if (data != null) {
        addAll(data);

    }
}



@Override
public void notifyDataSetChanged() {
    // TODO Auto-generated method stub
    super.notifyDataSetChanged();

}

@Override
public void setNotifyOnChange(boolean notifyOnChange) {
    // TODO Auto-generated method stub
    super.setNotifyOnChange(notifyOnChange);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    View vi;
    if (convertView == null) {
        vi = mInflator.inflate(R.layout.viewroom_layout, null);
    } else {
        vi = convertView;
    }

    TextView room_id = (TextView) vi.findViewById(R.id.roomsIDHidden);
    TextView room_title = (TextView) vi.findViewById(R.id.roomsName);
    TextView created_at = (TextView) vi.findViewById(R.id.createdTime);
    TextView username = (TextView) vi.findViewById(R.id.creatorName);
    TextView numOfComments = (TextView) vi.findViewById(R.id.numComments);
    ImageView image = (ImageView) vi.findViewById(R.id.userPic);
    //Log.d(TAG, "Within the room list adapter");
    RoomList info = getItem(position);
    room_id.setText(info.getmRoom_id());
    room_title.setText(info.getmRoomTitle());
    created_at.setText(info.getmCreated_at());
    username.setText(info.getmUsername());
    numOfComments.setText(info.getmNumberOfComments());
    imageLoader.DisplayImage(info.getmFilePath(), image);

    return vi;

}




}
4

2 回答 2

1

在 venkat 和 monica 的帮助下,我解决了它不需要 Syncadpter 我所需要的只是一个广播接收器,我这样做了 1)当 GCM 接收到消息时创建广播意图

Intent intent1 = new Intent();   
        intent1.setAction("com.gcm.updatecame"); 
        this.sendBroadcast(intent1); 

2)在我的活动中我注册接收器并创建类

filter1= new IntentFilter("com.gcm.updatecame");
    registerReceiver(myReceiver, filter1);

广播接收器

  private BroadcastReceiver myReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

        // write your code here to update the listview.
        if(mLoadManager != null){

            Reload.setVisibility(View.VISIBLE);
            Reload.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    mLoadManager.destroyLoader(Loader_ID);
                    mAdapter.notifyDataSetChanged();
                    mAdapter.SetData(null);
                    mRoomList.clear();
                    mLoadManager.initLoader(Loader_ID, null, MostRecentRooms.this);
                    Reload.setVisibility(View.INVISIBLE);

                }
            });
        }


    }

};  
于 2013-10-21T05:49:25.583 回答
0

用这个替换你的 onLoadFinished 方法:

@Override
public void onLoadFinished(Loader<List<RoomList>> arg0, List<RoomList> data) {
if(data != null){
    mAdapter = new RoomListAdapter(this, getApplicationContext());
    mAdapter.SetData(data);
    lv.setAdapter(mAdapter);
}

}

于 2013-10-21T03:18:18.813 回答