How can I connect to MySQL database with android (PHP)? - java

I have tried almost all the code that have been encountered about this issue.
I leave sample code below.
//select.php
<?php
$host='127.0.0.1';
$uname='root';
$pwd='';
$db="android";
$id=$_REQUEST['id'];
$con = mysql_connect($host,$uname,$pwd) or die("connection failed");
$sqlString = "select * from sample where id='$id' ";
$rs = mysql_query($sqlString);
if($rs){
while($objRs = mysql_fetch_assoc($rs)){
$output[] = $objRs; }
echo json_encode($output); }
mysql_close($con);
?>
//Main Activity
#Override
public void onClick(View v) {
id=e_id.getText().toString();
select();
}
});
}
public void select() {
ArrayList<NameValuePair> nameValuePairs = new
ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id",id));
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/select.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
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());
Toast.makeText(getApplicationContext(), "Invalid IP Address",
Toast.LENGTH_LONG).show();
}
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 2", e.toString());
}
try
{
JSONObject json_data = new JSONObject(result);
name=(json_data.getString("name"));
Toast.makeText(getBaseContext(), "Name : "+name,
Toast.LENGTH_SHORT).show();
}
catch(Exception e)
{
Log.e("Fail 3", e.toString());
} }}
I wrote this to.
<uses-permission android:name="android.permission.INTERNET"/>
//logcat
E/Fail 1: android.os.NetworkOnMainThreadException
E/Fail 2: java.lang.NullPointerException: lock == null
E/Fail 3: java.lang.NullPointerException
When I try to run the application I get the INVALID IP ADDRESS error.
I need some suggestions. What should I try to connect to MySQL database with android (PHP)?

Exception clearly showing that you are calling network operation on main thread that's why it is not working . Use async task for network operation and then it will work. From api level 11 android restricted network operations on main thread and if do this it will throw an error network on main thread exception. And you are getting the same exception.

#Developer_vaibhav I tried the way you said and I got the error again.
mainactivity.class
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://10.0.2.2/login.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, Main2Activity.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);
}
#user2508811 I used mysqli.
//login.php
<?php
define('HOST','localhost');
define('USER','root');
define('PASS','root1234');
define('DB','database');
$con = mysqli_connect(HOST,USER,PASS,DB);
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "select * from users 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
FATAL EXCEPTION: main
java.lang.NullPointerException
MainActivity$1LoginAsync.onPostExecute(MainActivity.java:118)
MainActivity$1LoginAsync.onPostExecute(MainActivity.java:64)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5319)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
I run the application on the emulator and when I click on the button I get the error that stopped the application.

Class inside method? OMG. Make asynctask in isolated .java file and call "new LoginAsync().execute();"

Related

Android sign up user on database

I have been given a registration api to use signup a user onto the backend
But it does not seem to work.Need help.Thanks.
Following is the registration api followed by the code
Params : username, email, pwd(password), cname(company name), cmobile(company mobile number), cwebsite(company website), cfbaddress( company’s fb address), cbssid(company’s bssid)
Link
public class MainActivity extends AppCompatActivity {
EditText inUsername,inEmail,inPassword,inCompanyName,inCompanyWeb,inCompanyPh,inCompanyFb,inBSSid;
TextView txt;
Button btnSignup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inUsername=(EditText)findViewById(R.id.input_user);
inEmail=(EditText)findViewById(R.id.input_email_user);
inCompanyPh=(EditText)findViewById(R.id.input_company_phone_number);
inPassword=(EditText)findViewById(R.id.input_password_user);
inCompanyName=(EditText)findViewById(R.id.input_company_name);
inCompanyFb=(EditText)findViewById(R.id.input_company_fb_address);
inBSSid=(EditText)findViewById(R.id.input_company_bssid);
inCompanyWeb=(EditText)findViewById(R.id.input_company_website);
txt=(TextView)findViewById(R.id.txt_response);
btnSignup=(Button)findViewById(R.id.btn_signup_user);
inUsername.setText("mega");
inEmail.setText("megasu08#gmail.com");
inPassword.setText("password");
inCompanyName.setText("ttd");
inCompanyWeb.setText("<website address as given>");
inCompanyPh.setText("7896325410");
inCompanyFb.setText("<fb address as given>");
inBSSid.setText("48f8b3aa05c5");
btnSignup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
InputStream inputStream = null;
String result = "";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://52.74.103.52/pages/create_user_using_app");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", inUsername.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("email", inEmail.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("pwd", inPassword.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("cname", inCompanyName.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("cwebsite", inCompanyWeb.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("cmobile", inCompanyPh.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("cfbaddress", inCompanyFb.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("cbssid", inBSSid.getText().toString()));
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Content-type", "application/json");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.d("ERROR", httppost.getEntity().toString());
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
inputStream = response.getEntity().getContent();
// 10. convert inputstream to string
if (inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
Log.d("ERROR",inputStream.toString());
Log.d("ERROR",result.toString());
txt.setText(result);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
});
}
private String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
#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);
}
}
LogCat :
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:110)
at libcore.io.IoBridge.connectErrno(IoBridge.java:137)
at libcore.io.IoBridge.connect(IoBridge.java:122)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:456)
at java.net.Socket.connect(Socket.java:882)
at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:124)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:149)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:169)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:124)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:365)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:560)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:492)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:470)
at com.example.anupamchugh.restraunt.MainActivity$1.onClick(MainActivity.java:100)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Please post logcat.It may be due to 'NetworkOnMainThreadException'.Because in your code,network operation is performing from main thread.
NameValuePairs and HttpClients are deprecated. And you cannot perform networking operation in main thread. For performing a post request you can use the following code.
public class RegisterUserClass {
public String sendPostRequest(String requestURL,
HashMap<String, String> postDataParams) {
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
response = br.readLine();
}
else {
response="Error Registering";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
}
Now you just call the sendPostRequest method from an AsyncTask
private void register(String name, String username, String password, String email) {
class RegisterUser extends AsyncTask<String, Void, String>{
ProgressDialog loading;
RegisterUserClass ruc = new RegisterUserClass();
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this, "Please Wait",null, true, true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(String... params) {
HashMap<String, String> data = new HashMap<String,String>();
data.put("name",params[0]);
data.put("username",params[1]);
data.put("password",params[2]);
data.put("email",params[3]);
String result = ruc.sendPostRequest(REGISTER_URL,data);
return result;
}
}
RegisterUser ru = new RegisterUser();
ru.execute(name,username,password,email);
}
Source: Visit For Detailed Explanation

NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I'm Getting this error when runtime my project.
java.lang.NullPointerException: Attempt to invoke virtual method
'boolean java.lang.String.equals(java.lang.Object)' on a null object
reference
at com.example.arhen.tugasrplii.Register$InputData.onPostExecute(Register.java:100)
This is full log :
03-05 03:22:02.822 2575-2575/com.example.arhen.tugasrplii E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.arhen.tugasrplii, PID: 2575
**java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at com.example.arhen.tugasrplii.Register$InputData.onPostExecute(Register.java:100)**
at com.example.arhen.tugasrplii.Register$InputData.onPostExecute(Register.java:54)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
This is my full code on Register.java :
/** * Created by arhen on 05/03/15. */
public class Register extends Activity{
ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText first_name,last_name,email,username,password;
private static String url = "http://127.0.0.1/login/register.php";
Button register;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
register = (Button)findViewById(R.id.btn_register);
first_name = (EditText)findViewById(R.id.fld_first);
last_name = (EditText)findViewById(R.id.fld_last);
email = (EditText)findViewById(R.id.fld_email);
username = (EditText)findViewById(R.id.fld_username);
password = (EditText)findViewById(R.id.fld_pwd);
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new InputData().execute();
}
});
}
public class InputData extends AsyncTask<String, String, String>{
String success;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Register.this);
pDialog.setMessage("Registering Account...");
pDialog.setIndeterminate(false);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
String strfirst_name = first_name.getText().toString();
String strlast_name = last_name.getText().toString();
String stremail = email.getText().toString();
String strusername = username.getText().toString();
String strpassword = password.getText().toString();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("first_name",strfirst_name));
params.add(new BasicNameValuePair("last_name",strlast_name));
params.add(new BasicNameValuePair("email",stremail));
params.add(new BasicNameValuePair("username",strusername));
params.add(new BasicNameValuePair("password",strpassword));
JSONObject json =
jsonParser.makeHttpRequest(url,
"POST", params);
try {
success = json.getString("success");
} catch (Exception e) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
}
});
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
if (success.equals("1")) {
Toast.makeText(getApplicationContext(),"Registration Succesfully",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(),"Registration Failed",Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onBackPressed(){
Intent i = new Intent(getApplicationContext(),Login.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
} }
i thought this error from JSONParser.java, .. this the code :
/**
* Created by arhen on 04/03/15.
*/
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
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();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " +
e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if (method == "POST") {
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new
DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new
UrlEncodedFormEntity(params));
HttpResponse httpResponse =
httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} else if (method == "GET") {
// request method is GET
DefaultHttpClient httpClient = new
DefaultHttpClient();
String paramString =
URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse =
httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new
InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " +
e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
this my register.php code:
<?php
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
$username = $_POST['username'];
$pwd = $_POST['password'];
include 'koneksi.php';
$namaTabel = "akun";
header('Content-Type:text/xml');
$query = "INSERT INTO $namaTabel VALUES('','$first_name','$last_name','$email','$username','$pwd')";
$hasil = mysql_query($query);
if($hasil)
{
$response["success"] = "1";
$response["message"] = "Data has Input";
echo json_encode($response);
}
else
{$response["success"] = "0";
$response["message"] = "Upss, Something Happens! Try again";
// echoing JSON response
echo json_encode($response);
}
?>
I have seen this post :
What is a NullPointerException, and how do I fix it?
and I'm try to give success a string like :
String success ="";
But it didnt Works.. it give this statement error has activated on my code :
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
}
});
I have no idea. Pls Help ..
thanks So Much ...
Looks like this line might be returning null, if String success = "" didn't work:
success = json.getString("success");
Have you inspected the JSON that you are parsing and verified that the "success" field is where you expect and properly formatted?

Send data from java android to webserver with post method

I want to send data from Java Android to mysql php server.
This is my code for button click:
public void loginPost(View view){
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
String result="";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://geospy.zz.mu/default.php");
try {
List <NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("UserName", username));
nameValuePairs.add(new BasicNameValuePair("PassWord", password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null) {
StringBuilder sb = new StringBuilder();
String line;
InputStream instream = entity.getContent();
BufferedReader bf = new BufferedReader(new InputStreamReader(instream));
while ((line = bf.readLine()) != null ) {
sb.append(line).append("\n");
}
result = sb.toString();
Log.i("Read from server", result);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
status.setText(username);
//Intent intent = new Intent(LoginActivity.this, PembukaActivity.class);
//startActivity(intent);
}
This is my code in login.php:
<?php
include("connect.php");
//define $myusername and $mypassword
$myusername = $_POST['UserName'];
$mypassword = $_POST['PassWord'];
//to protect mysql injection
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$mypassword = $mypassword;
$sql = "SELECT ID_MEMBER FROM MEMBER WHERE USERNAME='".$myusername."' and PASSWORD= '".$mypassword."'";
echo $sql;
$result = mysql_query($sql);
//mysql_num_row is counting table row
$count = mysql_num_rows($result);
echo "<script> alert('".$count."')</script>";
if($count == 1)
{
session_start();
$row = mysql_fetch_array($result);
//$_SESSION['login'] = $myusername;
$_SESSION['id_member'] = $row['id_member'];
header('Location: login.php');
}
else
{
header('Location: default.php');
}
?>
I add this permission in manifest:
<uses-permission android:name="android.permission.INTERNET" />
But the application was stopped after i run it. I don't know where is the error.
Try doing your networking in an ASyncTask so that your networking isnt done on the UIThread, i think thats why your crashing
something like this
class TheTask extends AsyncTask<Void,Void,Void>
{
protected void onPreExecute()
{ super.onPreExecute();
}
protected Void doInBackground(Void ...params)
{
loginPost();//View view); // View view replace
// i think even having view as a parameter will crash
// doinbackground method you have to change it i think
}
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
// Back to UIThread, i think handle status.setText(username);
// from here and take it out of your loginPost() method UI operations will
// crash doInBackground(Void ...params)
}
}
then call it in your code like this
new TheTask().execute();
EDIT: well all of your views and whatnot will crash doinbackground method use on PreExecute and OnpostExecute for begining and ending with UIOperations
You need to use AsyncTask.
public class UserLogin extends AsyncTask<ArrayList<String>, Void, String> {
protected String doInBackground(ArrayList<String>... userdata) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.website.com/script.php");
String result = null;
try{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("email", userdata[0].get(0)));
nameValuePairs.add(new BasicNameValuePair("pass", userdata[0].get(1)));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
InputStream is = response.getEntity().getContent();
String line = "";
StringBuilder total = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
while ((line = rd.readLine()) != null) {
total.append(line);
}
result = total.toString();
}
catch(NoHttpResponseException e){
Log.d("resultLoginError", e.getMessage());
}
catch(Exception e){
Log.d("resultLoginOther", e.toString());
}
return result;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected void onPostExecute(String result) {
Log.d("resultOnLogin", "LOGGED?");
}
}
public String Login(String user, String pass) throws InterruptedException, ExecutionException{
ArrayList<String> userdata = new ArrayList<String>();
userdata.add(user);
userdata.add(pass);
return new UserLogin().execute(userdata).get();
}
This is what I personally use for login.
script.php is a PHP file that handles POST values (Username and password) and sends back confirmation to app.

JSONException: Value <br of type java.lang.String cannot be converted to JSONObject

I tried hard to search the solution but I still not manage to solve it. Kindly help. Here my java code : -
public class MainActivity extends Activity {
String project_id;
String id;
InputStream is=null;
String result=null;
String line=null;
int code = 0;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText e_id =(EditText) findViewById(R.id.editText1);
final EditText e_prjId =(EditText) findViewById(R.id.editText2);
Button insert =(Button) findViewById(R.id.button1);
id = e_id.getText().toString();
project_id = e_prjId.getText().toString();
insert.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
insert();
}
});
}
public void insert() {
final ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id",id));
nameValuePairs.add(new BasicNameValuePair("Project_Id",project_id));
new Thread(new Runnable() {
public void run() {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.0.111/insert.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
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());
Toast.makeText(getApplicationContext(), "Invalid IP Address",
Toast.LENGTH_LONG).show();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null){
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
}
catch(Exception e){
Log.e("Fail 2", e.toString());
}
try {
Log.i("tagconvertstr", "["+result+"]");
JSONObject json_data = new JSONObject(result);
code=(json_data.getInt("code"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(code==1)
{
Toast.makeText(getBaseContext(), "Inserted Successfully",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getBaseContext(), "Sorry, Try Again",Toast.LENGTH_LONG).show();
}
}
}).start();
}
php:-
<?php
$uname='root';
$pwd='';
$con = new PDO("mysql:host=192.168.0.111;dbname=wktask", $uname, $pwd);
$ID=$_REQUEST['ID'];
$Project_Id=$_REQUEST['Project_Id'];
$flag['code']=0;
if($r= $con->query("insert into task(ID,Project_Id) values('$ID','$Project_Id')"))
{
$flag['code']=1;
}
echo(json_encode($flag));
?>
I really no idea that what is the reason I keep receive error message from JSON exception error. Really appreciate somemore can help me.
Thanks
Be careful, PHP associative array are case sensitive
You are sending id:
nameValuePairs.add(new BasicNameValuePair("id",id));
which is not equal to ID
In addition to that mistake, you dont check the data in your php script, I rewrote it for you:
$data = array();
if(isset($_POST['id'], $_POST['Project_Id']){
$id=$_POST['id'];
$project_id=$_POST['Project_Id'];
$uname='root';
$pwd='';
$con = new PDO("mysql:host=192.168.0.111;dbname=wktask", $uname, $pwd);
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$stmt = $con->prepare('INSERT INTO task (`ID`, `Project_Id`) values(:id, :project_id)'))
$success = $stmt->execute(array(':id'=>$id, ':project_id'=>$project_id));
if($success){
$data['code'] = 1;
$data['msg'] = 'INSERT successful';
}else{
$data['code'] = 0;
$data['msg'] = 'INSERT Failed';
}
}else{
$data['code'] = 0;
$data['msg'] = 'values are not set';
}
echo(json_encode($data));

Error NullPointerException: lock == null

Can anyone help me with this error please, Select Values from MySQL Database to Android when i run app and search for ID, It always said (Invalid IP Address)...
I have a PHP file on my web server that connects to a WampServer database and retrieves values that are returned to Android app..
String id
String name;
InputStream is=null;
String result=null;
String line;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final EditText e_id=(EditText) findViewById(R.id.editText1);
Button select=(Button) findViewById(R.id.button1);
select.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
id=e_id.getText().toString();
select();
}
});
}
public void select()
{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id",id));
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/test/select.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
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());
Toast.makeText(getApplicationContext(), "Invalid IP Address",
Toast.LENGTH_LONG).show();
}
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 2", e.toString());
}
try
{
JSONObject json_data = new JSONObject(result);
name=(json_data.getString("name"));
Toast.makeText(getBaseContext(), "Name : "+name,
Toast.LENGTH_SHORT).show();
}
catch(Exception e)
{
Log.e("Fail 3", e.toString());
}
}
LogCat Error:
11-17 02:40:58.059: E/Fail 1(1073): android.os.NetworkOnMainThreadException
11-17 02:40:58.079: E/Fail 2(1073): java.lang.NullPointerException: lock == null
11-17 02:40:58.079: E/Fail 3(1073): java.lang.NullPointerException
any help appreciated...
E/Fail 1(1073): android.os.NetworkOnMainThreadException
This error is raised because you run your network connectivity calls (like httpclient) on your main Activity's thread. To get rid of that you need to use another thread for these calls. The easy way to do so would be to use the Async Task

Categories