#android #connection #wamp
#Android #подключение #wamp
Вопрос:
Я пытаюсь вставить значения на сервер MySQL, но ничего не произошло.
Вот мой код..
@Override
protected String doInBackground(String... strings) {
String reg_url="http://192.168.43.198:80/android_connect/insert_to_profile_table.php";
String f_name = first_name.getText().toString();
String l_name = last_name.getText().toString();
String address = p_address.getText().toString();
String phne_hme = phne_home.getText().toString();
String phne_ofice = phne_office.getText().toString();
String State = state_spinner.getSelectedItem().toString();
String district = district_spinner.getSelectedItem().toString();
try {
URL url=new URL(reg_url);
HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream os=httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter=new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
String data= URLEncoder.encode("first_name","UTF-8") "=" URLEncoder.encode(f_name,"UTF-8") "amp;"
URLEncoder.encode("last_name","UTF-8") "=" URLEncoder.encode(l_name,"UTF-8") "amp;"
URLEncoder.encode("address","UTF-8") "=" URLEncoder.encode(address,"UTF-8") "amp;"
URLEncoder.encode("state","UTF-8") "=" URLEncoder.encode(State,"UTF-8") "amp;"
URLEncoder.encode("district","UTF-8") "=" URLEncoder.encode(district,"UTF-8") "amp;"
URLEncoder.encode("email","UTF-8") "=" URLEncoder.encode(phne_hme,"UTF-8");
//System.out.print(data.toString());
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
os.close();
InputStream IS=httpURLConnection.getInputStream();
IS.close();
return "Registration Successful";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Logcats :
D /WindowClient: добавить в mViews: DecorView@ef0b228[], this = android.view .WindowManagerGlobal@6d9edde D/OpenGLRenderer: CanvasContext() 0x95130800 D/ViewRootImpl[Profile_add]: аппаратное ускорение включено, this = ViewRoot{4906488 com.indiamission.mission/com.indiamission.mission.Profile_add,ident = 4} I/System.out: [сокет] [1] подключение /192.168.43.198:80;LocalPort=-1(0) D/: [Posix_connect Debug]Процесс com.indiamission.mission :80 Ввод / вывод: ввод в цикл while. D/Surface: Surface::allocateBuffers(this=0x957f9c00) D / OpenGLRenderer: CanvasContext() 0x95130800 инициализировать окно = 0x957f9c00, заголовок=com.indiamission.mission/com.indiamission.mission.Profile_add D/Surface: Surface::connect(this=0x957f9c00,api= 1) W/ libEGL: [ANDROID_RECORDABLE] формат: 1 D / mali_winsys: EGLint new_window_surface(egl_winsys_display*, void*, EGLSurface, EGLConfig, egl_winsys_surface**, egl_color_buffer_format*, EGLBoolean) возвращает 0x3000 D/OpenGLRenderer:~ CanvasContext() 0x9512d000 D / GraphicBuffer: регистр, дескриптор (0x95177600) (w: 552 h: 270 s: 560 f: 0x1 u: 0x000b00) D / GraphicBuffer: регистр, дескриптор (0x95177780) (w: 552 h: 270 s: 560 f: 0x1 u: 0x000b00) D/ GraphicBuffer: register, handle(0x95177840) (w: 552 h: 270 s: 560 f: 0x1 u: 0x000b00) I / System.out: [сокет] [/ 192.168.43.222:40230] подключенный I / System.out: проверка isMmsSendPdu PDU чтение len: 8192 MMS Тип PDU: 102: 105 I / System.out: [OkHttp] sendRequest>> I /System.out: [OkHttp] sendRequest<<
И ничего не происходит. Спасибо всем.
Ответ №1:
String ServerURL = "your_php_file_url" ;
EditText first_name, last_name,p_address,phne_home,phne_office ;
Button button;
Spinner state_spinner,district_spinner;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activity_name);
/*==================================================================
Bind Your spinners and Edittext with the IDs Here
====================================================================*/
fname = (EditText)findViewById(R.id.fname);
/*==================================================================
Bind Your spinners and Edittext with the IDs ABove ^^^
====================================================================*/
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
GetData();
InsertData(f_name,l_name,address,phne_hme,phne_ofice,State,district);
}
});
}
public void getData(){
String f_name = first_name.getText().toString();
String l_name = last_name.getText().toString();
String address = p_address.getText().toString();
String phne_hme = phne_home.getText().toString();
String phne_ofice = phne_office.getText().toString();
String State = state_spinner.getSelectedItem().toString();
String district = district_spinner.getSelectedItem().toString();
}
public void InsertData(final String fname, final String lname,final String address,final String phne_hme, final String phn_ofice, final String State, final String district){
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
String f_nameHolder = fname;
String l_nameHolder = lname;
String addressHolder = address;
String phne_hmeHolder = phne_hme;
String phne_oficeHolder = phne_ofice;
String StateHolder = State;
String districtHolder = district;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("replace these names with your key given in PHP files", f_nameHolder));
nameValuePairs.add(new BasicNameValuePair("replace these names with your key given in PHP files",l_nameHolder));
nameValuePairs.add(new BasicNameValuePair("replace these names with your key given in PHP files", addressHolder));
nameValuePairs.add(new BasicNameValuePair("replace these names with your key given in PHP files", phne_hmeHolder));
nameValuePairs.add(new BasicNameValuePair("replace these names with your key given in PHP files", phne_oficeHolder));
nameValuePairs.add(new BasicNameValuePair("replace these names with your key given in PHP files", StateHolder));
nameValuePairs.add(new BasicNameValuePair("replace these names with your key given in PHP files", districtHolder));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(ServerURL);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return "Data Inserted Successfully";
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(MainActivity.this, "Data Submit Successfully", Toast.LENGTH_LONG).show();
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(fname,lname,address,phne_hme,phn_ofice,State,district);
}
Не забудьте добавить Org.Apache.Http.Legacy эта зависимость в вашем файле gradle.
Ответ №2:
Я правильно понял, используя эту ссылку.
@Override
protected String doInBackground(String... strings) {
String f_name = first_name.getText().toString();
String l_name = last_name.getText().toString();
String address = p_address.getText().toString();
String phne_hme = phne_home.getText().toString();
String phne_ofice = phne_office.getText().toString();
String State = state_spinner.getSelectedItem().toString();
String district = district_spinner.getSelectedItem().toString();
String email_ = email.getText().toString();
HttpURLConnection conn;
URL url = null;
try {
// Enter URL address where your php file resides
url = new URL(getString(R.string.link) "insert_to_profile_table.php");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
conn.setDoOutput(true);
OutputStream os=conn.getOutputStream();
BufferedWriter bufferedWriter=new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
String data= URLEncoder.encode("first_name","UTF-8") "=" URLEncoder.encode(f_name,"UTF-8") "amp;"
URLEncoder.encode("last_name","UTF-8") "=" URLEncoder.encode(l_name,"UTF-8") "amp;"
URLEncoder.encode("address","UTF-8") "=" URLEncoder.encode(address,"UTF-8") "amp;"
URLEncoder.encode("state","UTF-8") "=" URLEncoder.encode(State,"UTF-8") "amp;"
URLEncoder.encode("district","UTF-8") "=" URLEncoder.encode(district,"UTF-8") "amp;"
URLEncoder.encode("phone_number1","UTF-8") "=" URLEncoder.encode(phne_hme,"UTF-8") "amp;"
URLEncoder.encode("phone_number2","UTF-8") "=" URLEncoder.encode(phne_ofice,"UTF-8") "amp;"
URLEncoder.encode("email","UTF-8") "=" URLEncoder.encode(email_,"UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
os.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
@Override
protected void onPostExecute(String result) {
pDialog.dismiss();
if(result.equals("Success! This message is from PHP")) {
Toast.makeText(Profile_add.this, result.toString(), Toast.LENGTH_LONG).show();
}else{
// you to understand error returned from doInBackground method
Toast.makeText(Profile_add.this, result.toString(), Toast.LENGTH_LONG).show();
}
}