Setting AppWidget's title using data encoded as JSON - android

I'm working with json. I parsed the JSON and I can show my JSON (images and text) on ListView. Now I want to show JSON's first item's title in my widget.
I successfully created the widget but I have a problem with the JSON's first item's title.
This is a my code:
public class AppWidget extends AppWidgetProvider {
public static String CLOCK_WIDGET_UPDATE = "CLOCK_WIDGET_UPDATE";
RemoteViews views;
int appWidgetId;
#Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (CLOCK_WIDGET_UPDATE.equals(intent.getAction())) {
Toast.makeText(context, "onReceiver()", Toast.LENGTH_LONG).show();
}
}
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
final int N = appWidgetIds.length;
for (int i = 0; i < N; i++) {
appWidgetId = appWidgetIds[i];
Intent intent = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
intent, 0);
views = new RemoteViews(context.getPackageName(),
R.layout.widget_demo);
String aa = (MainActivity.itemList.get(0)
.get(MainActivity.KEY_title)).toString();
views.setOnClickPendingIntent(R.id.widgetPic, pendingIntent);
views.setOnClickPendingIntent(R.id.widgetTitle, pendingIntent);
views.setOnClickPendingIntent(R.id.widgetDesc, pendingIntent);
views.setTextViewText(R.id.widgetDesc, aa);
views.setImageViewBitmap(
R.id.widgetPic,
((BitmapDrawable) context.getResources().getDrawable(
R.drawable.background)).getBitmap());
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
public void updateAppWidget(Context context,
AppWidgetManager appWidgetManager, int appWidgetId) {
RemoteViews updateViews = new RemoteViews(context.getPackageName(),
R.layout.widget_demo);
try {
} catch (Exception e) {
}
appWidgetManager.updateAppWidget(appWidgetId, updateViews);
}
}
BaseAdapter.java code:
public class MyAdapter extends BaseAdapter {
Context mContext;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;
private int screenSize;
public MyAdapter(Context context, ArrayList<HashMap<String, String>> d,
int screenSize) {
this.mContext = context;
this.data = d;
this.screenSize = screenSize;
inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(context.getApplicationContext());
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.list_row, null);
TextView journal = (TextView) vi.findViewById(R.id.smalljournal);
TextView title = (TextView) vi.findViewById(R.id.smalltitle);
TextView description = (TextView) vi
.findViewById(R.id.smallDescription);
ImageView thumb_image = (ImageView) vi.findViewById(R.id.smallthumb);
TextView statId = (TextView) vi.findViewById(R.id.smallstatID);
TextView DateTime = (TextView) vi.findViewById(R.id.smallDateTime);
HashMap<String, String> itemList = new HashMap<String, String>();
itemList = data.get(position);
journal.setText(itemList.get(MainActivity.KEY_journal));
statId.setText(itemList.get(MainActivity.KEY_statID));
journal.setTypeface(MainActivity.tf2);
String titleString = itemList.get(MainActivity.KEY_title);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
// coming date : 2014-02-03T18:45:00
String DateTimeTxt = itemList.get(MainActivity.KEY_pubDate).replace(
"T", " ");
// DateTimeTxt = date;
try {
Date _d = df.parse(DateTimeTxt);
SimpleDateFormat new_df = new SimpleDateFormat("dd.MM.yyyy");
String _s = new_df.format(_d);
DateTime.setText(_s);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (screenSize == Configuration.SCREENLAYOUT_SIZE_NORMAL)
description.setVisibility(View.INVISIBLE);
else
description.setVisibility(View.VISIBLE);
title.setText(titleString);
title.setTypeface(MainActivity.tf2);
description.setText(itemList.get(MainActivity.KEY_description));
description.setTypeface(MainActivity.tf2);
String url = itemList.get(MainActivity.KEY_image);
// url = url.replace("-c.jpg", ".jpg");
imageLoader.DisplayImage(url, thumb_image);
return vi;
}
}
MainActivity.java code
public class MainActivity extends Activity {
public String URL = "********************";
public static String KEY_title = "title";
public static String KEY_description = "description";
public static String KEY_image = "image";
public static String KEY_journal = "journal";
public static String KEY_JournalID = "JournalID";
public static String KEY_pubDate = "pubDate";
public static String KEY_statID = "statID";
public JSONArray jsonarray;
public ListView list;
public JSONParser jsonparser;
static MyAdapter adapter;
ProgressDialog pDialog, pDialog1;
static String fontPath2 = "font.ttf";
public static Typeface tf2;
public static ArrayList<HashMap<String, String>> itemList = new ArrayList<HashMap<String, String>>();
public ImageLoader imageLoader;
static final int DIALOG_ERROR_CONNECTION = 1;
public static String dateTime;
private ArrayList<Content> contents = new ArrayList<Content>();
public ImageView image;
public EditText searchInput;
public LinearLayout mainLayout, SlideLayout;
public TransparentProgressDialog pd;
public Tools tools;
public static boolean CheckListview = true;
private int screenSize;
int windowWidth;
public LoadDataAllChanelsToServer loadData;
public TextView journal, tittle, description, smalllink, DateTime,
smallstatID;
private ConnectionDetector cd;
AlertDialogManager alert = new AlertDialogManager();
Writer writer;
public File yourFile;
View menu_Slide;
#SuppressLint("CutPasteId")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
screenSize = getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK;
SlideLayout = (LinearLayout) findViewById(R.id.SlideLayout);
list = (ListView) findViewById(R.id.listView1);
cd = new ConnectionDetector(getApplicationContext());
adapter = new MyAdapter(MainActivity.this, itemList, screenSize);
Thread.setDefaultUncaughtExceptionHandler(new UnCaughtException(this,
this));
loadData = new LoadDataAllChanelsToServer();
menu_Slide = (findViewById(R.id.menu_button));
image = (ImageView) findViewById(R.id.imageView1);
searchInput = (EditText) findViewById(R.id.input_search_query);
tf2 = Typeface.createFromAsset(getAssets(), fontPath2);
pd = new TransparentProgressDialog(this, R.drawable.loader);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
journal = (TextView) view.findViewById(R.id.smalljournal);
tittle = (TextView) view.findViewById(R.id.smalltitle);
description = (TextView) view
.findViewById(R.id.smallDescription);
smalllink = (TextView) view.findViewById(R.id.smalllink);
DateTime = (TextView) view.findViewById(R.id.smallDateTime);
smallstatID = (TextView) view.findViewById(R.id.smallstatID);
String Stringjournal = journal.getText().toString();
String Stringtittle = tittle.getText().toString();
String Stringdescription = description.getText().toString();
String Stringlink = smalllink.getText().toString();
String StringdateTime = DateTime.getText().toString();
String StringstatID = smallstatID.getText().toString();
HideKeyBoadr();
Intent in = new Intent(MainActivity.this, Result.class);
in.putExtra("KEY_journal", Stringjournal);
in.putExtra("KEY_title", Stringtittle);
in.putExtra("KEY_description", Stringdescription);
in.putExtra("KEY_link", Stringlink);
in.putExtra("KEY_pubDate", StringdateTime);
in.putExtra("KEY_statID", StringstatID);
String url = itemList.get(position).get(MainActivity.KEY_image);
if (!cd.isConnectingToInternet()) {
in.putExtra("Bitmap", url);
}
else {
if (url.endsWith("-c.jpg"))
url = url.replace("-c.jpg", ".jpg");
in.putExtra("Bitmap", url);
}
in.putExtra("Bitmap", url);
startActivity(in);
overridePendingTransition(R.anim.trans_left_in,
R.anim.trans_left_out);
}
});
if (!cd.isConnectingToInternet()) {
return;
} else {
loadData.execute();
}
}
public void HideKeyBoadr() {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(searchInput.getWindowToken(), 0);
}
private class LoadDataAllChanelsToServer extends
AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
pd.show();
}
#Override
protected String doInBackground(String... urls) {
jsonparser = new JSONParser();
JSONObject jsonobject = jsonparser.getJSONfromURL(URL);
try {
jsonarray = jsonobject.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
HashMap<String, String> map = new HashMap<String, String>();
map.put("journal", jsonobject.getString(KEY_journal));
map.put("image", jsonobject.getString(KEY_image));
map.put("title", jsonobject.getString(KEY_title));
map.put("description",
jsonobject.getString(KEY_description));
map.put("JournalID", jsonobject.getString(KEY_JournalID));
map.put("pubDate", jsonobject.getString(KEY_pubDate));
map.put("statID", jsonobject.getString(KEY_statID));
Content cont = new Content(jsonobject.getString("journal"),
jsonobject.getString("image"),
jsonobject.getString("title"),
jsonobject.getString("pubDate"),
jsonobject.getString("description"),
jsonobject.getString("JournalID"),
jsonobject.getString("statID"));
contents.add(cont);
itemList.add(map);
dateTime = itemList.get(itemList.size() - 1).get(
KEY_pubDate);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return itemList.toString();
}
#Override
protected void onPostExecute(String result) {
try {
if (pd != null) {
pd.dismiss();
}
} catch (Exception e) {
}
try {
adapter = new MyAdapter(MainActivity.this, itemList, screenSize);
list.setAdapter(adapter);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
#Override
public void onBackPressed() {
createDialog();
}
private void createDialog() {
AlertDialog.Builder alertDlg = new AlertDialog.Builder(this);
alertDlg.setMessage("Are you sure you want to exit?");
alertDlg.setCancelable(false);
alertDlg.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MainActivity.super.onBackPressed();
}
}
);
alertDlg.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertDlg.create().show();
}
}
My problem is: When I click the widget I get
indexofboundexception (invalid index 0,size 1)
What is the problem?

My problem is: When I click the widget I get
indexofboundexception (invalid index 0,size 1)
What is the problem?
That is too much code to look at. Please narrow your issue down and show the exact point the issue is occurring at.
Use your debugger to step through your code. 1st, identify the exact line at which the issue is occurring. Next, use your debugger to inspect the variables at that point. The error is an index out of bounds, so you're accessing a point in a list that is bigger than the size of the list.

Related

How to get Arraylist<HashMap<String, String>> from AsyncTask through onPostExecute

I am trying to put storelist into StoreList variable. But it is not working.
doInBackground method is working perfectly but onPostexecute is not working.
Here is my code,
public class guest_main extends Fragment implements View.OnClickListener,GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {
Location mCurrentLocation, mDestination;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
String currentLon, currentLat;
private ListView mListView = null;
private ListViewAdapter mAdapter = null;
public ArrayList<HashMap<String, String>> StoreList;
class BackgroundWorker3 extends AsyncTask<String, Void,ArrayList<HashMap<String, String>>> {
Context context;
AlertDialog alertDialog;
BackgroundWorker3(Context ctx) {
context = ctx;
}
JSONArray store = null;
ArrayList<HashMap<String, String>> storeList;
protected ArrayList<HashMap<String, String>> doInBackground(String... params) {
String type = params[0];
storeList = new ArrayList<HashMap<String, String>>();
if (type.equals("Select2")) {
try {
String link = "...";
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
StringBuilder sb = new StringBuilder();
String json;
while ((json = reader.readLine()) != null) {
sb.append(json);
}
String s = sb.toString().trim();
JSONObject jsonObject = new JSONObject(s);
store = jsonObject.getJSONArray("result");
for (int i = 0; i < store.length(); i++) {
JSONObject c = store.getJSONObject(i);
String name = c.getString("name");
String tel = c.getString("tel");
String latitude = c.getString("latitude");
String longitude = c.getString("longitude");
HashMap<String, String> stores = new HashMap<String, String>();
stores.put("name", name);
stores.put("tel", tel);
stores.put("latitude", latitude);
stores.put("longitude", longitude);
storeList.add(stores);
}
return storeList;
} catch (Exception e) {
return null;
}
}
return storeList;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login Status");
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> arrayList) {
StoreList = arrayList;
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.guest_main, container, false);
StoreList = new ArrayList<HashMap<String, String>>();
getData();
buildGoogleApiClient();
mListView = (ListView)v.findViewById(R.id.mList);
mAdapter = new ListViewAdapter(getActivity());
for(int i=0; i<StoreList.size(); i++){
HashMap<String, String> each = StoreList.get(i);
String name = each.get("name");
String tel = each.get("tel");
String lat = each.get("latitude");
String lon = each.get("longitude");
mDestination.setLatitude(Double.valueOf(lat).doubleValue());
mDestination.setLongitude(Double.valueOf(lon).doubleValue());
float distance = mCurrentLocation.distanceTo(mDestination);
mAdapter.addItem(getResources().getDrawable(R.drawable.sin), name, tel,Float.toString(distance));
}
mListView.setAdapter(mAdapter);
Button btn = (Button) v.findViewById(R.id.button1);
btn.setOnClickListener(this);
return v;
}
public void getData(){
BackgroundWorker3 bk2 = new BackgroundWorker3(getActivity());
bk2.execute("Select2");
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.button1:
Intent intent = new Intent(getActivity().getApplicationContext(), gmenu_list.class);
startActivity(intent);
}
}
private class ViewHolder {
public ImageView mIcon;
public TextView mText;
public TextView mDate;
public TextView mDistance;
}
private class ListViewAdapter extends BaseAdapter {
private Context mContext = null;
private ArrayList<g_ListData> mListData = new ArrayList<g_ListData>();
public ListViewAdapter(Context mContext) {
super();
this.mContext = mContext;
}
#Override
public int getCount() {
return mListData.size();
}
#Override
public Object getItem(int position) {
return mListData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public void addItem(Drawable icon, String mTitle, String mDate, String mDistance){
g_ListData addInfo = null;
addInfo = new g_ListData();
addInfo.mIcon = icon;
addInfo.mTitle = mTitle;
addInfo.mDate = mDate;
addInfo.mDistance = mDistance;
mListData.add(addInfo);
}
public void remove(int position){
mListData.remove(position);
dataChange();
}
public void sort(){
Collections.sort(mListData, g_ListData.ALPHA_COMPARATOR);
dataChange();
}
public void dataChange(){
mAdapter.notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.gmenu_list_item, null);
holder.mIcon = (ImageView) convertView.findViewById(R.id.mImage);
holder.mText = (TextView) convertView.findViewById(R.id.mText);
holder.mDate = (TextView) convertView.findViewById(R.id.mDate);
holder.mDistance = (TextView)convertView.findViewById(R.id.mDistance);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
g_ListData mData = mListData.get(position);
if (mData.mIcon != null) {
holder.mIcon.setVisibility(View.VISIBLE);
holder.mIcon.setImageDrawable(mData.mIcon);
}else{
holder.mIcon.setVisibility(View.GONE);
}
holder.mText.setText(mData.mTitle);
holder.mDate.setText(mData.mDate);
holder.mDate.setText(mData.mDistance);
return convertView;
}
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(100000); // Update location every second
try{
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);}catch (SecurityException e){
}
if (mCurrentLocation != null) {
currentLat = String.valueOf(mCurrentLocation.getLatitude());
currentLon = String.valueOf(mCurrentLocation.getLongitude());
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
currentLat = String.valueOf(location.getLatitude());
currentLon = String.valueOf(location.getLongitude());
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
synchronized void buildGoogleApiClient(){
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
public void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
public void onDestroy() {
super.onDestroy();
mGoogleApiClient.disconnect();
}
}
Ok..The problem is in your case that the Async task runs on separate thread from UI thread So when you call BackgroundWorker3 in getData method then UI thread doesn't wait for Async task response(separte thread) and StoreList have null value. So you see StoreList doesn't have any value and in listView nothing will show.
Write this code in onPostExecute method not in onCreate..
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> arrayList) {
StoreList = arrayList;
mListView = (ListView)v.findViewById(R.id.mList);
mAdapter = new ListViewAdapter(getActivity());
for(int i=0; i<StoreList.size(); i++){
HashMap<String, String> each = StoreList.get(i);
String name = each.get("name");
String tel = each.get("tel");
String lat = each.get("latitude");
String lon = each.get("longitude");
mDestination.setLatitude(Double.valueOf(lat).doubleValue());
mDestination.setLongitude(Double.valueOf(lon).doubleValue());
float distance = mCurrentLocation.distanceTo(mDestination);
mAdapter.addItem(getResources().getDrawable(R.drawable.sin), name, tel,Float.toString(distance));
}
mListView.setAdapter(mAdapter);
}
Hope this will help you.

How to add adapter2 with asynctask inside adapter1

I've this adapter class :
public class NoteFeedListAdapter extends RecyclerView.Adapter<feedItemsHolder>{
private Activity activity;
private LayoutInflater inflater;
private List<NoteFeedItem> feedItems;
private List<CommentModel> commentItems;
private NoteCommentListAdapter adapter;
private RecyclerView mRecyclerView;
ImageLoader imageLoader = NoteAppController.getInstance().getImageLoader();
private static final String URL_LIST_VIEW_COMMENT = "http://url.com";
private int level = 0;
private Context mContext;
public NoteFeedListAdapter(Context context, List<NoteFeedItem> feedItems) {
this.feedItems = feedItems;
this.mContext = context;
}
public feedItemsHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.feed_item, null);
feedItemsHolder mh = new feedItemsHolder(v);
return mh;
}
public void onBindViewHolder(final feedItemsHolder fItemsHolder, final int i) {
final NoteFeedItem item = feedItems.get(i);
fItemsHolder.setLevel(item.getLevel());
if (item.getName2() != null) {
fItemsHolder.mHiddenComment.setText(item.getName2()+": "+item.getComment2());
fItemsHolder.feedImageView.setVisibility(View.VISIBLE);
and Inside onBindViewHolder :
int jComment = Integer.parseInt(item.getJumlahComment().toString());
if( jComment > 0){
fItemsHolder.mHiddenComment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//this code is what I used to call asyntask but result from asynctask cannot be shown in this adapter
commentItems = new ArrayList<CommentModel>();
adapter = new NoteCommentListAdapter(mContext, commentItems);
mRecyclerView = new RecyclerView(mContext);
getListViewComments(item.getUserid(), item.getId(),fItemsHolder,i, commentItems, adapter, mRecyclerView);
commentItems = new ArrayList<CommentModel>();
adapter = new NoteCommentListAdapter(mContext, commentItems);
mRecyclerView.setAdapter(adapter);
}
});
}
...
} else {
fItemsHolder.mHiddenComment.setVisibility(View.GONE);
fItemsHolder.mLinearHiddenComment.setVisibility(View.GONE);
}
if(item.getLevel() == Level.LEVEL_ONE){
level = Level.LEVEL_TWO;
}else if(item.getLevel() == Level.LEVEL_TWO){
level = Level.LEVEL_THREE;
}
}
public int getItemCount() {
return (null != feedItems ? feedItems.size() : 0);
}
private void getListViewComments(final String userid, String id_note,final feedItemsHolder feedItemsHolder, int i, final List<CommentModel> commentItems, final NoteCommentListAdapter adapter, final RecyclerView mRecyclerView) {
class ambilComment extends AsyncTask<String, Void, String> {
ProgressDialog loading;
com.android.personal.asynctask.profileSaveDescription profileSaveDescription = new profileSaveDescription();
String result = "";
InputStream inputStream = null;
#Override
protected void onPreExecute() {
feedItemsHolder.mLoading.setVisibility(View.GONE);
feedItemsHolder.mHiddenComment.setVisibility(View.GONE);
feedItemsHolder.mLinearHiddenComment.setVisibility(View.GONE);
feedItemsHolder.mLoading.setVisibility(View.VISIBLE);
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
HashMap<String, String> data = new HashMap<String,String>();
data.put("userid", params[0]);
data.put("id_note", params[1]);
String result = profileSaveDescription.sendPostRequest(URL_LIST_VIEW_COMMENT,data);
return result;
}
protected void onPostExecute(String s) {
JSONArray dataJsonArr = null;
if(s.equals(null)){
Toast.makeText(mContext, "Internet Problem.", Toast.LENGTH_SHORT).show();
}else{
try{
JSONObject json = new JSONObject(s);
String id_note = json.getString("id_note");
Toast.makeText(mContext, id_note, Toast.LENGTH_SHORT).show();
dataJsonArr = json.getJSONArray("data");
for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(i);
String id_comment = c.getString("id_comment");
String uid = c.getString("userid");
String profile_name = c.getString("profile_name");
String profile_photo = c.getString("profile_photo");
String amount_of_like = c.getString("amount_of_like");
String amount_of_dislike = c.getString("amount_of_dislike");
String amount_of_comment = c.getString("amount_of_comment");
String content_comment = c.getString("content_comment");
String tgl_comment = c.getString("tgl_comment");
String parent_id = c.getString("parent_id");
CommentModel citem = new CommentModel();
citem.setId_note(id_note);
citem.setId_comment(id_comment);
citem.setUserid(uid);
citem.setProfileName(profile_name);
String pPhoto = c.isNull("profile_photo") ? null : c.getString("profile_photo");
citem.setProfile_photo(pPhoto);
citem.setJumlahLove(amount_of_like);
citem.setJumlahNix(amount_of_dislike);
citem.setJumlahComment(amount_of_comment);
citem.setContent_comment(content_comment);
citem.setTimeStamp(tgl_comment);
String prntID = c.isNull("parent_id") ? null : c.getString("parent_id");
citem.setParent_id(prntID);
citem.setLevel(level);
commentItems.add(citem);
}
adapter.notifyDataSetChanged();
}catch(JSONException e){
e.printStackTrace();
Log.w("getListNotesComment", "exception");
}
}
/* iH.mHiddenComment.setText("");*/
}
}
ambilComment ru = new ambilComment();
ru.execute(userid, id_note);
}
The problem is that I wanna add data from Asynctask and shown on another adapter. But how can i do that? please help. view from another adapter couldn't show with this code.

Android update adapter doesn't work correctly

In this code I have a custom adapter, and after I add new data into ArrayList my adapter.notifyDataSetChanged(); doesn't work.
public class ReceiveListFragment extends ListFragment implements AbsListView.OnScrollListener {
public ArrayList<ReceivedItemStructure> items;
private int prevVisibleItem;
private boolean isFirstTime;
private DatabaseHandler db;
private String config_username;
private String config_password;
private ReceivedAdapter adapter;
private Cursor cursor;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
db = new DatabaseHandler(G.context);
config_username = Configuration.getInstance()
.getString(getActivity(),
Configuration.SharedPrefsTypes.USERNAME);
config_password = Configuration.getInstance()
.getString(getActivity(),
Configuration.SharedPrefsTypes.PASSWORD);
items = new ArrayList<ReceivedItemStructure>();
getRequestFromServer(0, 10);
adapter = new ReceivedAdapter(G.context, items);
setListAdapter(adapter);
Timer smsThread = new Timer();
GetSMSThread getSMSThread = new GetSMSThread();
smsThread.scheduleAtFixedRate(getSMSThread, 1, 10000); //(timertask,delay,period)
return super.onCreateView(inflater, container, savedInstanceState);
}
private String getRequestFromServer(long lastID, int count) {
String received = "";
try {
received = new JsonService(config_username, config_password, lastID, count, G.F_RECEIVE_SMS).request();
JSONArray data_array = new JSONArray(received);
String mUserID = config_username;
for (int i = 0; i < data_array.length(); i++) {
JSONObject json_obj = data_array.getJSONObject(i);
String mLastID = json_obj.getString("id_recived_sms");
String mSmsBody = json_obj.getString("sms_body");
String mSmsNumber = json_obj.getString("sms_number");
String mSenderName = json_obj.getString("mobile_number");
String mContactName = json_obj.getString("contact_name");
String mDate = json_obj.getString("recived_date");
ReceivedItemStructure item = new ReceivedItemStructure(
mLastID,
mUserID,
mSmsBody,
mSmsNumber,
mSenderName,
mContactName,
mDate
);
items.add(item);
//Log.e(" ", "" + mLastID);
}
/** Creating array adapter to set data in listview */
} catch (Exception e) {
e.printStackTrace();
}
return received;
}
public long getLastID() {
return Long.parseLong(items.get(items.size() - 1).getmLastID());
}
private void addDataToList(String LastID, String SmsBody, String SmsNumber, String SenderName, String ContactName, String Date) {
String mLastID = LastID;
String mUserID = config_username;
String mSmsBody = SmsBody;
String mSmsNumber = SmsNumber;
String mSenderName = SenderName;
String mContactName = ContactName;
String mDate = Date;
ReceivedItemStructure item = new ReceivedItemStructure(
mLastID,
mUserID,
mSmsBody,
mSmsNumber,
mSenderName,
mContactName,
mDate
);
items.add(item);
adapter.update(items);
adapter.notifyDataSetChanged();
}
public class GetSMSThread extends TimerTask {
private Long lastID;
private SQLiteDatabase dbHelper;
private List<ReceiveListFragment> rows;
#Override
public void run() {
lastID = getLastID();
if (Configuration.getInstance().checkInternetConnection(G.context)) {
try {
Thread threadTask = new Thread() {
#Override
public void run() {
G.activity.runOnUiThread(new Runnable() {
#Override
public void run() {
try {
int countSMS = 0;
String smsReceivedSender = "";
String receive_lastID = "";
String r = new JsonService(config_username, config_password, 0, 1, G.F_RECEIVE_SMS).request();
JSONArray data_array = new JSONArray(r);
ArrayList<String> items_array = new ArrayList<String>();
JSONObject json_obj = data_array.getJSONObject(0);
receive_lastID = json_obj.getString("id_recived_sms");
smsReceivedSender = json_obj.getString("mobile_number");
for (ReceivedItemStructure rf : items) {
items_array.add(rf.getmLastID());
}
if (items_array.indexOf(receive_lastID) == -1) {
countSMS++;
addDataToList(
json_obj.getString("id_recived_sms"),
json_obj.getString("sms_body"),
json_obj.getString("sms_number"),
json_obj.getString("mobile_number"),
json_obj.getString("contact_name"),
json_obj.getString("recived_date")
);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
};
threadTask.start();
} catch (Exception e) {
e.printStackTrace();
} // END TRY
}
}
}
}
My custom Adapter code is this:
public class ReceivedAdapter extends ArrayAdapter<ReceivedItemStructure> {
private ArrayList<ReceivedItemStructure> list;
public ReceivedAdapter(Context c, ArrayList<ReceivedItemStructure> items) {
super(c,0,items);
list = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ReceiveItemView itemView = (ReceiveItemView)convertView;
if (null == itemView)
itemView = ReceiveItemView.inflate(parent);
itemView.setItem(getItem(position));
return itemView;
}
public void update(ArrayList<ReceivedItemStructure> items) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
addAll(items);
} else {
for (ReceivedItemStructure item : items) {
add(item);
}
}
}
}
setListAdapter(adapter); works correctly and I don't have any problem, but after I add new data into items notifyDataSetChanged it doesn't work.
My manifest content:
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="21"/>
it is the super class that is handling the dataset, since you are not overriding getCount and getItem,
public void update(ArrayList<ReceivedItemStructure> items) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
addAll(items);
} else {
for (ReceivedItemStructure item : items) {
add(item)
}
}
}
addAll was introduced with Honeycomb, so you probably want to check the current supported sdk where you are app is running
You are modifying your original items collection. But you should to modify adapter's data. Use ArrayAdapter.add method to add new items.

On Click Of Tabs(Radio Button) My Memory Getting Double

My layout is very complex. I have to make full page scrollable so what i did is - i have a gridView adapter for my gridview items and one custom adapter which has four tabs and then i set my gridview in that custom adapter. Then this whole view is set on my main activity which has a listview so its now scrolling with full page but issue is with memory.
I have 4 tab click events on custom adapter from which i am sending those click events through put extra to main activity where i have four web service and a condition that if 1st tab is selected then 1st web service call will occur and new adapter will set on main activity.
problem: when i click on 1st tab my memory size is 130 MB and on click of 2nd tab it raises to double so and same thing is happen when i click on 3rd tab. I am using lazy loading for loading my images which also maintains my caching, i have tried clear(), notifyDataSetChanged() but doesn't make any change. My memory is increasing on each click of tabs.
Here is my code:
GallaryLoginMainActivity:
public class GallaryLoginMainActivity<T> extends BaseClass {
/**
* Description:Declare the UI components.
*/
private List<ArrayList<HashMap<String, String>>> data = null;
private ListView lstGallaryMain = null;
public ArrayList<HashMap<String, String>> userDataActivity;
public ArrayList<HashMap<String, String>> userDataSecondActivity;
private ProgressDialog loadingDialog = null;
LinkedHashMap<String, String> linkedMap;
ArrayList<Assignment> assignmentArrayList;
private String selectedTab = "popular";
private ImageLoader imageloader;
// public static ArrayAdapter mAdapter;
public ArrayAdapter mAdapter;
/**
* Description:This method use for prepare the request to get the response
* from API
*
*/
public void MediaGetFiles() {
final GallerySaxParserForGetFiles gsp = new GallerySaxParserForGetFiles();
final RestService restService = new RestService();
try {
linkedMap = new LinkedHashMap<String, String>();
gsp.parseXML(restService.getResponse());
// userDataActivity = new ArrayList<HashMap<String, String>>();
userDataActivity = gsp.userData;
System.out.println("RR : userDataActivity from LoginMainAct :" + userDataActivity.size());
System.out.println("RR : from userdataactivty for item:" + userDataActivity.get(0).toString());
data.add(userDataActivity);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Description:This method use for prepare the request to get the response
* from API
*
*/
public void MediaGetFilesInfo() {
// new Thread(new Runnable() {
// public void run() {
GallerySaxParserForGetFileInfo gisp = new GallerySaxParserForGetFileInfo();
try {
RestService restService = new RestService();
linkedMap = new LinkedHashMap<String, String>();
System.out.println("From GallaryUserLoginMainActivity1 : " + restService.getResponse());
gisp.parseXML(restService.getResponse());
userDataSecondActivity = new ArrayList<HashMap<String, String>>();
userDataSecondActivity = gisp.userSecondData;
data.add(userDataSecondActivity);
} catch (Exception e) {
e.printStackTrace();
}
// }
// }).start();
}
/**
* Description:This method use for prepare the request to get the response
* from API
*
*/
public void MediaGetShortedFilesByPopuler() {
final GallerySaxParserForGetFiles gsp = new GallerySaxParserForGetFiles();
final RestService restService = new RestService();
try {
linkedMap = new LinkedHashMap<String, String>();
gsp.parseXML(restService.getResponse());
userDataActivity = new ArrayList<HashMap<String, String>>();
userDataActivity = gsp.userData;
data.add(userDataActivity);
data.add(userDataSecondActivity);
// };
// }.execute();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Description:This method use for prepare the request to get the response
* from API
*
*/
public void MediaGetShortedFilesByRecent() {
final GallerySaxParserForGetFiles gsp = new GallerySaxParserForGetFiles();
final RestService restService = new RestService();
try {
linkedMap = new LinkedHashMap<String, String>();
gsp.parseXML(restService.getResponse());
userDataActivity = new ArrayList<HashMap<String, String>>();
userDataActivity = gsp.userData;
data.add(userDataActivity);
data.add(userDataSecondActivity);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Description:This method use for prepare the request to get the response
* from API
*
*/
public void MediaGetShortedFilesByComment() {
final GallerySaxParserForGetFiles gsp = new GallerySaxParserForGetFiles();
final RestService restService = new RestService();
try {
linkedMap = new LinkedHashMap<String, String>();
gsp.parseXML(restService.getResponse());
userDataActivity = new ArrayList<HashMap<String, String>>();
userDataActivity = gsp.userData;
data.add(userDataActivity);
data.add(userDataSecondActivity);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Description:This method use for prepare the request to get the response
* from API
*
*/
public void MediaGetShortedFilesByNearBy() {
final GallerySaxParserForGetFiles gsp = new GallerySaxParserForGetFiles();
final RestService restService = new RestService();
try {
linkedMap = new LinkedHashMap<String, String>();
gsp.parseXML(restService.getResponse());
userDataActivity = new ArrayList<HashMap<String, String>>();
userDataActivity = gsp.userData;
data.add(userDataActivity);
data.add(userDataSecondActivity);
} catch (Exception e) {
e.printStackTrace();
}
}
/** Called when the activity is first created. */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gallary_login_main_page_list);
init(GallaryLoginMainActivity.this, R.id.main, getIntent());
data = new ArrayList<ArrayList<HashMap<String, String>>>();
imageloader = new ImageLoader(getApplicationContext());
Intent intent = getIntent();
if (intent.getExtras().getString("SELECTED_TAB") != null) {
selectedTab = intent.getExtras().getString("SELECTED_TAB");
}
/*
*
* This method is used to Show The loading dialog till the data
* loads for main page.
*/
new AsyncTask<Void, Void, Void>() {
protected void onPreExecute() {
loadingDialog = ProgressDialog.show(GallaryLoginMainActivity.this, "", "Loading. Please wait...", true);
}
#Override
protected Void doInBackground(Void... params) {
return null;
};
protected void onPostExecute(Void result) {
if (selectedTab.equalsIgnoreCase("popular")) {
MediaGetShortedFilesByPopuler();
} else if (selectedTab.equalsIgnoreCase("recent")) {
MediaGetShortedFilesByRecent();
} else if (selectedTab.equalsIgnoreCase("commented")) {
MediaGetShortedFilesByComment();
}
if (mAdapter != null) {
mAdapter = null;
mAdapter.clear();
}
if (mAdapter == null) {
lstGallaryMain = (ListView) findViewById(R.id.lstGallaryMain);
mAdapter = new GalleryCustomAdapterForMainPage<T>(GallaryLoginMainActivity.this, data);
// mAdapter.notifyDataSetChanged();
}
lstGallaryMain.setAdapter(mAdapter);
if (loadingDialog != null && loadingDialog.isShowing()) {
loadingDialog.dismiss();
}
};
}.execute();
}
}
#Override
protected void onResume() {
System.gc();
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
System.gc();
}
#Override
public void onLowMemory() {
super.onLowMemory();
imageloader.clearCache();
}
#Override
protected void onDestroy() {
lstGallaryMain.setAdapter(null);
userDataActivity = null;
userDataSecondActivity = null;
System.gc();
super.onDestroy();
}
}
GalleryCustomAdapterForMainPage:
public class GalleryCustomAdapterForMainPage<T> extends ArrayAdapter<T> {
public static int gridviewHeight = 0;
private GridView refGridView;
/**
* Description:Declare the UI components.
*/
List<ArrayList<HashMap<String, String>>> data = null;
public ArrayList<HashMap<String, String>> userDataActivity;
public ArrayList<HashMap<String, String>> userDataSecondActivity;
private ProgressDialog loadingDialog = null;
// AQuery listAQ;
private Activity mContext = null;
private LayoutInflater inflater = null;
Bitmap galleryBitmapHadnling = null;
private PopupWindow mpopup;
LinkedHashMap<String, String> linkedMap;
Holder1 h1;
GalleryMainActivityGridViewAdapter gmaga = null;
private ImageLoader imageloader;
/**
* This method is use to set object that will control the listview
*
* #param activity
* that creates this thing
* #param data
* bind to this listview
*/
// This Class is used to Declare a CustomAdapter that we use to join the
// data set and the ListView
public GalleryCustomAdapterForMainPage(Activity activity, List data) {
super(activity, R.layout.gallery_main_page_content, data);
this.mContext = activity;
// listAQ = new AQuery(mContext);
this.data = data;
this.userDataActivity = this.data.get(0);
System.out.println("userDataActivity is : " + userDataActivity);
this.userDataSecondActivity = this.data.get(1);
// listAQ = new AQuery(mContext);
// Get a new instance of the layout view
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageloader = new ImageLoader(mContext);
}
// Total number of things contained within the adapter
#Override
public int getCount() {
return this.data.size() - 1;
}
// create View for each item referenced by the Adapter
#SuppressWarnings("deprecation")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
/* create a new view of our layout and inflate it in the row */
// Inflate the layout
convertView = inflater.inflate(R.layout.gallery_main_page_content, null);
// System.gc();
h1 = new Holder1();
// Initialize the UI components
h1.imgView_Gallery_Main_Background = (ImageView) convertView.findViewById(R.id.imgView_Gallery_Main_Background);
h1.txtView_main_img_title = (TextView) convertView.findViewById(R.id.txtView_main_img_title);
Typeface typeForTitile = Typeface.createFromAsset(getContext().getAssets(), "fonts/helvetica_bold_neue.ttf");
h1.txtView_main_img_title.setTypeface(typeForTitile);
h1.texView_featured = (TextView) convertView.findViewById(R.id.texView_featured);
Typeface typeForFeatured = Typeface.createFromAsset(getContext().getAssets(), "fonts/gotham_black_1.ttf");
h1.texView_featured.setTypeface(typeForFeatured);
h1.txtView_assignment_detail = (TextView) convertView.findViewById(R.id.txtView_assignment_detail);
Typeface typeAssignmentDetail = Typeface.createFromAsset(getContext().getAssets(), "fonts/arial_bold_1.ttf");
h1.txtView_assignment_detail.setTypeface(typeAssignmentDetail);
h1.imgView_Main_TumbNail = (ImageView) convertView.findViewById(R.id.imgView_Main_TumbNail);
h1.txtView_gallery_main_person_name = (TextView) convertView.findViewById(R.id.txtView_gallery_main_person_name);
Typeface txtViewPersonName = Typeface.createFromAsset(getContext().getAssets(), "fonts/arial_bold.ttf");
h1.txtView_gallery_main_person_name.setTypeface(txtViewPersonName);
h1.txtView_gallery_main_views = (TextView) convertView.findViewById(R.id.txtView_gallery_main_views);
Typeface txtViewViews = Typeface.createFromAsset(getContext().getAssets(), "fonts/arial_bold.ttf");
h1.txtView_gallery_main_views.setTypeface(txtViewViews);
h1.texView_gallery_main_comment = (TextView) convertView.findViewById(R.id.texView_gallery_main_comment);
Typeface txtViewComments = Typeface.createFromAsset(getContext().getAssets(), "fonts/arial_bold.ttf");
h1.texView_gallery_main_comment.setTypeface(txtViewComments);
h1.texView_gallery_main_favorite = (TextView) convertView.findViewById(R.id.texView_gallery_main_favorite);
Typeface txtViewFavorite = Typeface.createFromAsset(getContext().getAssets(), "fonts/arial_bold.ttf");
h1.texView_gallery_main_favorite.setTypeface(txtViewFavorite);
h1.btn_Gallery_Main_ShowMe = (RadioButton) convertView.findViewById(R.id.btn_Gallery_Main_ShowMe);
h1.btn_Gallery_Tab_Popular = (RadioButton) convertView.findViewById(R.id.btn_Gallery_Tab_Popular);
Typeface TabPopular = Typeface.createFromAsset(getContext().getAssets(), "fonts/helvetica_ce_regular.ttf");
h1.btn_Gallery_Tab_Popular.setTypeface(TabPopular);
h1.btn_Gallery_Tab_Popular.setChecked(true);
h1.btn_Gallery_Tab_recent = (RadioButton) convertView.findViewById(R.id.btn_Gallery_Tab_recent);
Typeface TabRecent = Typeface.createFromAsset(getContext().getAssets(), "fonts/helvetica_ce_regular.ttf");
h1.texView_gallery_main_favorite.setTypeface(TabRecent);
h1.btn_Gallery_Tab_Commented = (RadioButton) convertView.findViewById(R.id.btn_Gallery_Tab_Commented);
Typeface TabCommented = Typeface.createFromAsset(getContext().getAssets(), "fonts/helvetica_ce_regular.ttf");
h1.texView_gallery_main_favorite.setTypeface(TabCommented);
h1.btn_Gallery_Tab_Nearby = (RadioButton) convertView.findViewById(R.id.btn_Gallery_Tab_Nearby);
Typeface TabNearby = Typeface.createFromAsset(getContext().getAssets(), "fonts/helvetica_ce_regular.ttf");
h1.texView_gallery_main_favorite.setTypeface(TabNearby);
h1.imgView_ForPlayVideo = (ImageView) convertView.findViewById(R.id.imgView_ForPlayVideo);
if (userDataActivity.get(position).get("filetype").toString().endsWith("1")) {
h1.imgView_ForPlayVideo.setVisibility(View.GONE);
} else {
h1.imgView_ForPlayVideo.setVisibility(View.VISIBLE);
} // set the content in grid view of gallery main page
h1.gridview_Gallery = (GridView) convertView.findViewById(R.id.gridview_Gallery);
int gridHeight = (int) ((userDataActivity.size() / 3) * 140 * 1.80);
System.out.println("gridHeigh is : " + gridHeight);
if (h1.btn_Gallery_Tab_Popular != null) {
h1.txtView_gallery_main_person_name.setText(" " + userDataActivity.get(position).get("user_name"));
h1.txtView_main_img_title.setText(userDataActivity.get(position).get("title"));
h1.txtView_gallery_main_views.setText(" | " + userDataActivity.get(position).get("hits") + " views");
h1.texView_gallery_main_comment.setText(" | " + userDataActivity.get(position).get("commentcount") + " ");
h1.texView_gallery_main_favorite.setText(" | " + userDataActivity.get(position).get("votecount") + " ");
imageloader.DisplayImage(userDataActivity.get(position).get("thumbUrl") + "/12", h1.imgView_Gallery_Main_Background);
// h1.imgView_Main_TumbNail.setImageBitmap(getBitmap(userDataActivity.get(position).get("thumbUrl")
// + "/12"));
if (userDataActivity.get(position).get("publicUrl") != null) {
imageloader.DisplayImage(userDataActivity.get(position).get("publicUrl") + "/14", h1.imgView_Gallery_Main_Background);
} else {
h1.imgView_Gallery_Main_Background.setBackgroundResource(R.drawable.loading);
}
}
userDataActivity.remove(0);
if (h1.gridview_Gallery != null) {
// clearAdapter();
// setting the adapter
// if (gmaga == null) {
gmaga = new GalleryMainActivityGridViewAdapter(mContext, userDataActivity);
// }
h1.gridview_Gallery.setAdapter(gmaga);
// Total number of things contained within the adapter
int gridHeight1 = (int) ((h1.gridview_Gallery.getAdapter().getCount() / 3) * 120 * 1.80);
h1.gridview_Gallery.setLayoutParams(new LinearLayout.LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT, gridHeight1));
h1.gridview_Gallery.setSelector(new ColorDrawable(color.transparent));
h1.gridview_Gallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
Intent intent = new Intent(mContext, GalleryDetailPageActivity.class);
System.out.println("pos:" + userDataActivity.get(position).get("id"));
// This will send the items via intent to Gallery detail
// page to display data on that page.
intent.putExtra("tabId", R.id.tab_b01);
intent.putExtra("tabBackgroundId", R.drawable.tab_b01_on);
mContext.startActivity(intent);
}
});
}
if (h1.btn_Gallery_Tab_Popular != null) {
h1.btn_Gallery_Tab_Popular.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(mContext, GallaryLoginMainActivity.class);
intent.putExtra("SELECTED_TAB", "popular");
intent.putExtra("tabId", R.id.tab_b01);
intent.putExtra("tabBackgroundId", R.drawable.tab_b01_on);
mContext.startActivity(intent);
mContext.finish();
// }
}
});
}
if (h1.btn_Gallery_Tab_recent != null) {
h1.btn_Gallery_Tab_recent.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, GallaryLoginMainActivity.class);
intent.putExtra("SELECTED_TAB", "recent");
intent.putExtra("tabId", R.id.tab_b01);
intent.putExtra("tabBackgroundId", R.drawable.tab_b01_on);
mContext.startActivity(intent);
mContext.finish();
// }
}
});
}
if (h1.btn_Gallery_Tab_Commented != null) {
h1.btn_Gallery_Tab_Commented.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, GallaryLoginMainActivity.class);
intent.putExtra("SELECTED_TAB", "commented");
intent.putExtra("tabId", R.id.tab_b01);
intent.putExtra("tabBackgroundId", R.drawable.tab_b01_on);
mContext.startActivity(intent);
mContext.finish();
// }
}
});
}
convertView.setTag(h1);
}
return convertView;
}
private class Holder1 {
ImageView imgView_Gallery_Main_Background;
TextView txtView_main_img_title;
TextView texView_featured;
RadioButton btn_Gallery_Tab_Popular;
RadioButton btn_Gallery_Tab_recent;
RadioButton btn_Gallery_Tab_Commented;
RadioButton btn_Gallery_Tab_Nearby;
ImageView imgView_Main_TumbNail;
TextView txtView_assignment_detail;
TextView txtView_assignment_name;
TextView txtView_gallery_main_person_name;
TextView txtView_gallery_main_views;
TextView texView_gallery_main_comment;
TextView texView_gallery_main_favorite;
RadioButton btn_Gallery_Main_ShowMe;
GridView gridview_Gallery;
ImageView imgView_ForPlayVideo;
}
}
GalleryMainActivityGridViewAdapter:
public class GalleryMainActivityGridViewAdapter extends BaseAdapter {
// AQuery listAQ;
private Context mContext;
int layoutResourceId;
ArrayList<HashMap<String, String>> dataArray;
ArrayList<Boolean> selected;
private GallerySmartLazyLoader lazyloader;
private ImageLoader imageloder;
public static String dataExtension = " Views";
public GalleryMainActivityGridViewAdapter(Context context, ArrayList<HashMap<String, String>> resultArray) {
this.mContext = context;
// this.layoutResourceId = layoutId;
this.dataArray = resultArray;
// listAQ = new AQuery(mContext);
lazyloader = new GallerySmartLazyLoader(mContext);
imageloder = new ImageLoader(mContext.getApplicationContext());
// aa = new ArrayAdapter<Photo>(mContext, layoutResourceId);
}
public int getCount() {
return dataArray.size();
}
public void clear() {
dataArray.clear();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
// BitmapFactory.Options options = null;
// Bitmap cachedImage;
#SuppressWarnings("deprecation")
public View getView(int position, View convertView, ViewGroup parent) {
String url = null;
GalleryHolder holder = null;
if (convertView == null) {
convertView = ((LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.gallery_main_page_grid_item, parent, false);
convertView.setTag(holder);
} else {
holder = (GalleryHolder) convertView.getTag();
}
holder = new GalleryHolder();
try {
String thumbnail = dataArray.get(position).get("thumbUrl") + "/11";
holder.imgView_Grid_Thumbnail_Gallery = (ImageView) convertView.findViewById(R.id.imgView_Grid_Thumbnail_Gallery);
if (holder.imgView_Grid_Thumbnail_Gallery != null) {
}
} catch (Exception e) {
e.printStackTrace();
}
holder.txtView_Grid_Name_Gallery = (TextView) convertView.findViewById(R.id.txtView_Grid_Name_Gallery);
Typeface TabGridname = Typeface.createFromAsset(convertView.getContext().getAssets(), "fonts/arial_bold.ttf");
holder.txtView_Grid_Name_Gallery.setTypeface(TabGridname);
if (holder.txtView_Grid_Name_Gallery != null) {
// holder.txtView_Grid_Name_Gallery.getId()).text(dataArray.get(position).get("user_name"));
holder.txtView_Grid_Name_Gallery.setText(dataArray.get(position).get("user_name"));
Typeface txtViewForName = Typeface.createFromAsset(convertView.getContext().getAssets(), "fonts/arial_bold.ttf");
holder.txtView_Grid_Name_Gallery.setTypeface(txtViewForName);
}
ImageView v = holder.imgView_GridItem_Gallery = (ImageView) convertView.findViewById(R.id.imgView_GridItem_Gallery);
if (holder.imgView_GridItem_Gallery != null) {
String publicUrl = dataArray.get(position).get("publicUrl") + "/14";
imageloder.DisplayImage(publicUrl, holder.imgView_GridItem_Gallery);
}
holder.txtView_Grid_Views_Gallery = (TextView) convertView.findViewById(R.id.txtView_Grid_Views_Gallery);
Typeface TabGriddetail = Typeface.createFromAsset(convertView.getContext().getAssets(), "fonts/helvetica_ce_regular.ttf");
holder.txtView_Grid_Name_Gallery.setTypeface(TabGriddetail);
if (holder.txtView_Grid_Views_Gallery != null) {
if (isPopuler) {
holder.txtView_Grid_Views_Gallery.setText(dataArray.get(position).get("hits") + dataExtension);
}
else if (isUpload) {
GalleryMainActivityGridViewAdapter.dataExtension = dataArray.get(position).get("upload");
holder.txtView_Grid_Views_Gallery.setText(dataArray.get(position).get("upload"));
}
else if (isComments) {
holder.txtView_Grid_Views_Gallery.setText(dataArray.get(position).get("commentcount") + dataExtension);
}
// else if (isNearby) {
// aq.id(holder.txtView_Grid_Views_Gallery.getId()).text(dataArray.get(position).get("commentcount")
// + dataExtension);
// }
Typeface txtViewForViews = Typeface.createFromAsset(convertView.getContext().getAssets(), "fonts/arial_bold.ttf");
holder.txtView_Grid_Views_Gallery.setTypeface(txtViewForViews);
}
holder.imgView_Grid_PlayVideo = (ImageView) convertView.findViewById(R.id.imgView_Grid_PlayVideo);
if (holder.imgView_Grid_PlayVideo != null) {
if (dataArray.get(position).get("filetype").toString().equals("1")) {
holder.imgView_Grid_PlayVideo.setVisibility(View.GONE);
} else {
holder.imgView_Grid_PlayVideo.setVisibility(View.VISIBLE);
}
}
return convertView;
}
class GalleryHolder {
ImageView imgView_Grid_PlayVideo;
ImageView imgView_Grid_Thumbnail_Gallery;
TextView txtView_Grid_Views_Gallery;
TextView txtView_Grid_Name_Gallery;
ImageView imgView_GridItem_Gallery;
}
}
pic
The description you showed is indicating a possible memory leak. Check my answer for this question. My guess is that you should use the Application context instead of the Activity context in your code. Use the video in the answer mentioned to know how to identify the leak.

How to Use onresume() and onpause() for on tabclick Event

I had four tabs in my view and the tab output depend on other tab input in same view. So when I click on one tab, it generates an array list and show item in list view but when second time I click on the same tab it gives array index out of bound exception. I think it is because of previous downloaded content was in the view so how to remove/delete previous loaded content when I clicked first time on tab. I know it can be done onresume() and onpause() method but what code should be in onpause() for removing previous loaded content. For refreshing it with new content. ontabclick().
Thanks!
public class OpeningToday extends ListActivity {
String name = null;
String typename = null;
static String array_type[];
static int totalartist;
static String array_galleryname[]=null;
static String array_address[]=null;
static String array_galleryurl[]=null;
static String array_email[];
static String array_web[];
static String array_phone[];
static String array_latitude[];
static String array_longitude[];
SitesList2 sitesList;
//static String gallerynames;
//static String addresses;
private ProgressDialog dialog;
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i("saurabh trivedi","saurabh trivedui");
super.onCreate(savedInstanceState);
setContentView(R.layout.openingtoday);
ImageView iv=(ImageView)findViewById(R.id.imv);
iv.setBackgroundResource(R.drawable.fiiatlogo);
new ProgressTask6().execute();
}
protected void onPause() {
super.onPause();
}
protected void onResume()
{
super.onResume();
new ProgressTask6().execute();
}
private class ProgressTask6 extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
private Context context;
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(OpeningToday.this);
dialog.setMessage("Processing...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing())
{
dialog.dismiss();
setListAdapter(new MyAdapter(OpeningToday.this));
}
if(totalartist==0)
{
AlertDialog.Builder alt_bld = new AlertDialog.Builder(OpeningToday.this);
alt_bld.setMessage("galleries not found..")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = alt_bld.create();
// Title for AlertDialog
alert.setTitle("Title");
// Icon for AlertDialog
alert.setIcon(R.drawable.icon);
alert.show();
}
}
#Override
protected Boolean doInBackground(String... args) {
try{
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
String temp = "http://www.arteonline.mobi/iphone/output.php?visit=1";
temp = temp.replaceAll(" " ,"%20");
Log.i("temp url..",temp);
URL sourceUrl = new URL(temp);
XMLHandler myXMLHandler = new XMLHandler();
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource(sourceUrl.openStream()));
}
catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
sitesList = XMLHandler.sitesList2;
keywordresulttab.array_galleryname = new String[sitesList.getGalleryname().size()];
totalartist= sitesList.getGalleryname().size();
Log.i("opening today artist..",Integer.toString(totalartist));
for (int i = 0; i < sitesList.getGalleryname().size(); i++)
{
name = sitesList.getGalleryname().get(i);
keywordresulttab.array_galleryname[i] = name;
// Log.i("array_spinner" + i, array_galleryname[i]);
}
keywordresulttab.array_type = new String[sitesList.getType().size()];
for (int i = 0; i < sitesList.getType().size(); i++)
{
name = sitesList.getType().get(i);
keywordresulttab.array_type[i] = name;
// Log.i("array_spinner" + i, array_estado[i]);
}
keywordresulttab.array_email = new String[sitesList.getEmail().size()];
for (int i = 0; i < sitesList.getEmail().size(); i++)
{
name = sitesList.getType().get(i);
keywordresulttab.array_email[i] = name;
// Log.i("array_spinner" + i, array_estado[i]);
}
keywordresulttab.array_address = new String[sitesList.getAddress().size()];
for (int i = 0; i < sitesList.getAddress().size(); i++)
{
name = sitesList.getAddress().get(i);
keywordresulttab.array_address[i] = name;
//Log.i("array_spinner" + i, array_address[i]);
}
keywordresulttab.array_web = new String[sitesList.getWeb().size()];
for (int i = 0; i < sitesList.getWeb().size(); i++)
{
name = sitesList.getWeb().get(i);
keywordresulttab.array_web[i] = name;
}
keywordresulttab.array_lati = new String[sitesList.getLati().size()];
for (int i = 0; i < sitesList.getLati().size(); i++)
{
name = sitesList.getLati().get(i);
keywordresulttab.array_lati[i] = name;
Log.i("array_spinner" + i,keywordresulttab.array_lati[i]);
}
keywordresulttab.array_longi = new String[sitesList.getLongi().size()];
for (int i = 0; i < sitesList.getLongi().size(); i++)
{
name = sitesList.getLongi().get(i);
keywordresulttab.array_longi[i] = name;
Log.i("array_spinner" + i, keywordresulttab.array_longi[i]);
}
keywordresulttab.array_phone = new String[sitesList.getPhoneno().size()];
for (int i = 0; i < sitesList.getPhoneno().size(); i++)
{
name = sitesList.getPhoneno().get(i);
keywordresulttab.array_phone[i] = name;
}
keywordresulttab.array_imgurl = new String[sitesList.getImagegalleryurl().size()];
for (int i = 0; i < sitesList.getImagegalleryurl().size(); i++)
{
name = sitesList.getImagegalleryurl().get(i);
keywordresulttab.array_imgurl[i] = name;
}
} catch (Exception e){
Log.e("tag", "error", e);
return false;
}
return null;
}
class MyAdapter extends BaseAdapter implements OnClickListener
{
private LayoutInflater inflater;
public MyAdapter(Context ctx) {
super();
this.inflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return totalartist;
}
/* Not implemented but not really needed */
#Override
public Object getItem(int position) {
return null;
}
/* Not implemented but not really needed */
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View ConvertView, ViewGroup parent)
{
View v = inflater.inflate(R.layout.listitem_layout, parent, false);
// Log.i("array galoijewdh..",keywordresulttab.array_galleryname[position]);
Log.i("saurabh trivedi","saurabh trivedui");
// Variables.a=3;
String gallerynames = keywordresulttab.array_galleryname[position];
String addresses = keywordresulttab.array_address[position];
TextView tv = (TextView) v.findViewById(R.id.barrio);
tv.setText(gallerynames);
tv = (TextView) v.findViewById(R.id.ciudad);
tv.setText(addresses);
((BaseAdapter)(getListAdapter())).notifyDataSetChanged();
return v;
}
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}
}
}
Make your array list empty on onResume() method and fill it by new content now.

Categories

Resources