Create another ArrayList to populate a spinner in Android - java

I need to create another ArrayList with string values to fill a state spinner. When I initialize the application, the state spinner view is displaying blank data. Like this SS right here
Follow the code below.
public class Activity {
private Spinner states;
private Spinner cities;
ArrayList<String> statesList;
ArrayList<String> citiesList;
private void findcomponents() {
states = (Spinner) findViewById(R.id.spinner_cadastro_estado);
cities = (Spinner) findViewById(R.id.spinner_cadastro_cidade);
loadStatesAndCities();
states.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
State state = (State) states.getSelectedItem();
cities.setAdapter(new ArrayAdapter<>(Activity.this, android.R.layout.simple_spinner_dropdown_item, state.getCities()));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
cities.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void loadStatesAndCities() {
try {
JSONObject jsonObject = new JSONObject(loadJSONFromAsset());
JSONArray statesArray = jsonObject.getJSONArray("estados");
List<City> citiesList;
List<State> statesList;
statesList = new ArrayList<>();
for (int i = 0; i < statesArray.length(); i++) {
JSONObject states_object = statesArray.getJSONObject(i);
String estadoSigla = states_object.optString("sigla");
JSONArray citiesArray = states_object.getJSONArray("cidades");
citiesList = new ArrayList<>();
for (int j = 0; j < citiesArray.length(); j++) {
String cities_data = citiesArray.getString(j);
citiesList.add(new City(cities_data));
}
statesList.add(new State(estadoSigla,citiesList));
}
ArrayAdapter<State> stateAdapter;
stateAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, statesList);
stateAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
states.setAdapter(stateAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("estados-cidades.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}

Related

Android Studio ArrayAdapter GetFilter() is not working

I am trying to code a recipe app, I am pulling the recipes from an online JSON file.
Therefore I needed a custom ArrayAdapter and now I want to filter the List.
But as it turns out the adapter can't get the Filter function. I looked up other articles but none of them were helpful. Hope somebody can help out in this case.
This is the tutorial I watched to code online JSON to ListView: https://www.youtube.com/watch?v=v4X0y6-VOtM
Here is my Code:
public class Food_choosing_menu extends Fragment {
private ListView lv;
SearchView searchView;
ListAdapter adapter;
String name,time;
private static String JSON_URL = "https://---.github.io/---.json";
ArrayList<HashMap<String, String>> recepieList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_food_choosing_menu, container, false);
recepieList = new ArrayList<>();
lv = v.findViewById(R.id.Food_List_View);
searchView = v.findViewById(R.id.Searh_bar_food);
GetData getData = new GetData();
getData.execute();
return v;
}
public class GetData extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... strings) {
String current = "";
try {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(JSON_URL);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
int data = inputStreamReader.read();
while (data != -1) {
current += (char) data;
data = inputStreamReader.read();
}
return current;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}catch (Exception e){
e.printStackTrace();
}
return current;
}
#Override
protected void onPostExecute(String s) {
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("Recepies");
for (int i = 0; i< jsonArray.length(); i++){
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
name = jsonObject1.getString("name");
time = jsonObject1.getString("time");
HashMap<String, String> recepies = new HashMap<>();
recepies.put("name", name);
recepies.put("time", time);
recepieList.add(recepies);
}
}catch (JSONException e){
e.printStackTrace();
}
adapter = new SimpleAdapter(
getContext(),
recepieList,
R.layout.row_layout,
new String[] {"name", "time"},
new int[]{R.id.textView1});
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getContext(), "You Click -"+adapter.getItem(position).toString(), Toast.LENGTH_SHORT).show();
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
}
}

ViewPager Not getting Images from server

I am using ViewPager in my app and fetch the data(Images) from server(with JSON). Even if runs smoothly no image is shown in the viewpager.
I read so many tutorial regarding this, but nobody solve my problem. Please tell me where i am wrong...
Here is my code:
view_pager.xml
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="40dp" />
image_view.xml
<ImageView
android:id="#+id/image_adapter"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"/>
ViewPager_Adapter.java
public class ViewPager_Adapter extends PagerAdapter {
private String urls;
private LayoutInflater inflater;
private Context context;
ArrayList<String> mylist;
public ViewPager_Adapter(Context context, ArrayList<String> mylist) {
this.context = context;
this.urls = urls;
this.mylist = mylist;
inflater = LayoutInflater.from(context);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public int getCount() {
return mylist.size();
}
#Override
public Object instantiateItem(ViewGroup view, int position) {
View imageLayout = inflater.inflate(R.layout.image_view, null);
assert imageLayout != null;
final ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image_adapter);
Glide.with(context)
.load(mylist.get(position))
.into(imageView);
view.addView(imageLayout,0);
return imageLayout;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
#Override
public Parcelable saveState() {
return null;
}
}
View_Pager.Java
public class View_Pager extends Fragment {
private static ViewPager mPager;
JSONArray responsearray = null;
String imageOne;
private static final String TAG_PHOTO_ONE = "Gallery_Full";
ArrayList<String> myList;
HashMap<String, String> get;
ViewPager_Adapter viewpager_adapter;
LinearLayout addimages;
int REQUEST_CODE = 100;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.view_pager, null);
mPager = view.findViewById(R.id.viewpager);
new GetImages().execute(true);
return view;
}
class GetImages extends AsyncTask<Boolean, Void, String> {
#Override
protected String doInBackground(Boolean... booleans) {
ImageApi imageApi = new ImageApi();
String result = null;
try {
result = imageApi.galleryget(sharedPreferences.getString("id", ""));
JSONObject object = new JSONObject(result);
if (object.getString("error").equalsIgnoreCase("false")) {
responsearray = object.getJSONArray("response");
return "true";
} else {
String errormsg = object.getString(result);
return errormsg;
}
} catch (ApiException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (s != null) {
if (s.equalsIgnoreCase("true")) {
showList(responsearray);
}
}
}
}
public void showList(final JSONArray responsearray) {
try {
for (int i = 0; i < responsearray.length(); i++) {
JSONObject responseObject = responsearray.getJSONObject(i);
Log.e("COUNT" + i, String.valueOf(responseObject));
imageOne = responseObject.getString(TAG_PHOTO_ONE);
get = new HashMap<>();
get.put(TAG_PHOTO_ONE, imageOne);
myList = new ArrayList<>();
myList.add(String.valueOf(get));
}
viewpager_adapter = new ViewPager_Adapter(getActivity(), myList);
String test = String.valueOf(myList);
String imgpath = getString(R.string.imgpath);
String finalimgpath = imgpath + imageOne;
Log.e("FINALPATH", finalimgpath);
} catch (JSONException e) {
e.printStackTrace();
}
mPager.setAdapter(viewpager_adapter);
viewpager_adapter.notifyDataSetChanged();
}
}
Use this code for showList() as you are not populating you're arrayList properly the data is being over write in one position .
So , what you have to do is initialize it out side of for loop .
public void showList(final JSONArray responsearray) {
try {
//here
myList = new ArrayList<>();
for (int i = 0; i < responsearray.length(); i++) {
JSONObject responseObject = responsearray.getJSONObject(i);
Log.e("COUNT" + i, String.valueOf(responseObject));
imageOne = responseObject.getString(TAG_PHOTO_ONE);
get = new HashMap<>();
get.put(TAG_PHOTO_ONE, imageOne);
myList.add(String.valueOf(get));
}
viewpager_adapter = new ViewPager_Adapter(getActivity(), myList);
String test = String.valueOf(myList);
String imgpath = getString(R.string.imgpath);
String finalimgpath = imgpath + imageOne;
Log.e("FINALPATH", finalimgpath);
} catch (JSONException e) {
e.printStackTrace();
}
mPager.setAdapter(viewpager_adapter);
viewpager_adapter.notifyDataSetChanged();
}
Edit
Also if your final image path is as below then you have to update your code in adapter for image path as follow.
Update position in view.addView() too.
String test = String.valueOf(mylist.get(position));
String imgpath = getString(R.string.imgpath);
String finalimgpath = imgpath + test;
Glide.with(context)
.load(finalimgpath)
.into(imageView);
view.addView(imageLayout,position);
return imageLayout;
In your For loop you are initialising your list everytime
for (int i = 0; i < responsearray.length(); i++) {
JSONObject responseObject = responsearray.getJSONObject(i);
Log.e("COUNT" + i, String.valueOf(responseObject));
imageOne = responseObject.getString(TAG_PHOTO_ONE);
get = new HashMap<>();
get.put(TAG_PHOTO_ONE, imageOne);
myList = new ArrayList<>(); // THIS IS WRONG. don't initialise every time
myList.add(String.valueOf(get)); // THIS IS ALSO WRONG. you are adding hashmap object to list
}
So make your for loop like this
myList = new ArrayList<>();
for (int i = 0; i < responsearray.length(); i++) {
JSONObject responseObject = responsearray.getJSONObject(i);
Log.e("COUNT" + i, String.valueOf(responseObject));
imageOne = responseObject.getString(TAG_PHOTO_ONE);
get = new HashMap<>();
get.put(TAG_PHOTO_ONE, imageOne);
myList.add(imageOne);
}

How to use onSaveInstanceState and onActivityCreated on my ListFragment page

The problem is that whenever the user go to the third fragment then coming back to the first one, all the data in the first fragment will be gone.
the Data will parsed from a web service, using AsyncTask within the fragment
this my onCreate() method
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
int radius = 4;
double latitude = 51.3674718208489;
double longtitude = -0.119329656538836;
Boolean loyal = false;
int mer = 1;
try {
parameters.put(ConstantKeys.SEARCH_NAME, searchname);
parameters.put(ConstantKeys.LOYALTY, isLoyalty);
Log.d(CommunityFragment.class.getSimpleName(), parameters.toString());
} catch (JSONException e) {
e.printStackTrace();
}
FindOfferField();
}
this is my onCreateView() method
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.community_fragment, container, false);
return rootView;
}
and this is my AsynTask()
public void FindOfferField() {
RegisterRequest request = new RegisterRequest(getActivity());
SharedPreferences userpass = getActivity().getSharedPreferences("USERPASS", 0);
String email = userpass.getString("username", null);
String password = userpass.getString("password", null);
Log.d(CommunityFragment.class.getSimpleName(), "Email:" + email + " Password:" + password);
request.getToken(email, password, new ApiRequestListener() {
#Override
public void onSuccess(Object object) {
(new FindOfferTask() {
#Override
protected void onPostExecute(JSONObject data) {
super.onPostExecute(data);
try {
if (data.getString(ConstantKeys.RESULT).equals("OK")) {
array = data.getJSONArray(ConstantKeys.RESULTS);
RowItem items;
rowItem = new ArrayList<RowItem>();
for (int i = 0; i < array.length(); i++) {
final JSONObject list = array.getJSONObject(i);
items = new RowItem();
int id = Integer.parseInt(offerList.getString("Id"));
byID = id;
Log.d("AnotherID", String.valueOf(byID));
Boolean isCommunity = offerList.getBoolean(ConstantKeys.IS_COMMUNITY);
items.setId(list.getInt("Id"));
items.setMerchantid(list.getInt(ConstantKeys.MERCHANTID));
items.setDescription(list.getString(ConstantKeys.DESCRIPTION));
items.setDateEnd(list.getString(ConstantKeys.DATE).replace("T00:00:00", ""));
items.setTokensFor(list.getString(ConstantKeys.FOR));
if (!offerList.isNull("ImageId")) {
int bitmapImageID = offerList.getInt("ImageId");
Log.d("BITMAPHAHA", String.valueOf(bitmapImageID));
items.setImageId(bitmapImageID);
}
rowItem.add(items);
listView = (ListView) getView().findViewById(R.id.listViewCommunity);
adapter = new CustomListAdapter(getActivity(), rowItem);
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
getEndTask = new RowItemLoyalty();
getTask = new RowItem();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
boolean isCommunity = false;
try {
isCommunity = offerList.getBoolean(ConstantKeys.IS_COMMUNITY);
} catch (JSONException e) {
e.printStackTrace();
}
int ID = rowItem.get(position).getId();
int merID = rowItem.get(position).getMerchantid();
Intent intent = new Intent(getActivity(), CustomerPromotion.class);
getEndTask.endTask();
getTask.endTask();
intent.putExtra("ID", ID);
intent.putExtra("MERCHANT", merID);
intent.putExtra("BOOLEANVALUE", isCommunity);
startActivity(intent);
}
});
}
Log.d("JSON Data", data.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("JSON DATA", data.toString());
Log.w("Success Register", data.toString());
}
}).execute();
}
#Override
public void onError(String error) {
Log.e("Registration Error", error);
}
});
}
UPDATE
public class CommunityFragment extends ListFragment{
//LocationListener location;
ProgressDialog progressDialog;
Context context;
public static JSONObject parameters = new JSONObject();
private static final String STATE_LIST = "State Adapter Data";
public static final String DATA = "DATA";
public CustomerAccount customerAccount;
//---------Find Parameters----------
int byID;
//CustomListAdapter adapter;
public static String TAG = CommunityFragment.class.getSimpleName();
ListView listView;
ArrayList<RowItem> rowItem;
View view;
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
String searchname = ConstantSearch.SEARCHNAME;
CustomListAdapter adapter;
private String mParam1;
private String mParam2;
RowItemLoyalty getEndTask;
RowItem getTask;
RowItem storeData;
int index;
int top;
JSONArray array;
public CommunityFragment() {
}
public static CommunityFragment newInstance(String param1, String param2) {
CommunityFragment fragment = new CommunityFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
String dataInJson = new Gson().toJson(rowItem);
outState.putString(DATA, dataInJson);
super.onSaveInstanceState(outState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(savedInstanceState != null && savedInstanceState.containsKey(DATA))
{
Log.d("StringData", DATA);
String jsonData = savedInstanceState.getString(DATA);
rowItem = new Gson().fromJson(jsonData, new TypeToken<List<RowItem>>(){}.getType());
}
else
{
rowItem = new ArrayList<>();
}
adapter = new CustomListAdapter(getActivity(), rowItem);
listView.setAdapter(adapter);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
int radius = 4;
double latitude = 51.3674718208489;
double longtitude = -0.119329656538836;
Boolean isLoyalty = false;
int mer = 1;
try {
parameters.put(ConstantKeys.SEARCH_NAME, searchname);
parameters.put(ConstantKeys.LOYALTY, isLoyalty);
Log.d(CommunityFragment.class.getSimpleName(), parameters.toString());
} catch (JSONException e) {
e.printStackTrace();
}
FindOfferField();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.community_fragment, container, false);
rowItem = new ArrayList<RowItem>();
listView = (ListView) rootView.findViewById(R.id.listViewCommunity);
return rootView;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
public void FindOfferField() {
RegisterRequest request = new RegisterRequest(getActivity());
SharedPreferences userpass = getActivity().getSharedPreferences("USERPASS", 0);
String email = userpass.getString("username", null);
String password = userpass.getString("password", null);
Log.d(CommunityFragment.class.getSimpleName(), "Email:" + email + " Password:" + password);
request.getToken(email, password, new ApiRequestListener() {
#Override
public void onSuccess(Object object) {
(new FindOfferTask() {
#Override
protected void onPostExecute(JSONObject data) {
super.onPostExecute(data);
try {
if (data.getString(ConstantKeys.RESULT).equals("OK")) {
array = data.getJSONArray(ConstantKeys.RESULTS);
RowItem items;
rowItem = new ArrayList<RowItem>();
for (int i = 0; i < array.length(); i++) {
final JSONObject offerList = array.getJSONObject(i);
items = new RowItem();
int id = Integer.parseInt(offerList.getString("Id"));
byID = id;
Log.d("AnotherID", String.valueOf(byID));
Boolean isCommunity = offerList.getBoolean(ConstantKeys.IS_COMMUNITY);
items.setId(offerList.getInt("Id"));
items.setMerchantid(offerList.getInt(ConstantKeys.FAVORITE_MERCHANTID));
items.setDescription(offerList.getString(ConstantKeys.DESCRIPTION));
items.setDateEnd(offerList.getString(ConstantKeys.DATE_END).replace("T00:00:00", ""));
items.setTokensFor(offerList.getString(ConstantKeys.TOKENSFOR));
if (!offerList.isNull("ImageId")) {
int bitmapImageID = offerList.getInt("ImageId");
Log.d("BITMAPHAHA", String.valueOf(bitmapImageID));
items.setImageId(bitmapImageID);
}
rowItem.add(items);
adapter = new CustomListAdapter(getActivity(), rowItem);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
getEndTask = new RowItemLoyalty();
getTask = new RowItem();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
boolean isCommunity = false;
try {
isCommunity = offerList.getBoolean(ConstantKeys.IS_COMMUNITY);
} catch (JSONException e) {
e.printStackTrace();
}
int offerID = rowItem.get(position).getId();
int merID = rowItem.get(position).getMerchantid();
Intent intent = new Intent(getActivity(), CustomerPromotion.class);
getEndTask.endTask();
getTask.endTask();
intent.putExtra("ID", offerID);
intent.putExtra("MERCHANT", merID);
intent.putExtra("BOOLEANVALUE", isCommunity);
startActivity(intent);
}
});
}
Log.d("JSON Data", data.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("JSON DATA", data.toString());
Log.w("Success Register", data.toString());
}
}).execute();
}
#Override
public void onError(String error) {
Log.e("Registration Error", error);
}
});
}
public class FindOfferTask extends AsyncTask<Void, Void, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected JSONObject doInBackground(Void... params) {
ApiSecurityManager manager = ApiSecurityManager.getInstance();
String result = manager.apiCall("Offers/find", parameters.toString(), "C");
Log.d(CommunityFragment.class.getSimpleName(), result);
JSONObject jsonResult = new JSONObject();
Log.i(getClass().getSimpleName(), result);
try
{
jsonResult = new JSONObject(result);
}
catch (JSONException e)
{
e.printStackTrace();
}
return jsonResult;
}
protected void onPostExecute(JSONObject jsonObject) {
//loadingMore = false;
progressDialog.dismiss();
}
}
}
First of all, keep your view creation outside ApiRequestListener. Initialize all views in onCreateView() only.
// Key for storing data in `savedInstance`
public static final String DATA = "DATA";
In onCreateView()
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.community_fragment, container, false);
rowItem = new ArrayList<RowItem>();
listView = (ListView) rootView.findViewById(R.id.listViewCommunity);
return rootView;
}
When activity is created, check if data is available in savedInstanceState or not and based on that start web service.
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
if(savedInstanceState.containsKey(DATA))
{
String jsonData = savedInstanceState.getString(DATA);
rowItem = new Gson().fromJson(jsonData, new TypeToken<List<RowItem>>(){}.getType());
}
else
{
rowItem = new ArrayList<>();
}
adapter = new CustomListAdapter(getActivity(), rowItem);
listView.setAdapter(adapter);
// Now here, check the size of array list. If it is 0, then start service to fetch data from server
}
To convert your list into string, I am using Gson library here.
#Override
public void onSaveInstanceState(Bundle outState)
{
// Here use gson library from google to convert list of data to string.
String dataInJson = new Gson().toJson(rowItem);
outState.putString(DATA, dataInJson);
super.onSaveInstanceState(outState);
}
And your method will look like this:
public void FindOfferField() {
RegisterRequest request = new RegisterRequest(getActivity());
SharedPreferences userpass = getActivity().getSharedPreferences("USERPASS", 0);
String email = userpass.getString("username", null);
String password = userpass.getString("password", null);
Log.d(CommunityFragment.class.getSimpleName(), "Email:" + email + " Password:" + password);
request.getToken(email, password, new ApiRequestListener() {
#Override
public void onSuccess(Object object) {
(new FindOfferTask() {
#Override
protected void onPostExecute(JSONObject data) {
super.onPostExecute(data);
try {
if (data.getString(ConstantKeys.RESULT).equals("OK")) {
array = data.getJSONArray(ConstantKeys.RESULTS);
RowItem items;
for (int i = 0; i < array.length(); i++) {
final JSONObject list = array.getJSONObject(i);
items = new RowItem();
int id = Integer.parseInt(offerList.getString("Id"));
byID = id;
Log.d("AnotherID", String.valueOf(byID));
Boolean isCommunity = offerList.getBoolean(ConstantKeys.IS_COMMUNITY);
items.setId(list.getInt("Id"));
items.setMerchantid(list.getInt(ConstantKeys.MERCHANTID));
items.setDescription(list.getString(ConstantKeys.DESCRIPTION));
items.setDateEnd(list.getString(ConstantKeys.DATE).replace("T00:00:00", ""));
items.setTokensFor(list.getString(ConstantKeys.FOR));
if (!offerList.isNull("ImageId")) {
int bitmapImageID = offerList.getInt("ImageId");
Log.d("BITMAPHAHA", String.valueOf(bitmapImageID));
items.setImageId(bitmapImageID);
}
rowItem.add(items);
adapter.notifyDataSetChanged();
getEndTask = new RowItemLoyalty();
getTask = new RowItem();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
boolean isCommunity = false;
try {
isCommunity = offerList.getBoolean(ConstantKeys.IS_COMMUNITY);
} catch (JSONException e) {
e.printStackTrace();
}
int ID = rowItem.get(position).getId();
int merID = rowItem.get(position).getMerchantid();
Intent intent = new Intent(getActivity(), CustomerPromotion.class);
getEndTask.endTask();
getTask.endTask();
intent.putExtra("ID", ID);
intent.putExtra("MERCHANT", merID);
intent.putExtra("BOOLEANVALUE", isCommunity);
startActivity(intent);
}
});
}
Log.d("JSON Data", data.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("JSON DATA", data.toString());
Log.w("Success Register", data.toString());
}
}).execute();
}
#Override
public void onError(String error) {
Log.e("Registration Error", error);
}
});
}
Hope this helps.

Android how can i get value of ArrayList Hashmap in my baseadapter

I have an Activity called Myprofile and a baseAdapter called Myprofile_CustomView on my activity I get Json data which then I convert into a ArrayList with a hashmap and my question is how can I retrieve the values of the hashmap in the baseadapter ?
This is my activity Myprofile
public class Myprofile extends Activity {
String URI_URL;
Integer page;
ProgressBar pb;
ListView mm;
Myprofile_CustomView BA;
ArrayList<HashMap<String,String>> userslist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myprofile);
URI_URL = getResources().getString(R.string.PathUrl) + "/api/myprofile";
page=0;
// Listview for adapter
mm= (ListView)findViewById(R.id.myprofiles);
new Myprofile_Async().execute();
}
public class Myprofile_Async extends AsyncTask<String,String,String> {
HttpURLConnection conn;
URL url;
String result="";
DataOutputStream wr;
int id;
#Override
protected void onPreExecute() {
super.onPreExecute();
pb=(ProgressBar)findViewById(R.id.progressBar);
pb.setVisibility(View.VISIBLE);
id= getIntent().getExtras().getInt("id");
// page Int is used to keep count of scroll events
if(page==0)
{page=1;}
else {page=page+1;}
Toast.makeText(Myprofile.this,""+page,Toast.LENGTH_SHORT).show();
}
#Override
protected String doInBackground(String... params) {
// Gets data from api
BufferedReader reader=null;
String cert="id="+id+"&page="+page;
try{
url = new URL(URI_URL);
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.connect();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(cert);
wr.flush();
wr.close();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sBuilder = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
sBuilder.append(line + "\n");
}
result = sBuilder.toString();
reader.close();
conn.disconnect();
return result;
}
catch (Exception e)
{
e.printStackTrace();
}
System.err.println("cassies" + result);
return result;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
HashMap<String,String> map= new HashMap<>();
JSONObject jsonn= new JSONObject(result);
JSONArray jArray = jsonn.getJSONArray("myprofile");
JSONObject jobject=null;
JSONArray sss= new JSONArray();
for(int i=0; i < jArray.length(); i++) {
jobject= jArray.getJSONObject(i);
map.put("fullname",jobject.getString("fullname"));
sss.put(jobject);
}
jsonn.put("myprofile", sss);
// Add values to arrayList
userslist.add(map);
// Send information to BaseAdapter
BA= new Myprofile_CustomView(userslist,Myprofile.this);
mm.setAdapter(BA);
} catch (Exception e) {
System.err.println("mpee: " + e.toString());
}
pb.setVisibility(View.INVISIBLE);
}
}
}
this part above I have no issues with my problem is in the BaseAdapter with the ArrayList userList I don't know how to get HashMap keys from it. I am naming the keys because I have other fields that I will eventually do
public class Myprofile_CustomView extends BaseAdapter {
JSONObject names;
Context ctx;
LayoutInflater myiflater;
ArrayList<HashMap<String,String>> usersList;
// Have data come in and do a toast to see changes
public Myprofile_CustomView(ArrayList<HashMap<String,String>> arr, Context c) {
notifyDataSetChanged();
ctx = c;
usersList= arr;
myiflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
try {
JSONArray jaLocalstreams = names.getJSONArray("myprofile");
return jaLocalstreams.length();
} catch (Exception e) {
Toast.makeText(ctx, "Error: Please try again", Toast.LENGTH_LONG).show();
return names.length();
}
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row=convertView;
MyViewHolder holder=null;
try {
if(row==null) {
LayoutInflater li = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = li.inflate(R.layout.zmyprofile,parent,false);
holder=new MyViewHolder(row);
row.setTag(holder);
}
else
{
holder=(MyViewHolder)row.getTag();
}
// How can I get HashMap value for fullname here so I can set it to to Text
String fullname= usersList
holder.fullname.setText(fullname);
return row;
} catch (Exception e) {
e.printStackTrace();
}
return row;
}
class MyViewHolder{
TextView fullname;
MyViewHolder(View v)
{
fullname= (TextView)v.findViewById(R.id.fullname);
}
}
}
getCount should return the size of your dataset. In your case usersList
public int getCount() {
return usersList == null ? 0 : userLists.size();
}
int getView you want to retrieve the item at position:
HashMap<String, String> item = usersList.get(i);
String fullname = item.get("fullname");
the value of position changes with the scrolling,

Gridview is refreshed from start when scrollbar reaches end

This happens while loading data in gridview. This is my fragment containing scroll listener over gridview. But whenever i reload the data then whole gridview reload and scroll starts from top not from where the data is loaded. I am using single gridview.
public class Women_Ethnic_Fragment extends Fragment {
private static String url = "http://------/-------";
private int mVisibleThreshold = 5;
private int mCurrentPage = 0;
private int mPreviousTotal = 0;
private boolean mLoading = true;
private boolean mLastPage = false;
public Women_Ethnic_Fragment() {
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.gridview_fragment, container,
false);
setRetainInstance(true);
arrayList = new ArrayList<Items>();
gridView = (GridView) rootView.findViewById(R.id.gridView1);
new LoadData().execute(url);
//scrolling portion
gridView.setOnScrollListener(new OnScrollListener() {
#Override
public void onScroll(AbsListView view,
int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (mLoading) {
if (totalItemCount > mPreviousTotal) {
mLoading = false;
mPreviousTotal = totalItemCount;
mCurrentPage++;
if (mCurrentPage + 1 > 50) {
mLastPage = true;
}
}
}
if (!mLastPage
&& !mLoading
&& (totalItemCount - visibleItemCount) <= (firstVisibleItem + mVisibleThreshold)) {
//new asynctask called
new LoadData()
.execute("http://-------/---------");
mLoading = true;
}
}
#Override
public void onScrollStateChanged(AbsListView view,
int scrollState) {
}
});
return rootView;
}
//my asynctask
private class LoadData extends AsyncTask<String,
Void, Void> {
#Override
protected void onPostExecute(Void result) {
tp.dismiss();
adap = new Grid_View_Adatper(getActivity().getApplicationContext(),
arrayList);
gridView.setAdapter(adap);
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
tp = new TransparentProgressDialog(getActivity(),
R.drawable.spinner);
tp.setCancelable(false);
tp.setCanceledOnTouchOutside(false);
tp.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(String... urls) {
try {
HttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(urls[0]);
HttpResponse response = client.execute(httpget);
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONArray json = new JSONArray(data);
for (int i = 0; i < json.length(); i++) {
JSONObject e = json.getJSONObject(i);
String name = e.getString("name");
String price = e.getString("price");
String image = e.getString("image");
String code = e.getString("sku");
tems = new Items(name, price, image, code);
arrayList.add(tems);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
} catch (IOException e) {
} catch (RuntimeException e) {
}
return null;
}
}
Please help someone.
Thanks in advane.
The problem is you instantiate adapter over and over again. Instead check your adapter first, if it is not null, then set your data, then notify dataset changes.
if (adapter == null) {
adapter = new GridViewAdapter...
gridView.setAdapter(adapter)
}
// list refers the list inside in your adapter
list.addAll(newList); // or do your implementation
adapter.notifyDataSetChanged();

Categories