notifyDataSetChanged() not working with GridView inside Fragment - android

I have a gridview inside my fragment that is populated by a BaseAdapter.
The problem is that in my adapter i have a favorite button, and when i click i want the button to change. But the logic in API is done, but my button just change when i reload page.
I tried using adapter.notifyDataSetChanged(); but didn't work.
My getView adapter code:
//Implementando os clicks
itemHolder.imgFavorito.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!util.isLogado(context)) {
((MainActivity) context).selectDrawerItem(new LoginFragment());
}
try {
SharedPreferences pref = context.getSharedPreferences("MyPref", 0);
produtoFavorito(new favoritarProduto().execute(pref.getString("USID", "null"), item.getId() + "").get());
} catch (Exception e) {
e.printStackTrace();
}
fragment.notifyAdapterChanged();
}
});
In fragment.notifyAdapterChanged(); line a just call my Fragment that i recieve in constructor of adapter, and this is the function:
public void notifyAdapterChanged(){
adapter.notifyDataSetChanged();
}
EDIT1: How my layout looks like
http://i.imgur.com/SPr0HBS.png
EDIT2: My full Adapter
public class ProdutoAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private List<ProdutoResumido> itens;
private HomeFragment fragment;
public ProdutoAdapter(Context context, List<ProdutoResumido> itens, HomeFragment fragment) {
//Itens do listview
this.itens = itens;
//Objeto responsável por pegar o Layout do item.
//mInflater = LayoutInflater.from(context);
mInflater = (LayoutInflater) context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.fragment = fragment;
}
public int getCount() {
return itens.size();
}
public ProdutoResumido getItem(int position) {
return itens.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View view, ViewGroup parent) {
ItemSuporte itemHolder;
//se a view estiver nula (nunca criada), inflamos o layout nela.
if (view == null) {
//infla o layout para podermos pegar as views
view = mInflater.inflate(R.layout.lista_produtos_fg, null);
//cria um item de suporte para não precisarmos sempre
//inflar as mesmas informacoes
itemHolder = new ItemSuporte();
itemHolder.imgProduto = ((ImageView) view.findViewById(R.id.imgProduto));
itemHolder.txtPreco = ((TextView) view.findViewById(R.id.txtPreco));
itemHolder.imgFavorito = ((ImageView) view.findViewById(R.id.imgFavorito));
itemHolder.txtNomeProduto = ((TextView) view.findViewById(R.id.txtNomeProduto));
itemHolder.txtEstadoProduto = ((TextView) view.findViewById(R.id.txtEstadoProduto));
itemHolder.imgLoja = ((ImageView) view.findViewById(R.id.imgLoja));
itemHolder.txtNomeLoja = ((TextView) view.findViewById(R.id.txtNomeLoja));
//define os itens na view;
view.setTag(itemHolder);
} else {
//se a view já existe pega os itens.
itemHolder = (ItemSuporte) view.getTag();
}
final Context context = view.getContext();
//pega os dados da lista
//e define os valores nos itens.
final ProdutoResumido item = itens.get(position);
Loja loja = new Loja();
itemHolder.txtPreco.setText("R$ " + new DecimalFormat("#.00").format(item.getValor()));
itemHolder.imgFavorito.setImageResource(produtoFavorito(item.getFavorito()));
itemHolder.txtNomeProduto.setText(item.getNome());
itemHolder.txtEstadoProduto.setText("ESTADO: " + item.getTempoUso());
itemHolder.txtNomeLoja.setText(item.getLoja());
try {
if (item.getImagem() != null)
new DownloadImageTask(itemHolder.imgProduto).execute("http://200.98.202.23/JustForMoms/" + item.getImagem());
if (item.getLojaImg() != null)
new DownloadImageTask(itemHolder.imgLoja).execute("http://200.98.202.23/JustForMoms/" + item.getLojaImg());
} catch (Exception e) {
e.printStackTrace();
}
//Implementando os clicks
itemHolder.imgFavorito.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!util.isLogado(context)) {
((MainActivity) context).selectDrawerItem(new LoginFragment());
}
try {
SharedPreferences pref = context.getSharedPreferences("MyPref", 0);
produtoFavorito(new favoritarProduto().execute(pref.getString("USID", "null"), item.getId() + "").get());
} catch (Exception e) {
e.printStackTrace();
}
fragment.notifyAdapterChanged();
}
});
//retorna a view com as informações
return view;
}
private int produtoFavorito(Boolean favorito) {
if (favorito)
return R.drawable.favorite;
else
return R.drawable.notfavorite;
}
/**
* Classe de suporte para os itens do layout.
*/
private class ItemSuporte {
ImageView imgProduto;
TextView txtPreco;
ImageView imgFavorito;
TextView txtNomeProduto;
TextView txtEstadoProduto;
ImageView imgLoja;
TextView txtNomeLoja;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
public class favoritarProduto extends AsyncTask<String, Void, Boolean> {
private String retorno;
private String url;
#Override
protected Boolean doInBackground(String... params) {
String usID = params[0];
String prodID = params[1];
url = "http://200.98.202.23/JustForMoms/Produto/FavoritarProduto/" + usID + "/" + prodID;
webclient client = new webclient(url);
retorno = client.getmodel();
if (retorno != null) {
if (retorno.equals("\"incluido\"")) {
return true;
} else {
return false;
}
}
return false;
}
}
}
EDIT 3:
//Implementando os clicks
itemHolder.imgFavorito.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!util.isLogado(context)) {
((MainActivity) context).selectDrawerItem(new LoginFragment());
}
try {
SharedPreferences pref = context.getSharedPreferences("MyPref", 0);
itemHolder.imgFavorito.setImageResource(produtoFavorito(new favoritarProduto().execute(pref.getString("USID", "null"), item.getId() + "").get()));
} catch (Exception e) {
e.printStackTrace();
}
ProdutoAdapter.this. notifyDataSetChanged();
}
});

Ok, You are calling favoritarProduto() which in turn makes a call to server to update the favorite status :)
But you missed one simple thing :) Dude its Async call :) That means it takes time to execute the code inside doInBackground:) How can you expect the status to be updated and ready immediately as if it is synchronous call??? :)
Modify the code as shown here
public class favoritarProduto extends AsyncTask<String, Void, Boolean> {
private String retorno;
private String url;
#Override
protected Boolean doInBackground(String... params) {
String usID = params[0];
String prodID = params[1];
url = "http://200.98.202.23/JustForMoms/Produto/FavoritarProduto/" + usID + "/" + prodID;
webclient client = new webclient(url);
retorno = client.getmodel();
if (retorno != null) {
if (retorno.equals("\"incluido\"")) {
return true;
} else {
return false;
}
}
return false;
}
#Override
protected void onPostExecute(Boolean response) {
//call your produtoFavorito fro the item holder based on prodID you have received :)
}
}

Related

I used PagerAdapter for sliding images its not notifying properly

I used PagerAdapter for sliding images and i added a favorite button too in that sliding image. After clicking favorite button its not getting notified properly image not turns to unfavorite icon.
it is for loading api
private class PremiumProjectLoad extends AsyncTask<String, Void, JSONObject> {
JSONParser jsonParser = new JSONParser();
String url= ApiLinks.PremiumProject;
ProgressHUD mProgressHUD;
protected void onPreExecute(){
mProgressHUD = ProgressHUD.show(getActivity(),null, true);
super.onPreExecute();
}
protected JSONObject doInBackground(String... arg0) {
HashMap<String,String> params=new HashMap<>();
try {
params.put("languageID",CommonStrings.languageID);
params.put("cityID",CommonStrings.cityID);
if(session.isLoggedIn()){
params.put("userID",UserLogin.get(SessionManager.KEY_CUSTOMER_ID));
}
JSONObject json = jsonParser.SendHttpPosts(url,"POST",params);
if (json != null) {
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONObject json) {
if(json!=null) {
String Status=json.optString("status");
String Message=json.optString("message");
CommonImagePath=json.optString("imagepath");
PremiumDataArray.clear();
if(Status.equals("ok")){
JSONArray DataArray=json.optJSONArray("data");
if(DataArray!=null && DataArray.length()>0) {
for (int i = 0; i < DataArray.length(); i++) {
JSONObject DataObj = DataArray.optJSONObject(i);
String projectID = DataObj.optString("projectID");
String projectName = DataObj.optString("projectName");
String propertyUnitPriceRange = DataObj.optString("propertyUnitPriceRange");
String projectOfMonthImage = DataObj.optString("projectOfMonthImage");
String propertyUnitBedRooms = DataObj.optString("propertyUnitBedRooms");
String projectBuilderName = DataObj.optString("projectBuilderName");
String propertyTypeName = DataObj.optString("propertyTypeName");
String purpose = DataObj.optString("purpose");
String projectBuilderAddress = DataObj.optString("projectBuilderAddress");
String projectFavourite = DataObj.optString("projectFavourite");
PremiumData premiumData = new PremiumData();
premiumData.setProjectID(projectID);
premiumData.setProjectName(projectName);
premiumData.setPropertyUnitPriceRange(propertyUnitPriceRange);
premiumData.setProjectOfMonthImage(projectOfMonthImage);
premiumData.setPropertyUnitBedRooms(propertyUnitBedRooms);
premiumData.setProjectBuilderName(projectBuilderName);
premiumData.setPropertyTypeName(propertyTypeName);
premiumData.setPurpose(purpose);
premiumData.setProjectBuilderAddress(projectBuilderAddress);
premiumData.setProjectFavourite(projectFavourite);
PremiumDataArray.add(premiumData);
}
LoopViewPager viewpager = (LoopViewPager) homeView.findViewById(R.id.viewpager);
CircleIndicator indicator = (CircleIndicator) homeView.findViewById(R.id.indicator);
// if(pagerAdapter==null)
pagerAdapter = new PremiumProjectAdapter(getActivity(), PremiumDataArray);
viewpager.setAdapter(pagerAdapter);
indicator.setViewPager(viewpager);
// pagerAdapter.notifyDataSetChanged();
}
}
else {
Toast.makeText(getActivity(),Message, Toast.LENGTH_LONG).show();
}
}
mProgressHUD.dismiss();
}
}
pager adapter
public class PremiumProjectAdapter extends PagerAdapter {
private final Random random = new Random();
private ArrayList<PremiumData> mSize;
Context mContext;
LayoutInflater mLayoutInflater;
String ProjectID;
String path=CommonImagePath+"/uploads/projectOfMonth/orginal/";
// public PremiumProjectAdapter() {
// }
public PremiumProjectAdapter(Context contexts, ArrayList<PremiumData> count) {
mSize = count;
mContext=contexts;
}
#Override public int getCount() {
return mSize.size();
}
#Override public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override public void destroyItem(ViewGroup view, int position, Object object) {
view.removeView((View) object);
}
#Override public Object instantiateItem(ViewGroup view, final int position) {
mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = mLayoutInflater.inflate(R.layout.home_premium_layout, view, false);
ImageView imageView = (ImageView) itemView.findViewById(R.id.premium_ProImage);
TextView ProjectName = (TextView) itemView.findViewById(R.id.premium_ProName);
TextView ProjectUnitPrice = (TextView) itemView.findViewById(R.id.premium_UnitPrice);
TextView ProjectUnitBedroom = (TextView) itemView.findViewById(R.id.premium_UnitBedrooms);
TextView ProjectAddress = (TextView) itemView.findViewById(R.id.premium_ProAddress);
ImageView unshortlisted = (ImageView) itemView.findViewById(R.id.unshortlisted);
ImageView shortlisted = (ImageView) itemView.findViewById(R.id.shortlisted);
final PremiumData data = mSize.get(position);
if (data.getProjectFavourite() != null) {
if (data.getProjectFavourite().equals("ShortListed")) {
shortlisted.setVisibility(View.VISIBLE);
unshortlisted.setVisibility(View.GONE);
} else {
shortlisted.setVisibility(View.GONE);
unshortlisted.setVisibility(View.VISIBLE);
}
}
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
ProjectUnitPrice.setText(Html.fromHtml(data.getPropertyUnitPriceRange(), Html.FROM_HTML_MODE_COMPACT));
}else{
ProjectUnitPrice.setText(Html.fromHtml(data.getPropertyUnitPriceRange()));
}
ImageLoader.getInstance().displayImage(path+data.getProjectOfMonthImage(), imageView);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
if(!data.getProjectName().equals("null") && data.getProjectName().length()>30){
String s = data.getProjectName().substring(0, 25);
String subString = s + "...";
ProjectName.setText(subString);
}
else{
ProjectName.setText(data.getProjectName());
}
ProjectUnitBedroom.setText(data.getPropertyUnitBedRooms());
ProjectAddress.setText(data.getProjectBuilderAddress());
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent DetailsAction=new Intent(mContext, DetailsActivity.class);
DetailsAction.putExtra("projectID",data.getProjectID());
DetailsAction.putExtra("purpose",data.getPurpose());
mContext.startActivity(DetailsAction);
}
});
unshortlisted.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!session.isLoggedIn()){
Intent toLogin=new Intent(mContext, LoginActivity.class);
CommonStrings.FromSearchIndex="true";
mContext.startActivity(toLogin);
}else{
ProjectID=data.getProjectID();
new ShortlistProject().execute();
}
}
});
shortlisted.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ProjectID=data.getProjectID();
new UnShortlistProject().execute();
}
});
view.addView(itemView);
return itemView;
}
private class ShortlistProject extends AsyncTask<String, Void, JSONObject> {
JSONParser jsonParser = new JSONParser();
String url=ApiLinks.AddShortListProject;
ProgressHUD mProgressHUD;
protected void onPreExecute(){
mProgressHUD = ProgressHUD.show(mContext,null, true);
super.onPreExecute();
}
protected JSONObject doInBackground(String... arg0) {
HashMap<String,String> params=new HashMap<>();
try {
params.put("languageID",CommonStrings.languageID);
params.put("userID",User.get(SessionManager.KEY_CUSTOMER_ID));
params.put("projectID",ProjectID);
params.put("userType",User.get(SessionManager.KEY_USERTYPE_ID));
JSONObject json = jsonParser.SendHttpPosts(url,"POST",params);
if (json != null) {
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONObject json) {
if(json!=null) {
String status=json.optString("status");
String message=json.optString("message");
if(status.equals("ok")){
Toast.makeText(mContext,message,Toast.LENGTH_LONG).show();
//SearchFragment.getInstance().onResume();
HomeFragment.getInstance().async_premium();
}else{
Toast.makeText(mContext,message,Toast.LENGTH_LONG).show();
}
}
mProgressHUD.dismiss();
}
}
private class UnShortlistProject extends AsyncTask<String, Void, JSONObject> {
JSONParser jsonParser = new JSONParser();
String url=ApiLinks.RemoveShortListProject;
ProgressHUD mProgressHUD;
protected void onPreExecute(){
mProgressHUD = ProgressHUD.show(mContext,null, true);
super.onPreExecute();
}
protected JSONObject doInBackground(String... arg0) {
HashMap<String,String> params=new HashMap<>();
try {
params.put("userID",User.get(SessionManager.KEY_CUSTOMER_ID));
params.put("projectID",ProjectID);
params.put("userType",User.get(SessionManager.KEY_USERTYPE_ID));
JSONObject json = jsonParser.SendHttpPosts(url,"POST",params);
if (json != null) {
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONObject json) {
if(json!=null) {
String status=json.optString("status");
String message=json.optString("message");
if(status.equals("ok")){
Toast.makeText(mContext,message,Toast.LENGTH_LONG).show();
// HomeFragment.getInstance().async_Premium();
HomeFragment.getInstance().async_premium();
}else{
Toast.makeText(mContext,message,Toast.LENGTH_LONG).show();
}
}
mProgressHUD.dismiss();
}
}
As far as i am able to understand your question you want favorite and unfavorite functionality by adapter . Please use this code below to achieve that :
public class CustomGridAdapterFoodDrink extends BaseAdapter {
private Context mContext;
private ProgressDialog loading;
ArrayList<FoodDrink> foodDrinkArrayList = new ArrayList<>();
SharedPreferences pref;
String userId;
String like_dislike_value = "Like";
String likeValueStr = "1";
boolean like = true;
int positionVal = 444;
HashMap<Integer,Boolean> state = new HashMap<>();
public CustomGridAdapterFoodDrink(Context c, ArrayList<FoodDrink> foodDrinkArrayList) {
mContext = c;
this.foodDrinkArrayList = foodDrinkArrayList;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return foodDrinkArrayList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View grid;
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
grid = new View(mContext);
grid = inflater.inflate(R.layout.grid_single, null);
TextView projectNamtTxtView = (TextView) grid.findViewById(R.id.projectName);
TextView totalOfferText = (TextView) grid.findViewById(R.id.TotalOffers);
ImageView merchantImage = (ImageView) grid.findViewById(R.id.merchantImage);
final ImageView like_dislike_icon = (ImageView) grid.findViewById(R.id.like_dislike_icon);
totalOfferText.setText(foodDrinkArrayList.get(position).getOffers());
projectNamtTxtView.setText(foodDrinkArrayList.get(position).getProject_name());
Glide.with(mContext)
.load(foodDrinkArrayList.get(position).getProject_photo())
.centerCrop()
.placeholder(R.drawable.review_pro_pic1)
.crossFade()
.into(merchantImage);
like_dislike_icon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
userId = pref.getString("userId", null);
/* if(state.size()> 0){
like = state.get(position);*/
if (!like) {
like = true;
/* state.put(position,like);*/
like_dislike_icon.setImageResource(R.mipmap.like_it_act);
likeDislike2(foodDrinkArrayList.get(position).getID(), "1");
} else {
like = false;
/* state.put(position,like);*/
like_dislike_icon.setImageResource(R.mipmap.like_it);
likeDislike2(foodDrinkArrayList.get(position).getID(), "0");
}
/* } else {
like = true;
state.put(position,like);
like_dislike_icon.setImageResource(R.mipmap.like_it_act);
likeDislike2(foodDrinkArrayList.get(position).getID(), "1");
}*/
// if(positionVal !=position) {
// likeValueStr ="1";
// positionVal = position;
// likeDislike(foodDrinkArrayList.get(position).getID(), likeValueStr, like_dislike_icon);
// }
// else {
// likeValueStr ="0";
// likeDislike(foodDrinkArrayList.get(position).getID(), likeValueStr, like_dislike_icon);
// }
}
});
} else {
grid = (View) convertView;
}
return grid;
}
private void likeDislike(String merchantId, final String like_dislike, final ImageView imageView) {
loading = ProgressDialog.show(mContext, "Loading ", "Please wait...", true, true);
AsyncHttpClient client = new AsyncHttpClient();
String url = getlikeUrl(userId, merchantId, like_dislike);
client.setMaxRetriesAndTimeout(5, 20000);
client.post(url, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String responseString) {
try {
JSONObject _object = new JSONObject(responseString);
String status = _object.getString("success");
String msg = _object.getString("response");
if ("true".equalsIgnoreCase(status)) {
Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
if (msg.equalsIgnoreCase("Like")) {
imageView.setImageResource(R.mipmap.like_it_act);
} else {
imageView.setImageResource(R.mipmap.like_it);
}
} else {
Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
}
loading.dismiss();
// AppUtility.showToast(SignUp.this, message);
} catch (JSONException e) {
e.printStackTrace();
new Global().saveReport("abc", e.getStackTrace(), e.toString());
}
loading.dismiss();
}
#Override
public void onFailure(int statusCode, Throwable error, String content) {
}
});
}
private String getlikeUrl(String userId, String merchantId, String like_dislike) {
String url = "";
try {
url = NetworkURL.URL
+ "likeMerchant"
+ "?user_id=" + URLEncoder.encode(new Global().checkNull(userId), "UTF-8")
+ "&merchant_id=" + URLEncoder.encode(new Global().checkNull(merchantId), "UTF-8")
+ "&like_dislike=" + URLEncoder.encode(new Global().checkNull(like_dislike), "UTF-8")
;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
new Global().saveReport("abc", e.getStackTrace(), e.toString());
}
return url;
}
private void likeDislike2(String merchantId, final String like_dislike) {
loading = ProgressDialog.show(mContext, "Loading ", "Please wait...", true, true);
AsyncHttpClient client = new AsyncHttpClient();
String url = getlikeUrl(userId, merchantId, like_dislike);
client.setMaxRetriesAndTimeout(5, 20000);
client.post(url, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String responseString) {
try {
JSONObject _object = new JSONObject(responseString);
String status = _object.getString("success");
String msg = _object.getString("response");
if ("true".equalsIgnoreCase(status)) {
Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
}
loading.dismiss();
// AppUtility.showToast(SignUp.this, message);
} catch (JSONException e) {
e.printStackTrace();
new Global().saveReport("abc", e.getStackTrace(), e.toString());
}
loading.dismiss();
}
#Override
public void onFailure(int statusCode, Throwable error, String content) {
}
});
}
}

My questions is, how do I pass the list data i have obtained from JSON in a fragment to an activity?

This is my Fragment Class - Here i get the JSON array object and call the adapter class for setting it. In the corressponding XML file, i have used a card view and lsit view to display the data. i want to know how to implement a onItemClickListener{} function so that i can go to another activity and display the list in a more detailed manner.
{
String url = "http://www.appplay.in/student_project/public/staff_details";
ProgressDialog mProgressDialog;
ListView lvDetail;
Context context;
ArrayList<staff_model> myList = new ArrayList<>();
ListView lv;
public static ArrayList<staff_model> staff_array;
JSONObject jsonObject;
JSONObject jsonKey;
Button submit;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, final Bundle savedInstanceState) {
context=container.getContext();
View v = inflater.inflate(R.layout.tab_fragment_2, container, false);
lvDetail = (ListView) v.findViewById(R.id.CustomList);
// submit=(Button)v.findViewById(R.id.button) ;
new GetGalleryimage().execute();
v.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
Intent in = new Intent(getActivity(), Staff_Main.class);
startActivity(in);
}
});
return v;
}
public void positionAction(View view) {
int position = (int) view.getTag();
Toast.makeText(view.getContext(),Integer.toString(position),Toast.LENGTH_SHORT).show();
}
private class GetGalleryimage extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setMessage("Please wait...");
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray jsonarr = jsonObj.getJSONArray("User_Details");
for(int i=0; i<jsonarr.length(); i++)
{
JSONObject jsonObject = jsonarr.getJSONObject(i);
myList.add(new staff_model(jsonObject.getString("name"),jsonObject.getString("dob"),jsonObject.getString("occupation"),jsonObject.getString("emailid"),jsonObject.getString("contact"),jsonObject.getString("timetable"),jsonObject.getString("image")));
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
Log.v("result",""+result);
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
staff_BaseAdapter rcAdapter = new staff_BaseAdapter(getActivity(),0, myList);
lvDetail.setAdapter(rcAdapter);
}
}
public class MAP_Detailservice extends
AsyncTask<String, String, String> {
Context mContext;
JSONObject mJsnObj;
ProgressDialog mProgressDialog;
#Override
protected void onPreExecute() {
showProgress();
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
JSONObject json = new JSONObject();
String cricketAllMatchesLink = "http://www.appplay.in/student_project/public/staff_details";
try {
return String.valueOf(HttpUtils.getJson(cricketAllMatchesLink));
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
Log.v("POST EXECUTE", "RESULT :" + result);
super.onPostExecute(result);
hideProgress();
// mProgressDialog.dismiss();
// if (HttpUtils.status == 408) {
// Toast.makeText(getActivity(), "Conection Lost ",
// Toast.LENGTH_SHORT).show();
// }
try {
JSONArray array = new JSONArray(result);
JSONObject mJsonObject = array.getJSONObject(0);
// ArrayList<user_agent> GetSearchResults();
ArrayList<staff_model> staff_result = new ArrayList<staff_model>();
/**
* Question Array Parsing
*/
JSONArray jsonQuesstionsArray = mJsonObject
.getJSONArray("User_Details");
for (int i = 0; i < jsonQuesstionsArray.length(); i++) {
// Reading questions
JSONObject jsonQuestionObject = jsonQuesstionsArray
.getJSONObject(i);
String name = jsonQuestionObject.getString("name");
String dob = jsonQuestionObject.getString("dob");
String occupation = jsonQuestionObject.getString("occupation");
String emailid = jsonQuestionObject.getString("emailid");
String contact = jsonQuestionObject.getString("contact");
String timetable = jsonQuestionObject.getString("timetable");
String image = jsonQuestionObject.getString("image");
}
lvDetail.setAdapter(new staff_BaseAdapter(
getActivity(), 0,staff_result));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void showProgress() {
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setMessage("Loading please wait");
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
public void hideProgress() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
#Override
public void onDestroy(){
super.onDestroy();
if ( mProgressDialog!=null && mProgressDialog.isShowing() ){
mProgressDialog.cancel();
}
}
}
This is my Adapter class - Where I have gotten the data and set the code
ArrayList<StaffList> myList = new ArrayList<StaffList>();
LayoutInflater inflater;
Context context;
public StaffBaseAdapter(Context context, ArrayList<StaffList> myList) {
this.myList = myList;
this.context = context;
inflater = LayoutInflater.from(this.context);
}
#Override
public int getCount() {
return myList.size();
}
#Override
public StaffList getItem(int position) {
return myList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
MyViewHolder mViewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.staff_list_view, parent, false);
mViewHolder = new MyViewHolder(convertView);
convertView.setTag(mViewHolder);
} else {
mViewHolder = (MyViewHolder) convertView.getTag();
}
StaffList currentListData = getItem(position);
mViewHolder.tvTitle.setText(currentListData.getTitle());
return convertView;
}
private class MyViewHolder {
TextView tvTitle, tvDesc;
ImageView ivIcon;
public MyViewHolder(View item) {
tvTitle = (TextView) item.findViewById(R.id.tvTitle);
}
}
}
This is my Model Class
String title;
int imgResId;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getImgResId() {
return imgResId;
}
public void setImgResId(int imgResId) {
this.imgResId = imgResId;
}
}
first your model class "staff_model" implement parcelable it will help to transfer your single model item pass to other activity.
Then add ItemClickListener in your listview
add this into your getView function
MyViewHolder rowHolder=new MyViewHolder(convertView);
rowHolder.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//do whatever u want
}
});
listView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Here you can convert your json to string
startActivity(new Intent(this, MainActivity.class).putExtra("myList",new Gson().toJson(list)));
}
});
and in your receiving activity
Type type = new TypeToken<List<String>>() {
}.getType();
List<String> list1=new Gson().fromJson(getIntent().getStringExtra("myList"),type);
Here Specify the TypeToken .You will have the exact json that you passed in the intent.

Android Listview Scroll position

I have a ListView and a list view adapter. The adapter populates the ListView from a List. The list view has a onScrollListener. The problem I have is when on scroll new data are loaded to the view but the scroll bar jumps to the top of the view.
What I want is to keep the scroll position where it was!
Any help?
Thanks
List View class:
private class GetItems extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(AppList.this);
// Set progressdialog title
mProgressDialog.setTitle("Loading more");
mProgressDialog.setMessage("loading);
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params)
{
applicationList = new ArrayList();
try
{
GetDataAppList getDataAppList = new GetDataAppList();
JSONArray jsonData = getDataAppList.getJSONData(webfileName, limit, offset);
for (int i = 0; i <= jsonData.length() - 2; i++)
{
JSONObject c = jsonData.getJSONObject(i);
id = c.getString("id");
name = c.getString("name");
logo = c.getString("logo");
developer = c.getString("developer");
rate = c.getInt("rates");
category = c.getInt("category");
fileName = c.getString("filename");
path = c.getString("path");
appSize = c.getDouble("size");
if(category == 1001)
{
String gCat = c.getString("game_category");
applicationList.add(new ApplicationPojo(id,name,logo,developer,appSize,category,fileName,path,gCat));
}
else
{
applicationList.add(new ApplicationPojo(id,name,logo,developer,appSize,category,fileName,path));
}
}
JSONObject sizeObj = jsonData.getJSONObject(jsonData.length() - 1);
size = sizeObj.getInt("size");
}
catch (Exception ex)
{
Log.d("Thread:", ex.toString());
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
// Locate the ListView in listview.xml
listview = (ListView) findViewById(R.id.listView);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(AppList.this, applicationList,listview);
// Binds the Adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
// Create an OnScrollListener
listview.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
int threshold = 1;
int count = listview.getCount();
if (scrollState == SCROLL_STATE_IDLE) {
if (listview.getLastVisiblePosition() >= count - threshold) {
if (size >= offset)
{
new LoadMoreDataTask().execute();
offset = offset + 15;
}
else
{
Toast.makeText(getApplicationContext(), "ختم لست!", Toast.LENGTH_LONG).show();
}
}
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
}
});
RatingBar bar = (RatingBar) findViewById(R.id.ratingBarShow);
}
}
private class LoadMoreDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(AppList.this);
mProgressDialog.setTitle("Loading more");
mProgressDialog.setMessage("loading);
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params)
{
try
{
GetDataAppList getDataAppList = new GetDataAppList();
JSONArray jsonData = getDataAppList.getJSONData(webfileName, limit, offset);
for (int i = 0; i <= jsonData.length(); i++) {
JSONObject c = jsonData.getJSONObject(i);
id = c.getString("id");
name = c.getString("name");
logo = c.getString("logo");
developer = c.getString("developer");
rate = c.getInt("rates");
category = c.getInt("category");
fileName = c.getString("filename");
path = c.getString("path");
appSize = c.getDouble("size");
if(category == 1001)
{
String gCat = c.getString("game_category");
applicationList.add(new ApplicationPojo(id,name,logo,developer,appSize,category,fileName,path,gCat));
}
else
{
applicationList.add(new ApplicationPojo(id,name,logo,developer,appSize,category,fileName,path));
}
}
}
catch (Exception ex)
{
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
int position = listview.getLastVisiblePosition();
adapter = new ListViewAdapter(AppList.this, applicationList,listview);
listview.setAdapter(adapter);
listview.setSelectionFromTop(position, 0);
mProgressDialog.dismiss();
}
}
The Adpater class:
public ListViewAdapter(Activity activity, ArrayList<ApplicationPojo> applicationList, ListView listView)
{
this.activity = activity;
this.applicationList = applicationList;
this.inflater = LayoutInflater.from(activity);
downloader = new ApkFileDownloader(activity);
this.listView = listView;
}
#Override
public int getCount() {
return applicationList.size();
}
#Override
public ApplicationPojo getItem(int position) {
return applicationList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent)
{
if (view == null)
{
holder = new ViewHolder();
view = inflater.inflate(R.layout.singleapp, null);
holder.openInstalledAppBtn = (ImageView) view.findViewById(R.id.openInstalledApp);
holder.downloadBtn = (ImageView) view.findViewById(R.id.updateApp);
holder.progressBar = (ProgressBar)view.findViewById(R.id.updateProgress);
holder.cancelBtn = (ImageView) view.findViewById(R.id.cancel);
holder.appName = (TextView) view.findViewById(R.id.appName);
holder.developer = (TextView) view.findViewById(R.id.developer);
holder.size = (TextView) view.findViewById(R.id.size);
holder.appCat = (TextView) view.findViewById((R.id.appCat));
holder.installBtn = (ImageView) view.findViewById(R.id.install);
holder.catlogo = (ImageView) view.findViewById(R.id.catlogo);
view.setTag(holder);
}
else
{
holder = (ViewHolder) view.getTag();
}
try
{
final View finalView = view;
holder.logo = (ImageView) finalView.findViewById(R.id.appLogo);
logoName = applicationList.get(position).getLogo();
Picasso.with(activity)
.load(IPClass.SERVERIP + logoName)
.into(holder.logo);
// holder.logo.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View arg0) {
//
// }
// });
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String appid = applicationList.get(position).getId();
int category = applicationList.get(position).getCategory();
Intent rec1Intent = new Intent(activity, AppView.class);
activity.startActivity(rec1Intent);
AppView appView = new AppView();
appView.setParameters(appid, category);
AppList.adapter.notifyDataSetChanged();
}
});
final String id = applicationList.get(position).getId();
final String path = applicationList.get(position).getPath();
final String fileName = applicationList.get(position).getFileName();
final String name = applicationList.get(position).getName();
final String developer = applicationList.get(position).getDeveloper();
final double size = applicationList.get(position).getSize();
final String logo = applicationList.get(position).getLogo();
final int category = applicationList.get(position).getCategory();
final String appName = applicationList.get(position).getFileName();
String checkAppInstalled = appName.substring(0,appName.length() - 4);
//------------CHECK IF APPLICATION IS INSTALLED ----------------------------------------
if(appInstalled(checkAppInstalled))
{
holder.downloadBtn.setVisibility(View.GONE);
holder.cancelBtn.setVisibility(View.GONE);
holder.progressBar.setVisibility(View.GONE);
holder.installBtn.setVisibility(View.GONE);
holder.openInstalledAppBtn.setVisibility(View.VISIBLE);
holder.openInstalledAppBtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
String fileName = (applicationList.get(position).getFileName());
String appToOpen = fileName.substring(0,fileName.length() - 4);
Context ctx = activity.getApplicationContext();
Intent mIntent = ctx.getPackageManager().getLaunchIntentForPackage(appToOpen);
String mainActivity = mIntent.getComponent().getClassName();
Intent intent = new Intent("android.intent.category.LAUNCHER");
intent.setClassName(appToOpen, mainActivity);
activity.startActivity(intent);
}
});
}
//------------- IF APPLICATION IS NOT ALREADY INSTALLED --------------------------------
else
{
//------------------------ CHECK IF APK EXISTS -------------------------------------
String filePath = Environment.getExternalStorageDirectory().toString();
File file = new File(filePath + "/appsaraai/" + fileName);
if(file.exists())
{
holder.downloadBtn.setVisibility(View.GONE);
holder.cancelBtn.setVisibility(View.GONE);
holder.openInstalledAppBtn.setVisibility(View.GONE);
holder.progressBar.setVisibility(View.GONE);
holder.installBtn.setVisibility(View.VISIBLE);
holder.installBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/appsaraai/" + fileName)), "application/vnd.android.package-archive");
activity.startActivity(intent);
for (int i = 0; i < DownloadLists.list.size(); i++) {
if (DownloadLists.list.get(i).getName().equals(name)) {
DownloadLists.list.remove(i);
}
}
}
});
AppList.adapter.notifyDataSetChanged();
}
//------------------ IF APK DOES NOT EXIST -----------------------------------------
else
{
//-----CHECK IF DOWNLOAD IS IN PROGRESS ----------------------------------------
if (ApkFileDownloader.applicationList.containsKey(name))
{
holder.downloadBtn.setVisibility(View.GONE);
holder.installBtn.setVisibility(View.GONE);
holder.openInstalledAppBtn.setVisibility(View.GONE);
new ApkFileDownloader(activity).getDownloadStatus(holder.progressBar, name, holder.installBtn, holder.cancelBtn);
holder.progressBar.setVisibility(View.VISIBLE);
holder.cancelBtn.setVisibility(View.VISIBLE);
holder.cancelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
downloader.cancelDownload(name);
holder.cancelBtn.setVisibility(View.GONE);
holder.downloadBtn.setVisibility(View.VISIBLE);
DownloadLists dlist = new DownloadLists(activity);
dlist.deleteData(name);
try {
AppList.adapter.notifyDataSetChanged();
} catch (Exception ex) {
System.out.println(ex);
}
try
{
SearchResult.adapter.notifyDataSetChanged();
}
catch (Exception ex)
{
System.out.println(ex);
}
}
});
}
//-------------- IF DOWNLOAD IS NOT IN PROGRESS START NEW DOWNLOAD -------------
else
{
holder.progressBar.setVisibility(View.GONE);
holder.cancelBtn.setVisibility(View.GONE);
holder.installBtn.setVisibility(View.GONE);
holder.openInstalledAppBtn.setVisibility(View.GONE);
holder.downloadBtn.setVisibility(view.VISIBLE);
holder.downloadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
holder.downloadBtn.setVisibility(View.GONE);
holder.cancelBtn.setVisibility(View.VISIBLE);
holder.cancelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
downloader.cancelDownload(name);
holder.cancelBtn.setVisibility(View.GONE);
holder.downloadBtn.setVisibility(View.VISIBLE);
try {
AppList.adapter.notifyDataSetChanged();
} catch (Exception ex) {
System.out.println(ex);
}
try {
SearchResult.adapter.notifyDataSetChanged();
} catch (Exception ex) {
System.out.println(ex);
}
}
});
new Thread(new Runnable() {
#Override
public void run() {
try {
Bitmap logoImg = Picasso.with(activity).load(IPClass.SERVERIP + logo).get();
DownloadLists.list.add(new ApplicationPojo(id, name, developer, size, logoImg, holder.progressBar));
DownloadLists dlist = new DownloadLists(activity);
dlist.insertData(id, name, developer, size, fileName, logoImg);
UpdateServerDownload d = new UpdateServerDownload();
d.updateDownloadNo(id, category);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
new ApkFileDownloader(activity).setParameters(path, fileName, name);
try {
AppList.adapter.notifyDataSetChanged();
} catch (Exception ex) {
System.out.println(ex);
}
try {
SearchResult.adapter.notifyDataSetChanged();
} catch (Exception ex) {
System.out.println(ex);
}
}
});
}
}
}
holder.appName.setText(applicationList.get(position).getName());
holder.developer.setText(applicationList.get(position).getDeveloper());
String sizeText = " میگابایت ";
String appSize =String.valueOf(applicationList.get(position).getSize()) + sizeText;
holder.size.setText(appSize);
if(category == 1001)
{
String cat = applicationList.get(position).getgCat();
holder.appCat.setText(" " + returnGameCat(cat));
holder.catlogo.setImageResource(R.drawable.gamecatlogo);
}
}
catch (Exception ex)
{
Log.d("Adapter Exception", ex.toString());
}
return view;
}
//--------------- A METHOD TO CHECK IF APPLICATION IS ALREADY INSTALLED ------------------------
public boolean appInstalled(String checkApp)
{
pm = activity.getPackageManager();
try
{
pm.getPackageInfo(checkApp, PackageManager.GET_ACTIVITIES);
isAppInstalled = true;
}
catch (PackageManager.NameNotFoundException e)
{
isAppInstalled = false;
}
return isAppInstalled;
}
You are doing wrong in your GetItems and LoadMoreDataTask AsyncTask. you are setting new adapter each time when you scroll down so when new data are loaded to the view the scroll bar jumps to the top of the view.
You need to call
adapter = new ListViewAdapter(AppList.this, applicationList,listview);
listview.setAdapter(adapter);
only first time then you have to only call
adapter.notifyDataSetChanged()
to update your ListView no need to set adapter each time when making new request and also you have to set OnScrollListener to ListView only one time currently new OnScrollListener is set each time when making new request.
You need to setAdapter first time when adapter is null or you are fetching data first time after it just call notifyDataSetChanged()
Save state of listview before updating and then restore:
// save index and top position
int index = mListView.getFirstVisiblePosition();
View v = mListView.getChildAt(0);
int top = (v == null) ? 0 : v.getTop();
// notify dataset changed or re-assign adapter here
// restore the position of listview
mListView.setSelectionFromTop(index, top);
The most Optimal Solution will be
// Save the ListView state (= includes scroll position) as a Parceble
Parcelable state = listView.onSaveInstanceState();
// e.g. set new items
listView.setAdapter(adapter);
// Restore previous state (including selected item index and scroll position)
listView.onRestoreInstanceState(state);
Reference : Retain Scroll Position Android ListView

Fetching education and work details from linked in

I have to fetch LinkedIn details from the loginned user . I am able to get basic basic details through the below code.
d.setVerifierListener(new OnVerifyListener() {
#Override
public void onVerify(String verifier) {
try {
Log.i("LinkedinSample", "verifier: " + verifier);
accessToken = LinkedinDialog.oAuthService
.getOAuthAccessToken(LinkedinDialog.liToken,
verifier);
LinkedinDialog.factory.createLinkedInApiClient(accessToken);
client = factory.createLinkedInApiClient(accessToken);
Person p = client.getProfileForCurrentUser();
name.setText("Welcome " + p.getFirstName() + " "
+ p.getLastName());
} catch (Exception e) {
Log.i("LinkedinSample", "error to get verifier");
e.printStackTrace();
}
}
Now I want to take education and work details.
Educations items = p.getEducations();
System.out.println("items =="+items);
I got values for p.getfirstname(),p.getlastname() but for p.getEducations() , I got null.
I didn't find any solution anywhere. Please help me
Thanks in advance.
public class LinkCon_Main extends BaseActivityListView {
final LinkedInOAuthService oAuthService = LinkedInOAuthServiceFactory
.getInstance().createLinkedInOAuthService(Config.CONSUMER_KEY,
Config.CONSUMER_SECRET);
final LinkedInApiClientFactory factory = LinkedInApiClientFactory
.newInstance(Config.CONSUMER_KEY, Config.CONSUMER_SECRET);
/*LinkCon Widgets*/
ProgressDialog mPrograss;
String name;
View experiencePage;
TextView prof_Name, prof_Headline, prof_Location, prof_Industry;
String prof_name, prof_headline, prof_location, prof_industry, prof_summary, prof_experience,prof_education,prof_languages,prof_skills, prof_interests,prof_birthdate,prof_contatct,prof_email;
String con_name, con_headline, con_location,con_industry, con_summary,con_experience,con_education,con_languages,con_skills,con_interets,con_birthdate,con_phone;
Connections con_email;
String pic_url,con_pic_url;
String startDate, endDate;
String item;
String dty;
String dtm;
String dtd;
ImageView person_Pic, con_pic;
ListView connections_list;
ArrayList<Person> itemslist;
#SuppressWarnings({ "rawtypes" })
Iterator localIterator;
Person mylist;
RelativeLayout layout_persondetils,layout_con_profile;
LinkedInApiClient client;
Person person;
Connections connections;
ImageLoader imageLoader;
DisplayImageOptions options;
LinkConApp myLinkCon;
LayoutInflater inflater;
String[] months= {"Jan", "Feb", "March", "April", "May","June", "July", "August","Sep", "Oct", "Nov", "Dec"};
StringBuilder localStringBuilder;
#Override
#SuppressLint("NewApi")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myLinkCon=new LinkConApp();
prof_Name=(TextView)findViewById(R.id.user_name);
prof_Headline=(TextView)findViewById(R.id.user_headline);
prof_Location=(TextView)findViewById(R.id.user_Location);
prof_Industry=(TextView)findViewById(R.id.user_industry);
person_Pic=(ImageView)findViewById(R.id.profile_pic);
layout_persondetils=(RelativeLayout)findViewById(R.id.layout_profiledetils);
layout_con_profile=(RelativeLayout)findViewById(R.id.layout_con_profile);
layout_persondetils.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
userpersons();
}
});
mPrograss=new ProgressDialog(LinkCon_Main.this);
inflater=(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// ImageLoader options
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_launcher)
.showImageForEmptyUri(R.drawable.photo)
.showImageOnFail(R.drawable.ic_launcher).cacheInMemory(true)
.cacheOnDisc(true).considerExifParams(true).build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration.createDefault(this));
connections_list=(ListView)findViewById(R.id.connectionslist);
itemslist = new ArrayList<Person>();
if( Build.VERSION.SDK_INT >= 9){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
final SharedPreferences pref = getSharedPreferences(Config.OAUTH_PREF,
MODE_PRIVATE);
final String token = pref.getString(Config.PREF_TOKEN, null);
final String tokenSecret = pref.getString(Config.PREF_TOKENSECRET, null);
if (token == null || tokenSecret == null) {
startAutheniticate();
} else {
showCurrentUser(new LinkedInAccessToken(token, tokenSecret));
}
}
void startAutheniticate() {
mPrograss.setMessage("Loading...");
mPrograss.setCancelable(true);
mPrograss.show();
new AsyncTask<Void, Void, LinkedInRequestToken>() {
#Override
protected LinkedInRequestToken doInBackground(Void... params) {
return oAuthService.getOAuthRequestToken(Config.OAUTH_CALLBACK_URL);
}
#Override
protected void onPostExecute(LinkedInRequestToken liToken) {
final String uri = liToken.getAuthorizationUrl();
getSharedPreferences(Config.OAUTH_PREF, MODE_PRIVATE)
.edit()
.putString(Config.PREF_REQTOKENSECRET,
liToken.getTokenSecret()).commit();
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(i);
}
}.execute();
mPrograss.dismiss();
}
void finishAuthenticate(final Uri uri) {
if (uri != null && uri.getScheme().equals(Config.OAUTH_CALLBACK_SCHEME)) {
final String problem = uri.getQueryParameter(Config.OAUTH_QUERY_PROBLEM);
if (problem == null) {
new AsyncTask<Void, Void, LinkedInAccessToken>() {
#Override
protected LinkedInAccessToken doInBackground(Void... params) {
final SharedPreferences pref = getSharedPreferences(
Config.OAUTH_PREF, MODE_PRIVATE);
final LinkedInAccessToken accessToken = oAuthService
.getOAuthAccessToken(
new LinkedInRequestToken(
uri.getQueryParameter(Config.OAUTH_QUERY_TOKEN),
pref.getString(
Config.PREF_REQTOKENSECRET,
null)),
uri.getQueryParameter(Config.OAUTH_QUERY_VERIFIER));
pref.edit()
.putString(Config.PREF_TOKEN, accessToken.getToken())
.putString(Config.PREF_TOKENSECRET,
accessToken.getTokenSecret())
.remove(Config.PREF_REQTOKENSECRET).commit();
return accessToken;
}
#Override
protected void onPostExecute(LinkedInAccessToken accessToken) {
mPrograss.dismiss();
showCurrentUser(accessToken);
}
}.execute();
} else {
Toast.makeText(this,
"Appliaction down due OAuth problem: " + problem,
Toast.LENGTH_LONG).show();
finish();
}
}
}
void clearTokens() {
getSharedPreferences(Config.OAUTH_PREF, MODE_PRIVATE).edit()
.remove(Config.PREF_TOKEN).remove(Config.PREF_TOKENSECRET)
.remove(Config.PREF_REQTOKENSECRET).commit();
}
void showCurrentUser(final LinkedInAccessToken accessToken) {
client = factory.createLinkedInApiClient(accessToken);
mPrograss.setMessage("Loading..");
mPrograss.show();
new AsyncTask<Void, Void, Object>() {
#Override
protected Object doInBackground(Void... params) {
try {
final Person user_Profile = client.getProfileForCurrentUser(EnumSet.of(ProfileField.ID));
person = client.getProfileById(user_Profile.getId(), EnumSet.of(
ProfileField.FIRST_NAME,
ProfileField.LAST_NAME,
ProfileField.PICTURE_URL,
ProfileField.INDUSTRY,
ProfileField.MAIN_ADDRESS,
ProfileField.HEADLINE,
ProfileField.SUMMARY,
ProfileField.POSITIONS,
ProfileField.EDUCATIONS,
ProfileField.LANGUAGES,
ProfileField.SKILLS,
ProfileField.INTERESTS,
ProfileField.PHONE_NUMBERS,
ProfileField.EMAIL_ADDRESS,
ProfileField.DATE_OF_BIRTH,
ProfileField.PUBLIC_PROFILE_URL));
prof_name = person.getFirstName() + " " + person.getLastName();
prof_headline = person.getHeadline();
prof_location = person.getMainAddress();
prof_industry = person.getIndustry();
return person;
} catch (LinkedInApiClientException ex) {
return ex;
}
}
#Override
protected void onPostExecute(Object result) {
if (result instanceof Exception) {
//result is an Exception :)
final Exception ex = (Exception) result;
clearTokens();
Toast.makeText(
LinkCon_Main.this,
"Appliaction down due LinkedInApiClientException: "
+ ex.getMessage()
+ " Authokens cleared - try run application again.",
Toast.LENGTH_LONG).show();
finish();
} else if (result instanceof Person) {
final Person person = (Person) result;
prof_Name.setText( person.getFirstName() + " " + person.getLastName());
prof_Headline.setText(person.getHeadline());
prof_Location.setText(person.getMainAddress());
prof_Industry.setText(person.getIndustry());
prof_Name.setVisibility(0);
prof_Headline.setVisibility(0);
prof_Location.setVisibility(0);
prof_Industry.setVisibility(0);
person_Pic.setVisibility(0);
userConnections();
userDetails();
}
}
}.execute();
mPrograss.dismiss();
}
#Override
protected void onNewIntent(Intent intent) {
finishAuthenticate(intent.getData());
}
public void userDetails(){
if(person.getPictureUrl()!=null){
pic_url = person.getPictureUrl().toString();
imageLoader.displayImage(pic_url, person_Pic);
}else{
person_Pic.setImageResource(R.drawable.ic_launcher);
}
/*************** person Details Summary/experience/education/languages/skills/contacts/interests **********************/
if (person.getSummary()!=null) {
prof_summary = person.getSummary();
}
prof_experience="";
for (Position position:person.getPositions().getPositionList())
{
if(position.isIsCurrent()){
startDate=months[(int) (position.getStartDate().getMonth()-1)]+"-"+position.getStartDate().getYear();
endDate="Currently Working";
}else{
startDate=months[(int) (position.getStartDate().getMonth()-1)]+"-"+position.getStartDate().getYear();
endDate=months[(int) (position.getEndDate().getMonth()-1)]+"-"+position.getEndDate().getYear();
}
prof_experience=prof_experience+"<b>" +"Position :"+"</b>"+position.getTitle()+"<br><b>" +"Company :"+ "</b>"+ position.getCompany().getName()+"<br><b>" +"Start Date:"+ "</b>"+ startDate +"<br><b>" +"End Date:"+ "</b>"+ endDate +"<br>"+"<br>";
}
prof_education="";
for (Education education:person.getEducations().getEducationList())
{
prof_education=prof_education +"<b>" +"Gaduation :"+ "</b>" +education.getDegree()+"<br><b>" +"Institute :"+ "</b>" +education.getSchoolName()+ "<br><b>" +"Graduation Year :"+ "</b>" +education.getEndDate().getYear()+"<br>"+"<br>";
}
prof_languages="";
for(Language language:person.getLanguages().getLanguageList())
{
prof_languages=prof_languages+language.getLanguage().getName()+"\n";
}
prof_skills="";
for(Skill skill:person.getSkills().getSkillList())
{
prof_skills=prof_skills+skill.getSkill().getName()+"\n";
}
prof_contatct="";
PhoneNumbers contactinfo=person.getPhoneNumbers();
if(contactinfo!=null ){
for(PhoneNumber phoneno:person.getPhoneNumbers().getPhoneNumberList())
{
prof_contatct=prof_contatct+ phoneno.getPhoneNumber().toString();
}
}
if(person.getEmailAddress()!=null){
prof_email=person.getEmailAddress();
}
prof_interests = person.getInterests();
prof_birthdate= person.getDateOfBirth().getDay()+"-"+ months[(int) (person.getDateOfBirth().getMonth()-1)]+"-"+person.getDateOfBirth().getYear();
}
public void userConnections(){
final Set<ProfileField> connectionFields = EnumSet.of(ProfileField.ID,
ProfileField.FIRST_NAME,
ProfileField.LAST_NAME,
ProfileField.HEADLINE,
ProfileField.INDUSTRY,
ProfileField.PICTURE_URL,
);
connections = client.getConnectionsForCurrentUser(connectionFields);
for (Person person : connections.getPersonList()) {
itemslist.add(person);
}
connection_Adapter myadpter=new connection_Adapter();
connections_list.setAdapter(myadpter);
connections_list.setVisibility(0);
connections_list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
/*Connections List item position selection*/
person = itemslist.get(position);
/*Intent mycon=new Intent(LinkCon_Main.this, Con_Profile.class);
mycon.putExtra("conid", con_name);
startActivity(mycon);
*/
con_name=person.getFirstName()+" "+person.getLastName();
System.out.println("Name:"+con_name);
con_headline=person.getHeadline();
System.out.println("Designation:"+con_headline);
con_industry=person.getIndustry();
System.out.println("Industry:"+con_industry);
Location localLocation = person.getLocation();
if (localLocation != null){
con_location=String.format("%s", new Object[] { localLocation.getName() });
System.out.println("Con_Loaction:"+con_location);
}
/*****PICTURE/NAME/INDUSTRY/LOCATION Tested OK******/
/********need to get SUMMARY/EXPERIENCE/EDUCATION/SKILLS/LANGUAGES/DATEOFBIRTH/PHONENUMBER/EMAIL**********/
Toast.makeText(LinkCon_Main.this, "Name:"+" "+con_name +"\n"+"Position:"+" "+con_headline+"\n"+"Industry:"+" "+con_industry+"\n"+"Locations:"+" "+con_location, Toast.LENGTH_LONG).show();
}//onItemClick
});
}
public class connection_Adapter extends BaseAdapter{
#Override
public int getCount() {
// TODO Auto-generated method stub
return itemslist.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder = null;
if(convertView==null){
convertView = inflater.inflate(R.layout.list_row,
null);
holder = new ViewHolder();
holder.con_Itenames = (TextView) convertView
.findViewById(R.id.connection_name);
holder.con_designations = (TextView) convertView
.findViewById(R.id.connection_headline);
holder.con_ItemImage = (ImageView) convertView
.findViewById(R.id.connection_image);
holder.con_locationad = (TextView) convertView
.findViewById(R.id.connection_location);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
SetData(holder,position);
return convertView;
}
protected Context getBaseContext() {
// TODO Auto-generated method stub
return null;
}
public void SetData(final ViewHolder holder, int position) {
final Person con_details = itemslist.get(position);
holder.con_Itenames.setText(con_details.getFirstName()+" "+con_details.getLastName());
holder.con_designations.setText(con_details.getIndustry());
Location localLocation = con_details.getLocation();
if (localLocation != null){
con_location=String.format("%s", new Object[] { localLocation.getName() });
}
holder.con_locationad.setText(con_location);
holder.con_Itenames.setTag(con_details);
if (con_details.getPictureUrl()!=null) {
imageLoader.displayImage(con_details.getPictureUrl(), holder.con_ItemImage, options);
}else {
holder.con_ItemImage.setImageResource(R.drawable.ic_launcher);}
}
public void setListItems(ArrayList<Person> newList) {
itemslist = newList;
notifyDataSetChanged();
}
}
public class ViewHolder{
TextView con_Itenames,con_designations, con_locationad;
ImageView con_ItemImage;
}
private void userpersons() {
// TODO Auto-generated method stub
Intent user_prof = new Intent(LinkCon_Main.this, User_Profile.class);
user_prof.putExtra("pic", pic_url);
user_prof.putExtra("name", prof_name);
user_prof.putExtra("headline", prof_headline);
user_prof.putExtra("locations", prof_location);
user_prof.putExtra("industry", prof_industry);
user_prof.putExtra("summary", prof_summary);
user_prof.putExtra("languages", prof_languages);
user_prof.putExtra("experience", prof_experience);
user_prof.putExtra("education", prof_education);
user_prof.putExtra("skills", prof_skills);
user_prof.putExtra("interests", prof_interests);
user_prof.putExtra("dateofbirth", prof_birthdate);
user_prof.putExtra("phoneno", prof_contatct);
user_prof.putExtra("email", prof_email);
startActivity(user_prof);
}
}
I have used this api for linkedIn. It helps me to get education, recommendation and career.
http://code.google.com/p/socialauth-android/

Android ListView wrong images

I'm developing an Android app but I'm a newbie and I got stuck...
My ListView single element has an ImageView and some TextViews, but sometimes (when I scroll the page and there are more than 7-8 elements) it doesn't display the right image in the right row.
I'm using a custom Image Loader to manage the downloaded images.
Here's my Adapter:
public class AddVideogameActivityAdapter extends BaseAdapter {
private ArrayList<Videogame> videogames;
private Typeface typefaceMedium;
private Typeface typefaceLight;
private ImageLoader loader;
private LayoutInflater mInflater;
public AddVideogameActivityAdapter(Context context, ArrayList<Videogame> results) {
videogames = results;
mInflater = LayoutInflater.from(context);
typefaceMedium = Typeface.createFromAsset(context.getAssets(), "Roboto-Medium.ttf");
typefaceLight = Typeface.createFromAsset(context.getAssets(), "Roboto-Light.ttf");
loader = new ImageLoader(context);
}
public int getCount() {
return videogames.size();
}
public Object getItem(int position) {
return videogames.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_element,null);
holder = new ViewHolder();
holder.imgView = (ImageView) convertView.findViewById(R.id.thumbView);
holder.txtName = (TextView) convertView.findViewById(R.id.elementView);
holder.txtPlatform = (TextView) convertView.findViewById(R.id.elementView2);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
try {
Videogame vgame = (Videogame) videogames.get(position);
holder.txtName.setText(vgame.getTitle());
holder.txtName.setTypeface(typefaceMedium);
holder.txtPlatform.setText(videogames.get(position).getPlatform());
holder.txtPlatform.setTypeface(typefaceLight);
holder.imgUrl = videogames.get(position).getImage();
loader.display(holder.imgUrl, holder.imgView, R.drawable.youtube_icon);
}
catch (Exception e) {
e.printStackTrace();
Log.e(com.example.ludos2_0.MainActivity.TAG,
"Exception: " + e.getLocalizedMessage());
}
return convertView;
}
static class ViewHolder {
TextView txtName;
TextView txtPlatform;
public String imgUrl;
ImageView imgView;
}
}
Sorry for my english and thank you for your help!
EDIT:
Here's also the Loader:
public class ImageLoader implements ComponentCallbacks2 {
private TCLruCache cache;
public ImageLoader(Context context) {
ActivityManager am = (ActivityManager) context.getSystemService(
Context.ACTIVITY_SERVICE);
int memoryClass = am.getMemoryClass() * 1024 * 1024;
cache = new TCLruCache(memoryClass);
}
public void display(String url, ImageView imageview, int defaultresource) {
imageview.setImageResource(defaultresource);
Bitmap image = cache.get(url);
if (image != null) {
imageview.setImageBitmap(image);
}
else {
new SetImageTask(imageview).execute(url);
}
}
private class TCLruCache extends LruCache<String, Bitmap> {
public TCLruCache(int maxSize) {
super(maxSize);
}
}
private class SetImageTask extends AsyncTask<String, Void, Integer> {
private ImageView imageview;
private Bitmap bmp;
public SetImageTask(ImageView imageview) {
this.imageview = imageview;
}
#Override
protected Integer doInBackground(String... params) {
String url = params[0];
try {
bmp = getBitmapFromURL(url);
if (bmp != null) {
cache.put(url, bmp);
}
else {
return 0;
}
} catch (Exception e) {
e.printStackTrace();
return 0;
}
return 1;
}
#Override
protected void onPostExecute(Integer result) {
if (result == 1) {
imageview.setImageBitmap(bmp);
}
super.onPostExecute(result);
}
private Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection
= (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
}
RE-EDIT
Activity code:
public class AddVideogameActivity extends ListActivity {
private TextView searchField = null;
private final Handler handler = new Handler();
private ArrayList<Videogame> videogamesList = null;
private static AddVideogameActivity mContext = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_book);
mContext = this;
searchField = (TextView) findViewById(R.id.searchField);
searchField.setMaxLines(1);
searchField.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
searchField.setHint("");
}
});
// Setup the list view and its listener
getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Log.d(MainActivity.TAG,
"AddBookActivity ---> AddButton:onClick()");
// Sets typefaces for TextView
String videogameId = videogamesList.get(position).getId();
String videogameName = videogamesList.get(position).getTitle();
String thumbnail = videogamesList.get(position).getThumbnail();
String description = videogamesList.get(position)
.getDescription();
String image = videogamesList.get(position).getImage();
String platform = videogamesList.get(position).getPlatform();
if (videogameName != null && videogameName.length() > 0
&& thumbnail != null && thumbnail.length() > 0
&& description != null && description.length() > 0
&& image != null && image.length() > 0
&& platform != null && platform.length() > 0) {
if (ListsManager.getInstance().addVideogame(
new Videogame(videogameId, videogameName,
thumbnail, image, description, platform)) == 0) {
Log.d(MainActivity.TAG,
"AddBookActivity --> Videogame:[" + videogameId
+ "#" + videogameName + "]");
Toast toast = Toast.makeText(mContext, "["
+ videogameName + "] Saved !",
Toast.LENGTH_LONG);
toast.show();
} else {
Log.e(MainActivity.TAG,
"AddBookActivity --> Error ! Videogame already in the list ! ");
Toast toast = Toast.makeText(mContext,
"Error! Videogame already in the list!",
Toast.LENGTH_LONG);
toast.show();
}
} else {
Log.e(MainActivity.TAG,
"AddBookActivity --> Error ! Invalid Videogame Name or Thumbnail or Id or Deck");
Toast toast = Toast
.makeText(
mContext,
"Error ! Invalid Videogame Name or Thumbnail or Id or Deck",
Toast.LENGTH_LONG);
toast.show();
}
Intent newIntent = new Intent(getApplicationContext(),
MainActivity.class);
startActivity(newIntent);
}
});
// Setup the search button and its listener
Button searchButton = (Button) findViewById(R.id.searchButton);
searchButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d(com.example.ludos2_0.MainActivity.TAG, "Search Game ...");
String searchInputString = searchField.getText().toString();
if (searchInputString != null && searchInputString.length() > 0) {
try {
String requestURL = ("http://www.giantbomb.com/api/search/?api_key=fcf60d6d67b98b0d17b3905d1a90b3fd31ed1e8e&format=json&query="
+ Uri.encode(searchInputString) + "&resources=game");
// String requestURL =
// String.format("https://gdata.youtube.com/feeds/api/videos?v=2&alt=jsonc&category=Music&orderby=relevance&q=%s",Uri.encode(searchInputString));
Log.d(com.example.ludos2_0.MainActivity.TAG, requestURL);
DownloadGiantBombJSONData giantbombAsyncTask = new DownloadGiantBombJSONData();
giantbombAsyncTask.execute(new String[] { requestURL });
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
if (videogamesList == null)
videogamesList = new ArrayList<Videogame>();
else
updateVideogamesListView(videogamesList);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.add_book, menu);
return true;
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
}
public void updateVideogamesListView(ArrayList<Videogame> values) {
AddVideogameActivityAdapter adapter = new AddVideogameActivityAdapter(this, values);
setListAdapter(adapter);
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
The other classes involved in building the ListView are the REST classes and the AsyncTask class that downloads and parses the JSon files.
What does your ListView look like, does it look like this:
<ListView android:id="#id/android:list"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="0dip" ></ListView>
Especially the id of the ListView. Check your layout file, probably the bug exists there.

Categories

Resources