Iam making an app with connecting to server and reading the json,but am getting java.lang.String org.json.JSONObject.toString()' on a null object reference error.please help me.thanks in advance
Here is my activity
public class NewProductActivity extends Activity {
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputName;
Button createBtn;
private static String url_create_product = "http://10.0.2.2/create_product.php";
private static final String TAG_SUCCESS = "success";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_product);
inputName = (EditText)findViewById(R.id.nameEt);
createBtn = (Button)findViewById(R.id.createBt);
createBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new CreateNewProduct().execute();
}
});
}
class CreateNewProduct extends AsyncTask<String,String,String>{
String name = inputName.getText().toString();
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewProductActivity.this);
pDialog.setMessage("Creating Product..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args){
inputName = (EditText)findViewById(R.id.nameEt);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name",name ));
JSONObject json = jsonParser.makeHttprequest(url_create_product,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), AllProductsActivty.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
here is my Json parser
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser(){}
public JSONObject makeHttprequest(String url, String method, List<NameValuePair> params){
try {
if (method.equals( "POST")){
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 .equals( "GET")){
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params,"url");
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");
}
try {
jObj = new JSONObject(json);
}catch (JSONException e){
Log.e("JSON Parser","Error parsing");
}
return jObj;
}
}
here is my php file
<?php
$response = array();
if(isset($_POST['name'])){
$name = $_POST['name'];
$con = mysql_connect("localhost","root","root");
$db = mysql_select_db("db");
$result = mysql_query("INSERT INTO product(name) VALUES ('$name')");
if($result){
$response["success"] = 1;
$response["message"] = "successfully inserted";
echo json_encode($respone);
}
else {
$response["success"] = 0;
$response["message"] ="error occured";
echo json_encode($response);
}
} else{
$response["success"] = 0;
$response["message"] = "required feild missing";
echo json_encode($response);
}
?>
here is my error log
06-27 18:35:55.097 3462-4317/com.example.joel339.sample E/JSON Parser: Error parsing
--------- beginning of crash
06-27 18:35:55.097 3462-4317/com.example.joel339.sample E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.example.joel339.sample, PID: 3462
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference
at com.example.joel339.sample.NewProductActivity$CreateNewProduct$override.doInBackground(NewProductActivity.java:70)
at com.example.joel339.sample.NewProductActivity$CreateNewProduct$override.access$dispatch(NewProductActivity.java)
at com.example.joel339.sample.NewProductActivity$CreateNewProduct.doInBackground(NewProductActivity.java:0)
at com.example.joel339.sample.NewProductActivity$CreateNewProduct.doInBackground(NewProductActivity.java:50)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
i am able to create a new product,my product list json is being updated,but i cant see the products list
here is the products list activity
public class AllProductsActivty extends ListActivity {
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String,String>> productsList;
private static String url_all_products = "http://10.0.2.2/get_all_products_details.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "product";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
JSONArray products = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_products);
productsList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
new LoadAllProducts().execute(url_all_products);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String pid = ((TextView)view.findViewById(R.id.pid)).getText().toString();
Intent in = new Intent(getApplicationContext(),EditProductActivity.class);
in.putExtra(TAG_PID,pid);
startActivityForResult(in,100);
}
});
}
#Override
protected void onActivityResult(int requestCode,int resultCode , Intent data){
super.onActivityResult(requestCode,resultCode,data);
if(resultCode == 100){
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
class LoadAllProducts extends AsyncTask< String,String,String>{
#Override
protected void onPreExecute(){
super.onPreExecute();
pDialog = new ProgressDialog(AllProductsActivty.this);
pDialog.setMessage("LoadingProducts.Please Wait");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args){
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttprequest(url_all_products,"GET",params);
Log.d("Allproducts:",json.toString());
try{
int success = json.getInt(TAG_SUCCESS);
if (success == 1){
products = json.getJSONArray(TAG_PRODUCTS);
for (int i = 0;i < products.length();i++){
JSONObject c =products.getJSONObject(i);
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
HashMap<String,String> map = new HashMap<String, String>();
map.put(TAG_PID,id);
map.put(TAG_NAME,name);
productsList.add(map);
}
}else{
Intent i = new Intent(getApplicationContext(),NewProductActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
}
catch (JSONException e){
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url){
pDialog.dismiss();
runOnUiThread(new Runnable() {
#Override
public void run() {
ListAdapter adapter = new SimpleAdapter(
AllProductsActivty.this,productsList,R.layout.list_view,new String[]{TAG_PID,TAG_NAME},
new int[]{R.id.pid,R.id.name});
setListAdapter(adapter);
}
});
}
}
}
The error is in this line.
Log.d("Create Response", json.toString());
Because of null object, it gives you null pointer exception.
Double check with this line, Just add the safety check as below
if (json == null || json == JSONObject.NULL){
// error handling..
}
else
{
// Your code
}
Suggestion:(not related to crash)
Just remove this line inputName = (EditText)findViewById(R.id.nameEt); in doInBackground(). You already initilised this variable in onCreate(), so just remove it.
Related
Help is needed, I just started learning to code and trying to create a product app but I encountered some errors.
Here is my class:
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://127.0.0.1/android_connect2/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
// 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) {
// 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 response
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);
}
});
}
}
And my JSON parser:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
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.equals("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.equals("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 {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
This is the error I'm getting:
E/Buffer Error: Error converting result java.lang.NullPointerException
E/JSON Parser: Error parsing data org.json.JSONException: End of input at character 0 of
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.example.androidhive, PID: 3761
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:318)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
Caused by: 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.doInBackground(AllProductsActivity.java:130)
at com.example.androidhive.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:105)
at android.os.AsyncTask$2.call(AsyncTask.java:304)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
Any help is appreciated, I have searched this site for solutions but each question is answered code-specific. Cheers
Because this line returns null JSONObject
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
So check first that it's has null value or not before changing it into string
Like..
if (json != null && json.getInt(TAG_SUCCESS) != 0/*or failed value
*/){
// ALSO PARSE RESULT HERE
// Check your log cat for JSON response
Log.d("All Products: ", json.toString());
}else{
// SHOW NOTIFICIATION: URL/SERVER NOT REACHABLE
}
Hope this will help you.
my sql server collation is utf8 unicode
my php works fine
my android project is working fine with normal characters but in case of arabic char it display error "Error parsing json" line 233 in the activity listed below
I've tried my sql and php on other project its works but here I dont know whats the error json must be utf8 by defult
public class DealsListActivity extends Activity {
private String id;
// Progress Dialog
private ProgressDialog pDialog;
// creating JSON Parser object
JSONParser jParser = new JSONParser();
private static String url = "http://xxxxxxxxxxxx.get_all_deals_by_id.php";
// JSON Node names
private static final String TAG_DEALS = "deals";
private static final String TAG_ID = "id";
private static final String TAG_DEALNAME = "dealName";
private static final String TAG_PRICE = "price";
private static final String TAG_DESCRIPTION = "description";
private static final String TAG_RESTID = "restID";
private static final String TAG_RESTNAME = "restName";
private static final String TAG_RESTTYPE = "restType";
private static final String TAG_LAT = "restLat";
private static final String TAG_LNG = "restLng";
private static final String TAG_SUCCESS = "success";
private JSONObject json;
JSONArray restaurantDealsData = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> restaurantDealsList = new ArrayList<HashMap<String, String>>();
ListView myList;
private String[] dealID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_deals_list);
id = getIntent().getStringExtra("id");
myList = (ListView) findViewById(R.id. restDealListView);
new LoadDeals().execute();
}
/**
* Background Async Task to Load all deals by making
* HTTP Request
* */
class LoadDeals extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(DealsListActivity.this);
pDialog.setMessage("Loading Restaurant Deals. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
Log.v("id", id);
params.add(new BasicNameValuePair("id", id));
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url, "GET", params);
// check log cat for JSON string from URL
Log.v("restaurantDealsJSON: ", json.toString());
// return json as string to using in the user interface
return json.toString();
}
#Override
protected void onPostExecute(final String jsonStr) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
#Override
public void run() {
/**
* Updating parsed JSON data into listview
* */
try {
json = new JSONObject(jsonStr);
} catch (JSONException e1) {
// print error message to log
e1.printStackTrace();
error("There are no Deals");
}
try {
// Checking for SUCCES TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// restaurant found
// Getting Array of restaurant
restaurantDealsData = json.getJSONArray(TAG_DEALS);
displayDeals(restaurantDealsData.toString());
} else {
error("There is no Deals available!");
}
} catch (JSONException e) {
error("There has been an error please try again!");
e.printStackTrace();
}
}
});
}
}
public void error(String error) {
// Log.v("ERROR", "2");
AlertDialog.Builder builder = new AlertDialog.Builder(
DealsListActivity.this);
// Log.v("ERROR", "3");
builder.setTitle("Error");
builder.setMessage(error);
builder.setCancelable(false);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// Log.v("TEST", "1");
Intent i = new Intent(getApplicationContext(),
TabsViewPagerFragmentActivity.class);
startActivity(i);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public void displayDeals(String result) {
JSONArray restaurantDealsData = null;
try {
restaurantDealsList.clear();
restaurantDealsData = new JSONArray(result);
dealID = new String[restaurantDealsData.length()];
// looping through all technical data
for (int i = 0; i < restaurantDealsData.length(); i++) {
JSONObject td = restaurantDealsData.getJSONObject(i);
// Storing each json item in variable
String id = td.getString(TAG_ID);
dealID[i] = id;
String name = td.getString(TAG_DEALNAME);
String price = td.getString(TAG_PRICE);
String description = td.getString(TAG_DESCRIPTION);
String restaurantID = td.getString(TAG_RESTID);
String restaurantName = td.getString(TAG_RESTNAME);
String restaurantType = td.getString(TAG_RESTTYPE);
String lat = td.getString(TAG_LAT);
String lng = td.getString(TAG_LNG);
Log.v("lat", lat);
Log.v("lng", lng);
// 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_DEALNAME, name);
map.put(TAG_PRICE, price);
map.put(TAG_DESCRIPTION, description);
map.put(TAG_RESTID, restaurantID);
map.put(TAG_RESTNAME, restaurantName);
map.put(TAG_RESTTYPE, restaurantType);
map.put(TAG_LAT, lat);
map.put(TAG_LNG, lng);
// adding HashMap to ArrayList
restaurantDealsList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
error("Error parsing json");
}
// add to list view
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(getApplicationContext(),
restaurantDealsList, R.layout.deals_list_item, new String[] {
TAG_DEALNAME, TAG_RESTNAME, TAG_RESTTYPE }, new int[] {
R.id.dealName, R.id.restaurantName, R.id.type });
// updating listview
myList.setAdapter(adapter);
//handling user click list item
myList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
//start the next activity - Restaurant Details
Intent i = new Intent(getApplicationContext(), DealDetails.class);
i.putExtra("ID", dealID[arg2]);
startActivity(i);
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}
});
}
}
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
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 {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
You should read the input stream using the charset UTF-8 like this:
replace
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
by
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8));
I use this to decode json with japanese inside.
I've a problem with parsing json from facebook graph api.
When I'm using facebook URL:https://graph.facebook.com/interstacjapl/feed?access_token=MyTOKEN to grab json it's no working, but when I copied that json (it works in browser) and paste to my webiste http://mywebsite/fb.json and change site URL in the code, it works good.
When I'm using fb graph URL it shows error:
W/System.err(5534): org.json.JSONException: No value for data
Is this problem with parsing from https or URL or code?
JSONParser.java
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;
}
}
MainActivity
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 = "https://graph.facebook.com/interstacjapl/feed?access_token=CAACEdEose0cBANLR...";
//JSON Node Names
private static final String TAG = "data";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "message";
private static final String TAG_API = "type";
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);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String ver = c.getString(TAG_ID);
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_ID, 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_ID,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();
}
}
}
}
This works
String reply = "";
BufferedReader inStream = null;
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpRequest = new HttpGet(url);
try {
HttpResponse response = httpClient.execute(httpRequest);
inStream = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent()));
StringBuffer buffer = new StringBuffer("");
String line = "";
while ((line = inStream.readLine()) != null) {
buffer.append(line);
}
inStream.close();
reply = buffer.toString();
} catch (Exception e) {
//Handle Execptions
}
public class DialogSelectAmphurActivity extends Activity {
private final String TAG = "internet";
private ListView listview_province;
ArrayList<HashMap<String, String>> myList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
String strUrl =("http://192.168.1.4/test_projectEnd/amphur.php");
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_select_province_dialog);
new AsyncDownload().execute(strUrl);
}
public String getData(String strUrl, ArrayList<NameValuePair> params){
String jString;
HashMap<String, String> map;
String sProvince_id = getIntent().getStringExtra("provinceId");
params.add(new BasicNameValuePair("txtProvinceId",sProvince_id));
try {
jString = getJsonFromUrl(strUrl, params);
JSONArray jArray = new JSONArray(jString);
Log.d(TAG, jArray +","+ params);
for(int i =0; i< jArray.length(); i++)
{
JSONObject jObj = jArray.getJSONObject(i);
String sAmphur_id = jObj.getString("AMPHUR_ID");
String sAmphur_name = jObj.getString("AMPHUR_NAME");
map = new HashMap<String, String>();
map.put("amphur_id", sAmphur_id);
map.put("amphur_name", sAmphur_name);
myList.add(map);
Log.d(TAG, sAmphur_id + sAmphur_name);
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
private void showProvince(){
ListView listView = (ListView) findViewById(R.id.listView_province1);
ListAdapter adapter = new SimpleAdapter(this, myList, R.layout.row_layout_select_province,
new String[]{"amphur_id","amphur_name"}, new int[]{R.id.textView_province_id,R.id.textView_province_name});
listView.setAdapter(adapter);
}
private String getJsonFromUrl(String strUrl,ArrayList<NameValuePair> params)throws IOException{
URL url = new URL(strUrl);
HttpPost httpPost = new HttpPost(strUrl);
try {
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
Log.d(TAG, params+"check");
httpCon.setRequestMethod("GET");
httpCon.setConnectTimeout(6*1000);
int responseCode = httpCon.getResponseCode();
Log.d(TAG, "The response is" + responseCode);
if(responseCode == HttpsURLConnection.HTTP_OK){
Log.d(TAG, "size" + httpCon.getContentLength());
InputStream ins = httpCon.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(ins,"UTF-8"));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null){
response.append(line);
response.append("\n");
Log.d(TAG, line);
}
rd.close();
return response.toString();
}
} catch (Exception ex) {
Log.d(TAG,"Problem reading"+ ex.getLocalizedMessage());
}
return null;
}
private class AsyncDownload extends AsyncTask<String, Void, String>{
ProgressDialog pd;
#Override
protected void onPreExecute(){
pd = ProgressDialog.show(DialogSelectAmphurActivity.this, "Download", "Downloading....");
}
protected String doInBackground(String... Params){
String data = getData(strUrl, params);
return null;
}
protected void onPostExecute(String result){
pd.dismiss();
showProvince();
}
}
}
i sent txtprovinceId to php
"Sorry for any incorrect on my conversation, my English is not good."
<?php
$provinceid = trim($_GET["txtProvinceId"]);
require("libs/connection_to_abc.php");
mysql_query("SET character_set_results=utf8");
mysql_query("SET character_set_client=utf8");
mysql_query("SET character_set_connection=utf8");
$strSQL = "SELECT amphur.* FROM province,amphur
WHERE province.PROVINCE_ID = amphur.PROVINCE_ID
AND province.PROVINCE_ID ='$provinceid' ";
$objQuery = mysql_query($strSQL);
$intNumField = mysql_num_fields($objQuery);
$resultArray = array();
while($obResult = mysql_fetch_array($objQuery))
{
$arrCol = array();
for($i=0;$i<$intNumField;$i++)
{
$arrCol[mysql_field_name($objQuery,$i)] = $obResult[$i];
}
array_push($resultArray,$arrCol);
}
mysql_close($link);
echo json_encode($resultArray);
?>
php response in Logcat "Undefined index: txtProvinceId in amphur.php on line 3"
Help me please ! "Sorry for any incorrect on my conversation, my English is not good."
You never add your params to the query string. You can use URLEncodedUtils.format() to format them easily :
import org.apache.http.client.utils.URLEncodedUtils;
...
private String getJsonFromUrl(String strUrl,ArrayList<NameValuePair> params) {
String queryString = URLEncodedUtils.format(params, null);
URL url = new URL(strUrl + "?" + queryString);
...
}
Background : I am trying to develop my first android application which is a student discussion panel. I am good with PHP and MySQL but don't have much experience in android Java.
Issue:
In SelectedQuestionActivity class, if I simply give the URL as http://thewbs.getfreehosting.co.uk/talky/fetchans.php?qid=3, it works just fine and it fetches the corresponding answer to the question.
But if I do it the way I have shown in the code below, the application crashes. I am not sure where I am wrong.
CODE:
AllQuestionActivity.java
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.qid)).getText()
.toString();
//pid is the value of the selected question for example www.example.com/fetchans?qid=3 so here pid value is supposed to be 3.
// Starting new intent
Intent in = new Intent(getApplicationContext(),
SelectedQuestionActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
startActivity(in);
}
});
Now in SelectedQuestionActivity.java
code:
public class SelectedQuestionActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
Intent intent = getIntent();
String qid = intent.getExtras().getString(TAG_PID);
// url to get all products list
private String url_all_products = "http://thewbs.getfreehosting.co.uk/talky/fetchans.php?qid="+qid;
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "ques";
private static final String TAG_PID = "aid";
private static final String TAG_NAME = "aname";
private static final String TAG_INFO = "answer";
private static final String TAG_DATE = "date";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_ans);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
}
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SelectedQuestionActivity.this);
pDialog.setMessage("Loading Answers. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
// 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 Answers: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
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);
String info = c.getString(TAG_INFO);
String date = c.getString(TAG_DATE);
// 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);
map.put(TAG_INFO, info);
map.put(TAG_DATE, date);
// adding HashList to ArrayList
productsList.add(map);
}
}
else {
}
} 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(
SelectedQuestionActivity.this, productsList,
R.layout.list_selected_ques, new String[] { TAG_PID,
TAG_NAME, TAG_INFO, TAG_DATE },
new int[] { R.id.aid, R.id.aname, R.id.answer, R.id.date});
// updating listview
setListAdapter(adapter);
}
});
}
}
}
JSONparser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET method
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 {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Currently you are trying to getIntent outside onCreate of ListActivity so move it inside onCreate method as :
Intent intent;
String qid;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_ans);
// get Intent here
intent = getIntent();
qid = intent.getExtras().getString(TAG_PID);
// your code here
and also no need to use runOnUiThread method for updating UI from onPostExecute because onPostExecute method called on Ui thread we can access UI elements in it
EDIT:-
you are not adding any paramter to NameValuePair inside doInBackground . add quid before sending it to makeHttpRequest as :
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
add quid param here
params.add(new BasicNameValuePair("qid",qid)); //<<<< add here
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(
url_all_products,
"GET",
params);
// your code here
You are passing a string from one activity object to another , while you didn't write code to receive it on the new activity in the right place.
To solve this you should add some code to your onCreate:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_ans);
String url = getIntent().getStringExtra(TAG_PID);
if (url != null)
url_all_products = url;
You should need to get your intent values in onCreate() as below :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_ans);
Intent intent = getIntent();
String qid = intent.getExtras().getString(TAG_PID);
}