我知道已经多次接触过这个主题。但它总是使用Apache,已被弃用。 我想将数据从我的应用程序发送到我的数据库。我知道我的PHP代码有效。但是当我点击"发送"在我的应用程序中,要么崩溃应用程序,要么它可以工作,但不会将数据发送到我的数据库(或者我无法看到它)。
这就是我打电话给我的班级" AddDataAsyncTask":
btnnexttrip.setOnClickListener(new View.OnClickListener(){
public void onClick (View view) {
Intent myIntent =new Intent(getBaseContext(), trip.class);
AddData =new AddDataAsyncTask();
AddData.execute();
startActivityForResult(myIntent,0);
}
});
我的类AddDataAsyncTask:
private class AddDataAsyncTask extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
Log.i("add", "onPreExecute");
super.onPreExecute();
}
protected Void doInBackground(Void... params) {
//I Use HashMap, it works similar to NameValuePair
Map<String,String> dataToSend = new HashMap<>();
dataToSend.put("id",hisid);
dataToSend.put("name", hisname);
dataToSend.put("age", hisage);
dataToSend.put("job", hisjob);
dataToSend.put("gender", hisgender);
dataToSend.put("date_trip", hisdate);
dataToSend.put("mode_trip", hismode);
dataToSend.put("time_trip", histime);
dataToSend.put("crowded_trip", hiscrowded);
dataToSend.put("from_trip", hisfrom);
dataToSend.put("to_trip", histo);
dataToSend.put("majo_gender",hismajogender);
dataToSend.put("majo_origin",hismajoorigin);
String encodedStr = getEncodedData(dataToSend);
BufferedReader reader = null;
try {
URL url = new URL(urlAdd);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
writer.write(encodedStr);
} catch (Exception e) {
e.printStackTrace();
} finally {
if(reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
Log.i("add", "onPostExecute");
super.onPostExecute(result);
if(success==1)
{
Toast.makeText(getApplicationContext(), "Good "+message, Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "Error " +message, Toast.LENGTH_LONG).show();
}
}
}
似乎是&#34; getEncodedData&#34; in&#34; doInBackground&#34;那不起作用:
private String getEncodedData(Map<String,String> data) {
StringBuilder sb = new StringBuilder();
for(String key : data.keySet()) {
String value = null;
try {
value = URLEncoder.encode(data.get(key),"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if(sb.length()>0){
sb.append("&");
}
sb.append(key + "=" + value);
}
return sb.toString();
}
我有互联网许可......这是LogCat:
05-25 10:59:00.675 2468-3214/com.example.jeremydiez.sharedlifetracks E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.example.jeremydiez.sharedlifetracks, PID: 2468
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:325)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
at java.net.URLEncoder.encode(URLEncoder.java:205)
at com.example.jeremydiez.sharedlifetracks.tripsecondpart.getEncodedData(tripsecondpart.java:198)
at com.example.jeremydiez.sharedlifetracks.tripsecondpart.access$300(tripsecondpart.java:41)
at com.example.jeremydiez.sharedlifetracks.tripsecondpart$AddDataAsyncTask.doInBackground(tripsecondpart.java:268)
at com.example.jeremydiez.sharedlifetracks.tripsecondpart$AddDataAsyncTask.doInBackground(tripsecondpart.java:240)
at android.os.AsyncTask$2.call(AsyncTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
我尝试修复它(使用logcat)所以我更改了&#34; getEncodedData&#34;对此:
private String getEncodedData(Map<String,String> data) {
StringBuilder sb = new StringBuilder();
for(Map.Entry<String, String> entry : data.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
String encodedvalue = null;
try {
encodedvalue = URLEncoder.encode(key,"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if(sb.length()>0){
sb.append("&");
}
sb.append(key + "=" + encodedvalue);
}
return sb.toString();
}
有了这个,它没有崩溃,但没有向我的数据库发送任何东西:/
有人能帮助我吗?
编辑:这是我如何定义我的urlAdd:
String urlAdd="http://192.168.15.32/enis_android_club/add_dbadd.php";
这是一个好方法吗?
答案 0 :(得分:0)
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;
}
}
在你的doInBackground方法中输入以下代码:
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair(("id",hisid)));
params.add(new BasicNameValuePair("name", hisname)); // put your values like this
Log.e("params", params.toString());
// getting JSON Object
final JSONObject jsonValid = jsonParser.makeHttpRequest(
urlAdd, "POST", params);
int successValid = jsonValid.getInt("success");
if (successValid == 1) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), "success", Toast.LENGTH_SHORT).show();
}
});
} else {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), "Error",
Toast.LENGTH_SHORT).show();
}
});
}
}
我没有很好地组织这段代码,尝试组织它:)