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.
Related
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");
loginpage.java this is my activity for login page.
i am using this json for it {"status":"success","msg":"Your are now Login Successfully","user_login_id":2650}.
here i am getting one unique filed (user_login_id) when user log in successfully.it works fine.
after log in i am using Navigationdrawer which is Activity class and it has different types fragment behavior,one of them is HomeFragment which extended with Fragment.
in that HomeFragment class I want to get some json data in List view.for that I have another json file.which has following link like http://sdfkjksd.com/apps/matching?version=apps&user_login_id=2650
public class HomeFragment extends Fragment {
NavDrawerListAdapter adapters;
private ProgressDialog pDialog;
//JSON parser class
JSONParsing jsonParser = new JSONParsing();
String result = "";
List<HashMap<String,String>> aList;
private static final String TAG_USERID="user_login_id";
private static final String MATCH_URL = "http://sdfa.com/apps/matching?version=apps&user_login_id="+TAG_USERID;
JSONArray matching=null;
private static final String TAG_SUCCESS = "status";
private static final String TAG_MATCH="matching";
private static final String TAG_NAME="name";
private static final String TAG_PROFILE="profile_id";
private static final String TAG_IMAGE="image";
private static final String TAG_CAST="cast";
private static final String TAG_AGE="age";
private static final String TAG_LOCATION="location";
private ListView listview;
ArrayAdapter<String> adapter;
public HomeFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//String strtext = getArguments().getString("user_login_id");
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
aList = new ArrayList<HashMap<String,String>>();
/* Bundle bundle = this.getArguments();
if(bundle != null){
String i = bundle.getString("user_login_id", TAG_USERID);
}*/
new LoadAlbums().execute();
return rootView;
}
class LoadAlbums extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(HomeFragment.this.getActivity());
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("version", "apps"));
// getting JSON string from URL
String json = jsonParser.makeHttpRequest(MATCH_URL, "POST",
params);
// Check your log cat for JSON reponse
Log.d("Albums JSON: ", "> " + json);
try {
JSONObject Jasonobject = new JSONObject(result);
JSONArray Jarray = Jasonobject.getJSONArray("matching");
if (Jarray != null) {
// looping through All data
for (int i = 0; i < Jarray.length(); i++) {
JSONObject c = Jarray.getJSONObject(i);
// Storing each json item values in variable
String user_name = c.getString(TAG_NAME);
String user_profile=c.getString(TAG_PROFILE);
String user_image=c.getString(TAG_IMAGE);
String user_cast=c.getString(TAG_CAST);
String user_age=c.getString(TAG_AGE);
String user_location=c.getString(TAG_LOCATION);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_NAME,user_name);
map.put(TAG_PROFILE, user_profile);
map.put(TAG_IMAGE, user_image);
map.put(TAG_CAST, user_cast);
map.put(TAG_AGE, user_age);
map.put(TAG_LOCATION, user_location);
// adding HashList to ArrayList
aList.add(map);
}
}else{
Log.d("Albums: ", "null");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all albums
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
SimpleAdapter adapter = new SimpleAdapter(
getActivity().getBaseContext(), aList,
R.layout.list_item_matchs, new String[] { TAG_NAME,TAG_PROFILE,TAG_IMAGE,TAG_CAST,TAG_AGE,TAG_LOCATION
}, new int[] {
R.id.txtproname,R.id.txtprofileage,R.id.propic,R.id.txtprofilecast,R.id.txtprofileplace});
// updating listview
listview.setAdapter(adapter);
}
});
}
private void runOnUiThread(Runnable runnable) {
// TODO Auto-generated method stub
}
}
}
so the problem is , in that link i am using user_login_id field of login json,,so i want to send or pass that field during requesting with URL..
I just suggest you to use SharedPreference for this. When you get Login response, just parse the JSON and then get log_in_id field value and save it in SharedPreferences, then whenever you want to use this value you can use throughout your application.
you already used the same method in your doInBackground :
here is a suggested edit to prepare it for the next:
add "user_login_id" to params list
change POST to GET if it is so.
protected String doInBackground(String... args) {
// Building Parameters
List params = new ArrayList();
params.add(new BasicNameValuePair("version", "apps"));
// add the user_login_id to params.
params.add(new BasicNameValuePair("user_login_id ", "265"));
// getting JSON string from URL
// I think you are using GET bcz the url shows the parameters.
String json = jsonParser.makeHttpRequest(MATCH_URL, "GET",
params);
I'm new to android. I want to put one of the activity under one of the tab of my app(the tab is fragment) when i paste my code into fragment, there's a lot of error...
There's error in new JSONParse().execute(); It shows that the type JSONParse is not visible.
in this line private class JSONParse extends AsyncTask there's error
showing illegal modifier for the class JSONParse.only public, abstract and final are permitted.
this line pDialog = new ProgressDialog(TabActivityQueue.this); it shows the constructor progressDialog is undefined.
All the variables phonenumber, peoplenumber , remarks, status, table2, url are not resolved as variables.
What should I change? I'm really stuck.
Here's the activity code :
public class MainActivity extends Activity {
ListView list;
TextView number;
TextView info;
TextView remark;
TextView statuss;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "http://172.22.85.235:8080/Qproject/servlet/Qaction?action_flag=find";
//JSON Node Names
private static final String Table2 = "table2";
private static final String phonenumber = "phonenumber";
private static final String peoplenumber = "peoplenumber";
private static final String remarks = "remarks";
private static final String status = "status";
JSONArray table2 = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oslist = new ArrayList<HashMap<String, String>>();
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();
number = (TextView)findViewById(R.id.number);
info = (TextView)findViewById(R.id.info);
remark = (TextView)findViewById(R.id.remark);
statuss = (TextView)findViewById(R.id.statuss);
pDialog = new ProgressDialog(MainActivity.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 from URL
table2 = json.getJSONArray(Table2);
for(int i = 0; i < table2.length(); i++){
JSONObject c = table2.getJSONObject(i);
// Storing JSON item in a Variable
String number = c.getString(phonenumber);
String info = c.getString(peoplenumber);
String remark = c.getString(remarks);
String statuss = c.getString(status);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(phonenumber, number);
map.put(peoplenumber, info);
map.put(remarks, remark);
map.put(status, statuss);
oslist.add(map);
list=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_item,
new String[] { phonenumber,peoplenumber, remarks,status }, new int[] {
R.id.number,R.id.info, R.id.remark,R.id.statuss});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Here's the fragment where i pasted the activity code in :
public class TabActivityQueue extends Fragment {
ListView list;
TextView number;
TextView info;
TextView remark;
TextView statuss;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
public static String url = "http://172.22.85.235:8080/Qproject/servlet/Qaction?action_flag=find";
//JSON Node Names
public static final String Table2 = "table2";
public static final String phonenumber = "phonenumber";
public static final String peoplenumber = "peoplenumber";
public static final String remarks = "remarks";
public static final String status = "status";
JSONArray table2 = null;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
//This layout contains your list view
View view = inflater.inflate(R.layout.activity_tab_activity_queue, container, false);
oslist = new ArrayList<HashMap<String, String>>();
number = (TextView)view.findViewById(R.id.number);
info = (TextView)view.findViewById(R.id.info);
remark = (TextView)view.findViewById(R.id.remark);
statuss = (TextView)view.findViewById(R.id.statuss);
Btngetdata = (Button)view.findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
return view;
}
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(TabActivityQueue.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 from URL
table2 = json.getJSONArray(Table2);
for(int i = 0; i < table2.length(); i++){
JSONObject c = table2.getJSONObject(i);
// Storing JSON item in a Variable
String number = c.getString(phonenumber);
String info = c.getString(peoplenumber);
String remark = c.getString(remarks);
String statuss = c.getString(status);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(phonenumber, number);
map.put(peoplenumber, info);
map.put(remarks, remark);
map.put(status, statuss);
oslist.add(map);
list=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_item,
new String[] { phonenumber,peoplenumber, remarks,status }, new int[] {
R.id.number,R.id.info, R.id.remark,R.id.statuss});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public class TabActivityQueue extends Fragment {
ListView list;
TextView number;
TextView info;
TextView remark;
TextView statuss;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
// URL to get JSON Array
public static String url = "http://172.22.85.235:8080/Qproject/servlet/Qaction?action_flag=find";
// JSON Node Names
public static final String Table2 = "table2";
public static final String phonenumber = "phonenumber";
public static final String peoplenumber = "peoplenumber";
public static final String remarks = "remarks";
public static final String status = "status";
JSONArray table2 = null;
private Activity activity;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
// This layout contains your list view
View view = inflater.inflate(R.layout.activity_tab_activity_queue, container, false);
oslist = new ArrayList<HashMap<String, String>>();
number = (TextView) view.findViewById(R.id.number);
info = (TextView) view.findViewById(R.id.info);
remark = (TextView) view.findViewById(R.id.remark);
statuss = (TextView) view.findViewById(R.id.statuss);
Btngetdata = (Button) view.findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
activity = this.getActivity();
return view;
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(activity);
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 from URL
table2 = json.getJSONArray(Table2);
for (int i = 0; i < table2.length(); i++) {
JSONObject c = table2.getJSONObject(i);
// Storing JSON item in a Variable
String number = c.getString(phonenumber);
String info = c.getString(peoplenumber);
String remark = c.getString(remarks);
String statuss = c.getString(status);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(phonenumber, number);
map.put(peoplenumber, info);
map.put(remarks, remark);
map.put(status, statuss);
oslist.add(map);
list = (ListView) findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(activity, oslist, R.layout.list_item, new String[] {phonenumber, peoplenumber, remarks, status}, new int[] {R.id.number, R.id.info,
R.id.remark, R.id.statuss});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(activity, "You Clicked at " + oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Whereever you have used context as TabActivityQueue.this (or getApplicationCOntext()) change to getActivity() .
Also if some android pre defined method doesn't work try prefix getActivity() like:- getActivity().method();
declare private Activity activity as public Activity activity;
I already getting the string value from JSON but it seems to have the problem in Hash map or something, im getting null value on my List adapter. Can anyone help me or tell me if i did something wrong in my code. Thanks in advance.
Here is my code.
The Activity -
public class TestJSON extends Activity{
public static ListView lv;
public static ProgressDialog pDialog;
public static LazyAdapter adapter;
static final String KEY_ITEMS = "items";
static final String KEY_TITLE = "title";
static final String KEY_ID = "id";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.test_json_view);
new AsyncInitial().execute();
// Showing progress dialog before sending http request
pDialog = new ProgressDialog(this);
pDialog.setMessage("Please wait..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
lv = (ListView)findViewById(R.id.list);
//lv.setAdapter(new ArrayAdapter(getApplicationContext(), android.R.layout.simple_expandable_list_item_1, items));
}
private class AsyncInitial extends AsyncTask<Void, Void, ArrayList<HashMap<String, String>>> {
ArrayList<HashMap<String, String>> menuItems;
#Override
protected void onPreExecute() {
}
#Override
protected ArrayList<HashMap<String, String>> doInBackground(Void... arg0) {
menuItems = new ArrayList<HashMap<String, String>>();
try {
//if (vid_num <= 0) {
// Get a httpclient to talk to the internet
HttpClient client = new DefaultHttpClient();
// Perform a GET request to YouTube for a JSON list of all the videos by a specific user
//https://gdata.youtube.com/feeds/api/videos?author="+username+"&v=2&alt=jsonc
HttpUriRequest request = new HttpGet("http://gdata.youtube.com/feeds/api/playlists/SP86E04995E07F6BA8?v=2&start-index=1&max-results=50&alt=jsonc");
// Get the response that YouTube sends back
HttpResponse response = client.execute(request);
// Convert this response into a readable string
String jsonString = StreamUtils.convertToString(response.getEntity().getContent());
// Create a JSON object that we can use from the String
JSONObject json = new JSONObject(jsonString);
// For further information about the syntax of this request and JSON-C
// see the documentation on YouTube http://code.google.com/apis/youtube/2.0/developers_guide_jsonc.html
// Get are search result items
JSONArray jsonArray = json.getJSONObject("data").getJSONArray(KEY_ITEMS);
// Get the total number of video
//String vid_num = json.getJSONObject("data").getString("totalItems");
//System.out.println("vid_num-------->"+ vid_num);
// Loop round our JSON list of videos creating Video objects to use within our app
for (int i = 0; i < jsonArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jsonObject = jsonArray.getJSONObject(i);
// The title of the video
String title = jsonObject.getJSONObject("video").getString(KEY_TITLE);
System.out.println("Title-------->"+ title);
// A url to the thumbnail image of the video
// We will use this later to get an image using a Custom ImageView
//String TAG_thumbUrl = jsonObject.getJSONObject("video").getJSONObject("thumbnail").getString("sqDefault");
//System.out.println("thumbUrl-------->"+ thumbUrl);
String id = jsonObject.getJSONObject("video").getString(KEY_ID);
System.out.println("video_id-------->"+ id);
map.put(title, KEY_TITLE);
map.put(id, KEY_ID);
menuItems.add(map);
}
} catch (ClientProtocolException e) {
//Log.e("Feck", e);
} catch (IOException e) {
//Log.e("Feck", e);
} catch (JSONException e) {
//Log.e("Feck", e);
}
return menuItems;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
super.onPostExecute(result);
adapter = new LazyAdapter(TestJSON.this,menuItems);
lv.setAdapter(adapter);
pDialog.dismiss();
}
}
}
And The adapter
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private static LayoutInflater inflater;
private ArrayList<HashMap<String, String>> data;
public LazyAdapter(TestJSON testJSON, ArrayList<HashMap<String, String>> menuItems) {
activity = testJSON;
data = menuItems;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)vi = inflater.inflate(R.layout.list_row, null);
TextView title = (TextView)vi.findViewById(R.id.title);
TextView id = (TextView)vi.findViewById(R.id.artist);
HashMap<String, String> item = new HashMap<String, String>();
item = data.get(position);
title.setText(item.get(TestJSON.KEY_TITLE));
id.setText(item.get(TestJSON.KEY_ID));
return vi;
}
}
I am trying to consume json data from a server in android app. the format of data which is from a cakePHP web app looks like this;
[{"Chapter":{"id":"1","chapter":"4","chaptertitle":"The Bill of Rights"}}]
and below is the java code am using to achieve my goal;
public class Sheria extends SherlockListFragment {
// Progress Dialog
// private ProgressDialog pDialog;
// private View view;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> chapterList;
// url to get all products list
// private static String url_all_products =
// "http://10.0.2.2/android_projects/sanisani/today_getall.php";
private static String url_chapters = "http://10.0.2.2/constitution/laws/chapters";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_CHAPTERS = "Chapter";
private static final String TAG_CHAP = "chapter";
private static final String TAG_CHAP_TITLE = "chaptertitle";
JSONArray chaps = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.sheria, container, false);
new FetchDetails().execute();
return super.onCreateView(inflater, container, savedInstanceState);
}
class FetchDetails extends AsyncTask<String, String, String> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getSherlockActivity());
pDialog.setMessage("Fetching Data...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
// pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
chapterList = new ArrayList<HashMap<String, String>>();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url_chapters);
// Check your log cat for JSON reponse
Log.d("Chapters: ", json.toString());
try {
// Checking for SUCCESS TAG
// int success = json.getInt(TAG_SUCCESS);
// if (success == 1) {
// products found
// Getting Array of Products
chaps = json.getJSONArray(TAG_CHAPTERS);
System.out.println(chaps);
// looping through All Products
for (int i = 0; i < chaps.length(); i++) {
JSONObject c = chaps.getJSONObject(i);
// Storing each json item in variable
String chapter = c.getString(TAG_CHAP);
String chapter_title = c.getString(TAG_CHAP_TITLE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_CHAP, chapter);
map.put(TAG_CHAP_TITLE, chapter_title);
// adding HashList to ArrayList
chapterList.add(map);
// getSherlockActivity().finish();
}
// }
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
// Keys used in Hashmap
String[] from = { TAG_CHAP, TAG_CHAP_TITLE };
// Ids of views in listview_layout
int[] to = { R.id.chapter, R.id.chaptertitle };
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getActivity()
.getBaseContext(), chapterList, R.layout.sheriainfo, from,
to);
// Setting the adapter to the listView
setListAdapter(adapter);
}
}
}
When i run the code i get the error JSONArray cannot be converted to JSONObject.
Please help
Because you are getting a JSONArray not a JSONObject, try this:
JSONArray json = jParser.getJSONFromUrl(url_chapters);
and return JSONArray from getJSONFromUrl(String)
and also remove chaps = json.getJSONArray(TAG_CHAPTERS); because your TAG_CHAPTER is not an array.
And in the for loop do
JSONObject c = json.getJSONObject(i);
in place of
JSONObject c = chaps.getJSONObject(i);
Edit
public class Sheria extends SherlockListFragment {
// Progress Dialog
// private ProgressDialog pDialog;
// private View view;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> chapterList;
// url to get all products list
// private static String url_all_products =
// "http://10.0.2.2/android_projects/sanisani/today_getall.php";
private static String url_chapters = "http://10.0.2.2/constitution/laws/chapters";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_CHAPTERS = "Chapter";
private static final String TAG_CHAP = "chapter";
private static final String TAG_CHAP_TITLE = "chaptertitle";
JSONArray chaps = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.sheria, container, false);
new FetchDetails().execute();
return super.onCreateView(inflater, container, savedInstanceState);
}
class FetchDetails extends AsyncTask<String, String, String> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getSherlockActivity());
pDialog.setMessage("Fetching Data...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
// pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
chapterList = new ArrayList<HashMap<String, String>>();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
/*
HERE in the method getJSONFromUrl() convert the String u get from server into
JSONArray not JSONObject
*/
JSONArray json = jParser.getJSONFromUrl(url_chapters);
// Check your log cat for JSON reponse
Log.d("Chapters: ", json.toString());
try {
// Checking for SUCCESS TAG
// int success = json.getInt(TAG_SUCCESS);
// if (success == 1) {
// products found
// Getting Array of Products
// chaps = json.getJSONArray(TAG_CHAPTERS);
// System.out.println(chaps);
// looping through All Products
for (int i = 0; i < json.length(); i++) {
JSONObject c = json.getJSONObject(i);
JSONObject jObj = c.getJSONObject("TAG_CHAPTERS ");
// Storing each json item in variable
String chapter = jObj.getString(TAG_CHAP);
String chapter_title = jObj.getString(TAG_CHAP_TITLE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_CHAP, chapter);
map.put(TAG_CHAP_TITLE, chapter_title);
// adding HashList to ArrayList
chapterList.add(map);
// getSherlockActivity().finish();
}
// }
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
// Keys used in Hashmap
String[] from = { TAG_CHAP, TAG_CHAP_TITLE };
// Ids of views in listview_layout
int[] to = { R.id.chapter, R.id.chaptertitle };
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getActivity()
.getBaseContext(), chapterList, R.layout.sheriainfo, from,
to);
// Setting the adapter to the listView
setListAdapter(adapter);
}
}
}