how to parse JsonArray and set value on Textview in Android - 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();
}
}

Related

Android add JSON to <string>

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);
}
}

How to put json array in json object

This is code which I'm using:
#Override
protected String doInBackground(String... arg0) {
String yourJsonStringUrl = "GetCalender_Events";
JsonParser jParser = new JsonParser();
json = jParser.getJSONFromUrlArray(yourJsonStringUrl);
return null;
}
#Override
protected void onPostExecute(String strFromDoInBg) {
for (int i = 0; i < json.length(); i++) {
try {
JSONObject c = json.getJSONObject(i);
ldatosAgenda.add(new DatosAgenda(c.getString("Event_Name"), c.getString("Event_Name"),
sdf5.format(sdf1.parse(c.getString("Column1"))), sdf6.format(sdf1.parse(c.getString("Column1"))),
c.getString("Description")));
} catch (JSONException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
How to put my JSON Array into JSON object? Can anyone please help me, this is my first try with JSON Array.
My array looks like this:
{
"ContactList": [
{
"Column1": "22-05-2017",
"Event_Name": "Garba Compition",
"Description": "School organized garba compition"
},
{
"Column1": "24-05-2017",
"Event_Name": "Mahendi Compition",
"Description": "Mahendi compition"
}
]
}
#. Seems you are getting JSONObject as response. So you have to parse JSONObject first from sever response:
JSONObject json = jParser.getJSONFromUrlObject(yourJsonStringUrl);
#. Then parse ContactList and its item as below:
#Override
protected void onPostExecute(String strFromDoInBg) {
JSONArray jsonArray = json.getJSONArray("ContactList");
for (int i = 0; i < jsonArray.length(); i++) {
try
{
JSONObject c = jsonArray.getJSONObject(i);
ldatosAgenda.add(new DatosAgenda(c.getString("Event_Name"),c.getString("Event_Name"), sdf5.format(sdf1.parse(c.getString("Column1"))), sdf6.format(sdf1.parse(c.getString("Column1"))),c.getString("Description")));
} catch (JSONException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
JSONArray jsonarray = new JSONArray();
JSONObject jsonObject = new JSONObject();
try{
jsonObject.put(jsonarray);
} catch(JSONException e){
e.printStackTrace();
}
You get the values
JSONArray songobj = json.getJSONArray("ContactList");
Log.d(TAG, "List Length" + songobj.length());
for (int i = 0; i < songobj.length(); i++) {
JSONObject song = songobj.getJSONObject(i);
String column=song.getString("Column1");
String name=song.getString("Event_Name");
String desc=song.getString("Description");
ldatosAgenda.add(new DatosAgenda(column,name,desc));
}
}

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

AsyncTask: doInbackground() not called with executeOnExecutor and execute

The code below tested on LG G3 and it worked fine. However when I tested it on a Samsung Galaxy S3/S2 doInBackground() is not called for some reason.
Code to check api:
public void startBlat(String tosearch) {
AsynctaskMovie asynctaskMovie = new AsynctaskMovie();
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB) {
asynctaskMovie.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,tosearch);
}
else {
asynctaskMovie.execute(tosearch);
}
The Asynctask code:
class AsynctaskMovie extends AsyncTask<String, String, ArrayList<Movie>> {
JSONParser jsonParser = new JSONParser();
private static final String SEARCH_URL = "http://www.omdbapi.com/?";
#Override
protected void onPreExecute() {
super.onPreExecute();
movieArrayList = new ArrayList();
Log.i(getActivity().getCallingPackage(), "onPreExecute");
}
#Override
protected ArrayList<Movie> doInBackground(String... args) {
Log.i(getActivity().getCallingPackage(),"doInBackground");
HashMap<String, String> params = new HashMap<>();
params.put("s", args[0]);
params.put("r", "json");
JSONObject json = jsonParser.makeHttpRequest(SEARCH_URL, "GET", params);
Log.i(getActivity().getCallingPackage(), json.toString());
if (json != null) {
try {
if (json.getString("Response").equals("False")) {
return movieArrayList;
}
} catch (JSONException e) {
}
try {
JSONArray jsonArray = json.getJSONArray("Search");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
String movieid = jsonObject.getString(App.getInstance().IMDBimdbID);
if (!movieid.equals("null")) {
Movie movie = new Movie(movieid);
movieArrayList.add(movie);
}
}
jsonArray = new JSONArray();
for (Movie movie : movieArrayList) {
params = new HashMap<>();
params.put("i", movie.getMovieid());
params.put("plot", "short");
params.put("r", "json");
JSONObject jsongetfullinfo = jsonParser.makeHttpRequest(SEARCH_URL, "GET", params);
if (jsongetfullinfo != null) {
jsonArray.put(jsongetfullinfo);
Log.i("", jsongetfullinfo.toString());
}
}
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jObject = jsonArray.getJSONObject(i);
movieArrayList.get(i).updateFromIMDB(jObject);
}
for (Movie movie : movieArrayList) {
movie.setMovieposter(LoadFromUrl(movie.getPosterURL()));
}
return movieArrayList;
} catch (JSONException e) {
e.printStackTrace();
}
}
return movieArrayList;
}
#Override
protected void onPostExecute(ArrayList<Movie> movieArrayList) {
Log.i("ronen", "list size: " + movieArrayList.size());
if (movieArrayList.size() > 0) {
listView.setAdapter(new MovieAdapter(getActivity(), movieArrayList));
listView.setVisibility(View.VISIBLE);
} else {
Toast.makeText(getActivity().getApplicationContext(), "No found", Toast.LENGTH_SHORT).show();
}
}
private Bitmap LoadFromUrl(String theurl) {
URL url = null;
Bitmap bmp = null;
try {
url = new URL(theurl);
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e) {
}
return bmp;
}
}
I have no idea what could solve this problem.
Following the answers I read here it seems that the code should work, but not so.
Can't see anything suspicious.
I'd recommend running a very simple AsyncTask on a very simple app, make sure it works (if not, maybe it something to do with the phone, so try on an emulator to be sure)
Then change it step by step to resemble your code, and you'll see where the bug is.
G'Luck!

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