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();
}
}
}
}
Related
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);
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.
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());
so i was trying to create a simple login app connected to my wampserver by following tutorial on internet and it works fine, but the problem occurs when my device is not connected to internet and i can't figure it out why, but i'm pretty sure the problem is in my asynctask.
so i need help anyone, thanks.
here's my login.java
package id.wanda.smkkkristenimmanuelii;
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.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Login extends Activity implements OnClickListener {
private EditText user, pass;
private Button mSubmit;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "http://192.168.1.110:80/smkkimmanuel2/login.php";
// JSON element ids from repsonse of php script:
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private static final String TAG_LEVEL_AKSES = "level_akses";
private static final String TAG_JABATAN = "jabatan";
public static String level_akses = "5", jabatan = "", namaUser = "";
public static String login_status = "false";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// setup input fields
user = (EditText) findViewById(R.id.username);
pass = (EditText) findViewById(R.id.password);
// setup buttons
mSubmit = (Button) findViewById(R.id.btnLogin);
// register listeners
mSubmit.setOnClickListener(this);
}
#Override
public void onBackPressed() {
Login.this.finish();
startActivity(new Intent(this, MenuUtama.class));
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnLogin:
new AttemptLogin().execute();
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 levelaks, jabat;
String username = user.getText().toString();
String password = pass.getText().toString();
try {
// 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());
levelaks = json.getString(TAG_LEVEL_AKSES);
jabat = json.getString(TAG_JABATAN);
level_akses = levelaks;
jabatan = jabat;
namaUser = username;
login_status = "true";
Intent i = new Intent(Login.this, MenuUtama.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();
}
}
}
and here's my JSONParser.java :
package id.wanda.smkkkristenimmanuelii;
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() {
}
public JSONObject getJSONFromUrl(final String url) {
// Making HTTP request
try {
// Construct the client and the HTTP request.
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
// Execute the POST request and store the response locally.
HttpResponse httpResponse = httpClient.execute(httpPost);
// Extract data from the response.
HttpEntity httpEntity = httpResponse.getEntity();
// Open an inputStream with the data content.
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
// Create a BufferedReader to parse through the inputStream.
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
// Declare a string builder to help with the parsing.
StringBuilder sb = new StringBuilder();
// Declare a string to store the JSON object data in string form.
String line = null;
// Build the string until null.
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
// Close the input stream.
is.close();
// Convert the string builder data to an actual string.
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// Try to 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 the JSON Object.
return jObj;
}
// 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;
}
}
here's my crash report:
05-19 09:56:44.040: E/AndroidRuntime(24861): FATAL EXCEPTION: AsyncTask #1
05-19 09:56:44.040: E/AndroidRuntime(24861): Process: id.wanda.smkkkristenimmanuelii, PID: 24861
05-19 09:56:44.040: E/AndroidRuntime(24861): java.lang.RuntimeException: An error occured while executing doInBackground()
05-19 09:56:44.040: E/AndroidRuntime(24861): at android.os.AsyncTask$3.done(AsyncTask.java:300)
05-19 09:56:44.040: E/AndroidRuntime(24861): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
05-19 09:56:44.040: E/AndroidRuntime(24861): at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
05-19 09:56:44.040: E/AndroidRuntime(24861): at java.util.concurrent.FutureTask.run(FutureTask.java:242)
05-19 09:56:44.040: E/AndroidRuntime(24861): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
05-19 09:56:44.040: E/AndroidRuntime(24861): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
05-19 09:56:44.040: E/AndroidRuntime(24861): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
05-19 09:56:44.040: E/AndroidRuntime(24861): at java.lang.Thread.run(Thread.java:841)
05-19 09:56:44.040: E/AndroidRuntime(24861): Caused by: java.lang.NullPointerException
05-19 09:56:44.040: E/AndroidRuntime(24861): at id.wanda.smkkkristenimmanuelii.Login$AttemptLogin.doInBackground(Login.java:138)
05-19 09:56:44.040: E/AndroidRuntime(24861): at id.wanda.smkkkristenimmanuelii.Login$AttemptLogin.doInBackground(Login.java:1)
05-19 09:56:44.040: E/AndroidRuntime(24861): at android.os.AsyncTask$2.call(AsyncTask.java:288)
05-19 09:56:44.040: E/AndroidRuntime(24861): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
05-19 09:56:44.040: E/AndroidRuntime(24861): ... 4 more
05-19 09:56:44.040: W/ActivityManager(571): Force finishing activity id.wanda.smkkkristenimmanuelii/.Login
05-19 09:56:44.050: E/IMGSRV(192): :0: PVRDRMOpen: TP3, ret = 107
The best way to approach this is to use a ConnectivityManager to ascertain whether or not your device is online/has connectivity to the internet before attempting to do anything that requires a connection.
This way you can display a screen advising as such when offline, or attempt to run your code when online. From a user point of view this is favourable to your app just crashing when there is no connection available.
the problem is makeHttpRequest is returning null
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST", params);
you can simply add an extra catch to your try/catch
catch (NullPointerException e) {
e.printStackTrace();
}
Probably better practice is to check your connection with ConnectivityManager before you make the request
Change
private static final String LOGIN_URL = "http://192.168.1.110:80/smkkimmanuel2/login.php";
to
private static final String LOGIN_URL = "http://127.0.0.1:80/smkkimmanuel2/login.php";
The reason for this issue is that your IP is bound to that connection and when you are not connected then it's not your IP anymore.
The Best way to to avoid crash is just check the device if it is connected to the internet.
*ifConnected * : Do your process
*ifNotConnected *: Then display a dialog box to user that he/she is not connected to the internet.
This is what I do in the development.
This might help you :-
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
You need to add
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
The problem is solved now, thanks to #Karl and #Modge,
first, thanks to #Modge, to prevent the app from crashing, just add an catch exception in AttempLogin class, the doInBackground method which is inside Login.java, and it will keep showing the process dialog "Attempting to Login" :
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String levelaks, jabat;
String username = user.getText().toString();
String password = pass.getText().toString();
try {
// 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());
levelaks = json.getString(TAG_LEVEL_AKSES);
jabat = json.getString(TAG_JABATAN);
level_akses = levelaks;
jabatan = jabat;
namaUser = username;
login_status = "true";
Intent i = new Intent(Login.this, MenuUtama.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();
}catch (NullPointerException e) {
e.printStackTrace();
//THIS IS IT.
}
return null;
}
and to complete the app, i add ConnectivityManager as suggested by #Karl, by following the tutorial here http://www.androidhive.info/2012/07/android-detect-internet-connection-status/. after creating the ConnectionDetector class, i tweak my Login class and it will be like this :
package id.wanda.smkkkristenimmanuelii;
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.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
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.EditText;
import android.widget.Toast;
public class Login extends Activity implements OnClickListener {
private EditText user, pass;
private Button mSubmit;
//ADDED
// flag for Internet connection status
Boolean isInternetPresent = false;
// Connection detector class
ConnectionDetector cd;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// php login script location:
private static final String LOGIN_URL = "http://192.168.1.110:80/smkkimmanuel2/login.php";
// JSON element ids from repsonse of php script:
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private static final String TAG_LEVEL_AKSES = "level_akses";
private static final String TAG_JABATAN = "jabatan";
public static String level_akses = "5", jabatan = "", namaUser = "";
public static String login_status = "false";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// setup input fields
user = (EditText) findViewById(R.id.username);
pass = (EditText) findViewById(R.id.password);
//ADDED
cd = new ConnectionDetector(getApplicationContext());
// setup buttons
mSubmit = (Button) findViewById(R.id.btnLogin);
// register listeners
mSubmit.setOnClickListener(this);
}
#Override
public void onBackPressed() {
Login.this.finish();
startActivity(new Intent(this, MenuUtama.class));
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnLogin:
//ADDED
// get Internet status
isInternetPresent = cd.isConnectingToInternet();
// check for Internet status
if (isInternetPresent) {
// Internet Connection is Present
// make HTTP requests
showAlertDialog(Login.this, "Internet Connection",
"You have internet connection", true);
/*new AttemptLogin().execute();*/
} else {
// Internet connection is not present
// Ask user to connect to Internet
showAlertDialog(Login.this, "No Internet Connection",
"You don't have internet connection.", false);
}
break;
default:
break;
}
}
//ADDED
#SuppressWarnings("deprecation")
public void showAlertDialog(Context context, String title, String message, Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
// Setting alert dialog icon
alertDialog.setIcon((status) ? R.drawable.success : R.drawable.failed);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
// Showing Alert Message
alertDialog.show();
}
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 levelaks, jabat;
String username = user.getText().toString();
String password = pass.getText().toString();
try {
// 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());
levelaks = json.getString(TAG_LEVEL_AKSES);
jabat = json.getString(TAG_JABATAN);
level_akses = levelaks;
jabatan = jabat;
namaUser = username;
login_status = "true";
Intent i = new Intent(Login.this, MenuUtama.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();
}catch (NullPointerException 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();
}
}
}
and it works like a charm, thanks for the help guys. I really appreciate it.
I have an android application that crashes whenever I press the Login button; I keep getting a Null Pointer Exception in my JSONParser. I really hope you can help.
Here is my UserFunctions.java:
package com.example.sabre9.library;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import android.content.Context;
public class UserFunctions {
private JSONParser jsonParser;
// Testing in localhost using wamp or xampp
// use http://10.0.2.2/ to connect to your localhost ie http://localhost/
private static String loginURL = "http://10.0.2.2/Sabre1/";
//private static String registerURL = "http://10.0.2.2/Sabre1/";
private static String login_tag = "login";
//private static String register_tag = "register";
// constructor
public UserFunctions(){
jsonParser = new JSONParser();
}
/**
* function make Login Request
* #param email
* #param password
* */
public JSONObject loginUser(String email, String password){
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", login_tag));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
JSONObject json = jsonParser.makeHttpRequest(loginURL, "POST", params);
// return json
// Log.e("JSON", json.toString());
return json;
}
/**
* function make Register Request
* #param name
* #param email
* #param password
* */
/*
public JSONObject registerUser(String name, String email, String password){
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", register_tag));
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
//getting JSON Object
JSONObject json = jsonParser.makeHttpRequest(registerURL, "POST", params);
// return json
return json;
}*/
/**
* Function get Login status
**/
public boolean isUserLoggedIn(Context context){
DatabaseHandler db = new DatabaseHandler(context);
int count = db.getRowCount();
if(count > 0){
// user logged in
return true;
}
return false;
}
/**
* Function to logout user
* Reset Database
* */
public boolean logoutUser(Context context){
DatabaseHandler db = new DatabaseHandler(context);
db.resetTables();
return true;
}
}
JSONParser.java:
package com.example.sabre9.library;
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;
}
}
And here are my logcat errors:
02-13 03:15:01.921: E/Buffer Error(1263): Error converting result java.lang.NullPointerException: lock == null
02-13 03:15:01.931: E/JSON Parser(1263): Error parsing data org.json.JSONException: End of input at character 0 of
02-13 03:15:02.891: E/Buffer Error(1263): Error converting result java.lang.NullPointerException: lock == null
02-13 03:15:02.891: E/JSON Parser(1263): Error parsing data org.json.JSONException: End of input at character 0 of
Edit: My LoginActivity.java:
package com.example.sabre9;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.example.sabre9.library.DatabaseHandler;
import com.example.sabre9.library.UserFunctions;
public class LoginActivity extends Activity {
Button btnLogin;
//Button btnLinkToRegister;
EditText inputEmail;
EditText inputPassword;
TextView loginErrorMsg;
// JSON Response node names
private static String KEY_SUCCESS = "success";
//private static String KEY_ERROR = "error";
//private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
private class MyAsyncTask extends AsyncTask<String, Void, JSONObject> {
protected JSONObject doInBackground(String... params) {
UserFunctions userFunction = new UserFunctions();
if (params.length != 2)
return null;
JSONObject json = userFunction.loginUser(params[0], params[1]);
return json;
}
protected void onPostExecute(JSONObject json) {
try {
if (json != null && json.getString(KEY_SUCCESS) != null) {
loginErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully logged in
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// Clear all previous From in database
UserFunctions userFunction = new UserFunctions();
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
// Launch Main Screen
Intent main = new Intent(getApplicationContext(), MainActivity.class);
// Close all views before launching Dashboard
main.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(main);
// Close Login Screen
finish();
}else{
// Error in login
loginErrorMsg.setText("Incorrect username/password");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
// Importing all assets like buttons, text fields
inputEmail = (EditText) findViewById(R.id.loginEmail);
inputPassword = (EditText) findViewById(R.id.loginPassword);
btnLogin = (Button) findViewById(R.id.btnLogin);
//btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
loginErrorMsg = (TextView) findViewById(R.id.login_error);
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
new MyAsyncTask().execute(email, password);
}
});
//Link to Register Screen
/*btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
finish();
}
});*/
}
}
Your java.lang.NullPointerException: lock == null occurs >= Android 3.0 because networking is not allowed on the main(UI) thread, unless overridden via StrictMode policy. Try:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Note that as a result, httpClient.execute(httpPost); will lock up the system pretty bad as it waits for the response. (Instead, you might do that in an AsyncTask so it doesn't lock up the main thread.) Hope this helps.
I have fixed this error. Seems that through a very embarassing brain fart I have forgotten to include in my manifest file the internet permissions needed. Also, I have tweaked my php files a little. Thank you for the answers anyways :)