null pointer exception error in http POST request JSON object - java

I am doing android coding and sending a http POST request using httpClient. and it is giving me a null point expception error at the line
httpEntity = httpResponse.getEntity();
i used log cat and found that my code was stopping at the line mentioned above. please help me out with it. thanks in advance.
my code is for the establishment of http client is in the file serviceHandler:
package com.example.manumaheshwari.vigo;
/**
* Created by ManuMaheshwari on 30/06/15.
*/
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
StringBuilder sb;
public ServiceHandler() {
}
/**
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/**
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int 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);
httpPost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded ");
if (params != null) {
try {
httpPost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
}
catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
}
// Making HTTP Request
try {
HttpResponse response = httpClient.execute(httpPost);
// writing response to log
Log.d("Http Response: ", response.toString());
} catch (ClientProtocolException e) {
// writing exception to log
e.printStackTrace();
} catch (IOException e) {
// writing exception to log
e.printStackTrace();
}
}
} 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 the code for my main activity is as follows:
package com.example.manumaheshwari.vigo;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get pending rides JSON
private static String url = "http://128.199.206.145/vigo/v1/displayalldrivers";
// JSON Node names
private static final String TAG_SOURCE = "source";
private static final String TAG_DESTINATION = "destination";
private static final String TAG_DRIVER_ID = "driver_id";
private static final String TAG_NAME = "name";
// pending rides JSONArray
JSONArray pendingRides = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> pendingRidesList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pendingRidesList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Calling async task to get json
new GetRides().execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Async task class to get json by making HTTP call
* */
private class GetRides extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("contractor_id", "1"));
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.POST, nameValuePairs);
Log.d("Response: " , "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
pendingRides = jsonObj.getJSONArray("driver");
// looping through All Contacts
for (int i = 0; i < pendingRides.length(); i++) {
JSONObject c = pendingRides.getJSONObject(i);
String source = c.getString(TAG_NAME);
String destination = c.getString(TAG_DRIVER_ID);
// tmp hashmap for single contact
HashMap<String, String> pendingRide = new HashMap<String, String>();
// adding each child node to HashMap key => value
pendingRide.put(TAG_NAME, source);
pendingRide.put(TAG_DRIVER_ID, destination);
// adding pending ride to pending ride list
pendingRidesList.add(pendingRide);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, pendingRidesList,
R.layout.list_view, new String[] { TAG_SOURCE, TAG_DESTINATION,}, new int[] { R.id.source,R.id.destination});
setListAdapter(adapter);
}
}
}

It seems that httpResponse is null,because in POST method you didn't assign any value to it.So in POST method,change
HttpResponse response = httpClient.execute(httpPost);
// writing response to log
Log.d("Http Response: ", response.toString());
to
httpResponse = httpClient.execute(httpPost);
// writing response to log
Log.d("Http Response: ", httpResponse.toString());

Related

how can i fix the error when JSONException was detected while i try to connect to Mysql?

I try to connect to mysql.
I catch the exception on ligne "jObj = new JSONObject(json);" by used "pDialog.setMessage("7777");" because the application wass stopped when pDialog show "7777"
this is my class
JSONParser.java
package com.larig2.test;
/**
* Created by GNassro on 26/02/2018.
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.util.Log;
import java.util.Date;
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,ProgressDialog pDialog) {
// 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 (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
//convert byte-stream to character-stream.
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
try {
while((line = reader.readLine())!=null){
sb.append(line+"\n");
}
//close the input stream
is.close();
json = sb.toString();
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
// TODO Auto-generated catch block
pDialog.setMessage("7777");
pDialog.show();
e.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
pDialog.setMessage("00000");
pDialog.show();
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
pDialog.setMessage("99999");
pDialog.show();
// TODO Auto-generated catch block
e.printStackTrace();
}
return jObj;
}
}
Signin_Client.java
package com.larig2.test;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.content.Intent;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.ArrayAdapter;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class Signin_Client extends AppCompatActivity {
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputNom;
EditText inputPrenom;
EditText inputCIN;
EditText inputJour;
Spinner inputMois;
EditText inputAnnee;
Spinner inputAdresse;
EditText inputTel;
EditText inputMail;
EditText inputPwd;
//attribute string
String nom;
String prenom;
String cin;
String jour;
String mois;
String annee;
String sexe;
String adresse;
String tel;
String mail;
String pwd;
String date;
// url to create new product
private static String url_create_product = "http://192.168.1.177/Karhabti/signup_client.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signin__activity_client);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final Intent contactus = new Intent(this, Contactez_nous.class);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(contactus);
}
});
//Spinner for Address Start ****
Spinner spinner = (Spinner) findViewById(R.id.adresse);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.Tunisia_State, R.layout.spinnerthem1);
// Specify the layout to use when the list of choices appears
// Apply the adapter to the spinner
adapter.setDropDownViewResource(R.layout.spinnerthem);
spinner.setAdapter(adapter);
//Spinner for Address End ****
//Spinner for Months Date Start ****
Spinner spinnerMonths = (Spinner) findViewById(R.id.mois);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapterMonths = ArrayAdapter.createFromResource(this,
R.array.Mois_Date, R.layout.spinnerthem1);
// Specify the layout to use when the list of choices appears
// Apply the adapter to the spinner
adapterMonths.setDropDownViewResource(R.layout.spinnerthem);
spinnerMonths.setAdapter(adapterMonths);
//Spinner for Months Date End ****
//select input
inputNom = (EditText) findViewById(R.id.nom);
inputPrenom = (EditText) findViewById(R.id.prenom);
inputCIN = (EditText) findViewById(R.id.CIN);
inputJour = (EditText) findViewById(R.id.jour);
inputMois = (Spinner) findViewById(R.id.mois);
inputAnnee = (EditText) findViewById(R.id.annee);
inputAdresse = (Spinner) findViewById(R.id.adresse);
inputTel = (EditText) findViewById(R.id.tel);
inputMail = (EditText) findViewById(R.id.mail);
inputPwd = (EditText) findViewById(R.id.pwd);
}
public void signupClickC(View view) {
cin = inputCIN.getText().toString();
new CreateNewClient().execute();
}
/**
* Background Async Task to Create new product
* */
class CreateNewClient extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Signin_Activity_client.this);
pDialog.setMessage("Creation en cours ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("nomC", "Med"));
params.add(new BasicNameValuePair("prenomC", "Ali"));
params.add(new BasicNameValuePair("CIN", cin));
params.add(new BasicNameValuePair("date","1999-11/11" ));
params.add(new BasicNameValuePair("sexe", "h"));
params.add(new BasicNameValuePair("adresse", "gafsa"));
params.add(new BasicNameValuePair("tel", "556"));
params.add(new BasicNameValuePair("mail", "khhg"));
params.add(new BasicNameValuePair("psw", "kdlkdj"));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params, pDialog);
pDialog.setMessage("22222");
pDialog.show();
// 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(), ClientSpace.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} 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 done
pDialog.dismiss();
}
}
}
my question is how to fix this exception Although the insert to Mysql was successful ?
you should create pDialog object in JsonPArser class instead of passing as a parameter..
in JsonParser Class use this code below and dont use two prgressDialog at the same time.ProgressDialog pd = new ProgressDialog(context);
progressDialog.setMessage(your message);

php Required field(s) is missing when i test on browser they show that message

When I test my PHP file in the web browser I get the message...
{"success":0,"message":"required field(s) is missing"}.
I am trying to add data from my android app to my database on local host and have no idea what the required field that is missing could be.
My php Script is:
<?php
/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['date']) && isset($_POST['time']) ) {
$date = $_POST['date'];
$time = $_POST['time'];
// include db connect class
require_once __DIR__ . '/connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO datatime(date,time) VALUES('$date', '$time')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "sit created.";
$response["id"] = mysql_insert_id("SELECT id FROM sits ORDER BY id DESC LIMIT 1");
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
My JSON Parser Class
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
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() {
}
// 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;
}
}
I am calling my php file
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
public class MainActivity extends Activity implements
OnClickListener {
// Widget GUI
//Button btnCalendar, btnTimePicker;
EditText txtDate, txtTime;
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
// Variable for storing current date and time
private int mYear, mMonth, mDay, mHour, mMinute;
private static String url_create_product = "http://xxx.yyy.z.xxx/datetimejson/datetime.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtDate = (EditText) findViewById(R.id.txtDate);
txtTime = (EditText) findViewById(R.id.txtTime);
txtDate.setFocusable(false);
txtDate.setClickable(true);
txtTime.setFocusable(false);
txtTime.setClickable(true);
txtDate.setOnClickListener(this);
txtTime.setOnClickListener(this);
Button btnCreateProduct = (Button) findViewById(R.id.set);
// button click event
btnCreateProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
new CreateNewProduct().execute();
}
});
}
#Override
protected void onDestroy()
{
super.onDestroy();
if(pDialog.isShowing())
pDialog.dismiss();
}
#Override
public void onClick(View v) {
if (v == txtDate) {
// Process to get Current Date
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
// Launch Date Picker Dialog
DatePickerDialog dpd = new DatePickerDialog(this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
// Display Selected date in textbox
txtDate.setText(dayOfMonth + "-"
+ (monthOfYear + 1) + "-" + year);
}
}, mYear, mMonth, mDay);
dpd.show();
}
if (v == txtTime) {
// Process to get Current Time
final Calendar c = Calendar.getInstance();
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);
// Launch Time Picker Dialog
TimePickerDialog tpd = new TimePickerDialog(this,
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute) {
// Display Selected time in textbox
txtTime.setText(hourOfDay + ":" + minute);
}
}, mHour, mMinute, false);
tpd.show();
}
}
class CreateNewProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Creating Product..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
String date = txtDate.getText().toString();
String time = txtTime.getText().toString();
// Building Parameters
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("date", date));
params.add(new BasicNameValuePair("time", time));
Log.d("request!", "starting");
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
Log.d("Post Update", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Log.d("Updated!", json.toString());
Intent i = new Intent(getApplicationContext(), DailogBox.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
}
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 done
pDialog.dismiss();
}
}
}
I have been stuck with this issue for a few days now and pls help me.
One thing could be that you might be issuing a GET request, but in PHP script you are using $_POST array which will have valid data only when it's a POST request.
As you want to use both GET and POST methods, use $_REQUEST in PHP script. Thus will work for both get and POST requests.

JsonParser Android Error

I have two login applications with exactly the same code that calls the json parser class. the first one works fine (you can try it from the link, username admin and pass:123) however the second class gives a null pointer exception on the json.getInt(TAG_SUCCESS);
This is the JsonParser Class:
package com.example.mysqltest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
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() {
}
// 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;
}
}
The Working-fine Class:
package com.example.mysqltest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Login extends Activity implements OnClickListener{
private EditText user, pass;
private Button mSubmit, mRegister;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
//php login script location:
//testing from a real server:
private static final String LOGIN_URL = "http://www.eshteghel.comlu.com/dbservice/login.php";
//JSON element ids from repsonse of php script:
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
//setup input fields
user = (EditText)findViewById(R.id.username);
pass = (EditText)findViewById(R.id.password);
//setup buttons
mSubmit = (Button)findViewById(R.id.login);
mRegister = (Button)findViewById(R.id.register);
//register listeners
mSubmit.setOnClickListener(this);
mRegister.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.login:
new AttemptLogin().execute();
break;
case R.id.register:
Intent i = new Intent(this, Register.class);
startActivity(i);
break;
default:
break;
}
}
class AttemptLogin extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
*/
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Attempting login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = user.getText().toString();
String password = pass.getText().toString();
try {
/* try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(password.getBytes(),0,password.length());
password = new BigInteger(1,md5.digest()).toString(16);
//System.out.println("Signature: "+signature);
} catch (final NoSuchAlgorithmException e) {
e.printStackTrace();
}*/
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
//Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// check your log for json response
//Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
//Log.d("Login Successful!", json.toString());
Intent i = new Intent(Login.this, ReadComments.class);
finish();
startActivity(i);
return json.getString(TAG_MESSAGE);
}else{
//Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} 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();
if (file_url != null){
Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
While the class that gives the null pointer exception:
package test.example.com.test;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Sign_in extends FragmentActivity implements View.OnClickListener{
Button btSignUp,btLogin;
EditText etUser,etPass;
// Progress Dialog
private ProgressDialog nDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
//testing from a real server:
private static final String LOGIN_URL = "http://www.eshteghel.comlu.com/dbservice/login.php";
//JSON element ids from repsonse of php script:
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
etUser = (EditText) findViewById(R.id.etUser);
etPass = (EditText) findViewById(R.id.etPass);
btSignUp = (Button) findViewById(R.id.btSignUp);
btLogin = (Button) findViewById(R.id.btLogin);
btSignUp.setOnClickListener(this);
btLogin.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_sign_in, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void showDialog(){
ClientDialog cd = new ClientDialog();
cd.show(getSupportFragmentManager(), "DialogFragment");
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btLogin:
new AttemptLogin().execute();
break;
case R.id.btSignUp:
showDialog();
break;
default:
break;
}
}
class AttemptLogin extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
nDialog = new ProgressDialog(Sign_in.this);
nDialog.setTitle("Checking Network");
nDialog.setMessage("Loading..");
nDialog.setIndeterminate(false);
nDialog.setCancelable(true);
nDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = etUser.getText().toString();
String password = etPass.getText().toString();
try {
/*try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(password.getBytes(),0,password.length());
password = new BigInteger(1,md5.digest()).toString(16);
//System.out.println("Signature: "+signature);
} catch (final NoSuchAlgorithmException e) {
e.printStackTrace();
}*/
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
//Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// check your log for json response
//Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
//Log.d("Login Successful!", json.toString());
Intent i = new Intent(Sign_in.this, Company.class);
finish();
startActivity(i);
return json.getString(TAG_MESSAGE);
}else{
//Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} 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
nDialog.dismiss();
if (file_url != null){
Toast.makeText(Sign_in.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}

Send JSON from Java to PHP through Post

I am doing an Android program that is supposed to send data from the tablet to a PHP Web Service. The code for sending the JSON:
package com.example.shvalidation;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
public class MainMenuScreen extends Activity {
//JSON Variables
JSONParser jsonParser = new JSONParser();
String pid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_menu_layout);
new TestThread().execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_menu_layout, menu);
return true;
}
public void PlantToDome(View view) {
Intent intent = new Intent(this, SelectLocationScreen.class);
startActivity(intent);
}
//Código del Web Service
public class TestThread extends AsyncTask<Void, Void, Void> {
ProgressDialog dialog;
protected void onPreExecute() {
dialog = ProgressDialog.show(MainMenuScreen.this, "Loading", "Loading data, please wait..");
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
protected Void doInBackground(Void...args0) {
try {
HttpClient client = new DefaultHttpClient();
HttpResponse response;
HttpPost post = new HttpPost("http://192.168.1.101:8080/GetBook.php");
JSONObject holder = new JSONObject();
JSONObject euid = new JSONObject();
euid.put("euid", 1);
holder.accumulate("euids", euid);
euid.put("euid", 2);
holder.accumulate("euids", euid);
post.setHeader("json", holder.toString());
StringEntity se = new StringEntity(holder.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
if (response != null) {
InputStream in = response.getEntity().getContent();
String a = convertStreamToString(in);
Log.i("Read from Server", a);
}
} catch (Exception e) {
Log.d("error", e.toString());
}
return null;
}
protected void onPostExecute(Void unused) {
dialog.dismiss();
}
}
}
The PHP Web Service:
<?php
ob_start();
var_dump(json_decode(file_get_contents('php://input')));
$out = ob_get_contents();
ob_end_clean();
$f = fopen('out.txt', 'w+');
fwrite($f, html_entity_decode($out));
fclose($f);
?>
I have tried different methods for getting the JSON, but none of them have worked for me. Maybe the fine people of StackOverflow can help me out with this, as they always have for every other problem that I've had.
From the comments section, it appears you only want the JSON being sent to your PHP script. Normally, you post POST this to PHP, and extract it:
<?php
print_r($_POST);
$json_string = $_POST['message'];
$json = json_decode($json_string);
print_r($json);
?>
And then a small client example:
public static void main(String[] args) {
String json = "{\"message\":\"This is a message\"}";
HttpClient httpClient = new DefaultHttpClient();
try {
HttpPost request = new HttpPost("http://somesite.com/test.php");
StringEntity params =new StringEntity("message=" + json);
request.addHeader("content-type", "application/x-www-form-urlencoded");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
// handle response here...
System.out.println(org.apache.http.util.EntityUtils.toString(response.getEntity()));
org.apache.http.util.EntityUtils.consume(response.getEntity());
} catch (Exception ex) {
// handle exception here
} finally {
httpClient.getConnectionManager().shutdown();
}
}
The output of this is:
Array
(
[message] => {"message":"This is a message"}
)
stdClass Object
(
[message] => This is a message
)

How to extract the URL following an HTTPPost in Android

I'm scratching my head at this problem that I can't seem to figure out. What I'm trying to do is extract the URL following the HTTPpost. This will allow me to go through the Oauth process.
Currently I'm extracting the whole website into my entity.
For example: The data will be posted to https://mysite.com/login and will redirect after the post to https://mysite.com/dashboard?code=3593085390859082093720
How does one extract the url?
If you need any more information or can direct me in the right direction, all is appreciated! Thank you!
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class LoginActivity extends Activity implements OnClickListener {
Button ok,back,exit;
TextView result;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
// Login button clicked
ok = (Button)findViewById(R.id.submit);
ok.setOnClickListener(this);
result = (TextView)findViewById(R.id.result);
}
public void postLoginData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://mysite.com/login");
try {
// Add user name and password
EditText uname = (EditText)findViewById(R.id.username);
String username = uname.getText().toString();
EditText pword = (EditText)findViewById(R.id.password);
String password = pword.getText().toString();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("pseudonym_session[unique_id]", username));
nameValuePairs.add(new BasicNameValuePair("pseudonym_session[password]", password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
Log.w("CANVAS", "Execute HTTP Post Request");
HttpResponse response = httpclient.execute(httppost);
String str = inputStreamToString(response.getEntity().getContent()).toString();
Log.w("CANVAS", str);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String ResponseBody = httpclient.execute(httppost, responseHandler);
Intent intent = new Intent(getBaseContext(), DashboardActivity.class);
startActivity(intent);
if(str.toString().equalsIgnoreCase("true"))
{
Log.w("CANVAS", "TRUE");
result.setText("Login successful");
}else
{
Log.w("CANVAS", "FALSE");
result.setText(ResponseBody);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private StringBuilder inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Return full string
return total;
}
#Override
public void onClick(View view) {
if(view == ok){
postLoginData();
}
}
}
if you set a redirect handler, you can get back from the response the location the server's sending you to. here's a snippet of code I was just playing with... (and I should point out, if you DON'T set a redirect handler, you'll just get redirected to the final destination, which might be the login screen itself)
DefaultHttpClient htc = getHttpClient();
htc.setRedirectHandler(new RedirectHandler() {
#Override
public boolean isRedirectRequested(HttpResponse response, HttpContext context)
{
Log.d(TAG, "isRedirectRequested, response: " + response.toString());
return false;
}
#Override
public URI getLocationURI(HttpResponse response, HttpContext context)
throws ProtocolException
{
Log.d(TAG, "getLocationURI, response: " + response.toString());
return null;
}
});
HttpResponse resp = null;
StringBuilder out = new StringBuilder();
try
{
HttpGet get = new HttpGet(spec);
resp = htc.execute(get);
for (Header hdr : resp.getAllHeaders())
Log.d(TAG, "header " + hdr.getName() + " -> " + hdr.getValue());
...
}
catch (Exception e)
{
Log.e(TAG, "Error connecting to " + spec, e);
return null;
}
Search for a substring in the HttpPost url

Categories

Resources