Я новичок в Android, и я хочу работать над взятием данных и отправкой их в базу данных через PHP, проблема, с которой я сталкиваюсь, - я не уверен, что делать с вводом. Моя цель состоит в том, чтобы пользователь вводил строку в приложении android и отправлял ее в базу данных через PHP. Вот мой код:
package com.example.signals;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private String convertStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (Exception e) {
Toast.makeText(this, "Stream Exception", Toast.LENGTH_SHORT).show();
}
return total.toString();
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button send = (Button)findViewById(R.id.send);
final EditText input = (EditText)findViewById(R.id.input);
send.setOnClickListener(new OnClickListener(){
public void onClick(View v){
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://example.com/script.php?var1=androidprogramming");
try {
HttpResponse response = httpclient.execute(httppost);
if(response != null) {
String line = "";
InputStream inputstream = response.getEntity().getContent();
line = convertStreamToString(inputstream);
Toast.makeText(MainActivity.this, line, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Unable to complete your request", Toast.LENGTH_LONG).show();
}
} catch (ClientProtocolException e) {
Toast.makeText(MainActivity.this, "Caught ClientProtocolException", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(MainActivity.this, "Caught IOException", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(MainActivity.this, "Caught Exception", Toast.LENGTH_SHORT).show();
}
}
});
}}'
Спасибо за любую помощь!
Вы можете получить ввод как строку:
input.getText().toString();
И добавьте его в свой URL как параметр GET
Вы должны добавить свои данные в URL с помощью метода GET/POST. См. Этот учебник.
class SaveProductDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EditProductActivity.this);
pDialog.setMessage("Saving product ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Saving product
* */
protected String doInBackground(String... args) {
// getting updated data from EditTexts
String name = txtName.getText().toString();
String price = txtPrice.getText().toString();
String description = txtDesc.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_PID, pid));
params.add(new BasicNameValuePair(TAG_NAME, name));
params.add(new BasicNameValuePair(TAG_PRICE, price));
params.add(new BasicNameValuePair(TAG_DESCRIPTION, description));
// sending modified data through http request
// Notice that update product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_update_product,
"POST", params);
// check json success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully updated
Intent i = getIntent();
// send result code 100 to notify about product update
setResult(100, i);
finish();
} else {
// failed to update product
}
} 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 product uupdated
pDialog.dismiss();
}
}
Вы хотите создать HTTP-запрос. Передача данных через JSON очень удобна для Android: просто передайте все данные, которые вам нужно отправить, и включите их в JSON, как показано ниже. Поле "текст" возвращается и может быть проанализировано с помощью JSON по мере необходимости
private String postPullData(JSONObject json, String URL) throws JSONException {
HttpClient httpclient;
int CONNECTION_TIMEOUT = 20*1000;
int WAIT_RESPONSE_TIMEOUT = 20*1000;
HttpPost httppost = new HttpPost(URL);
String Error = "SCOMM Error: ";
JSONArray postjson;
URL url = null;
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpParameters, WAIT_RESPONSE_TIMEOUT);
HttpConnectionParams.setTcpNoDelay(httpParameters, true);
httpclient = new DefaultHttpClient(httpParameters);
try {
postjson = new JSONArray();
postjson.put(json);
// Post the data:
httppost.setHeader("json", json.toString());
httppost.getParams().setParameter("jsonpost", postjson);
// Execute HTTP Post Request
System.out.print(json);
HttpResponse response = httpclient.execute(httppost);
// for JSON:
if (response != null)
{
InputStream is = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
Error += " IO Exception: " + e;
Log.d("SCOMM", Error);
e.printStackTrace();
return Error;
} finally {
try {
is.close();
} catch (IOException e) {
Error += " closing connection: " + e;
Log.d("SCOMM", Error);
e.printStackTrace();
return Error;
}
}
return sb.toString();
<snip>
// more error recovery stuff below
Во-первых: вы не можете отправлять данные в основной поток на сервер. Во-вторых: используйте HttpGet, а не HttpPost. Получите данные пользователя, вы можете input.getText.toString()
. использовать AsynckTask
для отправки данных на сервер
class SendData extends AsyncTask<Void, Void, String>{
@Override
protected String doInBackground(Void... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = new HttpGet("http://example.com/script.php?var1=androidprogramming");
try {
HttpResponse response = httpclient.execute(httppost);
if(response != null) {
String line = "";
InputStream inputstream = response.getEntity().getContent();
line = convertStreamToString(inputstream);
return line;
}
} catch (ClientProtocolException e) {
//toas can't use here
}
catch (IOException e) {
} catch (Exception e) {
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if(s != null){
//toast here!
}
}
}
Применение
new SendData().execute()