Android sign up user on database - java

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

Related

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

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();"

Attempt to invoke virtual method 'int org.json.JSONObject.getInt(java.lang.String)' on a null object reference

I'm trying to check the username/psw on my phpmyadmin database
but I can't figure out the problem.
The logcat gives me this error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int org.json.JSONObject.getInt(java.lang.String)' on a null object reference
Java code:
public class MainActivity extends ActionBarActivity {
// Progress Dialog
private ProgressDialog pDialog;
private String password="";
private String userName="";
JSONParser jsonParser = new JSONParser();
// url to create new product
private static String url_login = "http://localhost/android_connect/get_login.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
Button btnSignIn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSignIn=(Button)findViewById(R.id.buttonSignIN);
}
public void signIn(View V)
{
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.login);
dialog.setTitle("Login");
// get the Refferences of views
final EditText editTextUserName=(EditText)dialog.findViewById(R.id.editTextUserNameToLogin);
final EditText editTextPassword=(EditText)dialog.findViewById(R.id.editTextPasswordToLogin);
Button btnSignIn=(Button)dialog.findViewById(R.id.buttonSignIn);
// Set On ClickListener
btnSignIn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// get The User name and Password
userName=editTextUserName.getText().toString();
password=editTextPassword.getText().toString();
new LoginUser().execute();
}
});
dialog.show();
}
class LoginUser extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Verificoo NomeUtente & Password ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Checking login
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("use_username", userName));
params.add(new BasicNameValuePair("use_psw", password));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_login,
"POST", params);
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS)
if (success == 1) {
//blablabla
} else {
Intent intent = getIntent();
finish();
Toast.makeText(MainActivity.this, "User Name or Password does not match", Toast.LENGTH_LONG).show();
startActivity(intent);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
#miselking
here the class JsonParser
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if (method == "POST") {
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} else if (method == "GET") {
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
check json is not null
if(json!=null){do something}
Error at this line
httpPost.setEntity(new UrlEncodedFormEntity(params));
Use this line
if (params!=null)
httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
and also in GET method use HTTP.UTF_8 instead of "utf-8"

JSON: Value of type java.lang.String cannot be converted to JSONObject

I'm trying to program an app to send a String to a service. A friend of mine has a service to receive the data.
Logcat shows this error: "org.json.JSONException: Value FIRST of type java.lang.String cannot be converted to JSONObject"
Here is my code:
Main Activity
public class MainActivity extends Activity {
private String URL = "String with my friend's url";
private Button btnAddValue;
String num = "1";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RadioGroup answer = (RadioGroup) findViewById(R.id.answer);
answer.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
switch (checkedId) {
case R.id.answerA:
num = "1";
break;
case R.id.answerB:
num = "2";
break;
case R.id.answerC:
num = "3";
break;
}
}
});
btnAddValue = (Button) findViewById(R.id.submit);
btnAddValue.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
new AddNewValue().execute(num);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
private class AddNewValue extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(String... arg) {
// TODO Auto-generated method stub
String number = arg[0];
// Preparing post params
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("number", number));
ServiceHandler serviceClient = new ServiceHandler();
String json = serviceClient.makeServiceCall(URL,
ServiceHandler.POST, params);
Log.d("Create Request: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
boolean error = jsonObj.getBoolean("error");
// checking for error node in json
if (!error) {
// new category created successfully
Log.e("Value added successfully ",
"> " + jsonObj.getString("message"));
} else {
Log.e("Add Error: ",
"> " + jsonObj.getString("message"));
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "JSON data error!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
Service Handler
public class ServiceHandler {
static InputStream is = null;
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
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, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
response = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error: " + e.toString());
}
return response;
}
}
I read questions to other people with the same problem. The solution seemed to be to add a "{" at the beginning of the json String and a "}" at the end, but it didn't work to me. I tried changing this:
String json = serviceClient.makeServiceCall(URL_NEW_PREDICTION,
ServiceHandler.POST, params);
to this:
String json = "{" + serviceClient.makeServiceCall(URL_NEW_PREDICTION,
ServiceHandler.POST, params) + "}";
but the I got this error:
"org.json.JSONException: Expected ':' after FIRST at character 9 of {FIRST DATA New record created successfully}"
You're receiving back a string that is not able to be parsed to JSON. You can't just make something JSON by adding braces, it needs to adhere to proper JSON formatting. This site shows some good examples of what that means.
Specifically, the parser is telling you that having a space after FIRST isn't okay without having quotes around it...but just adding that won't fix the issue, the problem is more deep than that.

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.

String Fails to pass between two activities

I'm passing two strings between two activities and for some strange reason, the strings aren't being passed. I've done all the correct protocols and nothing seems to work, despite tinkering around with the code for several hours, I'm sure it's an simple solution, but I have no clue, what's so ever.
1st Class:
public class LogIn extends Activity implements OnClickListener {
Button ok, back, exit;
TextView result;
EditText pword;
String password;
EditText uname;
String username;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Login button clicked
ok = (Button) findViewById(R.id.btn_login);
ok.setOnClickListener(this);
result = (TextView) findViewById(R.id.lbl_result);
}
//create bracket.
public void postLoginData() {
uname = (EditText) findViewById(R.id.txt_username);
uname.getText().toString();
pword = (EditText) findViewById(R.id.txt_password);
pword.getText().toString();
Bundle basket = new Bundle();
basket.putString("keypass", password);
basket.putString("keyuname", username);
Intent a = new Intent(LogIn.this, ChatService.class );
a.putExtras(basket);
startActivity(a);
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
/* login.php returns true if username and password is equal to saranga */
HttpPost httppost = new HttpPost("http://gta5news.com/login.php");
try {
// Add user name and password
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
Log.w("HttpPost(Login)", "Execute HTTP Post Request(Login 1)");
HttpResponse response = httpclient.execute(httppost);
String str = inputStreamToString(response.getEntity().getContent())
.toString();
Log.w("HttpPost", str);
if (str.toString().equalsIgnoreCase("true")) {
Log.w("HttpPost(Login2)", "TRUE");
result.setText("Login successful");
Intent login = new Intent(LogIn.this, ChatService.class);
startActivity(login);
}else {
Log.w("HttpPost(Login(3)", "FALSE");
result.setText(str);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private StringBuilder inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Return full string
return total;
}
public void onClick(View view) {
if (view == ok) {
postLoginData();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(pword.getWindowToken(), 0);
}
// Click end
}
// if statement
}
// class ends here
2nd class:
public class ChatService extends ListActivity {
/** Called when the activity is first created. */
BufferedReader in = null;
String data = null;
List headlines;
List links;
String GotPass;
String GotUname;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//get strings
Bundle gotData = getIntent().getExtras();
if(gotData !=null) {
GotPass = gotData.getString("keypass");
GotUname = gotData.getString("keyuname");
try {
//listview method
ContactsandIm();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
CheckLogin();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void CheckLogin() throws UnsupportedEncodingException {
// posts login data from "LogIn" class
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
/* login.php returns true if username and password is equal to saranga */
HttpPost httppost = new HttpPost("http://gta5news.com/login.php");
try {
// Add user name and password
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", GotUname));
nameValuePairs.add(new BasicNameValuePair("password", GotPass));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
Log.w("HttpPost(Login)", "Execute HTTP Post Request(ChatService 1)");
HttpResponse response = httpclient.execute(httppost);
String str = inputStreamToString(response.getEntity().getContent())
.toString();
Log.w("HttpPost", str);
if (str.toString().equalsIgnoreCase("true")) {
Log.w("HttpPost(ChatService 2)", "TRUE");
// make toast if str.equals("True")
Toast.makeText(getApplicationContext(), "Yayayaya, loged in", Toast.LENGTH_LONG );
}else {
Log.w("HttpPost(ChatService 3", "FALSE");
Toast.makeText(getApplicationContext(), "failed", Toast.LENGTH_LONG);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private StringBuilder inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Return full string
return total;
}
public void ContactsandIm() throws URISyntaxException,
ClientProtocolException, IOException {
headlines = new ArrayList();
// TODO Auto-generated method stub
BufferedReader in = null;
String data = null;
HttpClient get = new DefaultHttpClient();
URI website = new URI("http://www.gta5news.com/test.php");
HttpGet webget = new HttpGet();
webget.setURI(website);
HttpResponse response = get.execute(webget);
Log.w("HttpPost", "Execute HTTP Post Request");
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
StringBuffer sb = new StringBuffer("");
String l ="";
String nl ="";
while ((l =in.readLine()) !=null) {
sb.append(l + nl);
}
in.close();
data = sb.toString();
if(data.contains("null"));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
headlines.add(data);
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, headlines);
setListAdapter(adapter);
}
// end bracket for "ContactsandIm"
}
Try this way.
Intent a = new Intent(context, MyActivity.class);
a.putExtra("String1", "Hello World");
context.startActivity(a);
and
Bundle extras = getIntent().getExtras();
String s1 = extras.getString("String1");
You should add both 2 activity in Mainfest.xml file
Check have you register your activity in manifest file.

Categories