Android add JSON to <string> - android

I want to add json to listview,
but I have no idea
I list items with listview like that;
public class ListSectionActivity extends Activity {
private AndroidListAdapter list_adapter;
private ListView lv_android;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_section);
DataCollection.data_arr=new ArrayList<DataCollection>();
DataCollection.data_arr.add(new DataCollection("apple"));
DataCollection.data_arr.add(new DataCollection("car"));
lv_android=(ListView)findViewById(R.id.lv_android);
list_adapter=new AndroidListAdapter(ListSectionActivity.this, R.layout.list_item,DataCollection.data_arr);
ListSeparateAdapter<DataCollection> listsectionAdapter = new ListSeparateAdapter<DataCollection>(ListSectionActivity.this,
list_adapter, R.layout.enroll_section_list, R.id.tv_section);
lv_android.setAdapter(listsectionAdapter);
}
}
but I want to list item from json.
my json code:
#Override
protected void onPostExecute(String content) {
try {
JSONObject jsonObject = new JSONObject(content);
JSONArray jsonArray = jsonObject.getJSONArray("main");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
JSONArray server = c.getJSONArray("home");
for(int j=0; j<server.length(); j++){
JSONObject serverObject = server.getJSONObject(j);
string rank = serverObject.getString("rank");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
my json;
{
"main":[
{
"home":[
{"rank":"33"},
{"rank":"72"},
{"rank":"49"}
]
}
]
}
I want to add "string rank" to my listview.
How can I do that?
Thanks.
Edit: I could add json to listview but I can only list first json item. my new code
public class ListSectionActivity extends Activity {
private AndroidListAdapter list_adapter;
private ListView lv_android;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_section);
runOnUiThread(new Runnable() {
#Override
public void run() {
new ReadJSON().execute("url");
}
});
}
class ReadJSON extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
return readURL(params[0]);
}
#Override
protected void onPostExecute(String content) {
try {
JSONObject jsonObject = new JSONObject(content);
JSONArray jsonArray = jsonObject.getJSONArray("main");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
JSONArray server = c.getJSONArray("home");
for(int j=0; j<server.length(); j++){
JSONObject serverObject = server.getJSONObject(j);
String rank = serverObject.getString("rank");
DataCollection.data_arr=new ArrayList<DataCollection>();
DataCollection.data_arr.add(new DataCollection(rank));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
lv_android=(ListView)findViewById(R.id.lv_android);
list_adapter=new AndroidListAdapter(ListSectionActivity.this, R.layout.list_item,DataCollection.data_arr);
ListSeparateAdapter<DataCollection> listsectionAdapter = new ListSeparateAdapter<DataCollection>(ListSectionActivity.this,
list_adapter, R.layout.enroll_section_list, R.id.tv_section);
lv_android.setAdapter(listsectionAdapter);
}
}
private static String readURL(String theUrl) {
StringBuilder content = new StringBuilder();
try {
URL url = new URL(theUrl);
URLConnection urlConnection = url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
content.append(line + "\n");
}
bufferedReader.close();
} catch (Exception e) {
e.printStackTrace();
}
return content.toString();
}
}
DataCollection
public class DataCollection {
public String name;
public static ArrayList<DataCollection> data_arr=null;
public DataCollection(String name){
this.name=name;
}
}

UPDATED: You can do this inside your onPostexecute. Save the rank array inside a listview and use it inside your adapter.
protected void onPostExecute(String content) {
DataCollection.data_arr=new ArrayList<DataCollection>();
try {
JSONObject jsonObject = new JSONObject(content);
JSONArray jsonArray = jsonObject.getJSONArray("main");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
JSONArray server = c.getJSONArray("home");
for(int j=0; j<server.length(); j++){
JSONObject serverObject = server.getJSONObject(j);
String rank = serverObject.getString("rank");
DataCollection.data_arr.add(new DataCollection(rank));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
if(!data_arr.isEmpty()){
//you can set the adapter and listview here. Something like this
your_list_adapter=new AndroidListAdapter(this, R.layout.list_item,data_arr);
your_lv_android.setAdapter(list_adapter);
}
}

Related

Json file data parsing from URL in Android Studio

I have a problem with this Json file. I am trying to do a Parser that shows in a textview the results after a button is pressed. I wonna parse the "firstName" tag but to do this, I need to pass through the others tags like "league" and "standard". I don't know how to parse them in this Json file.
The Json file is structured like this:
{
"_internal":{
"pubDateTime":"2017-06-23 03:21:52.076",
"xslt":"xsl/league/roster/marty_active_players.xsl",
"eventName":"league_roster"
},
"league":{
"standard":[
{
"firstName":"Alex",
"lastName":"Abrines",
"personId":"203518",
"teamId":"1610612760 1610612760",
"jersey":"8",
"pos":"G-F",
"heightFeet":"6",
"heightInches":"6",
"heightMeters":"1.98",
"weightPounds":"190",
"weightKilograms":"86.2",
"dateOfBirthUTC":"1993-08-01",
"teams":[
{
"teamId":"1610612760",
"seasonStart":"2016",
"seasonEnd":"2016"
}
],
"draft":{
"teamId":"1610612760",
"pickNum":"32",
"roundNum":"2",
"seasonYear":"2013"
},
"nbaDebutYear":"2016",
"yearsPro":"0",
"collegeName":"",
"lastAffiliation":"Spain/Spain",
"country":"Spain"
},
This is my Java code:
public class MainActivity extends AppCompatActivity {
Button btnHit;
TextView txtJson;
ProgressDialog pd;
String Players[] = new String[100];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnHit = (Button) findViewById(R.id.btn);
txtJson = (TextView) findViewById(R.id.tvJsonItem);
btnHit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JsonTask().execute("http://data.nba.net/10s/prod/v1/2016/players.json");
}
});
}
private class JsonTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Please wait");
pd.setCancelable(false);
pd.show();
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
Log.d("Response: ", "> " + line); //here u ll get whole response...... :-)
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jsonObject = new JSONObject(result);
String DataPlayers = jsonObject.getString("standard");
JSONArray jsonArray = new JSONArray(DataPlayers);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject JO = jsonArray.getJSONObject(i);
Players[i] = JO.getString("firstName");
txtJson.append(Players[i] + "\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
if (pd.isShowing()) {
pd.dismiss();
}
}
}
Wrong:
JSONObject jsonObject = new JSONObject(result);
String DataPlayers = jsonObject.getString("standard");
Correct:
JSONObject jsonObject = new JSONObject(result);
JsonObject objStandard = jsonObject.getJSONObject("league");
Now from objStandard object, you can retrieve the json array and iterate through the sub json objects.
JSONArray jsonArray = objStandard.getJSONArray("standard");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject JO = jsonArray.getJSONObject(i);
Players[i] = JO.getString("firstName");
txtJson.append(Players[i] + "\n");
}
2 cents suggestion :)
It seems you have just started exploring android development, saying based on you are using a legacy method of json parsing, I would suggest you to check out GSON library, which is a Java serialization/deserialization library to convert Java Objects into JSON and back. In short, you will not be needed to parse JSON response manually but rather you will be having normal java class objects and members/methods to deal with.
Your code should be like this
try {
String result = "your_json_string";
JSONObject jsonObject = new JSONObject(result);
JSONObject leagueObject = jsonObject.getJSONObject("league");
JSONArray standardArray = leagueObject.getJSONArray("standard");
for (int i = 0; i < standardArray.length(); i++) {
JSONObject standardObject = standardArray.getJSONObject(i);
String name = standardObject.getString("firstName");
}
} catch (Exception e) {
System.out.println(e);
}

JSON Parser Error :Value null of type org.json.JSONObject$1 cannot be converted to JSONObject

I am getting the following error:
This is my source code:
package com.example.arpok.iomatic;
LineGraphSeries<DataPoint> series;
ArrayList<HashMap<String, String>> arrayListData;
public static String data;
TextView graphOneTV,graphTwoTV,graphThreeTV;
GraphView graph;
String x,y;
public Graph_Fragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_graph_, container, false);
}
HttpURLConnection connection;
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
graphOneTV = (TextView) getView().findViewById(R.id.TVGraph1);
graphTwoTV = (TextView) getView().findViewById(R.id.TVGraph2);
graphThreeTV = (TextView) getView().findViewById(R.id.TVGraph3);
graph = (GraphView) getView().findViewById(R.id.graph1);
graphDataClass gdc = new graphDataClass();
gdc.execute();
}
public class graphDataClass extends AsyncTask<String ,String ,String>
{
#Override
protected String doInBackground(String... strings) {
try {
URL url = new URL("http://192.168.1.34/getGraphData.php?");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while(line != null)
{
line = bufferedReader.readLine();
data = data + line;
}
JSONObject jo = new JSONObject(data);
for(int i=0;i<data.length();i++) {
x = jo.getString("twitter");
y = jo.getString("googleplus");
System.out.print("x: "+x+"y: "+y);
HashMap<String, String> tempHashMapData = new HashMap<>();
tempHashMapData.put("twitter",x);
tempHashMapData.put("googleplus",y);
arrayListData.add(tempHashMapData);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPreExecute()
{
super.onPreExecute();
}
protected void onPostExecute(String s )
{
super.onPostExecute(s);
graphOneTV.setText(data);
}
}}
The above code is the fragment in which I need to fetch the data form the JSON and plot it on the graph. The thing is when I am displaying the "data" named variable which is having the JSON data on a textView then it is showing properly but when I am assigning the same "data" variable to the JSONObject then the above error occurs.
This is my Json data which i need to plot on the Line Graph
[{"twitter":"200","googleplus":"60"},{"twitter":"150","googleplus":"180"},{"twitter":"90","googleplus":"120"}]
Someone please tell me how can I fetch the JSON data and parse it and plot it on a line graph.
try this one.
JSONArray jsonarray = new JSONArray(jsonStr);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
x = jo.getString("twitter");
y = jo.getString("googleplus");
System.out.print("x: "+x+"y: "+y);
HashMap<String, String> tempHashMapData = new HashMap<>();
tempHashMapData.put("twitter",x);
tempHashMapData.put("googleplus",y);
arrayListData.add(tempHashMapData);
}
Try this way
ArrayList<HashMap<String, String>> arrayListSocial = new ArrayList<>();
String string = "[{\"twitter\":\"200\",\"googleplus\":\"60\"},{\"twitter\":\"150\",\"googleplus\":\"180\"},{\"twitter\":\"90\",\"googleplus\":\"120\"}]";
try {
JSONArray jsonarray = new JSONArray(string);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String socailTwiter= jsonobject.getString("twitter");
String socailGplus = jsonobject.getString("googleplus");
Log.e("socailTwiter",socailTwiter);
HashMap<String, String> hashMap = new HashMap<>();
hashMap .put("twitter",socailTwiter);
hashMap .put("googleplus",socailGplus );
arrayListSocial.add(hashMap);
}
}catch (Exception e){
e.printStackTrace();
}

how to parse JsonArray and set value on Textview in Android

Below is my Json response from getting when Hit on Url with parsing parameter strlogid=101
[
{
"earnpoints": 411,
"type": "C"
},
{
"earnpoints": 1600,
"type": "G"
},
{
"earnpoints": 13540,
"type": "I"
}
]
Below is my code-To show Points on 3 different textview
private class PointTask extends AsyncTask<String, Void, Boolean> {
protected Boolean doInBackground(final String... args) {
JSONParse jParser = new JSONParse();
HashMap<String, String> hMap = new HashMap<>();
hMap.put("strlogid", "101");
JSONArray jsonarray = jParser.getJSONFromUrl(url,hMap);
// get JSON data from URL
for (int i = 0; i < jsonarray.length(); i++) {
try {
JSONObject c = (JSONObject) jsonarray.get(i);
c_point=c.getString("points");
g_point=c.getString("points");
i_point=c.getString("points");
t_point = cpoint+gpoint+ipoint;
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(final Boolean success) {
txtTotalPoints.setText(t_point);
txtOwnPoints.setText(g_point);
txtClubPoints.setText(c_point);
txtVoucherPoints.setText(i_point);
}
}
TotalPoints,OwnPoints,ClubPoints,VoucherPoints are show on Textview respectively
Try this
protected Boolean doInBackground(final String... args) {
JSONParse jParser = new JSONParse();
HashMap<String, String> hMap = new HashMap<>();
hMap.put("strlogid", "101");
JSONArray jsonarray = jParser.getJSONFromUrl(url,hMap);
// get JSON data from URL
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject c = (JSONObject) jsonarray.get(i);
if (c.getString("type").toString().equalsIgnoreCase("C")) {
c_point = c.getInt("earnpoints");
} else if (c.getString("type").toString().equalsIgnoreCase("G")) {
g_point = c.getInt("earnpoints");
} else if (c.getString("type").toString().equalsIgnoreCase("I")) {
i_point = c.getInt("earnpoints");
}
}
t_point = cpoint + gpoint + ipoint;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(final Boolean success) {
txtTotalPoints.setText(t_point);
txtOwnPoints.setText(g_point);
txtClubPoints.setText(c_point);
txtVoucherPoints.setText(i_point);
}
}
Dont use async task for json parsing. I would reccomend you to use volley.
Here is the link\
http://www.androidhive.info/2014/05/android-working-with-volley-library-1/
#Override
public void onPostSuccess(String result, int id, boolean isSucess) {
// Log.e("re<><><><>", result);
try {
JSONArray ja = new JSONArray(result);
for (int arr = 0; arr < ja.length(); arr++) {
JSONObject json1 = ja.getJSONObject(arr);
Log.e("length", "" + ja.length());
// Getting JSON Array node
String earnpoints= json1.getString("earnpoints");
String type = json1.getString("type");
}
catch (JSONException e) {
e.printStackTrace();
Toast.makeText(LoginPage.this, "Please try again later", Toast.LENGTH_SHORT).show();
}
}

how to parse json object and json array in listview android

I am beginner to android app. I am facing trouble how to parse json object and json array to listview in android. Here is my json output
UPDATED WITH JSON CORRECTION
{status: "ok", listUsers: [{"id":2,"username":"myusername","name":"myname","email":"myemail","password":"mypassword","groupid":1,"type":"mytype"},{"id":3,"username":"myusername","name":"myname","email":"myemail2","password":"mypassword2","groupid":1,"type":"mytype"},{"id":4,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":5,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":6,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":7,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":8,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":9,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":10,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":11,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"1"},{"id":12,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":13,"username":"yuwah","name":"yu","email":"mail#gmail.com","password":"pass1","groupid":1,"type":"type1"},{"id":14,"username":"myusername","name":"myname","email":"myemail2","password":"mypassword2","groupid":1,"type":"mytype"}] }
Can anyone explain me how to do it. I am searching all over the topics but I still can't get it. Thanks.
Here is my code block
public class MainActivity extends ListActivity {
String url = "http://staging.workberryplus.com/mobile/listUsers/1";
ProgressDialog PD;
ArrayList<String> listUsers;
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listUsers = new ArrayList<String>();
PD = new ProgressDialog(this);
PD.setMessage("Loading.....");
PD.setCancelable(false);
adapter = new ArrayAdapter(this, R.layout.items, R.id.tv, listUsers);
setListAdapter(adapter);
MakeJsonArrayReq();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
}
private void MakeJsonArrayReq() {
PD.show();
//JsonArrayRequest jr=new JsonArrayRequest(url, listener, errorListener)
final StringRequest jreq = new StringRequest(url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
for (int i = 0; i < response.length(); i++) {
try {
Log.d("Response","->"+response);
JSONObject jo = new JSONObject(response);
JSONArray jarray = jo.getJSONArray("listUsers");
JSONObject jo2 = jarray.getJSONObject(i);
String name = jo2.getString("name");
listUsers.add(name);
} catch (JSONException e) {
e.printStackTrace();
}
}
PD.dismiss();
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
MyApplication.getInstance().addToReqQueue(jreq, "jreq");
}
}
try {
JSONObject jo = new JSONObject(response);
JSONArray jarray =jo.getJSONArray("listUsers");
for (int i = 0; i < jarray.length(); i++){
JSONObject jo2 = jarray.getJSONObject(i);
String name = jo2.getString("name");
listUsers.add(name);
}
} catch (JSONException e) {
e.printStackTrace();
}
Convert your String which is response to Json Object
JSONObject jsonObj = new JSONObject(response);
Then do the following
try {
if (jsonObj != null) {
if (jsonObj.optString("status").equals("ok")) {
JSONArray jsonArray = jsonObj.optJSONArray("listUsers");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.optJSONObject(i);
if (jsonObject != null) {
//Do work here
}
}
}
}
}catch (Exception e1) {
e1.printStackTrace();
}
try this and make changes accordingly and let me know if it work for you or not
JSONObject jo2 = jarray.getJSONObject(i);
You are iterating over the length of the response (a string). You should iterate over the length of jarray

Stop creating fragmnet view until i have parsed all data from Json.

I receive a null pointer exeception when trying to populate the interface beacuse I have no data in my instance object.
I am using a login button and call a service, i receive a json and after I parse it i have a status handler...login ok... Here I want to start an asynk task to get some photo data
public void StatusHandlerLogin(String status, Activity currentActivity) {
if (status.equals("0")) {
new GetPhotoDataTask(currentActivity).execute();
Intent intent = new Intent(currentActivity,
NavigationActivity.class);
currentActivity.startActivity(intent);
}
//}
The asynk task is like this
public class GetPhotoDataTask extends
AsyncTask<Void, Void, List<PhotoData>> {
Activity activity;
public GetPhotoDataTask(Activity activity) {
this.activity = activity;
}
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
Log.d("GetPhotoDataTask onPreExecute",
"GetPhotoDataTask onPreExecute");
super.onPreExecute();
progressDialog = ProgressDialog.show(activity, "Preluare Date",
"Va rugam asteptati!");
}
#Override
protected List<PhotoData> doInBackground(Void... params) {
Log.d("GetPhotoDataTask doInBackground",
"GetPhotoDataTask doInBackground");
MyStyleApi myStyleApi = new MyStyleApi();
List<PhotoData> photoData = null;
try {
photoData = myStyleApi.getPhotoDataWithDispatch();
} catch (JSONException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
List<String> photoStr = new ArrayList<String>();
for (int i = 0; i < photoData.size(); i++) {
photoStr.add(photoData.get(i).getPhotoURL());
}
String[] photoUrls = new String[photoStr.size()];
photoUrls = photoStr.toArray(photoUrls);
for (int i = 0; i < photoUrls.length; i++) {
if (photoUrls[i].contains("\"")) {
photoUrls[i] = photoUrls[i].replace("\"", "");
}
}
AppManager.getInstance().setphotoUrls(photoUrls);
List<PhotoData> photoDataS = AppManager.getInstance().setPhotoData(
photoData);
return photoData;
}
protected void onProgressUpdate(Integer... percent) {
progressDialog = ProgressDialog.show(activity, "Preluare Date",
"Va rugam asteptati!");
}
protected void onPostExecute(List<PhotoData> photoData) {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
on do in background i have a method that call other service
get PhotoData with userId as param
public List<PhotoData> getPhotoDataWithDispatch() throws JSONException,
ClientProtocolException, IOException {
Log.d("getPhotoDataWithDispatch ", "getPhotoDataWithDispatch ");
UserData data = AppManager.getInstance().getUserData();
String userID = data.getUserID();
if (userID.contains("\"")) {
userID = userID.replace("\"", "");
}
Map<String, Object> params = new LinkedHashMap<String, Object>();
params.put("userID", userID);
JsonArray response = WebServiceApi.PostToServiceWithStringResponse(
"images/get_images_data", params);
List<PhotoData> photoDataList = new ArrayList<PhotoData>();
if (response != null) {
photoDataList = parseJsonArrayForFotoData(response);
}
return photoDataList;
}
and if response is not null i parse it
public static List<PhotoData> parseJsonArrayForFotoData(JsonArray jsonArray) {
List<PhotoData> photoDataList = new ArrayList<PhotoData>();
for (int i = 0; i < jsonArray.size(); i++) {
Log.d("getPhotoDataWithDispatch ", "getPhotoDataWithDispatch ");
JsonElement photoID = ((JsonObject) jsonArray.get(i)).get("pozaID");
JsonElement photoUrl = ((JsonObject) jsonArray.get(i))
.get("pozaURL");
JsonElement thumbURL = ((JsonObject) jsonArray.get(i))
.get("thumbURL");
JsonElement tags = ((JsonObject) jsonArray.get(i)).get("tags");
JsonParser parser = new JsonParser();
JsonArray array = parser.parse(tags.toString()).getAsJsonArray();
List<Tags> tagsList = new ArrayList<Tags>();
for (int j = 0; j < array.size(); j++) {
JsonElement tagId = ((JsonObject) array.get(j)).get("tagID");
JsonElement coordX = ((JsonObject) array.get(j)).get("coordX");
JsonElement coordY = ((JsonObject) array.get(j)).get("coordY");
JsonElement productId = ((JsonObject) array.get(j))
.get("productID");
Tags tagPData = new Tags(tagId.toString(), coordX.toString(),
coordY.toString(), productId.toString());
tagsList.add(tagPData);
}
PhotoData photoData = new PhotoData(photoID.toString(),
photoUrl.toString(), thumbURL.toString(), null, tagsList);
photoDataList.add(photoData);
}
return photoDataList;
}
ok in GetPhotoDataTaskFb do in background i set the instance of the photos object
AppManager.getInstance().setphotoUrls(photoUrls);
and in fragmnet
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.ac_image_pager, container,
false);
// Dummy code
if (counter == 0) {
for (int i = 0; i <= 20; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
counter++;
String[] imageUrls = AppManager.getInstance().getphotoUrls();
//here is where i get the null.. i tried some dummy code to delay and receive data but it is not working
How can I manage to stop create view until all data is parsed?

Categories

Resources