Parsing JSON data and storing into a listview - android

I'm currently developing a small android weather app. That passes through 3 strings to display three weather elements from the open source weatherAPI. I'm trying to display this in a listview. I got it working when passing in 1 string. But I'm having trouble passing in multiple strings. Any advice would be appreciated
ArrayList<Weather> weatherData = new ArrayList<Weather>();
private ListView listView1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView1 = (ListView) findViewById(R.id.listView1);
String[] city = {
new String("dublin,ire"),
new String("London,uk")
};
for (int i = 0; i < city.length; ++i) {
listView1.add(city[i]);
}
//String city2 = "Dublin,ire";
Button button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
setContentView(R.layout.activity_main);
Button button1 = (Button) findViewById(R.id.button1);
Log.d("MR.bool", "Button1 was clicked ");
startActivity(new Intent(MainActivity.this, WebViewActivity.class));
}
});
cityText = (TextView) findViewById(R.id.cityText);
condDescr = (TextView) findViewById(R.id.condDescr);
temp = (TextView) findViewById(R.id.temp);
hum = (TextView) findViewById(R.id.hum);
press = (TextView) findViewById(R.id.press);
windSpeed = (TextView) findViewById(R.id.windSpeed);
windDeg = (TextView) findViewById(R.id.windDeg);
imgView = (ImageView) findViewById(R.id.condIcon);
imgView2 = (ImageView) findViewById(R.id.imageView1);
JSONWeatherTask task = new JSONWeatherTask();
task.execute(new String[]{city});
if (city.contains("uk")) {
imgView2.setImageResource(R.drawable.uk);
} else if (city.contains("ire")) {
imgView2.setImageResource(R.drawable.ireland);
} else if (city.contains("de")) {
imgView2.setImageResource(R.drawable.germany);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class JSONWeatherTask extends AsyncTask<String, Void, Weather> {
#Override
protected Weather doInBackground(String... params) {
Weather weather = new Weather();
String data = ((new WeatherHttpClient()).getWeatherData(params[0]));
try {
weather = JSONWeatherParser.getWeather(data);
// Let's retrieve the icon
weather.iconData = ((new WeatherHttpClient()).getImage(weather.currentCondition.getIcon()));
} catch (JSONException e) {
e.printStackTrace();
}
return weather;
}
#Override
protected void onPostExecute(Weather weather) {
super.onPostExecute(weather);
if (weather.iconData != null && weather.iconData.length > 0) {
Bitmap img = BitmapFactory.decodeByteArray(weather.iconData, 0, weather.iconData.length);
imgView.setImageBitmap(img);
}
else if(weatherData.size() > 0)
{
ArrayAdapter<Weather> adapter = new ArrayAdapter<Weather>(MainActivity.this,
android.R.layout.activity_list_item, weatherData);
listView1.setAdapter(adapter);
// here you can also define your custom adapter and set it to listView
//according to your own defined layout as items
}
cityText.setText(weather.location.getCity() + "," + weather.location.getCountry());
condDescr.setText(weather.currentCondition.getCondition() + "(" + weather.currentCondition.getDescr() + ")");
temp.setText("" + Math.round((weather.temperature.getTemp() - 273.15)) + "�C");
hum.setText("" + weather.currentCondition.getHumidity() + "%");
press.setText("" + weather.currentCondition.getPressure() + " hPa");
windSpeed.setText("" + weather.wind.getSpeed() + " mps");
windDeg.setText("" + weather.wind.getDeg() + "�");
}
}
}

You can use Gson to parse the json.
I'm assuming that you are receiving a jsonArray. So, you can do something like this:
ArrayList<Weather> weatherArrayList = new ArrayList<Weather>();
Gson gson = new Gson();
JsonParser jsonParser = new JsonParser();
JsonArray jArray = jsonParser.parse(responseStr).getAsJsonArray();
for (JsonElement obj : jArray) {
Weather weatherModel = gson.fromJson(response, Weather.class);
weatherArrayList.add(weatherModel);
}
The code above parse the data in your json and adds them into your "weatherArrayList" this ArrayList you should place it in your adapter and just set in your listview.
This might be your custom adapter
public class WeatherAdapter extends ArrayAdapter<Weather> {
public WeatherAdapter(Context context) {
super(context, 0);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
// here you should set up the custom view. That is the view of each Item of your ListView
}
}
I hope I helped you :)

Related

How to display name in spinner dynamically from server

Hi Now I'm retrieving data to spinner dynamically, but now it displaying some id's but those Id details are stored in other table, I want display those details in the spinner instead of id. And if I select particular product in spinner according that product details should display in list.
I'm using Retrofit method for retrieving data from server
package cfirst.live.com.activity;
public class Pos_outlet extends AppCompatActivity implements RestCallback,View.OnClickListener{
Spinner spinner;
ArrayList<String> products;
String numberAsString, product_name;
int i;
private int cartProductNumber = 0;
String[] items;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pos_outlet);
sharedPreference = new MySharedPreference(Pos_outlet.this);
GsonBuilder builder = new GsonBuilder();
gson = builder.create();
initViews();
}
private void initViews() {
row1 =(TableRow)findViewById(R.id.row1);
spinner=(Spinner)findViewById(R.id.spinner);
POSStoreID = (TextView) findViewById(R.id.POSStoreID);
POSLocationID = (TextView) findViewById(R.id.POSLocationID);
Intent intent = getIntent();
id = intent.getStringExtra("id");
index_id= intent.getStringExtra("index_id");
callStoreDetaislsAPI();
callSmbProductsAPI();
getProductAPI();
}
// **Using this api I'm setting id'd to spinner**
private void getProductAPI() {
HashMap<String, String> map = new HashMap<String, String>();
map.put("store", index_id);
Toast.makeText(getApplicationContext(),index_id, Toast.LENGTH_LONG).show();
RestService.getInstance(Pos_outlet.this).getproductlist(map, new MyCallback<List<PosmultistoresModel>>(Pos_outlet.this,
Pos_outlet.this, true, "Finding products....", GlobalVariables.SERVICE_MODE.GET_PRODUCTS));
}
// **this API have product Id's Details**
private void callSmbProductsAPI() {
HashMap<String, String> map = new HashMap<String, String>();
map.put("index_id", product);
//Toast.makeText(getApplicationContext(),added_by, Toast.LENGTH_LONG).show();
RestService.getInstance(Pos_outlet.this).getSmbProduct(map, new MyCallback<List<PosSmbProductModel>>(Pos_outlet.this,
Pos_outlet.this, true, "Fetching details....", GlobalVariables.SERVICE_MODE.SMB_PRODUCT));
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.AddtoBasket:
callPosProductsAPI();
callSmbProductsAPI();
break;
}
}
#Override
public void onFailure(Call call, Throwable t, GlobalVariables.SERVICE_MODE mode) {
//Toast.makeText(getApplication(),"failure",Toast.LENGTH_LONG).show();
}
#Override
public void onSuccess(Response response, GlobalVariables.SERVICE_MODE mode) {
switch (mode) {
//** I'm setting data to spinner **
case GET_PRODUCTS:
try {
List<PosmultistoresModel> businessgroups = (List<PosmultistoresModel>) response.body();
product_name = businessgroups.get(0).getProduct();
List<PosmultistoresModel> list=null;
for(i=0;i<businessgroups.size();i++)
{
list=businessgroups;
}
items = new String[list.size()];
for(int i=0; i<businessgroups.size(); i++){
//Storing names to string array
items[i] = list.get(i).getProduct();
}
ArrayAdapter<String> adapter1;
adapter1 = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, items);
//setting adapter to spinner
spinner.setAdapter(adapter1);
} catch (Exception e) {
e.printStackTrace();
}
break;**
// ** Product id details (title, image, etc) Api
case SMB_PRODUCT:
try {
ArrayList<PosSmbProductModel> products = (ArrayList<PosSmbProductModel>) response.body();
//Product_id = products.get(0).getProduct();
// for (int i = 0; i < products(); i++) {
Title = products.get(0).getTitle();
productname1.setText(Title);
imageid12 = products.get(0).getMain_image();
Picasso.with(this).load("https://www.consumer1st.in/pre_production/uploads/" + imageid12).into(imageid1);
}
// }
catch(Exception e)
{
e.printStackTrace();
}
break;
}
}
}
I am assuming that your product_name = businessgroups.get(0).getProduct(); is getting a pruduct.
First of all please remove this part
product_name = businessgroups.get(0).getProduct();
List<PosmultistoresModel> list=null;
for(i=0;i<businessgroups.size();i++)
{
list=businessgroups;
}
items = new String[list.size()];
for(int i=0; i<businessgroups.size(); i++){
//Storing names to string array
items[i] = list.get(i).getProduct();
}
then can you try
ArrayList<String> productList = new ArrayList<>();
for (int i = 0; i < businessgroups.size(); i++) {
productList.add(businessgroups.get(i).getProduct());
}
And finally
adapter1 = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, productList);

Return button to previous activity with BaseAdapter

I currently have two activities doing HTTP requests.
The first activity contains a CustomList class extends BaseAdapter.
On the second, there is a previous button allowing me to return to the first activity.
Returning to the first activity, I would like to be able to recover the state in which I left it. That is to say to be able to find the information which also come from an HTTP request. I would like to find the data "infos_user" which is in the first activity and all the data in the BaseAdapter.
My architecture is as follows: Activity 0 (HTTP request) -> Activity 1 (with BaseAdapter and HTTP request) -> Activity 2 (HTTP request)
I put all the code because I really don't know how can I do this :/
First activity:
public class GetChildrenList extends AppCompatActivity implements View.OnClickListener {
private ArrayList<Child> childrenImeList = new ArrayList<Child>();
private Button btn_previous;
private ListView itemsListView;
private TextView tv_signin_success;
int id = 0;
String infos_user;
String email;
String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.get_children_list);
infos_user = (String) getIntent().getSerializableExtra("infos_user");
Intent intent = new Intent(GetChildrenList.this , GetLearningGoalsList.class);
intent.putExtra("username", infos_user);
btn_previous = (Button) findViewById(R.id.btn_previous);
btn_previous.setOnClickListener(this);
tv_signin_success = (TextView) findViewById(R.id.tv_signin_success);
tv_signin_success.setText("Bonjour " + infos_user + "!");
itemsListView = (ListView)findViewById(R.id.list_view_children);
new GetChildrenAsync().execute();
}
class GetChildrenAsync extends AsyncTask<String, Void, ArrayList<Child>> {
private Dialog loadingDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(GetChildrenList.this, "Please wait", "Loading...");
}
#Override
protected ArrayList<Child> doInBackground(String... params) {
int age = 0;
email = (String) getIntent().getSerializableExtra("email");
password = (String) getIntent().getSerializableExtra("password");
String first_name = null;
String last_name = null;
try {
SendRequest sr = new SendRequest();
String result = sr.sendHttpRequest("http://" + sr.getIP_ADDRESS() + "/childrenime/list", "GET", true, email, password);
String jsonResult = "{ \"children\":" + result + "}";
Log.d("result1", jsonResult);
//Manage JSON result
JSONObject jsonObject = new JSONObject(jsonResult);
JSONArray childrenArray = jsonObject.getJSONArray("children");
for (int i = 0; i < childrenArray.length(); ++i) {
JSONObject child = childrenArray.getJSONObject(i);
id = child.getInt("id");
first_name = child.getString("first_name");
last_name = child.getString("last_name");
age = child.getInt("age");
String name = first_name + " " + last_name;
childrenImeList.add(new Child(id,name,age));
}
} catch (JSONException e) {
e.printStackTrace();
}
return childrenImeList;
}
#Override
protected void onPostExecute(final ArrayList<Child> childrenListInformation) {
loadingDialog.dismiss();
if(childrenListInformation.size() > 0) {
CustomListChildrenAdapter adapter = new CustomListChildrenAdapter(GetChildrenList.this, childrenListInformation);
itemsListView.setAdapter(adapter);
}
else{
Toast.makeText(getApplicationContext(), "Impossible de récupérer la liste des enfants", Toast.LENGTH_LONG).show();
}
}
}
}
BaseAdapter:
public class CustomListChildrenAdapter extends BaseAdapter implements View.OnClickListener {
private Context context;
private ArrayList<Child> children;
private Button btnChoose;
private TextView childrenName;
private TextView childrenAge;
public CustomListChildrenAdapter(Context context, ArrayList<Child> children) {
this.context = context;
this.children = children;
}
#Override
public int getCount() {
return children.size(); //returns total item in the list
}
#Override
public Object getItem(int position) {
return children.get(position); //returns the item at the specified position
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.layout_list_view_children,null);
childrenName = (TextView)view.findViewById(R.id.tv_childrenName);
childrenAge = (TextView) view.findViewById(R.id.tv_childrenAge);
btnChoose = (Button) view.findViewById(R.id.btn_choose);
btnChoose.setOnClickListener(this);
} else {
view = convertView;
}
btnChoose.setTag(position);
Child currentItem = (Child) getItem(position);
childrenName.setText(currentItem.getChildName());
childrenAge.setText(currentItem.getChildAge() + "");
return view;
}
#Override
public void onClick(View v) {
Integer position = (Integer) v.getTag();
Child item = (Child) getItem(position);
String email = (String) ((Activity) context).getIntent().getSerializableExtra("email");
String password = (String) ((Activity) context).getIntent().getSerializableExtra("password");
Intent intent = new Intent(context, GetLearningGoalsList.class);
intent.putExtra("idChild",item.getId());
intent.putExtra("email",email);
intent.putExtra("password",password);
context.startActivity(intent);
}
}
Second Activity:
public class GetLearningGoalsList extends AppCompatActivity implements View.OnClickListener {
private ArrayList<LearningGoal> childrenLearningList = new ArrayList<LearningGoal>();
private Button btn_previous;
private ListView itemsListView;
String email;
String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.get_learning_goals_list);
btn_previous = (Button) findViewById(R.id.btn_previous);
btn_previous.setOnClickListener(this);
itemsListView = (ListView)findViewById(R.id.list_view_learning_goals);
new GetLearningGoalsAsync().execute();
}
#Override
public void onClick(View v) {
Intent myIntent = new Intent(GetLearningGoalsList.this, GetChildrenList.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(myIntent);
return;
}
class GetLearningGoalsAsync extends AsyncTask<String, Void, ArrayList<LearningGoal>> {
private Dialog loadingDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(GetLearningGoalsList.this, "Please wait", "Loading...");
}
#Override
protected ArrayList<LearningGoal> doInBackground(String... params) {
int id = 0;
email = (String) getIntent().getSerializableExtra("email");
password = (String) getIntent().getSerializableExtra("password");
int idChild = (int) getIntent().getSerializableExtra("idChild");
String name = null;
String start_date = null;
String end_date = null;
try {
List<BasicNameValuePair> parameters = new LinkedList<BasicNameValuePair>();
parameters.add(new BasicNameValuePair("idchild", Integer.toString(idChild)));
SendRequest sr = new SendRequest();
String result = sr.sendHttpRequest("http://" + sr.getIP_ADDRESS() + "/learningchild/list"+ "?"+ URLEncodedUtils.format(parameters, "utf-8"), "POST", true, email, password);
String jsonResult = "{ \"learningGoals\":" + result + "}";
Log.d("result1", jsonResult);
//Manage JSON result
JSONObject jsonObject = new JSONObject(jsonResult);
JSONArray learningGoalsArray = jsonObject.getJSONArray("learningGoals");
for (int i = 0; i < learningGoalsArray.length(); ++i) {
JSONObject learningGoal = learningGoalsArray.getJSONObject(i);
id = learningGoal.getInt("id");
name = learningGoal.getString("name");
start_date = learningGoal.getString("start_date");
end_date = learningGoal.getString("end_date");
childrenLearningList.add(new LearningGoal(id,name,start_date,end_date));
}
} catch (JSONException e) {
e.printStackTrace();
}
return childrenLearningList;
}
#Override
protected void onPostExecute(final ArrayList<LearningGoal> learningListInformation) {
loadingDialog.dismiss();
if(learningListInformation.size() > 0) {
CustomListLearningGoalAdapter adapter = new CustomListLearningGoalAdapter(GetLearningGoalsList.this, learningListInformation);
itemsListView.setAdapter(adapter);
}
else{
Toast.makeText(getApplicationContext(), "Impossible de récupérer la liste des scénarios de cet enfant", Toast.LENGTH_LONG).show();
}
}
}
}
Thanks for your help.
if you want to maintain GetChildrenList state as it is then just call finish() rather than new intent on previous button click as follow
replace in GetLearningGoalsList
#Override
public void onClick(View v) {
Intent myIntent = new Intent(GetLearningGoalsList.this, GetChildrenList.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(myIntent);
return;
}
with
#Override
public void onClick(View v) {
finish();
}

Remove an item from view inside an adapter

I am trying to remove an item from view when its flag become 4. I tried mObjects.remove(position) and then notifyDataSetChanged(). but it didn't worked.we tried all the following
if (getItem(position).getFlag().trim().equalsIgnoreCase("4")) {
remove(position);
adapter.notifyDataSetChanged();
matcheslistview.setAdapter(adapter);
also this one
// mObjects.remove(position)
// notifyDataSetChanged();
and this one
// mObjects.remove(position);
//remove(position);
//mainObjects.remove(position);
//notifyDataSetChanged();
and this one
// Object toRemove = adapter.getItem(position);
// mObjects.remove(toRemove);
// mObjects.clear();
and all the time we got java.lang.IndexOutOfBoundsException: Invalid index 1, size is 0.Here is the complete adapter class
private class MatchedDataAdapter extends BaseAdapter implements Filterable {
private AQuery aQuery;
private Activity mActivity;
private LayoutInflater mInflater;
private SessionManager sessionManager;
private int uflag;
MyFilter mfilter;
DatabaseHandler db;
ArrayList<LikeMatcheddataForListview> mObjects;
ArrayList<LikeMatcheddataForListview> mainObjects;
Context context;
public MatchedDataAdapter(Activity context,
ArrayList<LikeMatcheddataForListview> objects,
int imageHeigthAndWidth[]) {
this.mObjects = objects;
mainObjects = objects;
//Log.e("size", Integer.toString(mObjects.size()));
this.mActivity = context;
try {
mInflater = (LayoutInflater) mActivity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
catch (Exception e)
{
e.printStackTrace();
}
aQuery = new AQuery(context);
db = new DatabaseHandler(context);
}
#Override
public int getCount() {
return mObjects.size();
}
#Override
public LikeMatcheddataForListview getItem(int position) {
return mObjects.get(position);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.matchedlistviewitem,
null);
holder.imageview = (ImageView) convertView
.findViewById(R.id.userimage);
holder.textview = (TextView) convertView
.findViewById(R.id.userName);
holder.lastMasage = (TextView) convertView
.findViewById(R.id.lastmessage);
holder.imgStatus = (ImageView) convertView
.findViewById(R.id.imgStatus);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textview.setText(getItem(position).getUserName());
if (getItem(position).getFlag().trim().equalsIgnoreCase("4")) {
mObjects.remove(position);
adapter.notifyDataSetChanged();
matcheslistview.setAdapter(adapter);
we want to remove Item with flag 4,we are reading this flag with a service from db and onrecive we call class DisplayContentTask as below
class GetLikeMatchedReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
new DisplayContentTask(intent).execute();
}
}
how we can get Item position in order to remove the Item with flag 4...or My be another approach to remove Item with flag 4 we don't know but appreciate your help on this
class DisplayContentTask extends AsyncTask<Void, Void, Void> {
Intent intent;
private Ultilities mUltilities = new Ultilities();
private List<NameValuePair> getuserparameter;
private String likedmatchedata, Unmatchedata;
int match1;
private LikedMatcheData matcheData;
private ArrayList<com.appdupe.flamer.pojo.Likes> likesList;
private LikeMatcheddataForListview matcheddataForListview;
DatabaseHandler mDatabaseHandler = new DatabaseHandler(getActivity());
private boolean isResponseSuccess = true;
ArrayList<LikeMatcheddataForListview> tempArray = new ArrayList<LikeMatcheddataForListview>();
#Override
protected void onPreExecute() {
super.onPreExecute();
AppLog.Log(TAG, "BackgroundTaskForFindLikeMatched onPreExecute ");
}
DisplayContentTask(Intent intent) {
this.intent = intent;
}
#Override
protected Void doInBackground(Void... voids) {
try {
File appDirectory = mUltilities
.createAppDirectoy(getResources().getString(
R.string.appdirectory));
AppLog.Log(TAG,
"BackgroundTaskForFindLikeMatched doInBackground appDirectory "
+ appDirectory);
File _picDir = new File(appDirectory, getResources().getString(
R.string.imagedirematchuserdirectory));
AppLog.Log(TAG,
"BackgroundTaskForFindLikeMatched doInBackground ");
// getuserparameter = mUltilities.getUserLikedParameter(params);
likedmatchedata = intent.getStringExtra("GET_MATCHED_RESPONSE");
// Unmatchedata = intent.getStringExtra("GET_UNMATCHED_RESPONSE");//hadi
AppLog.Log(TAG,
"BackgroundTaskForFindLikeMatched doInBackground likedmatchedata "
+ likedmatchedata);
Gson gson = new Gson();
matcheData = gson.fromJson(likedmatchedata,
LikedMatcheData.class);
AppLog.Log(TAG,
"BackgroundTaskForFindLikeMatched doInBackground matcheData "
+ matcheData);
// "errNum": "51",
// "errFlag": "0",
// "errMsg": "Matches found!",
if (matcheData.getErrFlag() == 0) {
likesList = matcheData.getLikes();
AppLog.Log(TAG,
"BackgroundTaskForFindLikeMatched doInBackground likesList "
+ likesList);
if (tempArray != null) {
tempArray.clear();
}
AppLog.Log(TAG,
"BackgroundTaskForFindLikeMatched doInBackground likesList sized "
+ likesList.size());
Log.v("Matches", "" + likesList.size());
match1 = likesList.size();
for (int i = 0; i < likesList.size(); i++) {
Log.d("likelist", likesList.toString());
matcheddataForListview = new LikeMatcheddataForListview();
String userName = likesList.get(i).getfName();
String facebookid = likesList.get(i).getFbId();
// Log.i(TAG, "Background facebookid......"+facebookid);
String picturl = likesList.get(i).getpPic();
int falg = likesList.get(i).getFlag();
// if (likesList.get(i).getFlag()==4) {
// likesList.remove(getId());
// }
Log.i("komak10",""+likesList.get(i).getFlag());
String latd = likesList.get(i).getLadt();
matcheddataForListview.setFacebookid(facebookid);
matcheddataForListview.setUserName(userName);
matcheddataForListview.setImageUrl(picturl);
matcheddataForListview.setFlag("" + falg);
matcheddataForListview.setladt(latd);
// matcheddataForListview.setFilePath(filePath);
File imageFile = mUltilities.createFileInSideDirectory(
_picDir, userName + facebookid + ".jpg");
// logDebug("BackGroundTaskForUserProfile doInBackground imageFile is profile "+imageFile.isFile());
Utility.addBitmapToSdCardFromURL(likesList.get(i)
.getpPic().replaceAll(" ", "%20"), imageFile);
matcheddataForListview.setFilePath(imageFile
.getAbsolutePath());
if (!preferences.getString(Constant.FACEBOOK_ID, "")
.equals(facebookid)) {
tempArray.add(matcheddataForListview);
}
}
DatabaseHandler mDatabaseHandler = new DatabaseHandler(
getActivity());
// SessionManager mSessionManager = new SessionManager(
// MainActivity.this);
String userFacebookid = preferences.getString(
Constant.FACEBOOK_ID, "");
//
boolean isdataiserted = mDatabaseHandler.insertMatchList(
tempArray, userFacebookid);
} else if (matcheData.getErrFlag() == 1) {
if(tempArray!=null)
{
tempArray.clear();
}
} else {
// do nothing
}
} catch (Exception e) {
AppLog.handleException(
"BackgroundTaskForFindLikeMatched doInBackground Exception ",
e);
// some thing wrong happend
isResponseSuccess = false;
}
return null;
}
Don't remove the object in getview, if you have to filter it, filter it before sending out to adapter. May be possible that while creating the child view the 1st cell has tag "4" now the view didn't create(since return was not called) but you are trying to remove its position, so it will definitely give you IndexOutOfBoundsException.
My best solution would be, set the adapter with
new ArrayList<LikeMatcheddataForListview>()
whenever you start the screen. Once your AsyncTask completes filter out the child with tags "4"(better filter it out in the asynctask only, less task in ui thread) then refresh the adapter, like
public void refresh(ArrayList<LikeMatcheddataForListview>() arrObjects){
objects = arrObjects;
notifyDataSetChanged();
}
Check it out, it should do the trick
Please try following
Your code
if (getItem(position).getFlag().trim().equalsIgnoreCase("4")) {
mObjects.remove(position);
adapter.notifyDataSetChanged();
matcheslistview.setAdapter(adapter);
}
TO
do not set adapter again to list view
if (getItem(position).getFlag().trim().equalsIgnoreCase("4")) {
mObjects.remove(position);
notifyDataSetChanged();
}
This may not be correct approach to remove the item form listview.
Whenever your adapter data is getting changed then just check if that flag matches your string i.e. "4" in each item and remove the respective item from the list and just call notifyItemRemoved with position insted of notifyDataSetChanged

can't show the thumbnail from youtube?

this app should show thumbnail , title, and the duration of each video in the playlist selected , but thumbnail remain white
the application works but It don't show the thumbnail of the video in the playlist
how can I do ? you have any solution?
THIS IS MY CODE
public class MainActivity extends Activity {
ImageView mainThumb;
TextView mainTitle;
TextView mainTime;
LinearLayout videos;
ArrayList<String> links;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.videos);
new ParseVideoDataTask().execute();
mainThumb = (ImageView) findViewById(R.id.mainThumb);
mainTitle = (TextView) findViewById(R.id.mainTitle);
mainTime = (TextView) findViewById(R.id.mainTime);
videos = (LinearLayout) findViewById(R.id.videos);
}
private class ParseVideoDataTask extends AsyncTask<String, String, String> {
int count = 0;
#Override
protected String doInBackground(String... params) {
URL jsonURL;
URLConnection jc;
links = new ArrayList<String>();
try {
jsonURL = new URL("http://gdata.youtube.com/feeds/api/playlists/" +
"PL-7t9DoIELCRF7F7bZvvBwO1yvHRFsJiu" +
"?v=2&alt=jsonc");
//PL_VGbflD64WSR1MBcpWlNwsY0lRNVuJ3r
jc = jsonURL.openConnection();
InputStream is = jc.getInputStream();
String jsonTxt = IOUtils.toString(is);
JSONObject jj = new JSONObject(jsonTxt);
JSONObject jdata = jj.getJSONObject("data");
JSONArray aitems = jdata.getJSONArray("items");
for (int i=0;i<aitems.length();i++) {
JSONObject item = aitems.getJSONObject(i);
JSONObject video = item.getJSONObject("video");
String title = video.getString("title");
JSONObject player = video.getJSONObject("player");
String link = player.getString("default");
String length = video.getString("duration");
JSONObject thumbnail = video.getJSONObject("thumbnail");
String thumbnailUrl = thumbnail.getString("hqDefault");
String[] deets = new String[4];
deets[0] = title;
deets[1] = thumbnailUrl;
deets[2] = length;
links.add(link);
publishProgress(deets);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(final String... deets) {
count++;
if (count == 1) {
MainActivity.setImageFromUrl(deets[1], mainThumb, MainActivity.this);
mainTitle.setText(deets[0]);
mainTime.setText(formatLength(deets[2]));
mainThumb.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(links.get(1)));
startActivity(i);
}
});
} else {
LayoutInflater layoutInflater = (LayoutInflater)MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View video = layoutInflater.inflate(R.layout.video, null);
ImageView thumb = (ImageView) video.findViewById(R.id.thumb);
TextView title = (TextView) video.findViewById(R.id.title);
TextView time = (TextView) video.findViewById(R.id.time);
MainActivity.setImageFromUrl(deets[1], thumb, MainActivity.this);
title.setText(deets[0]);
time.setText(formatLength(deets[2]));
video.setPadding(20, 20, 20, 20);
videos.addView(video);
video.setId(count-1);
video.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(links.get(v.getId())));
startActivity(i);
}
});
}
}
}
private CharSequence formatLength(String secs) {
int secsIn = Integer.parseInt(secs);
int hours = secsIn / 3600,
remainder = secsIn % 3600,
minutes = remainder / 60,
seconds = remainder % 60;
return ((minutes < 10 ? "0" : "") + minutes
+ ":" + (seconds< 10 ? "0" : "") + seconds );
}
public static void setImageFromUrl(String string, ImageView mainThumb2,
MainActivity mainActivity) {
}
#Override
public void onDestroy() {
super.onDestroy();
for (int i=0;i<videos.getChildCount();i++) {
View v = videos.getChildAt(i);
if (v instanceof ImageView) {
ImageView iv = (ImageView) v;
((BitmapDrawable)iv.getDrawable()).getBitmap().recycle();
}
}
}
}
Use Picasso to set the image url like so:
Picasso.withContext(this).load(thumbnailUrl).into(myImageView);
To do this you'll need to return the JSON object in the doInBackground method, or use something like Retrofit (as I mentioned in the comment above) to get a nice POJO and return that. Then in the postExecute you can use the thumbnail url in the JSON (or POJO) and set it using Picasso above. Picasso will take care of downloading and caching the image for you and loading it into the image view.

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.

Categories

Resources