I am creating a application which gets the input from edit text and sends a mail acording to the information.I am using Http post to do this i want to communicate with the Php script to send the mail please have a look at my code..
Php script
<?php
$name = $_POST['name'];
$to = $_POST['to'];
$from = $_POST['from'];
$subject = $_POST['subject'];
$message = "From: ".$name."\r\n";
$message .= $_POST['message'];
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
?>
my Activity:
package dolphin.developers.com;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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.apache.http.protocol.HTTP;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import dolphin.devlopers.com.R;
public class misc1 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.eamilspoof);
EditText textw =(EditText) findViewById(R.id.editText1);
final String strd = textw.getText().toString();
EditText textw3 =(EditText) findViewById(R.id.editText2);
final String strd3 = textw3.getText().toString();
EditText textw3d =(EditText) findViewById(R.id.editText3d);
final String strd3d = textw3d.getText().toString();
EditText textw3dd =(EditText) findViewById(R.id.editText3);
final String name = textw3d.getText().toString();
EditText textw3df =(EditText) findViewById(R.id.editText4);
final String subject = textw3d.getText().toString();
Button pds = (Button)findViewById(R.id.button1d);
pds.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String site = "www.dolphin123.net78.net/mailer.php";
String namer1 = name;
String to = strd;
String from = strd3;
String subject1 = subject;
String message = strd3d;
String content = "";
try
{
/* Sends data through a HTTP POST request */
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(site);
List <NameValuePair> params = new ArrayList <NameValuePair> ();
params.add(new BasicNameValuePair("name", namer1));
params.add(new BasicNameValuePair("to", to));
params.add(new BasicNameValuePair("from", from));
params.add(new BasicNameValuePair("subject", subject1));
params.add(new BasicNameValuePair("message", message));
httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
/* Reads the server response */
HttpResponse response = httpClient.execute(httpPost);
InputStream in = response.getEntity().getContent();
StringBuffer sb = new StringBuffer();
int chr;
while ((chr = in.read()) != -1)
{
sb.append((char) chr);
}
content = sb.toString();
in.close();
/* If there is a response, display it */
if (!content.equals(""))
{
Log.i("HTTP Response", content);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
};
}
}
Logcat :
08-10 17:55:20.405: W/System.err(12988): java.lang.IllegalStateException: Target host must not be null, or set in parameters. scheme=null, host=null, path=www.dolphin123.net78.net/mailer.php
08-10 17:55:20.405: W/System.err(12988): at org.apache.http.impl.client.DefaultRequestDirector.determineRoute(DefaultRequestDirector.java:591)
08-10 17:55:20.405: W/System.err(12988): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:293)
08-10 17:55:20.405: W/System.err(12988): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:670)
08-10 17:55:20.405: W/System.err(12988): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:509)
08-10 17:55:20.410: W/System.err(12988): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
08-10 17:55:20.410: W/System.err(12988): at dolphin.developers.com.misc1$1.onClick(misc1.java:87)
08-10 17:55:20.410: W/System.err(12988): at android.view.View.performClick(View.java:4211)
08-10 17:55:20.410: W/System.err(12988): at android.view.View$PerformClick.run(View.java:17267)
08-10 17:55:20.410: W/System.err(12988): at android.os.Handler.handleCallback(Handler.java:615)
08-10 17:55:20.410: W/System.err(12988): at android.os.Handler.dispatchMessage(Handler.java:92)
new Log:
08-05 13:08:17.365: D/SntpClient(73): request time failed: java.net.SocketException: Address family not supported by protocol
Prepend the protocol to the String representation of your URI.
So it should be: "http://www.dolphin123.net78.net/mailer.php"
You can your url with above url with prepend http://
Related
i have a problem with a java code for Android. I will send a httpsRequest and i get back an JSON file. but i get a Error and i dont know why. I hope you can help me.
this is the LogCat what i get:
05-27 10:14:34.779: E/AndroidRuntime(24498): java.lang.RuntimeException: An error occured while executing doInBackground()
05-27 10:14:34.779: E/AndroidRuntime(24498): at android.os.AsyncTask$3.done(AsyncTask.java:300)
05-27 10:14:34.779: E/AndroidRuntime(24498): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
05-27 10:14:34.779: E/AndroidRuntime(24498): at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
05-27 10:14:34.779: E/AndroidRuntime(24498): at java.util.concurrent.FutureTask.run(FutureTask.java:242)
05-27 10:14:34.779: E/AndroidRuntime(24498): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
05-27 10:14:34.779: E/AndroidRuntime(24498): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
05-27 10:14:34.779: E/AndroidRuntime(24498): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
05-27 10:14:34.779: E/AndroidRuntime(24498): at java.lang.Thread.run(Thread.java:818)
05-27 10:14:34.779: E/AndroidRuntime(24498): Caused by: java.lang.IllegalArgumentException: HostnameVerifier is null
05-27 10:14:34.779: E/AndroidRuntime(24498): at javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(HttpsURLConnection.java:128)
05-27 10:14:34.779: E/AndroidRuntime(24498): at com.example.test.JSONTaskRegistrieren.doInBackground(JSONTaskRegistrieren.java:33)
05-27 10:14:34.779: E/AndroidRuntime(24498): at com.example.test.JSONTaskRegistrieren.doInBackground(JSONTaskRegistrieren.java:1)
05-27 10:14:34.779: E/AndroidRuntime(24498): at android.os.AsyncTask$2.call(AsyncTask.java:288)
05-27 10:14:34.779: E/AndroidRuntime(24498): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
05-27 10:14:34.779: E/AndroidRuntime(24498): ... 4 more
My Code is
package com.example.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
public class JSONTaskRegistrieren extends AsyncTask<String, String, String>{
private static final HostnameVerifier HostnameVerifier = null;
#Override
protected String doInBackground(String...params){
String Servicepass;
String SecretToken;
BufferedReader reader = null;
URL url;
try{
url = new URL(params[0]);
HttpsURLConnection.setDefaultHostnameVerifier(HostnameVerifier);
new NullHostnameVerifier();
HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("WWSVC-REQID", "1");
InputStream stream = con.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String output;
while ((output = reader.readLine()) != null){
buffer.append(output);
}
String finalJson = buffer.toString();
//System.out.println(buffer.toString());
JSONObject parentObject = new JSONObject(finalJson);
JSONObject servicepassobjekt = parentObject.getJSONObject("SERVICEPASS");
//System.out.println(servicepassobjekt.toString());
StringBuffer finalBufferedData = new StringBuffer();
JSONObject finalObject = servicepassobjekt;
Servicepass = finalObject.getString("PASSID");
SecretToken = finalObject.getString("APPID");
return finalBufferedData.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
System.out.println(result);
}
}
and this is my Mainclass where i start the Request:
package com.example.test;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import org.json.JSONArray;
import org.json.JSONObject;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("unused")
public void onClick(View v) {
// ServiceURL
String ServiceURL = "https://192.168.0.64";
// Hersteller Hash
String HHash = "fa9b0dec3776ba123eba3049ec9f398h754";
// AppHash
String HAHash = "d20439ab3eabf9ebc3fae2c89b4869ai967";
// AppID
int AppID = 1;
new JSONTaskRegistrieren().execute(ServiceURL + "/WWSVC/WWSERVICE/REGISTER/"+HHash+"/"+HAHash+"/"+AppID+"/");
}});
}
}
Thank you very much for the help.
The piece to look for is the last Caused by: section of a stacktrace. In your case a IllegalArgumentException: HostnameVerifier is null which is caused by your code at com.example.test.JSONTaskRegistrieren.doInBackground(JSONTaskRegistrieren.java:33) (it's the first line mentioning your code)
From this you should find that the offending line of code is
HttpsURLConnection.setDefaultHostnameVerifier(HostnameVerifier);
and that the state of the HostnameVerifier variable at that point in time is null. When you check where assignments to that variable happen you see that the only time you assign something to it is at initialization time.
private static final HostnameVerifier HostnameVerifier = null;
Change that to
private static final HostnameVerifier HostnameVerifier = new NullHostnameVerifier();
and remove the line that did new NullHostnameVerifier();. It's creating a verifier and throws it away immediately since it's not stored in a variable.
HttpsURLConnection.setDefaultHostnameVerifier(HostnameVerifier);
HostnameVerifier argument sent here is null, as globally declared!
What is this statement for?
new NullHostnameVerifier();
Did you want to do HostnameVerfier = new NullHostnameVerifier();?
I think this variable is the cause
private static final HostnameVerifier HostnameVerifier = null;
you should use the following
url = new URL(params[0]);
HttpsURLConnection.setDefaultHostnameVerifier(url);
It is always giving Incorrect credentials, I have double checked the database ,Is there some issue with the code . I am new to android studio,
Any kind of help will be appreciated.
MainActivity
package com.tarun.proxy_maar;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
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.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.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private EditText editTextUserName;
private EditText editTextPassword;
public static final String USER_NAME = "USERNAME";
String username;
String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextUserName = (EditText) findViewById(R.id.editTextUserName);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
}
public void invokeLogin(View view){
username = editTextUserName.getText().toString();
password = editTextPassword.getText().toString();
login(username,password);
}
private void login(final String username, String password) {
class LoginAsync extends AsyncTask<String, Void, String>{
private Dialog loadingDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(MainActivity.this, "Please wait", "Loading...");
}
#Override
protected String doInBackground(String... params) {
String uname = params[0];
String pass = params[1];
InputStream is = null;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", uname));
nameValuePairs.add(new BasicNameValuePair("password", pass));
String result = null;
try{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(
"http://shaadi.web44.net/hello.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String result){
String s = result.trim();
loadingDialog.dismiss();
if(s.equalsIgnoreCase("success")){
Intent intent = new Intent(MainActivity.this, UserProfile.class);
intent.putExtra(USER_NAME, username);
finish();
startActivity(intent);
}else {
Toast.makeText(getApplicationContext(), "Invalid User Name or Password", Toast.LENGTH_LONG).show();
}
}
}
LoginAsync la = new LoginAsync();
la.execute(username, password);
}
#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);
}
}
PHP SCRIPT ON WEBSERVER
<?php
define('HOST','host');
define('USER','user');
define('PASS','password');
define('DB','database');
$con = mysqli_connect(HOST,USER,PASS,DB);
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "select * from login where username='$username' and password='$password'";
$res = mysqli_query($con,$sql);
$check = mysqli_fetch_array($res);
if(isset($check)){
echo 'success';
}else{
echo 'failure';
}
mysqli_close($con);
?>
Logcat
10-11 07:57:42.852 28481-28481/? I/art﹕ Not late-enabling -Xcheck:jni (already on)
10-11 07:57:42.852 28481-28481/? I/art﹕ Late-enabling JIT
10-11 07:57:42.856 28481-28481/? I/art﹕ JIT created with code_cache_capacity=2MB compile_threshold=1000
10-11 07:57:42.897 28481-28488/? E/art﹕ Failed writing handshake bytes (-1 of 14): Broken pipe
10-11 07:57:42.897 28481-28488/? I/art﹕ Debugger is no longer active
10-11 07:57:42.900 28481-28481/? W/System﹕ ClassLoader referenced unknown path: /data/app/com.tarun.proxy_maar-2/lib/x86
10-11 07:57:43.079 28481-28504/? D/OpenGLRenderer﹕ Use EGL_SWAP_BEHAVIOR_PRESERVED: true
10-11 07:57:43.082 28481-28481/? D/﹕ HostConnection::get() New Host Connection established 0xabe7d170, tid 28481
10-11 07:57:43.135 28481-28504/? D/﹕ HostConnection::get() New Host Connection established 0xabe7d480, tid 28504
10-11 07:57:43.141 28481-28504/? I/OpenGLRenderer﹕ Initialized EGL, version 1.4
10-11 07:57:43.311 28481-28504/? W/EGL_emulation﹕ eglSurfaceAttrib not implemented
10-11 07:57:43.311 28481-28504/? W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xad7918a0, error=EGL_SUCCESS
10-11 07:58:56.273 28481-28504/com.tarun.proxy_maar W/EGL_emulation﹕ eglSurfaceAttrib not implemented
10-11 07:58:56.274 28481-28504/com.tarun.proxy_maar W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xad7bf200, error=EGL_SUCCESS
10-11 07:58:56.939 28481-28504/com.tarun.proxy_maar E/Surface﹕ getSlotFromBufferLocked: unknown buffer: 0xab815a40
10-11 07:58:57.128 28481-28504/com.tarun.proxy_maar W/EGL_emulation﹕ eglSurfaceAttrib not implemented
10-11 07:58:57.128 28481-28504/com.tarun.proxy_maar W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa2e1e6c0, error=EGL_SUCCESS
10-11 07:59:00.474 28481-28504/com.tarun.proxy_maar E/Surface﹕ getSlotFromBufferLocked: unknown buffer: 0xab8159d0
I use the jsoup library to post data from my android apps and it's way easier, where's an example
Document doc = Jsoup.connect("http://shaadi.web44.net/hello.php")
.data("username", uname)
.data("password", pass)
.userAgent("some user agent..or not...")
.timeout(30000)
.post();
String httpresponse = doc.text();
I am new to develop an android application. I have read a lot of related post regarding the question I was asking but the tips or solution from the post did not solve my problem. (Looking for the solution for a week already, really need help in order to proceed with my project) Thanks a lot...
Error line No 121
Image LinK
update.java:
package pounkumarpurushothaman.ghssvmm;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Toast;
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 java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class update extends ActionBarActivity {
public static final String KEY_121 ="http://ghssvmm.site40.net/update.php";
static Activity thisActivity = null;
InputStream is = null;
// LinearLayout yy=(LinearLayout)findViewById(R.id.uy);
// LinearLayout pp=(LinearLayout)findViewById(R.id.up);
//LinearLayout cc=(LinearLayout)findViewById(R.id.uc);
//LinearLayout ca=(LinearLayout)findViewById(R.id.uca);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
getServerData();
}
#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_update, 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);
}
private void getServerData() {
thisActivity=this;
EditText f = (EditText) findViewById(R.id.ufst);
EditText l = (EditText) findViewById(R.id.ulst);
Spinner bld=(Spinner)findViewById(R.id.ubld);
Spinner stat=(Spinner)findViewById(R.id.ustatus);
Spinner bth=(Spinner)findViewById(R.id.ubat);
EditText dob = (EditText) findViewById(R.id.udob);
EditText phn1 = (EditText) findViewById(R.id.uphn);
EditText phn2 = (EditText) findViewById(R.id.uphn2);
EditText padd = (EditText) findViewById(R.id.upadd);
EditText radd = (EditText) findViewById(R.id.uradd);
EditText vill = (EditText) findViewById(R.id.uvill);
Spinner sec=(Spinner)findViewById(R.id.usec);
Spinner deg=(Spinner)findViewById(R.id.udeg);
EditText dept = (EditText) findViewById(R.id.udept);
EditText clg = (EditText) findViewById(R.id.uclg);
EditText yop = (EditText) findViewById(R.id.uyop);
EditText pos = (EditText) findViewById(R.id.upos);
EditText cmp = (EditText) findViewById(R.id.ucom);
EditText cadd = (EditText) findViewById(R.id.ucaddr);
String result = "";
//the year data to send
final ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("email","abc#gmail.com"));
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(KEY_121);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Toast.makeText(thisActivity, "Error in http connection " + e.toString(),Toast.LENGTH_LONG).show();
}
}
});
thread.start();
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line+"n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Toast.makeText(this, "Error converting result "+e.toString(),Toast.LENGTH_LONG).show();
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
f.setText(json_data.getString("fname"));
l.setText(json_data.getString("lname"));
dob.setText(json_data.getString("dob"));
switch(json_data.getString("blood")){
case "O Positive":
bld.setSelection(1);
break;
case "O Negative":
bld.setSelection(2);
break;
case "A Positive":
bld.setSelection(3);
break;
case "A Negative":
bld.setSelection(4);
break;
case "B Positive":
bld.setSelection(5);
break;
case "B Negative":
bld.setSelection(6);
break;
case "AB Positive":
bld.setSelection(7);
break;
case "AB Negative":
bld.setSelection(8);
break;
}
switch(json_data.getString("section")) {
case "A":
sec.setSelection(1);
break;
case "B":
sec.setSelection(2);
break;
case "C":
sec.setSelection(3);
break;
}
phn1.setText(json_data.getString("phn"));
phn2.setText(json_data.getString("phn2"));
padd.setText(json_data.getString("add"));
radd.setText(json_data.getString("add2"));
switch(json_data.getString("status")) {
case "Student":
stat.setSelection(1);
/* cc.setVisibility(View.INVISIBLE);
yy.setVisibility(View.INVISIBLE);
pp.setVisibility(View.INVISIBLE);
ca.setVisibility(View.INVISIBLE);*/
break;
case "Employee":
stat.setSelection(2);
/*cc.setVisibility(View.VISIBLE);
yy.setVisibility(View.VISIBLE);
pp.setVisibility(View.VISIBLE);
ca.setVisibility(View.VISIBLE);*/
break;
case "Un Employee":
stat.setSelection(3);
/* cc.setVisibility(View.INVISIBLE);
yy.setVisibility(View.VISIBLE);
pp.setVisibility(View.INVISIBLE);
ca.setVisibility(View.INVISIBLE);*/
break;
}
switch(json_data.getString("degree")) {
case "B.E":
deg.setSelection(1);
break;
case "Arts and Science":
deg.setSelection(2);
break;
case "Medical":
deg.setSelection(3);
break;
}
dept.setText(json_data.getString("dept"));
clg.setText(json_data.getString("clg"));
yop.setText(json_data.getString("yop"));
pos.setText(json_data.getString("pos"));
cmp.setText(json_data.getString("com"));
cadd.setText(json_data.getString("caddr"));
vill.setText(json_data.getString("vill"));
//Get an output to the screen
}
}catch(JSONException e) {
Toast.makeText(this, "Error parsing data " + e.toString(), Toast.LENGTH_LONG).show();
}
}
}
**
Logcat :
**
04-06 14:11:39.580 25919-25919/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: pounkumarpurushothaman.ghssvmm, PID: 25919
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{pounkumarpurushothaman.ghssvmm/pounkumarpurushothaman.ghssvmm.update}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2225)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2388)
at android.app.ActivityThread.access$800(ActivityThread.java:148)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1292)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5312)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
at android.app.Activity.findViewById(Activity.java:2081)
at pounkumarpurushothaman.ghssvmm.update.<init>(update.java:34)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1572)
at android.app.Instrumentation.newActivity(Instrumentation.java:1088)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2215)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2388)
at android.app.ActivityThread.access$800(ActivityThread.java:148)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1292)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5312)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
.
Here's how you get response after your POST request is executed .
HttpResponse response = httpClient.execute(httpPost);
String op = EntityUtils.toString(response.getEntity(), "UTF-8");
Log.d("Response:", op);
i am the newbee in Android Development.
I had developed an app contains a login, the credentials must be passed in the text field and later it will call a webservice.
I am facing the issue as user and password is not getting copied at the required position.
Please help me out.
package com.authorwjf.http_get;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
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.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import android.app.Activity;
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;
public class Main extends Activity implements OnClickListener {
EditText txtUserName;
EditText txtPassword;
#Override
public void onCreate(Bundle savedInstanceState) {
txtUserName=(EditText)this.findViewById(R.id.editText1);
txtPassword=(EditText)this.findViewById(R.id.editText2);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(false);
new LongRunningGetIO().execute();
}
private class LongRunningGetIO extends AsyncTask <Void, Void, String> {
protected String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n>0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n>0) out.append(new String(b, 0, n));
}
return out.toString();
}
#Override
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
String user= txtUserName.getText().toString();
String pass= txtPassword.getText().toString();
System.out.println("USERRRR"+user);
System.out.println(pass);
//String user="at#ril.com";
//String pass= "123456";
String accessTokenQry = "{"+
"\"uid\":\""+user+"\","+
"\"password\":\""+pass+"\","+
"\"consumptionDeviceId\":\"fder-et3w-3adw2-2erf\","+
"\"consumptionDeviceName\":\"Samsung Tab\""+
"}";
HttpPost httpPost = new HttpPost("http://devssg01.ril.com:8080/v2/dip/auth/login");
httpPost.setHeader("Content-Type",
"application/json");
httpPost.setHeader("X-API-Key",
"l7xx7914b8704b2d4b029ab9c4b1b9c66dbf");
StringEntity input;
try {
input = new StringEntity(accessTokenQry);
httpPost.setEntity(input);
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String text = null;
try {
HttpResponse response = httpClient.execute(httpPost, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e) {
return e.getLocalizedMessage();
}
return text;
}
protected void onPostExecute(String results) {
if (results!=null) {
EditText et = (EditText)findViewById(R.id.my_edit);
et.setText(results);
}
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(true);
}
}
}
The LogCat Output is:
08-10 01:20:23.977: W/dalvikvm(760): threadid=14: thread exiting with uncaught exception (group=0x414c4700)
08-10 01:20:23.984: E/AndroidRuntime(760): FATAL EXCEPTION: AsyncTask #4
08-10 01:20:23.984: E/AndroidRuntime(760): java.lang.RuntimeException: An error occured while executing doInBackground()
08-10 01:20:23.984: E/AndroidRuntime(760): at android.os.AsyncTask$3.done(AsyncTask.java:299)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.lang.Thread.run(Thread.java:841)
08-10 01:20:23.984: E/AndroidRuntime(760): Caused by: java.lang.NullPointerException
08-10 01:20:23.984: E/AndroidRuntime(760): at com.authorwjf.http_get.Main$LongRunningGetIO.doInBackground(Main.java:66)
08-10 01:20:23.984: E/AndroidRuntime(760): at com.authorwjf.http_get.Main$LongRunningGetIO.doInBackground(Main.java:1)
08-10 01:20:23.984: E/AndroidRuntime(760): at android.os.AsyncTask$2.call(AsyncTask.java:287)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
08-10 01:20:23.984: E/AndroidRuntime(760): ... 3 more
You are trying to initialize EditTexts before layout loaded.
If you want to get EditText on layout, you must initialize it after layout loaded.
Here is correct code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
txtUserName=(EditText)this.findViewById(R.id.editText1);
txtPassword=(EditText)this.findViewById(R.id.editText2);
}
use this
EditText textw3d =(EditText) findViewById(R.id.editText3d);
final String strd3d = textw3d.getText().toString();
I suggest following change in your code.
Just write following lines
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
above
txtUserName=(EditText)this.findViewById(R.id.editText1);
txtPassword=(EditText)this.findViewById(R.id.editText2);
Move the lines where you get the reference to text views after the setContentView function call:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
txtUserName=(EditText)this.findViewById(R.id.editText1);
txtPassword=(EditText)this.findViewById(R.id.editText2);
}
The fact is you need to call setContentView before initializing any widget in your layout because this is the call that "loads" your layout defined in layout_main.xml file into your activity.
Thanks a lot Guyz,
The issue is resolved now.
Special appreciation to JustWork
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
txtUserName=(EditText)this.findViewById(R.id.editText1);
txtPassword=(EditText)this.findViewById(R.id.editText2);
}
I'm new to android and i would like to create an application that reads data from mysql server. I've taken from web an example about this, but i cannot make it work
I'm using eclipse for this and for the other part, php and mysql.
First of all, here is my php script that is running ok (city.php):
<?php
//connecting to database
$sql=mysql_query("select * from city");
$output = array();
while(list($id,$name)=mysql_fetch_array($sql)){
$output[$id]=$name;
}
print(json_encode($output));
mysql_free_result($sql);
?>
This is returning:
{"1":"Brasov","2":"Bucuresti"}
On my android project from eclipse, I have in the MainActivity.java:
package com.example.mycity;
import android.os.Bundle;
import android.app.Activity;
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.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.net.ParseException;
import android.util.Log;
import android.widget.Toast;
public class MainActivity extends Activity {
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.steagu.ro/android/city.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() != 200) {
Log.d("MyApp", "Server encountered an error.");
}
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
//e.printStackTrace();
Log.e("log_tag", "Error in http connection: "+e.toString());
}
}
}
But when I'm running this, I receive an error on logcat:it's not connecting to the file:Error in http connection: android.os.NetworkOnMainThreadException
10-24 13:04:34.429: I/dalvikvm(982): threadid=3: reacting to signal 3
10-24 13:04:34.649: I/dalvikvm(982): Wrote stack traces to '/data/anr/traces.txt'
10-24 13:04:34.859: E/log_tag(982): Error in http connection: android.os.NetworkOnMainThreadException
10-24 13:04:34.919: I/dalvikvm(982): threadid=3: reacting to signal 3
10-24 13:04:34.949: I/dalvikvm(982): Wrote stack traces to '/data/anr/traces.txt'
10-24 13:04:35.151: D/gralloc_goldfish(982): Emulator without GPU emulation detected.
10-24 13:04:35.479: I/dalvikvm(982): threadid=3: reacting to signal 3
10-24 13:04:35.499: I/dalvikvm(982): Wrote stack traces to '/data/anr/traces.txt'
I have permission for internet in the AndroidManifest.xml:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mycity"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I don't know where is the problem. Can anybody help me with this? Thank you!
You may use an AsyncTask class to carry out your network operations as strictmode does not allow it to be done on the main UI example as follows
public class MainActivity extends Activity {
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new httpRequest().execute();
}
private class httprRequest extends AsyncTask<String, Integer, String>{
#override
public String doInBackground(String.... params){
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.steagu.ro/android/city.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() != 200) {
Log.d("MyApp", "Server encountered an error.");
}
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
//e.printStackTrace();
Log.e("log_tag", "Error in http connection: "+e.toString());
}
}
}
}
}
The problem is this:
10-24 13:04:34.859: E/log_tag(982): Error in http connection:
android.os.NetworkOnMainThreadException
You need to do your network access on a different thread.
Thank you kabuto178, I'm made the changes and it's connecting. I've wrote the code also for retrieving data from mysql, so who need this, can use my example
Here is the code:
package com.example.mycity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
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.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.net.ParseException;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
String result = "";
InputStream is = null;
StringBuilder sb=null;
//String ct_name = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new httprRequest().execute();
int ct_id=0;
String ct_name="";
//Toast.makeText(getBaseContext(), "This is "+result, 3000).show();
try {
Thread.sleep(1000L);
} catch (Exception te) {}
try{
//ct_name = result;
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data= jArray.getJSONObject(i);
ct_id=json_data.getInt("CITY_ID");
ct_name += json_data.getString("CITY_NAME")+":";
}
}
catch(JSONException e1){
e1.printStackTrace();
} catch (ParseException e1) {
e1.printStackTrace();
}
TextView tv1 = (TextView) findViewById(R.id.textView1);
tv1.setText(ct_name);
}
private class httprRequest extends AsyncTask<String, Integer, String>{
#Override
public String doInBackground(String... params){
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.steagu.ro/android/city.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() != 200) {
Log.d("MyApp", "Server encountered an error.");
}
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
//e.printStackTrace();
Log.e("log_tag", "Error in http connection: "+e.toString());
}
//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){
//Toast.makeText(getBaseContext(), "Am eroare aici", 3000).show();
Log.e("log_tag", "Error converting result "+e.toString());
}
/*
Toast.makeText(getBaseContext(), "Here i am", 3000).show();
*/
return result;
}
}
}
I have to change a little bit the code, cause i put a thread.sleep. Instead of it, i have to check if i have a value into result (in a while loop). I think this is happening because at that moment when i try to parse the value, i don;t have a value in result.
The php code is:
<?php
//connecting to database
$sql=mysql_query("select * from city where CITY_NAME like '%'");
$output = array();
while($row=mysql_fetch_assoc($sql)){
$output[]=$row;
}
echo json_encode($output);
mysql_free_result($sql);
?>
Table 'city' has two columns, CITY_ID and CITY_NAME.