Cant get ArrayList from another class. Its always empty - java

im still Android beginner and new to Stackowerflow, i hope you will understand my problem. Im using Volley libary and Singleton class. I have JsonParser class which after parsing should return the filled list with objects.
public class JsonParse {
Context context;
public ArrayList<ParseItem> parseItemList = new ArrayList<>();
String json_url = "myurl";
public JsonParse(Context context) {
this.context = context;
}
public ArrayList<ParseItem> getList() {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, json_url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
ParseItem parseItem = new ParseItem();
String naslov = jsonObject.getString("naslov");
String url = jsonObject.getString("url");
parseItem.setTitle(naslov);
parseItem.setUrl(url);
JSONArray niz = jsonObject.getJSONArray("niz");
ArrayList<String> podnaslovTMP = new ArrayList<>();
ArrayList<String> podurlTMP = new ArrayList<>();
for (int j = 0; j < niz.length(); j++) {
JSONObject nizOBJ = niz.getJSONObject(j);
String podnaslov = nizOBJ.getString("podnaslov");
String podurl = nizOBJ.getString("podurl");
podnaslovTMP.add(podnaslov);
podurlTMP.add(podurl);
}
parseItemList.add(parseItem);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
MySingleton.getInstance(context).addToRequestQueue(jsonArrayRequest);
return parseItemList;
}}
Then im trying to call getList and take my list i HomeFragment.
public class HomeFragment extends Fragment implements View.OnClickListener {
private Context context;
private static final int REQUEST_CALL = 1;
private View view;
private ParseItem parseItem = new ParseItem();
public ArrayList<ParseItem>arrayList = new ArrayList<>();
public HomeFragment() {
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable final ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_home, container, false);
init();
JsonParse jsonParse = new JsonParse(getActivity());
arrayList = jsonParse.getList();
return view;
}
My arrayList is always empty. I hope someone can help me.

create listner
public interface GetArrayListListner{
void getArrayData(ArrayList<ParseItem>);
}
and
public class JsonParse {
private GetArrayListListner arrayListListner;// add this line
Context context;
public ArrayList<ParseItem> parseItemList = new ArrayList<>();
String json_url = "myurl";
public JsonParse(Context context,GetArrayListListner arrayListListner) {
this.context = context;
this.arrayListListner = arrayListListner; //Add this line
}
public void getList() {
new JsonArrayRequest(Request.Method.POST, json_url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
ParseItem parseItem = new ParseItem();
String naslov = jsonObject.getString("naslov");
String url = jsonObject.getString("url");
parseItem.setTitle(naslov);
parseItem.setUrl(url);
JSONArray niz = jsonObject.getJSONArray("niz");
ArrayList<String> podnaslovTMP = new ArrayList<>();
ArrayList<String> podurlTMP = new ArrayList<>();
for (int j = 0; j < niz.length(); j++) {
JSONObject nizOBJ = niz.getJSONObject(j);
String podnaslov = nizOBJ.getString("podnaslov");
String podurl = nizOBJ.getString("podurl");
podnaslovTMP.add(podnaslov);
podurlTMP.add(podurl);
}
parseItemList.add(parseItem);
} catch (JSONException e) {
e.printStackTrace();
}
}
arrayListListner.getArrayData(parseItemList);//add this line
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
MySingleton.getInstance(context).addToRequestQueue(jsonArrayRequest);
return parseItemList;
}
}
and call it
JsonParse jsonParse = new JsonParse(getActivity(),new GetArrayListListner(){
#Overrid void getArrayData(ArrayList<ParseItem>){
arrayList = jsonParse.getList();
}
});

Your method getList() calls a web service, which is executed on a separate thread. When you use MySingleton.getInstance(context).addToRequestQueue(jsonArrayRequest);
you are placing the request to a Queue, that means it is not gonna be executed right now, but you are already returning your array. As the request hasn't been executed yet, your array list hasn't been filled yet.
The practice recommended by Google today is using LiveData, it can be hard to a beginner, but with a little study, you can solve it.
https://developer.android.com/topic/libraries/architecture/livedata
Maybe you can look at Reactive Programming as well.
Another easy solution would be using interfaces, so you can pass the interface as a parameter, which will be triggered when your array gets filled.
Let me know if I was of any help, thanks

Related

How to make ViewModel display network data on first run

I am just getting into Android Architecture and have encountered an issue after following this tutorial by mitch:
ViewModel doesn't show any data from the internet- I'm using volley- on first run.
The UI remains blank and only shows data on the views only onChange. i.e A screen rotation/refresh
If I manually set this data, it shows them on first run as required
i.e dataSet.add(new DecodeHouseDetails(1,1,1,"H2345","treutue.jpg","House 1","4345423232312","3224342434232") ); //Add data to the mutatable list
But once I include the network data, it misbehaves.
I have tried checking if my repository could be returning a null list on first run but the toast attached inside the repository shows that the data was well received, only that I dont understand why it wont display until either a change in screen rotation or a refresh
My Repository
public class GetHouseDetailsRepository {
private Context mContext;
private static final String URL_initializeDashboard= CustomFunctions.root_house_admin_url+"initialize_dashboard";
CustomFunctions func= new CustomFunctions();
private static GetHouseDetailsRepository instance;
private ArrayList<DecodeHouseDetails> dataSet= new ArrayList<>();
private JSONObject jsonObject;
public static GetHouseDetailsRepository getInstance(){
if(instance == null){
instance = new GetHouseDetailsRepository();
}
return instance;
}
//Make a mutable list of the data that we will be getting from the database
public MutableLiveData<List<DecodeHouseDetails>> getHouseDetails(Context mContext){
this.mContext=mContext;
getDatabaseHouseDetails();
MutableLiveData<List<DecodeHouseDetails>> myData= new MutableLiveData<>();
if(dataSet ==null){
getDatabaseHouseDetails();
}
myData.setValue(dataSet);
return myData;
}
//Method to actually get the data from the database
public void getDatabaseHouseDetails(){
//dataSet.add(new DecodeHouseDetails(1,1,1,"H2345","treutue.jpg","Keja Mkononi","1","A nice house","Water,electrivit","Other amenities","5","1","Embu","1","1","1","1","4345423232312","3224342434232") ); //Add data to the mutatable list
jsonObject= new JSONObject();
try {
jsonObject.put("me",""+func.getSharedUserID(mContext) );//Logged in user
} catch (JSONException e) {
Log.e("JSONObject Here", e.toString());
}
VolleyNetworkRequestInterfaceSingleton.getResponse(mContext,Request.Method.GET, URL_initializeDashboard, jsonObject,new VolleyNetworkRequestInterfaceSingleton.VolleyCallback(){
#Override
public void onSuccessResponse(String response) {
if(response!=null) {
try {
JSONObject json = new JSONObject(response);
//Successfully fetched
String sarray = json.getString("house_details");
Toast.makeText(mContext, sarray, Toast.LENGTH_SHORT).show();
JSONArray jsonArray = new JSONArray(sarray);
//Clear list to refresh list in every selection
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json_list = jsonArray.getJSONObject(i);
DecodeHouseDetails houses_array = new DecodeHouseDetails(
json_list.getInt("active_identifier"),
json_list.getInt("house_id"),
json_list.getInt("house_status"),
json_list.getString("house_number"),
json_list.getString("house_cover"),
json_list.getString("house_name"),
json_list.getString("longitude"),
json_list.getString("latitude")
);
dataSet.add(houses_array);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
}
}
My ViewModel
public class GetHouseDetailsViewModel extends AndroidViewModel {
//The data we fetch from asynchronously
private MutableLiveData<List<DecodeHouseDetails>> mHouseDetailsList;
private GetHouseDetailsRepository mHouseDetailsRepository;
public GetHouseDetailsViewModel(#NonNull Application application) {
super(application);
}
public void init(){
if(mHouseDetailsList != null){
mHouseDetailsList= new MutableLiveData<>();
}
mHouseDetailsRepository = GetHouseDetailsRepository.getInstance(); //Initialize the repository
mHouseDetailsList = mHouseDetailsRepository.getHouseDetails(this.getApplication());
}
public LiveData<List<DecodeHouseDetails>> getHouseInfo() {
if(mHouseDetailsList == null){
mHouseDetailsList = new MutableLiveData<>();
}
return mHouseDetailsList;
}
}
My View - Fragment
public class AdmManageHouses extends Fragment {
private ProgressBar progressloader,progressloader_large;
SwipeRefreshLayout refreshLayout;
private TextView house_number_text,house_title_text,house_name_text;
private GetHouseDetailsViewModel mHouseDetailsViewModel;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab1_manage_houses, container, false);
mHouseDetailsViewModel = ViewModelProviders.of(getActivity()).get(GetHouseDetailsViewModel.class);
//Innitialize objects
house_title_text= rootView.findViewById(R.id.house_title);
house_number_text= rootView.findViewById(R.id.house_number);
house_name_text= rootView.findViewById(R.id.house_name);
//Initialize the view model
mHouseDetailsViewModel.init();
mHouseDetailsViewModel.getHouseInfo().observe(getViewLifecycleOwner(), new Observer<List<DecodeHouseDetails>>() {
#Override
public void onChanged(List<DecodeHouseDetails> decodeHouseDetails) {
for(int i=0; i<decodeHouseDetails.size(); i++) {
house_number_text.setText(String.valueOf(decodeHouseDetails.get(i).getHouse_number()));
house_title_text.setText(decodeHouseDetails.get(i).getHouse_name());
house_name_text.setText(decodeHouseDetails.get(i).getHouse_name());
}
}
});
//Refresh on swipe
refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
initializeDashboard();
refreshLayout.setRefreshing(false);
}
});
initializeDashboard();
return rootView;
}
private void initializeDashboard() {
for(int i=0; i<mHouseDetailsViewModel.getHouseInfo().getValue().size(); i++) {
house_number_text.setText(String.valueOf(mHouseDetailsViewModel.getHouseInfo().getValue().get(i).getHouse_number()));
house_title_text.setText(mHouseDetailsViewModel.getHouseInfo().getValue().get(i).getHouse_name());
house_name_text.setText(mHouseDetailsViewModel.getHouseInfo().getValue().get(i).getHouse_name());
}
}
}
After thorough checking of the viewmodel, I discovered that problem was in the repository and not the viewModel. I was not calling setValue() properly.
This made the first run - when the list is null - fail to populate the UI until onChange.
I made the following changes to the repository
i.e
Declare myData variable
Private MutableLiveData<List<DecodeHouseDetails>> myData= new MutableLiveData<>();
//Make a mutable list of the data that we will be getting from the database
public MutableLiveData<List<DecodeHouseDetails>> getHouseDetails(Context mContext){
this.mContext=mContext;
getDatabaseHouseDetails();
return myData;
}
//Method to actually get the data from the database
public void getDatabaseHouseDetails(){
//dataSet.add(new DecodeHouseDetails(1,1,1,"H2345","treutue.jpg","Keja Mkononi","1","A nice house","Water,electrivit","Other amenities","5","1","Embu","1","1","1","1","4345423232312","3224342434232") ); //Add data to the mutatable list
jsonObject= new JSONObject();
try {
jsonObject.put("me",""+func.getSharedUserID(mContext) );//Logged in user
} catch (JSONException e) {
Log.e("JSONObject Here", e.toString());
}
VolleyNetworkRequestInterfaceSingleton.getResponse(mContext,Request.Method.GET, URL_initializeDashboard, jsonObject,new VolleyNetworkRequestInterfaceSingleton.VolleyCallback(){
#Override
public void onSuccessResponse(String response) {
if(response!=null) {
try {
JSONObject json = new JSONObject(response);
//Successfully fetched
String sarray = json.getString("house_details");
Toast.makeText(mContext, sarray, Toast.LENGTH_SHORT).show();
JSONArray jsonArray = new JSONArray(sarray);
//Clear list to refresh list in every selection
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json_list = jsonArray.getJSONObject(i);
DecodeHouseDetails houses_array = new DecodeHouseDetails(
json_list.getInt("active_identifier"),
json_list.getInt("house_id"),
json_list.getInt("house_status"),
json_list.getString("house_number"),
json_list.getString("house_cover"),
json_list.getString("house_name"),
json_list.getString("longitude"),
json_list.getString("latitude")
);
dataSet.add(houses_array);
}
myData.setValue(dataSet);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
}

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 send values from an arraylist from AsyncTask class to another class in Android?

I have the next problem, I tried to send Arraylist<string> values from AsyncTask class to other class call graphics but I don’t know what I do wrong and how to get Arraylist<string> values in the other class, because I have a lot of sintaxis errors I my code
AsyncTask class
public class fetch extends AsyncTask<Void,Void,ArrayList<String>> {
//v funcional
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected ArrayList<String> doInBackground(Void... voids) {
String Id ="";
String Time ="";
String Pressure="";
ArrayList<String> IdArray = new ArrayList<String>();
ArrayList<String> TimeArray = new ArrayList<String>();
ArrayList<String> PressureArray = new ArrayList<String>();
String IdS=""+IdArray;
String TimeS=""+TimeArray;
String PresureS=""+PressureArray;
data.set(1,TimeS);
data.set(2,TimeS);
data.set(3,TimeS);
return data;
}
#Override
protected void onPostExecute(ArrayList<String> result){
super.onPostExecute(result);
Graphics.data.setText(data);
}}
The graphics class
public class Graphics extends AppCompatActivity {
public static TextView data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.graphics);
Button firstButton = (Button) findViewById(R.id.json);
data = (TextView) findViewById(R.id.msgTxt);
firstButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
fetch process = new fetch();
ArrayList<String> data= process.execute();
data.get(1);
}
});
}
you can create an interface which your "Graphics" implements it , and pass it to your AsyncTask class.
like this
public interface BlaBlaBla {
void doBla(ArrayList<String> myBla);
}
and in your "Graphics" :
class Graphics extends AppCompatActivity implements BlaBlaBla {
fetch process = new fetch(this);
}
and for asyncClass :
public class fetch extends AsyncTask<Void,Void,ArrayList<String>> {
//constructor
BlaBlaBla bla;
public fetch(BlaBlaBla bla){
this.bla=bla;
}
//when your task is complete use bla.doBla(pass your array here);
}
my solution
Fetch class
public class Fetch extends AsyncTask<Void,Void,String[][]> {
public static int KEY = 0;
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected String[][] doInBackground(Void... voids) {
HttpHandler sh = new HttpHandler();
String url = "http:xxxxxxx/xxx.json";
String jsonStr = sh.makeServiceCall(url);
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject(jsonStr);
int nTiempos=jsonObj.length();
String[] IdKeyArray = new String[nTie];
for (int i = 0; i < jsonObj.length(); i++) {
JSONObject c = jsonObj.getJSONObject(String.valueOf(i));
IdKeyArray[i] = c.getString("Key");
String[][] valores={IdKeyArray};
return valores;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
And this is the "call" the other class where I get the values
private String[][] valores;
Fetch process = new Fetch();
process.execute();
try {
valores=process.get();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
pm.setText(String.valueOf(valores[Fetch.Key][0]));
}
}
}

Sorting data from Json array using android volley into activity

Im using volley to get and handle the Json object into the activity
and here are the classes and the following :
The problem is when im trying to get the Address ,Phones, Emails as sorting for each line from the object it show up like this first it get the address with the first line then it jumps to line 5 to get id then line 8 to get twitterUrl.
Inside the APP Data
web Service reponse on the postman
[
{
"address": "adddress1",
"emails": "ggggdjd#ttttt.com",
"facebookUrl": "ddddd",
"googlePlus": "ddddddd",
"id": 1,
"instagramUrl": "ddddd",
"phones": "0100098763 - 82726353",
"twitterUrl": "ddddd",
"youtubeUrl": "dddd"
}
]
Content Volley.java
extends BaseVolley {
// base url for srever
String TAG = "sjnsn";
private final String url = url ;
protected enum ActionType implements BaseVolley.ActionType {
appcontactus
}
public ContentVolley(String TAG, Context context) {
super(TAG, VolleySingleton.getInstance(context));
}
// method created as an example for post request for a certain api
public void getAboutUs() {
params = new HashMap<>();
actionType = ActionType.appcontactus;
requestAction(Request.Method.GET, url + ((Enum) actionType).name(), true);
}
#Override
protected void onPreExecute(BaseVolley.ActionType actionType) {
ActionType action = (ActionType) actionType;
onPreExecute(action);
}
#Override
protected void getResponseParameters(String response) throws JSONException {
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
String message = "";
try {
jsonArray = new JSONArray(response);
Log.d(TAG, "getResponseParameters: "+response);
} catch (JSONException e) {
jsonObject = new JSONObject(response);
message = jsonObject.optString("msg");
}
ActionType action = (ActionType) actionType;
switch (action) {
case appcontactus:
ArrayList<ContactUsItem> contactUsList = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
String address = jsonObject.optString("address");
String emails = jsonObject.optString("emails");
String phones = jsonObject.optString("phones");
String facebookUrl = jsonObject.optString("facebookUrl");
String googlePlus = jsonObject.optString("googlePlus");
String instagramUrl = jsonObject.optString("instagramUrl");
String twitterUrl = jsonObject.optString("twitterUrl");
String youtubeUrl = jsonObject.optString("youtubeUrl");
String id = jsonObject.optString("id");
ContactUsItem contactUsItem = new ContactUsItem(id, address, emails, phones, facebookUrl,googlePlus,instagramUrl
,twitterUrl,youtubeUrl);
contactUsList.add(contactUsItem);
}
onPostExecuteAboutUs(true, message,contactUsList) ;
break;
}
}
#Override
protected void onPostExecuteError(boolean success, String message, BaseVolley.ActionType actionType) {
ActionType action = (ActionType) actionType;
switch (action) {
case appcontactus:
onPostExecuteAboutUs(false, message, null);
break;
}
}
protected abstract void onPreExecute(ActionType actionType);
protected void onPostExecuteAboutUs(boolean success, String message,ArrayList<ContactUsItem> contactUsList) {
}
protected void onPostExecuteappnews(boolean success, String message, Object result) {
}
}
AboutUsFragment.java
public class AboutusFragment extends Fragment {
private final String TAG = AboutusFragment.class.getSimpleName();
private RelativeLayout relativeLayoutLoading;
private TextView email;
private TextView phone;
private TextView addres;
private ImageView imageViewFacebook, imageViewInstagram, imageViewTwitter;
public AboutusFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_about_us, container, false);
relativeLayoutLoading = (RelativeLayout) rootView.findViewById(R.id.relativeLayoutLoading);
email = (TextView) rootView.findViewById(R.id.textViewEmail);
phone = (TextView) rootView.findViewById(R.id.textViewPhone);
addres = (TextView) rootView.findViewById(R.id.textViewAddress);
imageViewFacebook = (ImageView) rootView.findViewById(R.id.imageViewFacebook);
imageViewInstagram = (ImageView) rootView.findViewById(R.id.imageViewInstagram);
imageViewTwitter = (ImageView) rootView.findViewById(R.id.imageViewTwitter);
Content content = new Content();
content.getAboutUs();
return rootView;
}
private class Content extends ContentVolley {
public Content() {
super(TAG, getContext());
}
#Override
protected void onPreExecute(ActionType actionType) {
}
protected void onPostExecuteAboutUs(boolean success, String message, ArrayList<ContactUsItem> contactUsList) {
if (success) {
for (int i = 0; i < contactUsList.size(); i++) {
ContactUsItem contactUsItem = contactUsList.get(i);
email.setText(contactUsItem.getEmail());
phone.setText(contactUsItem.getPhone());
addres.setText(contactUsItem.getAddress());
}
} else {
Toast.makeText(getContext(), "Failed: " + message, Toast.LENGTH_LONG).show();
}
}
}
}

ArrayList using hashmap not working

I have this code where I get the data from Facebook Graph API which seems working, my problem is when i add the hashmap to my arraylist its not working, i toasted the size of my array and I always get zero. please help. here is the code:
public class PageFeedHome extends Fragment {
ArrayList<HashMap<String, String>> feedList;
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_MESSAGE = "message";
private String feedMessage;
ListView listView;
BaseAdapter adapter;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.feed_home_activity,
container, false);
listView = (ListView) view.findViewById(R.id.feed_lv);
feedList = new ArrayList<HashMap<String, String>>();
new LoadPosts().execute();
return view;
}
private class LoadPosts extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
Session.openActiveSession(getActivity(), true,
new Session.StatusCallback() {
// callback when session changes state
#Override
public void call(Session session, SessionState state,
Exception exception) {
if (session.isOpened()) {
new Request(session, "/163340583656/feed",
null, HttpMethod.GET,
new Request.Callback() {
public void onCompleted(
Response response) {
/* handle the result */
Log.i("PostFeedResponse", response.toString());
try {
GraphObject graphObj = response
.getGraphObject();
JSONObject json = graphObj
.getInnerJSONObject();
JSONArray jArray = json
.getJSONArray("data");
for (int i = 0; i < jArray.length(); i++) {
JSONObject currObj = jArray.getJSONObject(i);
final String feedId = currObj.getString("id");
if (currObj.has("message")) {
feedMessage = currObj.getString("message");
} else if (currObj.has("story")) {
feedMessage = currObj.getString("story");
} else {
feedMessage = "Posted a something";
}
JSONObject fromObj = currObj.getJSONObject("from");
String from = fromObj.getString("name");
HashMap<String, String> feed = new HashMap<String, String>();
feed.put(TAG_ID, feedId);
feed.put(TAG_MESSAGE, feedMessage);
feed.put(TAG_NAME, from);
feedList.add(feed);
Log.i("added" , feedList.toString());
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).executeAsync();
}
}
});
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Toast.makeText(getActivity(), ""+feedList.size(), Toast.LENGTH_LONG).show();
adapter = new SimpleAdapter(getActivity(), feedList,
R.layout.feed_item_view, new String[] { TAG_MESSAGE, TAG_NAME,
TAG_ID }, new int[] { R.id.message, R.id.author, R.id.id_tv });
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
}

Categories