I have the class below and I can fetch information from a JSONArray in this format:
{"cliente":[{"id":"1334","nome":"Bruno"}]}
TextView nome_usuario;
private static final String TAG_CLIENTE = "cliente";
private static final String TAG_NOME = "nome";
JSONArray cliente = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View grafico = inflater.inflate(R.layout.fragment_fragment_perfil, container, false);
nome_usuario = (TextView ) grafico.findViewById(R.id.txtNome);
new JSONParse().execute();
return grafico;
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Atualizando");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl("url do json");
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
cliente = json.getJSONArray(TAG_CLIENTE);
JSONObject c = cliente.getJSONObject(0);
String nome = c.getString(TAG_NOME);
nome_usuario.setText(nome);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
But now I would like to work with a json in the following format:
{"name": "Bruno"}
I found a question similar to my How to parse JSON Object Android Studio, but I could not apply it to my example.
Getting information from an JSONObject:
JSONObject aJsonObject = new JSONObject(aJsonResponse);
JSONArray aJsonArray = aJsonObject.getJSONArray("cliente");
for (int i = 0; i < aJsonArray.length(); i++) {
aJsonObject = aJsonArray.getJSONObject(i);
String aId = aJsonObject .getString("id");
String aNome = aJsonObject .getString("nome");
}
Try using this, you should replace aJsonResponse with the response from the server
JSONObject aJsonObject = new JSONObject(aJsonResponse);
String aId = aJsonObject.getString("id");
String aNome = aJsonObject.getString("name");
Related
I am developing an app, here i want to display fetched items of table I tried following code but it gives error at this line JSONObject c = result.getJSONObject(0);.
How do i solve this?
//java file
public class Details extends Activity {
TextView uid;
TextView name1, amount1;
TextView email1;
Button Btngetdata;
//URL to get JSON Array
private static String url = "http://example.in/ticket1.php";
//JSON Node Names
private static final String TAG_USER = "result";
// private static final String TAG_ID = "id";
private static final String TAG_NAME = "pname";
private static final String TAG_AMOUNT = "pamount";
JSONArray result = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.details);
Btngetdata = (Button)findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
uid = (TextView)findViewById(R.id.uid);
name1 = (TextView)findViewById(R.id.name);
amount1 = (TextView)findViewById(R.id.email);
pDialog = new ProgressDialog(Details.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array
result = json.getJSONArray(TAG_USER);
JSONObject c = result.getJSONObject(0);
// Storing JSON item in a Variable
// String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String amount = c.getString(TAG_AMOUNT);
//Set JSON Data in TextView
// uid.setText(id);
name1.setText(name);
amount1.setText(amount);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Check the size of the result array before you iterate over it.
#Override
protected void onPostExecute(JSONObject json) {
{
pDialog.dismiss();
try {
// Getting JSON Array
result = json.getJSONArray(TAG_USER);
if (result.length() > 0) {
JSONObject c = result.getJSONObject(0);
// Storing JSON item in a Variable
// String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String amount = c.getString(TAG_AMOUNT);
//Set JSON Data in TextView
// uid.setText(id);
name1.setText(name);
amount1.setText(amount);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
In this i want to cancel the asynctask i called aysnc task in listview onclickitem...
so if there is no data in particular row's then it will stop execution and remain on same activity.
I called the class in click and if condition if false as file_path is null then it will remain on same activity will not proceed further in another activity.
but in my case it will move to another activity i tried lot many things on this like oncancelled(), cancel(), etc methods but they are not working i put all in loop as well as switch case to break.
public class EAdFragment extends Fragment {
ListView lvAdSurvey;
JSONObject json = null;
public static final String FIRST_COLUMN = "Upl_ID";
public static final String SECOND_COLUMN = "File_Description";
JSONArray jarray = null;
JSONObject jsonObj = null;
String upload_type;
String upl_id;
File f;
String imgurl;
ProgressDialog pDialog;
String upl_ID, type_of_upload, file_description, amount;
String file_path = null;
String file_type, related_to, country, state, city, Number_of_user,
type_illegal;
GetData task;
ViewHolder holder;
public ListAdapter adapter;
String text;
public List<EAdvertActivityData> listData = new ArrayList<EAdvertActivityData>();
public void onViewCreated(View view, Bundle savedInstanceState) {
lvAdSurvey = (ListView) view.findViewById(R.id.lvAdSurvey);
new GetList().execute();
lvAdSurvey.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
// String text =
// lvAdSurvey.getItemAtPosition(position).toString();
holder = (ViewHolder) view.getTag();
text = holder.txtFirstColumn.getText().toString();
Log.d("text:", text);
task = new GetData();
task.execute();
}
});
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_ead, container,
false);
return rootView;
}
private class GetList extends AsyncTask<String, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected JSONObject doInBackground(String... args) {
String url = "url";
JSONParser jParser = new JSONParser();
jsonObj = jParser.getJSONFromUrl(url);
try {
jarray = jsonObj.getJSONArray("result");
Log.d("lengtharray:", String.valueOf(jarray.length()));
for (int i = 0; i < jarray.length(); i++) {
EAdvertActivityData data = new EAdvertActivityData();
JSONObject jobject = new JSONObject(jarray.get(i)
.toString());
upload_type = jobject.optString("Upl_ID").toString();
String description = jobject.optString("File_description")
.toString();
/*
* Log.d("upload_type",upload_type);
* Log.d("description",description);
*/data.setUpl_ID(upload_type);
data.setFile_description(description);
listData.add(data);
Log.d("data:", listData.toString());
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonObj;
}
protected void onPostExecute(JSONObject jsonObject) {
EAdListViewAdapter adapter = new EAdListViewAdapter(getActivity(),
listData);
lvAdSurvey.setAdapter(adapter);
}
}
private class GetData extends AsyncTask<String, String, String> {
int flag=0;
protected void onPreExecute() {
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading Image ....");
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
SharedPreferences pref = getActivity().getSharedPreferences(
"SoundSettings", Context.MODE_PRIVATE);
String user_id = pref.getString("user_id", LoginActivity.userid);
String url = "url"
+ text;
JSONParser jParser = new JSONParser();
try {
json = jParser.getJSONFromUrl(url);
Log.d("jsonadvert:", json.toString());
String status = json.getString("fetchdata");
if (status.equals("Success")) {
type_of_upload = json.getString("Type_of_Upload");
file_description = json.getString("File_description");
amount = json.getString("Amount");
file_path = json.getString("file_path");
file_type = json.getString("File_type");
related_to = json.getString("Related_to");
country = json.getString("Country");
// state = json.getString("state");
Number_of_user = json.getString("Number_of_usr");
type_illegal = json.getString("Type_llegal");
Log.d("type_illegal:", type_illegal);
Log.d("file_path:", file_path);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String args) {
pDialog.dismiss();
if(file_path==null){
Toast.makeText(getActivity(), "Image does not exists", Toast.LENGTH_LONG).show();
pDialog.cancel();
task.cancel(true);
}else{
imgurl = "http://sharpersofttech.com/sign_up/" + file_path;
Intent in = new Intent(getActivity(), AdvertActivity.class);
in.putExtra("upl_id", text);
in.putExtra("file_description", file_description);
in.putExtra("imgurl", imgurl);
startActivity(in);
((Activity) getActivity()).overridePendingTransition(0, 0);
}
}
}
}
I am trying to parse a single JSON object that looks like this:
{
"message":"Request Successful",
"data":{
"id":"g8nEDt",
"name":"Twins Bazil Twins",
"nameDisplay":"Twins Bazil Twins",
"abv":"6.75",
"isOrganic":"N",
"description":"Beers",
}
},
"status":"success"
}
This is the code that I am using.
public class randomBeer extends Activity {
TextView name1;
TextView description1;
TextView abv1;
TextView ibu1;
Button Btngetdata;
//URL to get JSON Array
private static String urlRandom = "http://api.brewerydb.com/v2/beer/random?key=mykey";
//JSON Node Names
private static final String TAG_DATA = "data";
private static final String TAG_NAME = "name";
private static final String TAG_DESCRIPTION = "description";
private static final String TAG_ABV = "abv";
private static final String TAG_IBU = "ibu";
JSONObject data = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.randombeer);
Btngetdata = (Button)findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
name1 = (TextView)findViewById(R.id.name);
description1 = (TextView)findViewById(R.id.description);
abv1 = (TextView)findViewById(R.id.abv);
ibu1 = (TextView)findViewById(R.id.ibu);
pDialog = new ProgressDialog(randomBeer.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(urlRandom);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array
data= json.getJSONArray(TAG_DATA);
JSONObject c = data.getJSONObject(0);
// Storing JSON item in a Variable
String name = c.getString(TAG_NAME);
String ibu;
if(c.has("ibu")) {
ibu = c.getString(TAG_IBU);
} else {
ibu = "No ibu value";
}
String abv;
if(c.has("abv")) {
abv = c.getString(TAG_ABV);
} else {
abv = "No abv value";
}
String description;
if(c.has("description")) {
description = c.getString(TAG_DESCRIPTION);
} else {
description = "No description available";
}
//Set JSON Data in TextView
name1.setText(name);
description1.setText(description);
abv1.setText(abv);
ibu1.setText(ibu);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
The problem is that it is trying to get an array but I just need and object.
How can I transform this code so it gets the object instead of trying to get an array?
I tried to change
data = json.getJSONArray(TAG_DATA);
to
data = json.getJSONObject(TAG_DATA);
but then on the line
JSONObject c = data.getJSONObject(0);
I get an Error:
(87, 51) error: incompatible types: int cannot be converted to
String.
It should be
data= json.getJSONObject(TAG_DATA);
instead of
data= json.getJSONArray(TAG_DATA);
in onPostExecute. It now has
"data":{
"id":"g8nEDt",
"name":"Twins Bazil Twins",
"nameDisplay":"Twins Bazil Twins",
"abv":"6.75",
"isOrganic":"N",
"description":"Beers",
}
in it. To get i.e. the "name" use
String name = data.getString("name");
IN ADDITION:
Make sure to execute HttpGet instead of HttpPost when using this link
http://api.brewerydb.com/v2/beer/random?key=mykey
Replace this:
// Getting JSON Array
data= json.getJSONArray(TAG_DATA);
JSONObject c = data.getJSONObject(0);
with:
// Getting JSON Object
data= json.getJSONObject(TAG_DATA);
Also, replace all "c" variable usages with "data".
I want to get the profile details from mysql db from fragment class. should display to textview. like student name, address, mobile etc.. I used JSON format to send the data from php.
here is my code
public class ProfileFragment extends Fragment {
private View parentView;
// Session Manager Class
SessionManager session;
TextView student_name;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private String url;
//JSON Node Names
private static final String TAG_ARRAY = "student_profile";
private static final String TAG_NAME = "student_name";
JSONArray student_profile = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//return inflater.inflate(R.layout.profile, container, false);
parentView = inflater.inflate(R.layout.profile, container, false);
//session.checkLogin();
session = new SessionManager(getActivity());
session.checkLogin();
return parentView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
oslist = new ArrayList<HashMap<String, String>>();
new JSONParse().execute();
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
private JSONObject json;
#Override
protected void onPreExecute() {
super.onPreExecute();
student_name = (TextView)getView().findViewById(R.id.studentname);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
// get user data from session
HashMap<String, String> user = session.getUserDetails();
// name
String emailaddr = user.get(SessionManager.KEY_NAME);
url = "http://XXXXXXX.org/api/profile.php?emailid="+emailaddr;
// Getting JSON from URL
json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
student_profile = json.getJSONArray(TAG_ARRAY);
for(int i = 0; i < student_profile.length(); i++){
JSONObject c = student_profile.getJSONObject(i);
String student_firstname = null;
// Storing JSON item in a Variable
String name = c.getString(student_firstname);
Toast.makeText(getActivity(), "name="+name, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
I got the error like this
12-24 09:29:44.817: W/System.err(30999): org.json.JSONException: No value for student_profile
12-24 09:29:44.818: W/System.err(30999): at org.json.JSONObject.get(JSONObject.java:355)
12-24 09:29:44.819: W/System.err(30999): at org.json.JSONObject.getJSONArray(JSONObject.java:549)
12-24 09:29:44.819: W/System.err(30999): at com.tutorialsface.ResideMenuDemo.ProfileFragment$JSONParse.onPostExecute(ProfileFragment.java:89)
I think your json has no values for TAG_ARRAY.So its giving JSONException.
You should first check value like :
if (json.has(TAG_ARRAY)) {
student_profile = json.getJSONArray(TAG_ARRAY);
}
Then it will not produce JSONException.
I have two asynctask in one class and i am having trouble in executing them at the same time.
Here is my scenario, my the user clicks the view january calendar button it will show up the events for the month of calendar and the comments for it. The events and comments are stored in mysql database so i have to fetch different url. I used asyctask to fetch the url. Whenever i call the other asynctask it cannot be resolved. help me out!
Here is my code:
package sscr.stag;
#SuppressLint("ShowToast")
public class Calendar extends ListActivity {
// All xml labels
TextView txtEvent;
// Progress Dialog
private ProgressDialog pDialog;
JSONArray user;
JSONObject hay;
private static final String CALENDAR_URL = "http://www.stagconnect.com/StagConnect/calendar/januaryCalendar.php";
private static final String COMMENT_URL = "http://www.stagconnect.com/StagConnect/calendar/januaryReadComment.php";
private static final String TAG_USER = "username";
private static final String TAG_MESSAGE = "message";
private static final String TAG_TIME = "time";
private static final String TAG_ARRAY = "posts";
private JSONArray mCalendar = null;
private ArrayList<HashMap<String, String>> mCommentList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calendaradmin);
txtEvent = (TextView) findViewById(R.id.event);
new LoadCalendar().execute();
new LoadCommentCal().execute(); // error here, says cannot be resolved in this type
}
private class LoadCalendar extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Calendar.this);
pDialog.setMessage("Loading Calendar.. ");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
String json = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(CALENDAR_URL);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
json = EntityUtils.toString(resEntity);
Log.i("Profile JSON: ", json.toString());
} catch (Exception e) {
e.printStackTrace();
}
return json;
}
#Override
protected void onPostExecute(String json) {
super.onPostExecute(json);
pDialog.dismiss();
try
{
hay = new JSONObject(json);
JSONArray user = hay.getJSONArray("posts");
JSONObject jb= user.getJSONObject(0);
String event = jb.getString("activities");
txtEvent.setText(event);
}catch(Exception e)
{
e.printStackTrace();
}
}
public void updateJSONdata() {
mCommentList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(COMMENT_URL);
try {
mCalendar = json.getJSONArray(TAG_ARRAY);
for (int i = 0; i < mCalendar.length(); i++) {
JSONObject c = mCalendar.getJSONObject(i);
String username = c.getString(TAG_USER);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_USER, username);
mCommentList.add(0, map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private void updateList() {
ListAdapter adapter = new SimpleAdapter(Calendar.this, mCommentList,
R.layout.calendar_comment, new String[] { TAG_MESSAGE,
TAG_USER, TAG_TIME }, new int[] { R.id.message,
R.id.username, R.id.time });
setListAdapter(adapter);
ListView lv = getListView();
lv.scrollTo(0, 0);
}
public class LoadCommentCal extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Calendar.this);
pDialog.setMessage("Loading Comments...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(Void... args) {
updateJSONdata();
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pDialog.dismiss();
updateList();
}
}
}
}
Your second asynctask public class LoadCommentCal extends AsyncTask is inside the first asynctask!
You need to move it out of the first asynctask.
private class LoadCalendar extends AsyncTask<String, String, String> {
...
}
... other functions
private class LoadCommentCal extends AsyncTask<Void, Void, String> {
...
}
You are declaring lots of things inside the first AsyncTask I strongly reccomend to close your AsyncTask after the onPostExecute
#Override
protected void onPostExecute(String json) {
super.onPostExecute(json);
pDialog.dismiss();
try
{
hay = new JSONObject(json);
JSONArray user = hay.getJSONArray("posts");
JSONObject jb= user.getJSONObject(0);
String event = jb.getString("activities");
txtEvent.setText(event);
}catch(Exception e)
{
e.printStackTrace();
}
}
}
and then removing one } at the end of the java file (and also reindent if you wish)