How to Parse URL with JSON object -Android [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
i have the URL (.com) which has the JSON object .. i created the JSON object using PHP and uploaded in a server so it will be dynamically updated (similar to RSS). I face two problems the first one shows error " and of type java.Lang.String cannot be converted to JSON object" so i used this code and the error goes:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
The SingleMenuItemActivity calss:
public class SingleMenuItemActivity extends Activity {
// JSON node keys
private static final String TAG_Title = "Title";
private static final String TAG_Date = "Date";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_list_item);
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
String name = in.getStringExtra(TAG_Title);
String description = in.getStringExtra(TAG_Date);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblCost = (TextView) findViewById(R.id.email_label);
lblName.setText(name);
lblCost.setText(description);
}
}
The AndroidJasonParsingActivity calss:
public class AndroidJSONParsingActivity extends ListActivity {
// url to make request
private static String url = "http://www.rssparser.host22.com/";
// JSON Node names
private static final String TAG_NAME = "Title";
private static final String TAG_Image = "Image";
private static final String TAG_Category = "Category";
private static final String TAG_Venue = "Venue";
private static final String TAG_Date = "Date";
// contacts JSONArray
JSONArray contacts = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
//contacts = json.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String name = c.getString(TAG_NAME);
String Image = c.getString(TAG_Image);
String Category = c.getString(TAG_Category);
String Venue = c.getString(TAG_Venue);
String Date = c.getString(TAG_Date);
// Phone number is agin JSON Object
JSONObject phone = c.getJSONObject(TAG_Date);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_NAME, name);
map.put(TAG_Image, Image);
map.put(TAG_Date , Date );
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.list_item,
new String[] { TAG_NAME, TAG_Date }, new int[] {
R.id.name, R.id.email, R.id.mobile });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.email)).getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_Date, description);
startActivity(in);
}
});
}
}

first create JSONParser.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
then create activity
public class AndroidJSONParsingActivity extends ListActivity {
// url to make request
private static String url = "http://api.androidhive.info/contacts/";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray contacts = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone number is agin JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_EMAIL, email);
map.put(TAG_PHONE_MOBILE, mobile);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.list_item,
new String[] { TAG_NAME, TAG_EMAIL, TAG_PHONE_MOBILE }, new int[] {
R.id.name, R.id.email, R.id.mobile });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.email)).getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_PHONE_MOBILE, description);
startActivity(in);
}
});
}
}
and write Internet permission in manifest file
this is best tutorial

Related

Json parsing errors at android

I want to parse below data but I got a errors when I try other url like this http://api.learn2crack.com/android/jsonos/ for the parsing json data I can parsing data,but when I try below code for the parsing I got a below error.
Activity jsonparse.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41b86fb8 V.E..... R......D 0,0-580,162} that was originally added here
android.view.WindowLeaked: Activity jsonparse.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41b86fb8 V.E..... R......D 0,0-580,162} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:409)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:218)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:281)
at jsonparse.MainActivity$DownloadJSON.onPreExecute(MainActivity.java:58)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at jsonparse.MainActivity.onCreate(MainActivity.java:38)
at android.app.Activity.performCreate(Activity.java:5122)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2307)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)
at android.app.ActivityThread.access$600(ActivityThread.java:162)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5371)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
)
{
"AllUsersResult":[
{
"GroupID":null,
"ID":1,
"Password":"1234",
"Role":null,
"Username":"admin",
"customerID":null
}
]
}
MainActivity class
public class MainActivity extends Activity {
ListView list;
TextView ver;
TextView name;
TextView api;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "http://192.168.0.39:8090/TrackBinSvc.svc/AllUsers/admin/1234";
//JSON Node Names
private static final String TAG_OS = "AllUsersResult";
private static final String TAG_VER = "GroupID";
private static final String TAG_NAME = "Password";
private static final String TAG_API = "Username";
JSONArray android = 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();
ver = (TextView)findViewById(R.id.vers);
name = (TextView)findViewById(R.id.name);
api = (TextView)findViewById(R.id.api);
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
android = json.getJSONArray(TAG_OS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String ver = c.getString(TAG_VER);
String name = c.getString(TAG_NAME);
String api = c.getString(TAG_API);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_VER, ver);
map.put(TAG_NAME, name);
map.put(TAG_API, api);
oslist.add(map);
list = (ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_v,
new String[] { TAG_VER,TAG_NAME, TAG_API }, new int[] {
R.id.vers,R.id.name, R.id.api});
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();
}
}
}
}
JSONParser class
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
I am suggest you parse data with volley library it is easy to use and also flexible ! Here is Tutorial link !
Hope this will helps you ! Cheers !
Change your JSONParse class to this..
private class JSONParse extends AsyncTask<String, String, ArrayList<HashMap<String, String>>> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
ver = (TextView)findViewById(R.id.vers);
name = (TextView)findViewById(R.id.name);
api = (TextView)findViewById(R.id.api);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected ArrayList<HashMap<String, String>> doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
if(json!=null)
{
// Getting JSON Array from URL
android = json.getJSONArray(TAG_OS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String ver = c.getString(TAG_VER);
String name = c.getString(TAG_NAME);
String api = c.getString(TAG_API);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_VER, ver);
map.put(TAG_NAME, name);
map.put(TAG_API, api);
oslist.add(map);
return oslist;
}
//else DATA Not Found or Server not connected
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result_list) {
if(pDialog!=null)
{
pDialog.dismiss();
}
list = (ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, result_list,
R.layout.list_v,
new String[] { TAG_VER,TAG_NAME, TAG_API }, new int[] {
R.id.vers,R.id.name, R.id.api});
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 "+result_list.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
}
}
Hope this will help you.

Android Get data from server to android issue

I want to get data from server and save it in the listview I have write right code there is no error but when I click on activity app stopped here is my activity code/
public class UserListActivity extends ActionBarActivity {
String myJSON;
private static final String TAG_RESULTS="result";
// private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL ="email";
JSONArray peoples = null;
ArrayList<HashMap<String, String>> personList;
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_list);
list = (ListView) findViewById(R.id.listView);
personList = new ArrayList<HashMap<String,String>>();
getData();
}
protected void showList(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
peoples = jsonObj.getJSONArray(TAG_RESULTS);
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
//String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
HashMap<String,String> users = new HashMap<String,String>();
// persons.put(TAG_ID,id);
users.put(TAG_NAME,name);
users.put(TAG_EMAIL,email);
personList.add(users);
}
ListAdapter adapter = new SimpleAdapter(
UserListActivity.this, personList, R.layout.list_item,
new String[]{TAG_NAME,TAG_EMAIL},
new int[]{R.id.name, R.id.email}
);
list.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://samplechatapp.gear.host/Get-Data.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
}
This is log cat message:
This is the data on the server which I want to get.

Android Json Parse returns nothing

I have a Json Parser Class which looks like this:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
JSONArray jObj = new JSONArray(json);
System.out.println(jObj.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Near the end at the last try and catch statement I print out the jsonObject as a string I correctly get the data in the console, the json looks like this:
[{"id":1,"name":"Blooper","description":"Blooper","video_url":"Blooper","platform":1100110011,"logo":"","avaible":0,"token":"","created_at":"2016-04-03
17:19:49","updated_at":"2016-04-03
17:19:49","release_at":"2016-05-08"},{"id":2,"name":"Blooper","description":"Blooper","video_url":"Blooper","platform":"11000000000","logo":"","avaible":0,"token":"","created_at":"2016-04-03
17:26:13","updated_at":"2016-04-03
17:26:13","release_at":"2016-05-08"}]
I used a validator and it is fine.
In my AllProducts activity I try to display that inside the android app.
It looks like this:
public class AllProductsActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://192.168.155.27:8000/index";
// JSON Node names
private static final String TAG_SUCCESS = "id";
private static final String TAG_PRODUCTS = "name";
private static final String TAG_PID = "description";
private static final String TAG_NAME = "video_url";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_products);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
EditProductActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllProductsActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AllProductsActivity.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME},
new int[] { R.id.pid, R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
If I try to print out this json:
JSONObject json = new JSONObject();
I get no values (null), so my view keeps being empty.
I get follwing error message:
java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.String org.json.JSONObject.toString()' on a null object
reference
at
com.example.androidhive.AllProductsActivity$LoadAllProducts$1.run(AllProductsActivity.java:150)
Line 150 is this :
Log.d("All Products: ", json.toString());
Thus Android Studio tells my that
jObj
here, in my jsonparser:
try {
JSONArray jObj = new JSONArray(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
is never used.
http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/
I am not really experienced with this so I really hope for some help, thanks.
With JSONObject json = new JSONObject(); you are creating an empty JSONObject,
the JSONObject returned by jParser.makeHttpRequest(url_all_products, "GET", params); is never used.
You have to do it like this:
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
so your JSONObject from the JParser will be stored in json.

JSON respone in list view display based on the particular condition in android

I need to display the items on particular condition .I done that one.I have three tabs are present.In the first tab A ,i display the list of items,in that only one item is present.But when you move to tab B and again come to tab A,we can see two items.I need to avoid that repeating item displaying, how to do that one, please help me if you have an idea,Thank you in advance
Here is my code:
List View list;
ListViewAdapter adapter;
ArrayList<String> title_array = new ArrayList<String>();
ArrayList<String> title_array1 = new ArrayList<String>();
ArrayList<String> title_array2 = new ArrayList<String>();
ArrayList<String> title_array3 = new ArrayList<String>();
ArrayList<String> title_array4 = new ArrayList<String>();
ArrayList<String> title_array5 = new ArrayList<String>();
ArrayList<String> title_array6 = new ArrayList<String>();
String response_value;
JSONObject result;
JSONArray tokenList;
JSONObject oj5;
String appid;
JSONObject oj;
String fileid;
HttpEntity entity;
String status ,borrowername,coborrowername,loannumber,addrs1,city;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.menu_frame, container, false);
list = (ListView) rootView.findViewById(R.id.listview);
// Pass results to ListViewAdapter Class
new AsyncTaskParseJson().execute();
return rootView;
}
// you can make this class as another java file so it will be separated from your main activity.
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
final String TAG = "AsyncTaskParseJson.java";
// contacts JSONArray
JSONArray dataJsonArr = null;
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(String... arg0) {
// post the specific format data to json url
try {
HttpClient httpClient = new DefaultHttpClient();
JSONObject object = new JSONObject();
object.put("Username", "******");
object.put("Password", "******");
JSONObject jsonObject = new JSONObject();
jsonObject.put("Authentication", object);
jsonObject.put("RequestType", 4);
HttpPost postMethod = new HttpPost("*********");
postMethod.setEntity(new StringEntity(jsonObject.toString()));
postMethod.setHeader("Accept", "application/json");
postMethod.setHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(postMethod);
entity = response.getEntity();
response_value = EntityUtils.toString(entity).toString();
// Log.e(TAG, response_value);
if (entity != null) {
//Convert String to JSON Object
JSONObject result = new JSONObject(response_value);
JSONArray tokenList = result.getJSONArray("Files");
}
} catch (Exception e) {
e.printStackTrace();
}
return response_value;
}
#Override
protected void onPostExecute(String response_value) {
super.onPostExecute(response_value);
// dismiss the dialog after getting all products
try
{
if (entity != null) {
result = new JSONObject(response_value);
tokenList = result.getJSONArray("Files");
for(int i=0;i<=tokenList.length();i++)
{
oj = tokenList.getJSONObject(i);
String oj1 = oj.getString("FileID");
JSONObject oj12= (JSONObject) tokenList.getJSONObject(i).get("Borrower");
JSONObject oj2 = (JSONObject) tokenList.getJSONObject(i).get("CoBorrower");
JSONObject oj3 = (JSONObject) tokenList.getJSONObject(i).get("LoanDetails");
JSONObject oj4 = (JSONObject) tokenList.getJSONObject(i).get("PropertyAddress");
fileid = oj.getString("FileID");
borrowername = oj12.getString("FirstName");
coborrowername = oj2.getString("FirstName");
loannumber = oj3.getString("LoanNumber");
addrs1 = oj4.getString("Address1");
city = oj4.getString("City");
JSONArray orders = oj.getJSONArray("Orders");
for(int n=0;n<orders.length();n++){
JSONObject oj5 = orders.getJSONObject(n);
appid = oj5.getString("ApplicationOrderId");
String duedate = oj5.getString("DueDate");
status = oj5.getString("Status");
// Log.e(TAG, appid +"/"+ appid1);
Log.e(TAG, appid + "/" + borrowername + "/"+ coborrowername + "/"+ addrs1 + "/"+ city + "/"+ loannumber + fileid );
if(status.equals("1")){
title_array3.add("New");
title_array1.add(addrs1 + " ,"+ city);
title_array.add(borrowername +" , "+coborrowername);
title_array2.add("Duedate");
// title_array3.add(status);
title_array4.add(appid);
title_array5.add(loannumber);
title_array6.add(fileid);
list.setOnItemClickListener(new OnItemClickListener() {
#Override public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
{
Intent first = new Intent(getActivity(),DetailView.class);
first.putExtra("fileid", fileid);
startActivity(first);
} });
}
}
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
adapter = new ListViewAdapter(getActivity(), title_array,title_array1,title_array2,title_array3,title_array4,title_array5,title_array6);
list.setAdapter(adapter);
}
}
}

Populating listview from database (localhost phpmyadmin)

I tried searching for similar questions but I cant find anything that fits in to what I am doing.. I'm trying to populate a listview from a database and whenever I run it, it doesn't display anything in the listview..
here is the logcat..
JSONException: Value {"message":"Patient Available","success":1,"post":[{"lname":"miradora doringo","address":"navotas, pilipinas","email":"tam.muqu23","age":"20","gender":"babae","remarks":"mabuting estudyante","patient_id":"6","contact":"361008762","fname":"jenelien"},{"lname":"andres","address":"manila","email":"julieannandres#gmail.com","age":"20","gender":"female","remarks":"trial","patient_id":"7","contact":"926644895","fname":"julie"}]} of type org.json.JSONObject cannot be converted to JSONArray
this is my Viewpatient.java:
public class Viewpatient extends ListActivity {
private Button create;
private ProgressDialog pDialog;
private static final String READ_PATIENT_URL = "http://192.168.43.15:8080/DoctorScheduler/activities/viewpatient.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private static final String TAG_POST = "post";
private static final String TAG_PATIENT = "patient_id";
private static final String TAG_FNAME = "fname";
private static final String TAG_LNAME = "lname";
private static final String TAG_AGE = "age";
private static final String TAG_GENDER = "gender";
private static final String TAG_CONTACT = "contact";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_REMARKS = "remarks";
JSONParser jsonParser = new JSONParser();
//array of all patient information by patient
JSONArray Apatient = null;
//manages all patient in a list
ArrayList<HashMap<String, String>> ApatientList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_viewpatient);
ApatientList = new ArrayList<HashMap<String, String>>();
new LoadInformation().execute();
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
// INSERT ALL PREVIOUS CONSULTATIONS OF THE PATIENT HERE
}
});
create = (Button) findViewById(R.id.BtnAdd);
create.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent createInfo = new Intent(Viewpatient.this, Viewupdate.class);
startActivity(createInfo);
}
});
};
public class LoadInformation extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(Viewpatient.this);
pDialog.setMessage("Loading all patient information....");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
}
#Override
protected Void doInBackground(Void... args) {
// TODO Auto-generated method stub
List<NameValuePair> params = new ArrayList<NameValuePair>();
// Making a request to url and getting response
String json = jsonParser.getJSONFromURL(READ_PATIENT_URL, "POST", params);
Log.d("Response: ", "> " + json);
try {
Apatient = new JSONArray(json);
if (Apatient != null) {
// looping
for (int i = 0; i < Apatient.length(); i++) {
JSONObject c = Apatient.getJSONObject(i);
String patient_id = c.getString(TAG_PATIENT);
String fname = c.getString(TAG_FNAME);
String lname = c.getString(TAG_LNAME);
String age = c.getString(TAG_AGE);
String gender = c.getString(TAG_GENDER);
String contact = c.getString(TAG_CONTACT);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String remarks = c.getString(TAG_REMARKS);
// tmp hashmap for single contact
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PATIENT, patient_id);
map.put(TAG_FNAME, fname);
map.put(TAG_LNAME, lname);
map.put(TAG_AGE, age);
map.put(TAG_GENDER, gender);
map.put(TAG_CONTACT, contact);
map.put(TAG_EMAIL, email);
map.put(TAG_ADDRESS, address);
map.put(TAG_REMARKS, remarks);
// adding contact to contact list
ApatientList.add(map);
}
} else {
Log.e("Error", "Couldn't get any data from the url");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
//super.onPostExecute(result);
pDialog.dismiss();
runOnUiThread(new Runnable(){
public void run(){
ListAdapter adapter = new SimpleAdapter(
Viewpatient.this, ApatientList, R.layout.main,
new String[] { TAG_PATIENT, TAG_FNAME, TAG_LNAME, TAG_AGE,
TAG_GENDER, TAG_CONTACT, TAG_EMAIL, TAG_ADDRESS, TAG_REMARKS },
new int[] { R.id.txtID, R.id.txtFName, R.id.txtLName, R.id.txtAge, R.id.txtGender,
R.id.txtContact, R.id.txtEmail, R.id.txtAddress, R.id.txtRemarks});
setListAdapter(adapter);
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.viewpatient, menu);
return true;
}
}
this my JSONParser.java:
public class JSONParser {
//new
static String response = null;
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
//constructor
public JSONParser(){
}
public String getJSONFromURL(String url, String method,
List<NameValuePair> params){
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == "POST") {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == "GET") {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
and this is my viewpatient.php:
<?php
require ("../config.inc.php");
$query = "Select * From patientinfo";
try{
$stmt = $dbname->prepare($query);
$result = $stmt->execute();
}catch(PDOException $ex){
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
//retrieve all the rows
$rows = $stmt->fetchAll();
if($rows){
$response["success"] = 1;
$response["message"] = "Patient Available";
$response["post"] = array();
foreach($rows as $row){
$post = array();
$post["patient_id"] = $row["patient_id"];
$post["fname"] = $row["fname"];
$post["lname"] = $row["lname"];
$post["age"] = $row["age"];
$post["gender"] = $row["gender"];
$post["contact"] = $row["contact"];
$post["email"] = $row["email"];
$post["address"] = $row["address"];
$post["remarks"] = $row["remarks"];
//update json response
array_push($response["post"], $post);
}
echo json_encode($response);
}
else{
$response["success"] = 0;
$response["message"] = "No available patient information";
die(json_encode($response));
}
?>
You should change this part Apatient = new JSONArray(json);
Create a JSONObject JSONObject ApatientObject = new JSONObject(json);
Then get your JSONArray from there like this :
Apatient = new JSONArray(ApatientObject.getJSONArray("post"))
The problem is that the response you receive from the server is a JSONObject, not a JSONArray. The JSONObject contains 2 Strings, "message" and "success", and also contains a JSONArray "post" which holds the data you are looking for.
EDIT:
If you're only retreiving data from the server then it can be useful to think in terms of using GET for retrieving / viewing information and POST for creating / editing information as mentioned here:
When do you use POST and when do you use GET?

Categories

Resources