i'm kind a new to Android, MySQL and PHP. I'm having problem with my project in register page. When i input name and ID value and hit save button, my data is in mysql database, but when i fill the same name and password again and hit save, it's says Data saved to server, instead of error -> if (res.equals("1")) error.setText("Error"). Is anybody got any clue? Thanks.
Here's my code:
register.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TableLayout
android:layout_width="311dp"
android:layout_height="fill_parent"
android:layout_marginLeft="25dp"
android:layout_marginTop="25dp" >
<TextView
android:text="Registration"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="25dp"
/>
<TextView
android:text=""
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="20dp"
/>
<TableRow android:baselineAligned="true" android:layout_width="match_parent">
<TextView
android:text="Name :"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="15dp"
/>
<EditText android:id="#+id/edtname"
android:maxWidth="180sp"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_gravity="center_vertical" >
</EditText>
</TableRow>
<TableRow>
<TextView
android:text="ID no :"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15dp"
/>
<EditText android:id="#+id/edtid"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_gravity="center_vertical"
android:inputType="textPassword">
</EditText>
</TableRow>
<TableRow>
</TableRow>
<TextView
android:text=""
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="20dp"
/>
<TableRow
android:gravity="center"
android:layout_width="match_parent">
<Button android:text="SAVE"
android:id="#+id/btnsave"
android:layout_width="wrap_content"
android:onClick="next"
android:layout_height="wrap_content">
</Button>
<Button android:text="BACK"
android:id="#+id/btnback"
android:onClick="back"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
</TableRow>
<TextView
android:text=""
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="20dp"
/>
<TextView
android:text=""
android:id="#+id/error"
android:gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
android:textSize="20dp"
/>
</TableLayout>
</ScrollView>
Register.java
package com.example.m_vote;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
public class Register extends Activity {
EditText nm,id;
TextView error;
Button save,back;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
nm=(EditText)findViewById(R.id.edtname);
id=(EditText)findViewById(R.id.edtid);
save=(Button)findViewById(R.id.btnsave);
back=(Button)findViewById(R.id.btnback);
error=(TextView)findViewById(R.id.error);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
//TODO Auto-generated method stub
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("name", nm.getText().toString()));
postParameters.add(new BasicNameValuePair("id", id.getText().toString()));
/* String valid = "1";*/
String response = null;
try {
response = CustomHttpClient.executeHttpPost("http://10.0.2.2/appmysql/data.php", postParameters);
String res = response.toString();
res = res.trim();
res = res.replaceAll("\\s+","");
error.setText(res);
if (res.equals("1")) error.setText("Error");
else
{
error.setText("Registration complete! ");
}
}
catch (Exception e) {
id.setText(e.toString());
}
}
});
}
public void back (View theButton)
{
Intent a = new Intent (this,Mainmenu.class);
startActivity(a);
}
}
CustomHttpClient.java
package com.example.m_vote;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
public class CustomHttpClient {
/** The time it takes for our client to timeout */
public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
/** Single instance of our HttpClient */
private static HttpClient mHttpClient;
/**
* Get our single instance of our HttpClient object.
*
* #return an HttpClient object with connection parameters set
*/
private static HttpClient getHttpClient() {
if (mHttpClient == null) {
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}
/**
* Performs an HTTP Post request to the specified url with the
* specified parameters.
*
* #param url The web address to post the request to
* #param postParameters The parameters to send via the request
* #return The result of the request
* #throws Exception
*/
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* Performs an HTTP GET request to the specified url.
*
* #param url The web address to post the request to
* #return The result of the request
* #throws Exception
*/
public static String executeHttpGet(String url) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
data.php
<?php
$nm=$_POST['name'];
$id=$_POST['id'];
$conn = mysql_connect("localhost","root","");
mysql_select_db("projek1");
$query = "INSERT INTO user (ID,name) values ('$id','$nm')";
$result = mysql_query($query) or die("REPORTGagal Query Simpan KRS.");
if (mysql_num_rows($result) == 1){
echo 1;
}
else {
// print status message
echo 0;
}
?>
Related
I am currently working with an app that can access an online game to acquire information of my account. I need to use JSON to communicate with the server. I used the following code to try to communicate with the server, but there are no responds from the server. I also noticed that the httpclient and some other popular class were deprecated and I can't find some proper tutorial to teach me on this topic. Any help is appreciated.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="deardanielxd.travain2.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Username : "
android:id="#+id/Username_Lbl"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:editable="true"
android:minHeight="20dp"
android:layout_alignBottom="#+id/Username_Field"
android:layout_toStartOf="#+id/Username_Field"
android:layout_alignEnd="#+id/Password_Lbl" />
<EditText
android:layout_width="wrap_content"
android:layout_height = "40dp"
android:textAppearance="?android:attr/textAppearanceSmall"
android:id="#+id/Username_Field"
android:editable="true"
android:contextClickable="true"
android:textIsSelectable="true"
android:enabled="true"
android:focusable="true"
android:clickable="true"
android:inputType="text"
android:minHeight="40dp"
android:layout_alignParentTop="true"
android:layout_alignEnd="#+id/Load_Btn"
android:layout_toEndOf="#+id/Password_Lbl" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Password : "
android:id="#+id/Password_Lbl"
android:layout_below="#+id/Username_Lbl"
android:layout_alignParentStart="true"
android:minHeight="20dp"
android:layout_alignBottom="#+id/Password_Field" />
<EditText
android:layout_width="wrap_content"
android:layout_height="40dp"
android:textAppearance="?android:attr/textAppearanceSmall"
android:id="#+id/Password_Field"
android:password="true"
android:editable="true"
android:textIsSelectable="true"
android:enabled="true"
android:focusable="true"
android:contextClickable="true"
android:clickable="true"
android:inputType="text"
android:minHeight="40dp"
android:layout_below="#+id/Username_Field"
android:layout_alignParentEnd="true"
android:layout_alignStart="#+id/Username_Field" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Load"
android:id="#+id/Load_Btn"
android:layout_alignParentEnd="true"
android:layout_alignBottom="#+id/spinner"
android:layout_below="#+id/Password_Field" />
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/spinner"
android:spinnerMode="dropdown"
android:layout_alignParentStart="true"
android:layout_toStartOf="#+id/Load_Btn"
android:layout_below="#+id/Password_Lbl" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/SysMsg"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:text="System : "
android:textColor="#FF0000" />
<ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/scrollView"
android:layout_below="#+id/spinner"
android:layout_alignParentStart="true"
android:layout_above="#+id/SysMsg"
android:layout_alignParentEnd="true" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/OutPut"
android:enabled="true" />
</ScrollView>
MainActivity.java
package deardanielxd.travain2;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class MainActivity extends AppCompatActivity {
Spinner spinner;
EditText Username, Password;
Button Load_Btn;
TextView Main_Output;
TextView Sys_Output;
String server = "";
boolean debug = true;
PlayerInfo curr = new PlayerInfo();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SetupGadget();
attachListener();
}
private void SetupGadget() {
spinner = (Spinner) findViewById(R.id.spinner);
Username = (EditText) findViewById(R.id.Username_Field);
Password = (EditText) findViewById(R.id.Password_Field);
Load_Btn = (Button) findViewById(R.id.Load_Btn);
Main_Output = (TextView) findViewById(R.id.OutPut);
Sys_Output = (TextView) findViewById(R.id.SysMsg);
ArrayAdapter adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,Constants.Servers);
spinner.setAdapter(adapter);
}
private void attachListener() {
Load_Btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (debug) {
MainOutput( "Username : " + Username.getText());
MainOutput( "Password : " + Password.getText());
MainOutput( "Server : " + server);
MainOutput( "Internet Connection : " + (InternetAccess()?"Yes":"No"));
MainOutput( "" );
}
new test(MainActivity.this).execute();
}
});
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
server = parent.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
private void SystemOutput(String output) {
Sys_Output.setText("System : " + output);
}
public void MainOutput(String output) {
Main_Output.append("\n" + output);
}
private boolean InternetAccess() {
ConnectivityManager cm =
(ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
}
public class test extends AsyncTask<Void, Void, Void>
{
private MainActivity MA;
test(MainActivity ma) {
MA = ma;
}
#Override
protected Void doInBackground(Void... n) {
try {
URL url = new URL("http://"+MA.server+"/api/external.php");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type","application/json");
urlConnection.setRequestProperty("Host", "android.schoolportal.gr");
urlConnection.setRequestMethod("POST");
urlConnection.setUseCaches(false);
urlConnection.connect();
OutputStream printout = new DataOutputStream(urlConnection.getOutputStream ());
printout.write(URLEncoder.encode(this.getObj().toString(),"UTF-8").getBytes());
printout.flush ();
printout.close ();
try {
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader r = new BufferedReader(new InputStreamReader(in));
StringBuilder total = new StringBuilder(in.available());
String line;
while ((line = r.readLine()) != null) {
total.append(line).append('\n');
}
MA.MainOutput(total.toString());
MA.MainOutput("End of Doc");
} finally {
urlConnection.disconnect();
return null;
}
} catch (java.net.MalformedURLException e) {
} catch (java.io.IOException e) {
};
return null;
}
private JSONObject getObj() {
JSONObject jobj = new JSONObject();
try {
jobj.put("email","funckybuggy#gmail.com");
jobj.put("siteName","EasyTravian");
jobj.put("sitUrl","testing.com");
jobj.put("public",false);
} catch (org.json.JSONException e) {
}
return jobj;
}
}
public PlayerInfo getCurrentPlayerInfo() {
return this.curr;
}
public void UpdateCurr() {
this.curr.Username = this.Username.getText().toString();
this.curr.Password = this.Password.getText().toString();
this.curr.Server = this.server;
}
}
Constants.java
public class Constants {
public static final String[] Servers = {
"ts1.travian.hk",
"ts2.travian.hk",
"ts20.travian.hk",
"tx3.travian.hk",
"ts4.travian.hk",
"ts19.travian.hk",
"ts3.travian.hk",
"ts6.travian.hk",
"ts5.travian.hk"
};
}
I don't think you should encode the body of the message.
The reason it is called "URLEncoder" is because it is used to encode a URL but this is the body of your message.
Also, the internal try block you have is redundant and also you should change the request method to GET in the middle of the request.
There's no need to flush the bytes.
Remember that with a POST request, nothing is sent until you read the response using your InputStream.
You should use Volley Library for it.
It's very good for the Rest API's.
And managing server calls is simple with it.
Add the library by compiling
compile 'com.android.volley:volley:1.0.0'
then make a Singleton class to handle all the volley requests.
Volley provides JsonArrayRequest and JsonObjectRequest which are very helpful during network calls.
Here is volley singleton class
public class MyApplication extends Application
{
private RequestQueue mRequestQueue;
private static MyApplication mInstance;
#Override
public void onCreate()
{
super.onCreate();
mInstance = this;
}
public static synchronized MyApplication getInstance()
{
return mInstance;
}
public RequestQueue getReqQueue()
{
if (mRequestQueue == null)
{
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToReqQueue(Request<T> req, String tag)
{
getReqQueue().add(req);
}
public <T> void addToReqQueue(Request<T> req)
{
getReqQueue().add(req);
}
public void cancelPendingReq(Object tag)
{
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
Add this to your application tag in manifest
<application
android:name="MyApplication">
This is a sample JsonObjectRequest
JsonObjectRequest request = new JsonObjectRequest("requestMethod","url","input_data",
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response)
{
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
}
});
MyApplication.getInstance().addToReqQueue(request);
I have research on this about how to post a request and receive response from server concurrently which I finally got to some reasonable walk-through but it is not working. Please kindly help.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
process();
} catch(Exception ex){
Log.e("Url Error Encoding", "Url Error Encoding");
}
}
});
}
public void process() throws UnsupportedEncodingException{
Prog = spinner1.getSelectedItem().toString();
Dept = spinner2.getSelectedItem().toString();
Session = spinner3.getSelectedItem().toString();
Semester = spinner4.getSelectedItem().toString();
Level = spinner5.getSelectedItem().toString();
Matric = matric.getText().toString();
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
College = sharedPreferences.getString(Config.COLLEGE_SHARED_PREF,"Not Available");
// Toast.makeText(ProfileActivity.this, Matric + College, Toast.LENGTH_SHORT).show();
// content.setText(Prog);
String data = URLEncoder.encode("program", "UTF-8")
+ "=" + URLEncoder.encode(Prog, "UTF-8");
data += "&" + URLEncoder.encode("dept", "UTF-8") + "="
+ URLEncoder.encode(Dept, "UTF-8");
data += "&" + URLEncoder.encode("session", "UTF-8") + "="
+ URLEncoder.encode(Session, "UTF-8");
data += "&" + URLEncoder.encode("semester", "UTF-8") + "="
+ URLEncoder.encode(Semester, "UTF-8");
data += "&" + URLEncoder.encode("level", "UTF-8") + "="
+ URLEncoder.encode(Level, "UTF-8");
data += "&" + URLEncoder.encode("college", "UTF-8") + "="
+ URLEncoder.encode(College, "UTF-8");
data += "&" + URLEncoder.encode("matric", "UTF-8") + "="
+ URLEncoder.encode(Matric, "UTF-8");
String text = "";
BufferedReader reader=null;
try{
//Send data
URL url = new URL("http://www.example.com/locator/checkresult.php");
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + "\n");
}
text = sb.toString();
} catch(Exception ex){
ex.printStackTrace();
}
finally {
try
{
reader.close();
}
catch(Exception ex) {
ex.printStackTrace();
}
}
// Show response on activity
content.setText(text);
}
My php code
<?php
mysql_connect("localhost", "root", "zzz") or die(mysql_error());
mysql_select_db("sis");
$conn = mysql_connect("localhost", "root", "zzz");
$college = urldecode($_POST['college']);
$program = urldecode($_POST['program']);
$level = urldecode($_POST['level']);
$department = urldecode($_POST['dept']);
$semester = urldecode($_POST['semester']);
$session = urldecode($_POST['session']);
$matric = urldecode($_POST['matric']);
print "$program $level $department";
?>
//My profile.xml
<?xml version="1.0" encoding="UTF-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent">
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="10dp">
<TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="Large Text" android:id="#+id/textView" android:layout_marginBottom="20dp" />
<TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:id="#+id/textView2" android:layout_marginBottom="20dp" />
<TableLayout android:id="#+id/table" android:layout_width="wrap_content" android:layout_height="25dp" android:focusableInTouchMode="true" android:focusable="true" />
<TextView android:id="#+id/content" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="5dp" />
<TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Program" android:layout_marginBottom="5dp" />
<Spinner android:id="#+id/programme" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#fff" android:layout_marginBottom="10dp" />
<TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Level" android:layout_marginBottom="5dp" />
<Spinner android:id="#+id/level" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#fff" android:layout_marginBottom="10dp" />
<TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Department" android:layout_marginBottom="5dp" />
<Spinner android:id="#+id/dept" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#fff" android:layout_marginBottom="10dp" />
<TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Semester" android:layout_marginBottom="5dp" />
<Spinner android:id="#+id/semester" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#fff" android:layout_marginBottom="10dp" />
<TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Session" android:layout_marginBottom="5dp" />
<Spinner android:id="#+id/session" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#fff" android:layout_marginBottom="10dp" />
<TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="8dp" android:textStyle="bold" android:text="Enter your matric number" />
<EditText android:id="#+id/rmatric" android:layout_width="match_parent" android:layout_height="50dp" />
<Button android:id="#+id/checkresult" android:layout_width="match_parent" android:layout_height="match_parent" android:text="Check Result" />
</LinearLayout>
</ScrollView>
Please kindly help. Thanks.
Here is your example code
your php file
<?php
$val =file_get_contents('php://input');
$jsonObj = json_decode($val);
$jsonObj = (object)$jsonObj;
$data1 = $jsonObj->yourkey;
$data2 = $jsonObj->yourkey;
// your sql execution
$returnData = array(
"code" => 500,
"msg" => "UserName Already Exist!! Try with diffrent user Name!!",
);
$a = json_encode($returnData);
echo $a;
die();
?>
here is some java code
//fill your json object with key and value pairs
JSONObject object=new JSONObject();
try {
object.put("key", value);
object.put("key", value);
}catch (JSONException e){}
// make a request this should run on ui thred
String urlString = "";
RestHelper restHelper = new RestHelper(context);
RequestFuture requestFuture = RequestFuture.newFuture();
response = restHelper.postRequestTest(urlString,object,requestFuture);
System.out.println("Json Data" + response.toString() );
//libraries need to compile
compile 'com.mcxiaoke.volley:library:1.0.19'
compile 'com.google.code.gson:gson:2.3'
Here is RestHelper.java
import android.content.Context;
import android.graphics.Bitmap;
import android.widget.ImageView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.RequestFuture;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.naitiks.helpme.Model.HappyMomentsModel;
import com.naitiks.helpme.R;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
/**
* Created by Naitik on 25-04-2016.
*/
public class RestHelper {
private RequestQueue queue = null;
private Context context = null;
public void setQueue(RequestQueue queue) {
this.queue = queue;
}
public RequestQueue getQueue() {
return queue;
}
public RestHelper(Context context){
this.context = context;
queue= Volley.newRequestQueue(context);
}
public JSONObject postRequestTest(String url, final JSONObject userMap,final RequestFuture requestFuture){
JsonObjectRequest postRequest = new JsonObjectRequest(Request.Method.POST, url, userMap,requestFuture,requestFuture);
postRequest.setRetryPolicy(new RetryPolicy() {
#Override
public int getCurrentTimeout() {
return 40000;
}
#Override
public int getCurrentRetryCount() {
return 5;
}
#Override
public void retry(VolleyError volleyError) throws VolleyError {
}
});
queue.add(postRequest);
try {
Object object = requestFuture.get();
System.out.println("*** result" +object.toString());
JSONObject result = (JSONObject)object;
return result;
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return null;
}
}
Why you dont try with volley library and another thing i would like to suggest is use json instead of sending data with url encode.
This is just suggestion.
I need help on this. I am getting error on "getText().toString()" it says "getTEXT METHOD SHOULD BE CALLED FROM THE UI THREAD...".. what does this mean?and when submit the data ,data is not saved on the database. Can someone help me please?I am running out of time already :'(. if there is anything required, let me know.
Here is my code:
SecondScreen.java
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.EditText;
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.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
public class SecondScreen extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText name_eT;
EditText age_eT;
EditText email_eT;
EditText phone_eT;
EditText descr_eT;
private static String url_submit_data = "http://khaty-ismail0.rhcloud.com/phptutorial/submit.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private Button submitButton;
String Name="1";
String Age="1";
String Gender ="1";
String Email ="1";
String Phone ="1";
String IncidentType ="1";
String Description ="1";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_layout);
// Edit Text
inputName = (EditText) findViewById(R.id.name_eT);
age_eT = (EditText) findViewById(R.id.age_eT);
email_eT = (EditText) findViewById(R.id.email_eT);
phone_eT = (EditText) findViewById(R.id.phone_eT);
descr_eT = (EditText) findViewById(R.id.descr_eT);
CheckBox cBoxMale = (CheckBox) findViewById(R.id.checkBoxMale);
CheckBox cBoxFemale = (CheckBox) findViewById(R.id.checkBoxFemale);
Spinner list = (Spinner) findViewById(R.id.spinner);
// Create button
Button submitButton = (Button) findViewById(R.id.subm_btn);
// button click event
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
/*String Name = name_eT.getText().toString();
String Age = age_eT.getText().toString();
String Email = email_eT.getText().toString();
String Phone = phone_eT.getText().toString();
String Description = descr_eT.getText().toString();*/
/*Intent i = new Intent(getApplicationContext(),SubmitData.class);
startActivity(i);*/
new SubmitData().execute(Name, Age, Gender, Email, Phone, IncidentType, Description);
}
});
}
public void onCheckboxClicked(View V) {
boolean checked = ((CheckBox) V).isChecked();
switch (V.getId()) {
case R.id.checkBoxMale:
if (checked);
//Male
else
//No gender
break;
case R.id.checkBoxFemale:
if (checked);
//Female
else
//No gender
break;
}
}
/**
* Background Async Task to Create new product
* */
class SubmitData extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SecondScreen.this);
pDialog.setMessage("Submitting your data...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
//noinspection ResourceType
String Name = name_eT.getText().toString();
//noinspection ResourceType
String Age = age_eT.getText().toString();
String Email = email_eT.getText().toString();
String Phone = phone_eT.getText().toString();
String Description = descr_eT.getText().toString();
String Name = args[0];
String Age = args[1];
String Gender = args [2];
String Email = args[3];
String Phone = args[4];
String IncidentType = args[5];
String Description = args[6];
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Name", Name));
params.add(new BasicNameValuePair("Age", Age));
params.add(new BasicNameValuePair("Gender", Gender));
params.add(new BasicNameValuePair("Email", Email));
params.add(new BasicNameValuePair("Phone", Phone));
params.add(new BasicNameValuePair("Incident Type", IncidentType));
params.add(new BasicNameValuePair("Description", Description));
// getting JSON Object
// Note that create product url accepts POST method
ServiceHandler serviceClient = new ServiceHandler();
String json = serviceClient.makeServiceCall(url_submit_data, ServiceHandler.POST, params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
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("Prediction added successfully ", "> " + jsonObj.getString("message"));
} else {
Log.e("Add Prediction Error: ",
"> " + jsonObj.getString("message"));
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "JSON data error!");
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
}
here is my ServiceHandler.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.util.Log;
public class ServiceHandler {
static String response = null;
static InputStream is = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
Log.d("url", 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;
}
}
here is layout file secondlayout.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="#string/User_info"
android:id="#+id/userInfo"
android:textSize="30sp"
android:textColor="#color/colorFont"
android:textStyle="bold"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"/>
<TextView
android:layout_width="70dp"
android:layout_height="wrap_content"
android:text="Name:"
android:id="#+id/name_tV"
android:textColor="#color/colorFont"
android:layout_marginTop="24dp"
android:layout_below="#+id/userInfo"
android:layout_alignLeft="#+id/userInfo"
android:layout_alignStart="#+id/userInfo" />
<TextView
android:layout_width="70dp"
android:layout_height="wrap_content"
android:text="Age:"
android:id="#+id/age_tV"
android:textColor="#color/colorFont"
android:layout_alignBottom="#+id/age_eT"
android:layout_alignLeft="#+id/name_tV"
android:layout_alignStart="#+id/name_tV" />
<TextView
android:layout_width="70dp"
android:layout_height="wrap_content"
android:text="Gender"
android:id="#+id/gender_tV"
android:textColor="#color/colorFont"
android:layout_above="#+id/email_eT"
android:layout_alignLeft="#+id/age_tV"
android:layout_alignStart="#+id/age_tV" />
<TextView
android:layout_width="70dp"
android:layout_height="wrap_content"
android:text="Email:"
android:id="#+id/email_tV"
android:textColor="#color/colorFont"
android:layout_alignBottom="#+id/email_eT"
android:layout_alignLeft="#+id/gender_tV"
android:layout_alignStart="#+id/gender_tV"
android:layout_marginTop="32dp"/>
<TextView
android:layout_width="70dp"
android:layout_height="wrap_content"
android:text="Phone"
android:id="#+id/phone_tV"
android:textColor="#color/colorFont"
android:layout_alignBottom="#+id/phone_eT"
android:layout_alignLeft="#+id/gender_tV"
android:layout_alignStart="#+id/gender_tV" />
<EditText
android:layout_width="200dp"
android:layout_height="30dp"
android:layout_marginBottom="5dp"
android:inputType="textPersonName"
android:hint="#string/hint_required"
android:textColorHint="#color/colorBackground"
android:background="#drawable/border_style"
android:ems="10"
android:id="#+id/name_eT"
android:textColor="#color/inputFont"
android:layout_alignBottom="#+id/name_tV"
android:layout_alignRight="#+id/userInfo"
android:layout_alignEnd="#+id/userInfo" />
<EditText
android:layout_width="200dp"
android:layout_height="30dp"
android:inputType="number"
android:ems="10"
android:hint="#string/hint_required"
android:textColorHint="#color/colorBackground"
android:background="#drawable/border_style"
android:id="#+id/age_eT"
android:textColor="#color/inputFont"
android:layout_below="#+id/name_eT"
android:layout_alignLeft="#+id/name_eT"
android:layout_alignStart="#+id/name_eT" />
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male"
android:id="#+id/checkBoxMale"
android:onClick="onCheckboxClicked"
android:textColor="#color/colorFont"
android:layout_below="#+id/age_tV"
android:layout_alignLeft="#+id/age_eT"
android:layout_alignStart="#+id/age_eT" />
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"
android:id="#+id/checkBoxFemale"
android:onClick="onCheckboxClicked"
android:textColor="#color/colorFont"
android:layout_alignTop="#+id/checkBoxMale"
android:layout_alignRight="#+id/userInfo"
android:layout_alignEnd="#+id/userInfo" />
<EditText
android:layout_width="200dp"
android:layout_height="30dp"
android:layout_marginBottom="5dp"
android:inputType="textEmailAddress"
android:ems="10"
android:id="#+id/email_eT"
android:hint="#string/hint_required"
android:textColorHint="#color/colorBackground"
android:textColor="#color/inputFont"
android:background="#drawable/border_style"
android:layout_below="#+id/checkBoxMale"
android:layout_alignLeft="#+id/checkBoxMale"
android:layout_alignStart="#+id/checkBoxMale" />
<EditText
android:layout_width="200dp"
android:layout_height="30dp"
android:inputType="phone"
android:ems="10"
android:id="#+id/phone_eT"
android:textColor="#color/inputFont"
android:hint="#string/hint_required"
android:textColorHint="#color/colorBackground"
android:background="#drawable/border_style"
android:layout_below="#+id/email_eT"
android:layout_alignLeft="#+id/email_eT"
android:layout_alignStart="#+id/email_eT" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/incident_info"
android:id="#+id/incidentInfo"
android:textColor="#color/colorFont"
android:textStyle="bold"
android:textSize="30sp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/spinner"
android:prompt="#array/incident_type"
android:entries="#array/incident_type"
android:layout_below="#+id/incidentInfo"
android:layout_alignLeft="#+id/phone_eT"
android:layout_alignStart="#+id/phone_eT"
android:layout_alignRight="#+id/phone_eT"
android:layout_alignEnd="#+id/phone_eT" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="#string/incident_type_DD"
android:textColor="#color/colorFont"
android:id="#+id/incident_DD"
android:layout_below="#+id/incidentInfo"
android:layout_toLeftOf="#+id/spinner"
android:layout_toStartOf="#+id/spinner" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="#string/description"
android:id="#+id/description_tV"
android:textColor="#color/colorFont"
android:layout_below="#+id/spinner"
android:layout_alignLeft="#+id/phone_tV"
android:layout_alignStart="#+id/phone_tV" />
<EditText
android:layout_width="300dp"
android:layout_height="60dp"
android:inputType="textMultiLine"
android:ems="10"
android:id="#+id/descr_eT"
android:hint="#string/descr_hint"
android:textColorHint="#color/colorBackground"
android:gravity="top"
android:background="#drawable/border_style"
android:textColor="#color/inputFont"
android:layout_below="#+id/description_tV"
android:layout_alignLeft="#+id/description_tV"
android:layout_alignStart="#+id/description_tV" />
<Button
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_margin="5dp"
android:text="SUBMIT"
android:onClick="SubmitButton"
android:textStyle="bold"
android:textSize="35sp"
android:id="#+id/subm_btn"
android:background="#drawable/custom_btn"
android:textColor="#color/buttonFont"
android:layout_alignParentBottom="true"/>
</RelativeLayout>
here is my submit.php file:
<?php
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['Name']) && isset($_POST['Age']) && isset($_POST['Email']) && isset($_POST['Phone']) && isset($_POST['Description'])) {
$Name = $_POST['Name'];
$Age = $_POST['Age'];
$Gender = $_POST['Gender'];
$Email = $_POST['Email'];
$Phone = $_POST['Phone'];
$Incident Type = $_POST['Incident Type'];
$Description = $_POST['Description'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO user(Name, Age, Email, Phone, Description VALUES('$Name', '$Age', '$Email', '$Phone', '$Description')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Product successfully created.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
You can't use getText() on UI elements (your EditText-s) as AsyncTask.doInBackground() is run in separate thread and has no access to UI elements.
You are actually doing right by new SubmitData().execute(Name, Age, Gender, Email, Phone, IncidentType, Description); and referring them by args[] from inside doInBackground()
I'm going to create a simple register form app that when user insert their username and password, EditText in UI shows the id of their record in database.
My app insert users into database correctly and show JSON output into EditText.
For Example when I insert first user to my database, EditText show this:
{
"id": "1", "0":"1"
}
But, I want show this in EditText:
1 instead of
{
"id" : "1", "0" : "1"
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00aeef"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="50dp"
android:layout_marginTop="18dp"
android:text="Register Example"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#ffffff" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/textView3"
android:layout_centerHorizontal="true"
android:layout_marginTop="45dp"
android:text="Username:"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#ffffff" />
<EditText
android:id="#+id/edt_username"
android:layout_width="250dp"
android:layout_height="40dp"
android:layout_below="#+id/textView3"
android:layout_centerHorizontal="true"
android:background="#ffffff"
android:ems="10"
android:padding="5dp" >
<requestFocus />
</EditText>
<Button
android:id="#+id/btn_insert"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/edt_result"
android:layout_below="#+id/edt_password"
android:layout_marginTop="16dp"
android:background="#ffffff"
android:text="Insert"
android:textColor="#00aeef" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/textView1"
android:layout_below="#+id/edt_username"
android:text="Password:"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#ffffff" />
<EditText
android:id="#+id/edt_password"
android:layout_width="250dp"
android:layout_height="40dp"
android:layout_alignLeft="#+id/edt_username"
android:layout_below="#+id/textView2"
android:background="#ffffff"
android:ems="10"
android:padding="5dp" />
<EditText
android:id="#+id/edt_result"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_below="#+id/btn_insert"
android:layout_centerHorizontal="true"
android:layout_marginTop="22dp"
android:background="#ffffff"
android:ems="10"
android:padding="5dp" />
</RelativeLayout>
InsertClass.java
package com.example.testphp;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
public class InsertClass extends AsyncTask<String, Void, String>{
private Context context;
private ProgressDialog pDialog;
private EditText edt;
private String json = "";
private JSONObject jObj = null;
public InsertClass(Context context, EditText edt)
{
this.context = context;
pDialog = new ProgressDialog(context);
this.edt = edt;
}
#Override
protected void onPreExecute() {
pDialog.setMessage("Loading... Please wait");
pDialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
try
{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link = "http://10.0.2.2:8020/test/test.php";
String data = URLEncoder.encode("username","utf-8") +
"=" + URLEncoder.encode(username,"utf-8");
data += "&" + URLEncoder.encode("password","utf-8") +
"=" + URLEncoder.encode(password,"utf-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader
(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
json = sb.toString();
jObj = new JSONObject(json);
return sb.toString();
}
catch(JSONExeption e)
{
return new String("Exeption: " + e.getMessage());
}
catch(Exception e)
{
return new String("Exeption: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
super.onPostExecute(result);
try
{
edt.setText(jObj.getString("id"));
}
catch (JSONExeption e)
{ e.printStackTrace(); }
}
}
MainActivity.java
package com.example.testphp;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
String username;
String password;
EditText edtUsername;
EditText edtPassword;
EditText edtResult;
Button btnInsert;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnInsert = (Button) findViewById(R.id.btn_insert);
edtPassword = (EditText) findViewById(R.id.edt_password);
edtUsername = (EditText) findViewById(R.id.edt_username);
edtResult = (EditText) findViewById(R.id.edt_result);
btnInsert.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
username = edtUsername.getText().toString();
password = edtPassword.getText().toString();
new InsertClass(MainActivity.this, edtResult).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.main, menu);
return true;
}
}
test.PHP
<?php
$con = mysqli_connect("localhost" , "root" , "","test");
if(mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_errno();
}
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysqli_query($con,"INSERT INTO test (username,pass) VALUES '$username','$password')") or die(mysqli_query($con));
if($result)
{
$id_result = mysqli_query($con,"SELECT id FROM test WHERE username = '$username'") or die(mysqli_query($con));
if($id_result)
{
$id_result = mysqli_fetch_array($id_result);
$response = array("id" => $id_result);
echo json_encode($response);
}
}
mysqli_close($con);
?>
Any suggestion, would be appreciated ...
Your response from PHP for user id=17 is {"id":{"0":"17","id":"17"}}
Try to change in php script
//$response = array("id" => $id_result);
$response["id"] = $id_result["id"];
then your rsponse will be {"id":"17"}
In your class InsertClass and function doInBackground() where you are converting result string to JsonObject like
json = sb.toString();
jObj = new JSONObject(json);
Add code:
String result = jObj.getString ("id");
Return result;
can someone help me plsss, the error message comes in the textbox on the login form, the error is when i submit my information on the first form it won't go to database instead showing error "error java.net.socketException: permission denied" here's my code:
tambah_user.java
package com.wilis.hellomysql;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
public class tambah_user extends Activity {
EditText un,pw,rpw,nl,al,nt,nh;
RadioGroup jk;
TextView error;
Button simpan,keluar;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tambah_user);
un=(EditText)findViewById(R.id.et_un);
pw=(EditText)findViewById(R.id.et_pw);
rpw=(EditText)findViewById(R.id.et_rpw);
nl=(EditText) findViewById(R.id.et_nama);
jk=(RadioGroup) findViewById(R.id.jekel);
al=(EditText) findViewById(R.id.et_alamat);
nt=(EditText) findViewById(R.id.et_notel);
nh=(EditText) findViewById(R.id.et_nohp);
simpan=(Button)findViewById(R.id.btn_simpan);
keluar=(Button)findViewById(R.id.btn_keluar);
error=(TextView)findViewById(R.id.error);
simpan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//atur variabel utk menampung pilihan jenis kelamin
String type=null;
switch (jk.getCheckedRadioButtonId()) {
case R.id.pria:
type="Pria";
break;
case R.id.perempuan:
type="Perempuan";
break;
}
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", un.getText().toString()));
postParameters.add(new BasicNameValuePair("password", pw.getText().toString()));
postParameters.add(new BasicNameValuePair("repassword", rpw.getText().toString()));
postParameters.add(new BasicNameValuePair("nama", nl.getText().toString()));
postParameters.add(new BasicNameValuePair("jekel", type));
postParameters.add(new BasicNameValuePair("alamat", al.getText().toString()));
postParameters.add(new BasicNameValuePair("nomor_tlp", nt.getText().toString()));
postParameters.add(new BasicNameValuePair("nomor_hp", nh.getText().toString()));
/* String valid = "1";*/
String response = null;
try {
response = CustomHttpClient.executeHttpPost("http://10.0.2.2/appmysql/simpan.php", postParameters);
String res = response.toString();
res = res.trim();
res = res.replaceAll("\\s+","");
error.setText(res);
if (res.equals("1")) error.setText("Data Tersimpan");
else error.setText("Data Tersimpan Ke server");
}
catch (Exception e) {
un.setText(e.toString());
}
}
});
}
public void keluar (View theButton)
{
}
}
CustomHttpClient.java
package com.wilis.hellomysql;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
public class CustomHttpClient {
public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
private static HttpClient mHttpClient;
private static HttpClient getHttpClient() {
if (mHttpClient == null) {
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static String executeHttpGet(String url) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
tambah_user.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ff00ffff"
>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:text="Silakan Masukkan Data Pengguna"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColor="#ff0000ff"
/>
<TableRow android:baselineAligned="true" android:layout_width="match_parent">
<TextView
android:text="Username:"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
/>
<EditText android:id="#+id/et_un"
android:maxWidth="140sp"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_gravity="center_vertical" >
</EditText>
</TableRow>
<TableRow>
<TextView
android:text="Password:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
/>
<EditText android:id="#+id/et_pw"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_gravity="center_vertical"
android:inputType="textPassword">
</EditText>
</TableRow>
<TableRow>
<TextView
android:text="retype-Password:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
/>
<EditText android:layout_height="wrap_content"
android:id="#+id/et_rpw"
android:layout_width="match_parent"
android:inputType="textPassword">
</EditText>
</TableRow>
<TableRow>
<TextView
android:text="Nama Lengkap:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
/>
<EditText android:layout_height="wrap_content"
android:id="#+id/et_nama"
android:layout_width="match_parent">
</EditText>
</TableRow>
<TableRow>
<TextView android:text="Jekel:"
android:textColor="#ff0000ff"/>
<RadioGroup android:id="#+id/jekel">
<RadioButton android:id="#+id/pria"
android:text="Pria"
/>
<RadioButton android:id="#+id/perempuan"
android:text="Perempuan"
/>
</RadioGroup>
</TableRow>
<TableRow>
<TextView
android:text="Alamat:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
/>
<EditText android:layout_height="wrap_content"
android:id="#+id/et_alamat"
android:layout_width="match_parent">
</EditText>
</TableRow>
<TableRow>
<TextView
android:text="Nomor Tlp:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
/>
<EditText android:layout_height="wrap_content"
android:id="#+id/et_notel"
android:layout_width="match_parent">
</EditText>
</TableRow>
<TableRow>
<TextView
android:text="Nomor HP:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
/>
<EditText android:layout_height="wrap_content"
android:id="#+id/et_nohp"
android:layout_width="match_parent">
</EditText>
</TableRow>
<TableRow >
<Button android:text="S I M P A N"
android:id="#+id/btn_simpan"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
<Button android:text="K E L U A R"
android:id="#+id/btn_keluar"
android:onClick="keluar"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
</TableRow>
<TextView
android:text=""
android:id="#+id/error"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
/>
</TableLayout>
</ScrollView>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.wilis.hellomysql"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".tambah_user"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".CustomHttpClient" android:label="#string/app_name">
</activity>
</application>
<uses-sdk android:minSdkVersion="8" />
</manifest>
You have to add the internet permission to you manifiest file:
<uses-permission android:name="android.permission.INTERNET" />
And also Android wont let you do http connections in the main thread, for more info look up:
http://developer.android.com/reference/android/os/AsyncTask.html
You have forgotten the internet permission in your manifest file.
<uses-permission android:name="android.permission.INTERNET" />
After that you will get an networkonmainthreadexception because you are doing web request in the main thread.
Use another AsyncTask or another thread for that.
You did forget too add
<uses-permission android:name="android.permission.INTERNET" />
in your manifest.xml.
But after that you will receive a networkmainthreadexception, to avoid this you need to use AsyncTask or an extra thread. If you get problems to use this things you read this post which may helps you.