I have two activites: Mainpage.java and Secondary.java. And I am trying to access the same php file from both the class. When the second class is called the following error is revoked.
java.lang.nullpointerexception.
How can i remove this error?
This is causing the apllication to force close.
Thanks.
This the code for the first class:
void login(){
try{
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://10.0.2.2/ABC/login.php");
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username",et.getText().toString().trim()));
nameValuePairs.add(new BasicNameValuePair("password",pass.getText().toString().trim()));
nameValuePairs.add(new BasicNameValuePair("action","LOGIN"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
response=httpclient.execute(httppost);
final String response = httpclient.execute(httppost, responseHandler);
System.out.println("Response : " + response);
tv.setText("Response from PHP : " + response);
if(response.equalsIgnoreCase("User Found"))
{
Toast.makeText(Axdroid.this,"Login Success",Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),Secondary.class));
} else
{
showAlert();
}
dialog.dismiss();
}catch(Exception e){
System.out.println("Exception : " + e.getMessage());
}
}
And this for the secondary class
void jsr(){
try{
httpclient = new DefaultHttpClient();
httppost= new HttpPost("http://10.0.2.2/AndroidLeave/login.php");
nameValuePairs.add(new BasicNameValuePair("action","SUMMARY"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);
System.out.println(" ++++++++ +++++++++++++"+response);
entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
System.out.println(" ++++++++ After getting data from PHP file +++++++++++++");
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());}
}}
LOGCAT:
10-26 18:10:01.313: W/SingleClientConnManager(2296): Make sure to release the connection before allocating another one.
10-26 18:10:01.964: E/log_tag(2296): Error in http connectionjava.lang.NullPointerException
10-26 18:10:01.974: E/log_tag(2296): Error converting result java.lang.NullPointerException
The error happens because you try to initiate the second connection, but you didn't close the first one.
Since you didn't use and InputStream in the first class, you didn't call, like in the second one, is.close().
I don't quite understand why, in the first class, you make two calls to execute().
You could do this:
delete these two lines
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
and after this line
response=httpclient.execute(httppost);
add:
final String responseString = EntityUtils.toString(response.getEntity());
then use responseString where ever you use response as a String.
If it still happening, add after that
EntityUtils.consume(response.getEntity());
the toString shoud do the consume as well, but just in case it doesn't.
If it still doestn' work, let me know.
Just quickly looking at your code, the exception is probably occurring on this line in the second class:
nameValuePairs.add(new BasicNameValuePair("action","SUMMARY"));
because nameValuePairs is null. You might try adding something like:
nameValuePairs = new ArrayList<NameValuePair>(2);
before you try calling nameValuePairs.add()
Related
i have written an android app which post data to my database. The app should access an webservice which post the data to the database. the webservice works fine. ive testet it with my browser, he is already on the server. now i want my app to execute the webservice. but that doesnt work. My debugger doesnt work too so im not able to debug. here is my code to for accessing the webservice. any ideas??
public class PostBlog extends AsyncTask<String, Void, String> {
String BlogURL;
public PostBlog(String insertBlogURL) {
BlogURL = insertBlogURL;
}
#Override
protected String doInBackground(String... params) {
postBlogData(BlogURL);
return null;
}
public void postBlogData(String url) {
String result = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("year", "1980"));
//http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
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();
result = sb.toString();
} catch (Exception e) {
//(TextView)rootView.findViewById(R.id.question)
Log.e("log_tag", "Error converting result " + e.toString());
}
}
}
The Class is called from my main Activity by
new PostBlog(insertBlogURL).execute("");
Is there another easier way to execute my ".jsp?asdd=sdsd" file on the server?
Thanks for your ideas.
Instead of doing :
new PostBlog(insertBlogURL).execute("");
Change your constructor and retrieve the url from the doInBackground method, by doing params[0]
Then initiate the download like this
PostBlog blogPoster = new PostBlog();
try {
blogPoster.execute(insertBlogURL);
} catch (InterruptedException e) {} catch (ExecutionException e) {}
I should say this is a modified snippet of code from my own project, so it might not work exactly the way you expect.
This question already has answers here:
Android, Java: HTTP POST Request
(8 answers)
Closed 7 years ago.
I am doing a post request in Android. It should give me a response in the form of a string. Thats what i do to check it. However it gives me an empty string back. It's in the toast message. Am i doing something wrong, any hints for me guys?
private void makePostRequest() throws UnsupportedEncodingException {
SharedPreferences postpreference = this.getSharedPreferences("preferences", MODE_PRIVATE);
String password = postpreference.getString("Password", null);
String username = postpreference.getString("Username", null);
String data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
String text = "";
BufferedReader reader = null;
try {
// send post data request
URL url = new URL("secreturl but working");
URLConnection conn = url.openConnection();
OutputStreamWriter streamWriter = new OutputStreamWriter(conn.getOutputStream());
streamWriter.write(data);
streamWriter.flush();
//read the response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
// Append server response in string
sb.append(line + "\n");
}
text = sb.toString();
} catch (Exception ex) {
} finally {
try {
reader.close();
} catch (Exception e) {
}
}
// Show response on activity
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
}
Check for response code. Then only get the response if you are getting the correct response code.
int responseCode = conn.getResponseCode();
I fixed it following the first solution in this link : Android, Java: HTTP POST Request
Thanks for help
Edit : Correct way to do the post request.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
So I'm moving hosting packages from bluehost to namecheap. I'm currently developing an Android application for a university problem. The image upload worked fine on the bluehost webhost. However when I try do the same technique I run into an error.
I've done some debugging and have come to the conclusion that it's server-side related as it's the same code but with parameters changed and nothing on android throws up any errors whatsoever. The entries get added to the database but the image doesn't get uploaded (registration system).
Error:
413 Request Entity Too Large
Request Entity Too Large
The requested resource does not allow request data with GET requests, or the amount of data provided in the request exceeds the capacity limit.
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.
PHP Code:
$user = $_POST['userName'];
$base = $_REQUEST['image'];
$binary = base64_decode($base);
header('Content-Type: bitmap; charset=utf-8');
mkdir('../usr/'.$user);
$file = fopen('../usr/'.$user.'/display_picture.png', 'wb');
fwrite($file, $binary);
fclose($file);
Java Code: (Just incase)
public void uploadDisplayPicture(final ProgressDialog uploadingImage) {
final String UPLOAD_DISPLAY_PICTURE = "Upload Display Picture";
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
Log.d(UPLOAD_DISPLAY_PICTURE,"Do In Background Running");
InputStream is;
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("userName", registrationDetails[0]));
nameValuePairs.add(new BasicNameValuePair("image", encodedString));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Config.IP + Config.DISPLAY_PHOTO_PATH);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) sb.append(line + "\n");
String resString = sb.toString();
is.close();
Log.d("Http Post Response:", response.toString());
Log.d("Http Response:", resString);
} catch (Exception e) {
System.out.println("Error: " + e);
}
return "";
}
#Override
protected void onPostExecute(String msg) {
Log.d(UPLOAD_DISPLAY_PICTURE, "On Post Execute Running");
super.onPostExecute(msg);
uploadingImage.setMessage("Registering User Details...");
new registerUserDetails().execute(registrationDetails);
}
}.execute(null, null, null);
}
I am developing an android app, I have run into a situation where the app will use an API to send some data to the php webservice and the webservice will greate some json encoded message which will be echoed back.
My question is
How Do I store this json message that was sent by php echo into a variable in the android app?
How Do I then go about parsing the json and use the data to construct a switch case?
I had raised a similar question sometime back and was told to use AsyncTask but what I don't understand is why would I need to use it.
The sample json response that will be sent by the phpwebservice is
{"error":false,"message":"New user created"}
I want to be able to get the error variable and decide if there is any error and also get the message in a variable and display it to the user in the app.
I currently have the android signup.java code like this
public void post() throws UnsupportedEncodingException
{
// Get user defined values
uname = username.getText().toString();
email = mail.getText().toString();
password = pass.getText().toString();
confirmpass = cpass.getText().toString();
phone = phn.getText().toString();
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = null;
HttpPost httppost = new HttpPost("http://www.rgbpallete.in/led/api/signup");
if (password.equals(confirmpass)) {
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("uname", uname));
nameValuePairs.add(new BasicNameValuePair("pass", password));
nameValuePairs.add(new BasicNameValuePair("email", email));
nameValuePairs.add(new BasicNameValuePair("phone", phone));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpResponse = httpclient.execute(httppost);
//Code to check if user was successfully created
final int statusCode = httpResponse.getStatusLine().getStatusCode();
switch (statusCode)
{
case 201:
Toast.makeText(getBaseContext(), "Successfully Registered", Toast.LENGTH_SHORT).show();
break;
case 400:
Toast.makeText(getBaseContext(), "Username already taken", Toast.LENGTH_SHORT).show();
username.setText("");
break;
default:
Toast.makeText(getBaseContext(), "Unknown error occurred", Toast.LENGTH_SHORT).show();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
else
{
Toast.makeText(getBaseContext(), "Password mismatch", Toast.LENGTH_SHORT).show();
//Reset password fields
pass.setText("");
cpass.setText("");
}
}
While this checks the http header code and might work( I havent tested it out) I want to use the jsnon response and do the handling using it.
Use java-json:
HttpURLConnection urlConnection = (HttpURLConnection) (uri.toURL().openConnection());
urlConnection.setConnectTimeout(1500);
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("uname", uname));
params.add(new BasicNameValuePair("pass", password));
params.add(new BasicNameValuePair("email", email));
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();
urlConnection.connect();
if(urlConnection.getResponseCode() == 200){
InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader streamReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
while ((inputStr = streamReader.readLine()) != null)
responseStrBuilder.append(inputStr);
JSONObject json = new JSONObject(responseStrBuilder.toString());
String message = json.getString("message");
}
I am trying to send an http post request to a PHP service. Here is an example of how the input may look with some test data
I know that the Java alternative to the PHP associative arrays are HashMaps, but I wonder can this be done with NameValuePairs? What is the best way to format this input and call the PHP service via post request?
Extending #Sash_KP's answer, you can post the nameValuePairs like this too:
params.add(new BasicNameValuePair("Company[name]", "My company"));
params.add(new BasicNameValuePair("User[name]", "My Name"));
Yes this can be done with NameValuePair.You can have something like
List<NameValuePair> params;
//and when making `HttpPost` you can do
HttpPost httpPost = new HttpPost("Yoururl");
httpPost.setEntity(new UrlEncodedFormEntity(params));
//and while building parameters you can do somethin like this
params.add(new BasicNameValuePair("name", "firemanavan"));
params.add(new BasicNameValuePair("cvr", "1245678"));
....
Here's a neat and nice parsing method which you can use.
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
InputStream is = null;
String json = "";
JSONObject jObj = null;
// Making HTTP request
try {
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 {
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();
Log.e("JSON", json);
} 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 jObj;
}
And you can simply use it something like
getJSONFromUrl("YourUrl", params);
Now this is just a basic idea of how you can achieve this using NameValuePair.You will have to need some more workaround to implement exactly as you want, but this should provide you the basic idea.Hope this helps.