.readLine() not getting any value giving result as null - java

The reader.readLine() is returning NULL.
I am trying to send the value from my android to PHP and then get back the result and display it but stuck due to this error.
The database just has name and password. Getting all usernames with the same password.
Thanks in advance.
Java Code:
package com.example.my;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.os.Build;
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#SuppressLint("NewApi")
public class MainActivity extends ActionBarActivity {
String id;
InputStream is = null;
String result = null;
String line = null;
String name = null;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
final EditText et_p = (EditText) findViewById(R.id.etPSWD);
Button b_go = (Button) findViewById(R.id.bGO);
System.out.println("YO");
b_go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
id = et_p.getText().toString();
go();
}
});
}
public void go() {
ArrayList<NameValuePair> pair = new ArrayList<NameValuePair>();
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.2.5/login.php");
pair.add(new BasicNameValuePair("id", id));
httppost.setEntity(new UrlEncodedFormEntity(pair));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
} catch (Exception e) {
Log.e("Fail 1", e.toString());
System.out.println("ERROR IS" + e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address",
Toast.LENGTH_LONG).show();
}
try {
int count = 0;
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "ISO-8859-1"), 8);
System.out.println("READERTOSTRING" + reader.toString());
StringBuilder sb = new StringBuilder();
System.out.println("RANDOM");
/*
*
* ERROR AFTER THIS
*
*/
line = reader.readLine();
System.out.println("VALUE OF LINE:"+line);
while (line != null) {
sb.append(line + "\n");
System.out.println("ROUND" + count + "--" + sb.toString());
count++;
line = reader.readLine();
}
is.close();
result = sb.toString();
System.out.println("RESULT IS " + result);
Log.e("pass 2", "connection success ");
} catch (Exception e) {
Log.e("Fail 2", e.toString());
}
try {
System.out.println("HERE0" + result);
JSONObject json_data = new JSONObject(result);
System.out.println("HERE1");
name = (json_data.getString("success"));
System.out.println("HERE1");
Toast.makeText(getBaseContext(), "Name : " + name,
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Log.e("Fail 3", e.toString());
}
}
#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);
return true;
}
}
THE XML CODE IS:-
<?php
$con = mysqli_connect("localhost","root","sen","test1");
if(mysqli_connect_errno($con))
{
echo "Failed to connect ".mysqli_connect_error();
}
$name=$_GET['name'];
$password=$_GET['password'];
$result = mysqli_query($con,"SELECT name FROM users where name='$name' and password='$password'");
//$result = mysqli_query($con,"SELECT name FROM users");
while($arr = mysqli_fetch_array($result))
{
if (mysql_num_rows($result) > 0) {
$product=array();
$product["name"]=$arr["arr"];
$product["password"]=$arr["password"];
$response["success"]=1;
$response["get"]=array();
array_push($response["get"],$product);
//IF NOT TRY $output[]=$arr;
echo json_encode($response);
}
else
{
$response["success"] = 0;
$response["message"] = "No product found";
echo json_encode($response);
}
}
//print(json_encode($product));
mysqli_close($con);
?>
ERROR
04-21 13:10:44.332: I/System.out(1339): READERTOSTRINGjava.io.BufferedReader#5275e610
04-21 13:10:44.332: I/System.out(1339): RANDOM
04-21 13:10:44.336: I/System.out(1339): VALUE OF LINE:null
04-21 13:10:44.336: I/System.out(1339): RESULT IS
04-21 13:10:44.336: E/pass 2(1339): connection success
04-21 13:10:44.340: I/System.out(1339): HERE0
04-21 13:10:44.344: E/Fail 3(1339): org.json.JSONException: End of input at character 0 of

It looks like maybe your PHP code is not returning any value at all. I'm not sure if this matters, but shouldn't you be using mysqli_num_rows() instead of mysql_num_rows()?
EDIT: $password=$_GET['password']; According to your error, there is no 'password' value sent in your request. Check for a typo, and make sure a value is actually being sent for the password.
EDIT 2: You're using post in your Android code (HttpPost), but get in PHP ($_GET). Change your $_GET to $_REQUEST or $_POST instead.
EDIT 3:
Add password to your select. You are trying to access it from your result array without having selected it in SQL.
$product["name"]=$arr["arr"]; should be $product["name"]=$arr["name"];
EDIT 4:
Move this: $response["get"]=array(); before the while loop, and move this: echo json_encode($response); (both of them) after the while loop. Then you should have a JSON structure like this:
{
"success":1,
"post":[
{"name":"Abc","password":null},
{‌​"name":"Def","password":null},
{"name":"Ghi","password":null‌​},
{"name":"Jkl","password":null},
{"na‌​me":"Mno","password":null}
]
}
As you can see your results are in a JSONArray (signified by the [ ] tags) called "post". So something like this:
JSONArray results = json_data.getJSONObject("post");
for (int i = 0; i < results .size(); i++) {
JSONObject item = results.getJSONObject(i);
String name = item.getString("name");
}

Related

Data insertion Using PHP SQL & Android App

I have created a application for connecting the PHP, Mysql & Android. I am inserting the Name , Price & Description. Layout is good, ids given perfect but the data is not inserting into SQL DB.
package com.oplo.user.demo2;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
/**
* Created by user on 6/2/2015.
*/
#SuppressWarnings("deprecation")
public class addRecord extends Activity {
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
if(android.os.Build.VERSION.SDK_INT > 9)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
final EditText txtA = (EditText) findViewById(R.id.txtA);
final EditText txtB = (EditText) findViewById(R.id.txtB);
final EditText txtC = (EditText) findViewById(R.id.txtC);
final Button getData = (Button) findViewById(R.id.btnSave);
final Button btnBack = (Button) findViewById(R.id.btnBack);
btnBack.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
});
getData.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(txtA.getText().length()<2){
Toast.makeText(getApplicationContext(), "Input Name", Toast.LENGTH_LONG).show();
}if(txtB.getText().length()<2){
Toast.makeText(getApplicationContext(), "Input Price", Toast.LENGTH_LONG).show();
}if(txtC.getText().length()<2){
Toast.makeText(getApplicationContext(), "Input Description", Toast.LENGTH_LONG).show();
}else{
String url = "http://www.xyz.in/demo.php";
List params = new ArrayList();
//noinspection deprecation
params.add(new BasicNameValuePair("strA", txtA.getText().toString()));
params.add(new BasicNameValuePair("strB", txtB.getText().toString()));
params.add(new BasicNameValuePair("strC", txtC.getText().toString()));
#SuppressWarnings("unused")
String resultServer = getHttpPost(url,params);
//result.setText(resultServer);
Toast.makeText(addRecord.this, "1 Record inserted...", Toast.LENGTH_LONG).show();
emtyText();
txtA.requestFocus();
}
}
public void emtyText(){
txtA.setText("");
txtB.setText("");
txtC.setText("");
}
});
}
public String getHttpPost(String url,List params) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
HttpResponse response = client.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Status OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
} else {
Log.e("Log", "Failed to download result..");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}
}
PHP Code:
<?php
$host = "localhost";
$user = "xcxc";
$pass = "xcxc";
$database = "xcxc";
$con = mysql_connect($host, $user, $pass) or die("Cannot connect Database");
mysql_select_db($database) or die("Cannot select Database.");
$a = $_POST["strA"];
$b = $_POST["strB"];
$c = $_POST["strC"];
$sql = "INSERT INTO demo (name, price, description) VALUES('$a', '$b', '$c')";
$result = mysql_query("SET NAMES 'UTF8'", $con);
$result = mysql_query($sql, $con);
if(!$result){
die ('Error: '.mysql_error($con));
}
//echo "1 record added...";
mysql_close($con);
Heres my code, but the data is not inserting into SQL.
Please let me know wheres the problem in this code.
thanks in advance.
You are not allowed to do any network related stuff on your main thread,go for asynctask or retrofit.
this link may help
http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/

Error converting result java.lang.NullPointerException: lock == null and Error parsing data org.json.JSONException: End of input at character 0 of

Here is the relevant log-cat information:
11-09 16:45:47.354 5149-5149/com.example.apex.apex E/Buffer Error﹕ Error converting result java.lang.NullPointerException: lock == null
11-09 16:45:47.354 5149-5149/com.example.apex.apex E/JSON Parser﹕ Error parsing data org.json.JSONException: End of input at character 0 of
11-09 16:45:47.354 5149-5149/com.example.apex.apex D/AndroidRuntime﹕ Shutting down VM
11-09 16:45:47.354 5149-5149/com.example.apex.apex W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41bd9ce0)
Process: com.example.apex.apex, PID: 5149
java.lang.NullPointerException
at com.example.apex.apex.RegisterActivity$1.onClick(RegisterActivity.java:70)
at android.view.View.performClick(View.java:4445)
at android.view.View$PerformClick.run(View.java:18446)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5146)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:732)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
at dalvik.system.NativeStart.main(Native Method)
11-09 16:46:36.686 5149-5149/com.example.apex.apex I/Process﹕ Sending signal. PID: 5149 SIG: 9
RegisterActivity.java:
I am new to Java and Android development, therefore I am initially hard-coding data to communicate with a remote server through PHP.
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class RegisterActivity extends Activity {
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
Button btnRegister;
TextView registerErrorMsg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
if(Build.VERSION.SDK_INT > 8)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
// import all assets
btnRegister = (Button) findViewById(R.id.btnRegister);
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// inputs
String fName = "John";
String lName = "Smith";
String email = "someone#example.com";
String password = "123345";
String location = "Sligo";
String dob = "07-10-1993";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
java.util.Date date = null;
try {
date = sdf.parse(dob);
} catch (ParseException e) {
e.printStackTrace();
}
java.sql.Date sqlDob = new Date(date.getTime());
String gender = "Male";
int height = 128;
double weight = 78.5;
CyclistFunctions cyclistFunction = new CyclistFunctions();
JSONObject json = cyclistFunction.registerCyclist(fName, lName, email, password,
location, sqlDob, gender, height, weight);
// check for register response
try {
if (json.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1) {
// user successfully registered
// store user details in SQLite DB
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// clear all previous data in database
finish();
} else {
registerErrorMsg.setText("Error in registration occurred! :/");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.register, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
activity_register.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.example.apex.apex.RegisterActivity">
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/btnRegister"
android:text="Click!"/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/btnRegister"
android:layout_marginTop="50dp"/>
JSONParser.java
package com.example.apex.apex;
import android.util.Log;
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.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
// make HTTP request
try {
// creates a new HTTP client from parameters and a connection manager
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();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
// buffer input from is
BufferedReader reader = new BufferedReader(new InputStreamReader
(is, HTTP.UTF_8), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try to parse the string to JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
CyclistFunctions.java
package com.example.apex.apex;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
public class CyclistFunctions {
private JSONParser jsonParser;
private static final String registerURL = "http://127.0.0.1/apexdb/include/db_functions.php/";
private static String register_tag = "register";
// constructor
public CyclistFunctions() {
jsonParser = new JSONParser();
}
/**
* make register request
*/
public JSONObject registerCyclist(String first_name, String last_name, String email_address,
String password, String location, Date birth_date, String gender,
int height_cm, double weight_kg) {
// build parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", register_tag));
params.add(new BasicNameValuePair("first_name", first_name));
params.add(new BasicNameValuePair("last_name", last_name));
params.add(new BasicNameValuePair("email_address", email_address));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("location", location));
params.add(new BasicNameValuePair("birth_date", String.valueOf(birth_date)));
params.add(new BasicNameValuePair("gender", gender));
params.add(new BasicNameValuePair("height_cm", String.valueOf(height_cm)));
params.add(new BasicNameValuePair("weight_kg", String.valueOf(weight_kg)));
// fetch JSON object
JSONObject json = jsonParser.getJSONFromUrl(registerURL, params);
// return json
return json;
}
}
db_functions.php
<?php
class DB_Functions {
private $db;
// constructor
function __construct() {
require_once 'db_connect.php';
// connecting to database
$this->db = new db_connect();
$this->db->connect();
}
// destructor
function __destruct() {
}
/**
Storing new cyclist
return user details
**/
public function storeCyclist($first_name, $last_name, $email_address,
$password, $birth_date, $gender, $height_cm, $weight_kg) {
$hash = $this->hashSSHA($password);
$encrypted_password = $hash["encrypted"]; // password
$salt = $hash["salt"]; // salt
$result = mysqli_query("INSERT INTO cyclist (first_name, last_name, email_address,
encrypted_password, salt, birth_date, gender, height_cm, weight_kg, date_created)
VALUES ('$first_name', '$last_name', '$email_address', '$encrypted_password', '$salt', '$birth_date',
'$gender', '$height_cm', '$weight_kg', NOW())");
if($result) {
// successfully inserted cyclist into database
$response["success"] = 1;
$response["message"] = "Cyclist succesfully created";
// echo JSON response
echo json_encode($response);
} else {
// insert fail
$response["success"] = 1;
$response["message"] = "Woops, something went wrong - failed to create new cyclist! :(";
}
}
public function userExists($email_address) {
$result = mysqli_query("SELECT email_address from cyclist WHERE email_address = '$email_address'");
$no_of_rows = mysqli_num_rows($result);
if($no_of_rows > 0) {
// user exists
return true;
} else {
// user exists
return false;
}
}
/**
encrypt password
#param password
returns salt
**/
public function hashSSHA($password) {
$salt = sha1(rand());
$salt = substr($salt, 0, 10);
$encrypted = base64_encode(sha1($password . $salt, true) . $salt);
$hash = array("salt" => $salt, "encrypted" => $encrypted);
return $hash;
}
/**
decrypting password
#params salt, password
returns hash string
**/
public function checkSSHA($salt, $password) {
$hash = base64_encode(sha1($password . $salt, true) . $salt);
return $hash;
}
}
?>
DB_Connect.php
<?php
class DB_Connect {
// constructor
function __construct() {
}
// destructor
function __destruct() {
// $this->close();
}
// connecting to database
public function connect() {
require_once 'config.php';
// connecting to mysqli
$con = new mysqli_connect($db_host, $db_user, $db_password, $db_name);
// check connection
if(mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " .mysqli_connect_errno();
}
// return db handler
return $con;
}
public function close() {
// close connection
mysqli_close();
}
}
?>
You have not given value to registerErrorMsg due to this you are getting null pointer.
registerErrorMsg = (TextView) findViewById(R.id.registerErrorMsg);
i think this will solve your problem.
You must post your json model and cyclistic functions in order to identify exact issues.
This line is creating errors
JSONObject json = cyclistFunction.registerCyclist(fName, lName, email, password,
location, sqlDob, gender, height, weight);
It has to be like this
String result_json = cyclistFunction.registerCyclist(fName, lName, email, password,location, sqlDob, gender, height, weight);
if (result_json != null) {
try {
JSONObject jsonObj = new JSONObject(result_json );
if (jsonObj != null) {
String res = json.getString(KEY_SUCCESS);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}

Error in parsing data NullPointerException

I am working in a simple android application and i am trying to retrieve data from mysql database on localhost. Below is the code that i have written so far.The error that i am getting is the following:
Error in parsing data java.lang.NullPointerException
I used the debugger to check if the retrieved data is correct. And it is. The retrieved data is : [{"CropID":"1","CropName":"Corn"},{"CropID":"2","CropName":"Wheat"}]
What i am getting that error?
package com.testexternaldatabase;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView resultView;
#SuppressLint("NewApi") #Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(android.os.Build.VERSION.SDK_INT > 9){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
System.out.println("*** My thread is now configured to allow connection");
}
setContentView(R.layout.activity_main);
resultView = (TextView) findViewById(R.id.result);
getData();
}
public void getData(){
String result = "";
InputStream isr = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.0.2.2:8080/android_connect/getCrops.php");
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
isr = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
resultView.setText("Could not connect to the database");
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(isr),8);
StringBuilder sb = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
sb.append(line + "\n");
}
isr.close();
result = sb.toString();
System.out.println(result);
} catch (Exception e) {
Log.e("log_tag", "Error in converting result " + e.toString());
}
//parse json data
try {
String s = "";
JSONArray jArray = new JSONArray(result);
int id = 0;
String name = null;
for(int i = 0 ; i < jArray.length(); i++){
JSONObject json = jArray.getJSONObject(i);
if(json != null){
id = json.getInt("CropID");
name = json.getString("CropName");
}
s = s + "Crop ID: " + id + "\n" + "Crop Name: " + name + "\n\n";
}
resultView.setText(s);
} catch (Exception e){
Log.e("log_tag", "Error in parsing data " + e.toString());
}
}
}
LOG CAT

unable to call method

I'm trying to implement ZXing barcode scanner into my program. After getting the scanned result, I wanted to parse the result to a method named getData() which belong to another Java class. No syntax error on IDE, but mysql.getData(contents) won't call the method no matter what. Please advise.
If I put this code under onCreate, the whole program force closed:
package com.posQR.ip;
import com.posQR.ip.MySQL;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class PosQRActivity extends Activity{
MySQL mysql;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mysql.getData("productID");
Button button = (Button)findViewById(R.id.button1);
button.setOnClickListener(scanListener);
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
TextView textView = (TextView)findViewById(R.id.textView1);
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
try {
String contents = intent.getStringExtra("SCAN_RESULT");
Toast.makeText(getApplicationContext(), contents + "from main", Toast.LENGTH_LONG).show();
mysql.getData(contents);
String string = Double.toString(mysql.getPrice());
textView.setText(string);
}
catch (Exception e) {
Toast.makeText(getApplicationContext(), "Please scan on the product's QR Code.", Toast.LENGTH_LONG).show();
}
} else if (resultCode == RESULT_CANCELED) {
// Handle cancel
}
}
}
private OnClickListener scanListener = new OnClickListener() {
public void onClick(View v) {
try{
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);
}
catch (Exception e){
Toast.makeText(getApplicationContext(), "error opening scanner.", Toast.LENGTH_SHORT).show();
}
}
};
}
.
package com.posQR.ip;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.net.ParseException;
import android.util.Log;
import android.widget.Toast;
public class MySQL{
double Price;
private Context localContext;
public void getData(String productID) {
InputStream is = null;
String result = "";
Toast.makeText(localContext.getApplicationContext(), productID, Toast.LENGTH_LONG).show();
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id",productID));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://dl.dropbox.com/u/11233767/mysqlRequest.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
//convert response to string
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(localContext.getApplicationContext(), "Error converting result.", Toast.LENGTH_LONG).show();
}
//paring data
try{
JSONArray jArray = new JSONArray(result);
JSONObject json_data=null;
json_data = jArray.getJSONObject(0);
Price=json_data.getDouble("price");
}
catch(JSONException e1){
Toast.makeText(localContext.getApplicationContext(), "No City Found" ,Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
}
public double getPrice(){
return Price;
}
}
There are many problems here, such as:
the mysql variable is null when you use it in onCreate, you must declare it.
The localContext object in MySql is never initialized, which will cause another NullPointerException when you call getData(). You should create a constructor that accepts a Context object for the MySql class, and use that constructor when you're fixing the first problem. Alternatively you could pass a Context object to getData()
the getData() method accesses the network in the main/UI thread, which will cause another Exception. Call this method in a different thread or spin off a new thread within the method itself. You may want to use an AsyncTask

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