我想使用asyncTask发送附带文件的消息, 我的PHP代码是好的..因为当上传小尺寸文件时,每个人都可以,当我发送消息时,一切都将按照我想要的方式...但是当上传大尺寸的文件时(比如大约6 Mb的apk文件)我在这一行得到空指针异常:(查看onPostExecute)
success2 = json2.getInt("success");
这里是asyncTasck
public class PostDataAsyncTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... strings) {
try {
uploadFile(fichier);
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String lenghtOfFile) {
int success2= 0;
try {
success2 = json2.getInt("success");
} catch (JSONException e) {
e.printStackTrace();
}
if(success2==1) {
((EditText) findViewById(R.id.etMsg)).setText("");
if (attach) {
changerAttach();
} }
} }
这是上传functopn:
private void uploadFile(String filePath) {
try {
try {
HttpPost httpost = new HttpPost(url_upload);
MultipartEntity entity = new MultipartEntity();
entity.addPart("Mdp", new StringBody(mdp));
entity.addPart("Msg", new StringBody(URLEncoder.encode(msg)));
entity.addPart("type", new StringBody(type));
if(type.equals("1")) {
entity.addPart("Emailm", new StringBody(email));
entity.addPart("Emailp", new StringBody(emaildest));
}else {
entity.addPart("Emailp", new StringBody(email));
entity.addPart("Emailm", new StringBody(emaildest));
}
if (attach){
entity.addPart("attachement", new FileBody(new File(filePath)));
entity.addPart("attacher", new StringBody("oui"));
}else{
entity.addPart("attacher", new StringBody("non"));
}
httpost.setEntity(entity);
HttpResponse response;
HttpClient httpclient = new DefaultHttpClient();
response = httpclient.execute(httpost);
if (response != null) {
HttpEntity entity2 = response.getEntity();
String responseString = EntityUtils.toString(entity2, "UTF-8");
System.out.println(responseString);
json2=new JSONObject(responseString);
} else { //erreur
}
} catch (IOException e) {
e.printStackTrace();
}
}catch (Exception e){
}
}
请注意字符串“ fichier ”我要卸载的文件的路径。
附加是布尔变量,表示我已选择要上传的文件。
json2 是一个全局变量(JSONObject),将在上传函数中初始化
我认为这就是你需要的(PHP代码没问题)
注意:我认为这个问题导致了我的问题,这是真的吗? 非常感谢
修改 upload.php
<?php
date_default_timezone_set ("Africa/Algiers");
include('connect.php');
$response = array();
if (isset($_REQUEST['Emailm'])&& isset($_REQUEST['Mdp'])&&isset($_REQUEST['type']) && isset($_REQUEST['Emailp'])&&isset($_REQUEST['Msg']) ) {
$Emailm = $db->real_escape_string($_REQUEST['Emailm']);
$Emailp = $db->real_escape_string($_REQUEST['Emailp']);
$Mdp = $db->real_escape_string($_REQUEST['Mdp']);
$Msg = $_REQUEST['Msg'];
$Mdp = $_REQUEST['Mdp'];
$Msg= $db->real_escape_string(htmlentities(urldecode($Msg)));
$type= $_REQUEST['type'];
$target_path1 = "attachement/";
if($type=="0"){ //compte patient
if ($result = $db->query("SELECT * FROM `patient` WHERE `Email_p`='$Emailp' AND `Mdp`='$Mdp'")) {
$row_cnt = $result->num_rows; }
}else { //compte médecin
if ($result = $db->query("SELECT * FROM `med` WHERE `Email`='$Emailm' AND `Mdp`='$Mdp'")) {
$row_cnt = $result->num_rows; }
}
$b=false;
$a=false;
if ($row_cnt>0) {
if($_REQUEST['attacher']=="oui"){
$filecount = 0;
$files = glob($target_path1 . "*");
if ($files){
$filecount = count($files);
}
$nomFichier=$filecount.basename( $_FILES['attachement']['name']) ;
$target_path1 = $target_path1 . $nomFichier;
$nomFichierOrigin=basename( $_FILES['attachement']['name']);
if(move_uploaded_file($_FILES['attachement']['tmp_name'], $target_path1)) {
$b=true;}
}
else{
$nomFichier="";
$nomFichierOrigin="";
};
$h=new DateTime("now") ;
$s=$h->format('G:i:s');
$s2=$h->format('Y-m-d');
if($result = mysqli_query($db,"INSERT INTO `msg`(`cle`, `email_m`, `email_p`, `message`, `attachement`, `type`, `attachementNomOrigin`, `heure`, `date`,`vu`)
VALUES ('','$Emailm','$Emailp','$Msg','$nomFichier','$type','$nomFichierOrigin','$s','$s2','non')"))
{$a=true;}
if($a==true && $b==true && $_REQUEST['attacher']=="oui"){
$dernierId = $db->insert_id;
if ($result = $db->query("SELECT * FROM `med` WHERE `Email`='$Emailm' AND `Mdp`='$Mdp'")) {
if (mysqli_num_rows($result) > 0) {
$response["Msg"] = array();
while ($row = mysqli_fetch_array($result)) {
$Msg = array();
$Msg["cle"] = intval($row["cle"]);
$Msg["heure"] = $row["heure"];
$Msg["date"] = $row["date"];
$Msg["email_m"] = $row["email_m"];
$Msg["email_p"] = $row["email_p"];
$Msg["message"] = $row["message"];
$Msg["type"] = $row["type"];
$Msg["attachement"] = $row["attachement"];
$Msg["attachementNomOrigin"] = $row["attachementNomOrigin"];
array_push($response["Msg"], $Msg);
}
$response["success"] = 1;
$response["message"] = "Succès";
}}} else
if($a==true && $_REQUEST['attacher']=="non"){
$response["success"] = 1;
$response["message"] = "Succès";
}else{
$response["success"] = 0;
$response["message"] = "Erreur lors de l'envoi";
}
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "Email ou Mot de passe incorrect";
echo json_encode($response);
}
}else {
$response["success"] = 0;
$response["message"] = "Champs manqués";
echo json_encode($response);
}
?>
logCat:
04-20 18:05:00.149 4509-4509/eddine.charef.mechalikh.swipedemo E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at eddine.charef.mechalikh.swipedemo.message$PostDataAsyncTask.onPostExecute(message.java:231)
at eddine.charef.mechalikh.swipedemo.message$PostDataAsyncTask.onPostExecute(message.java:207)
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:137)
at android.app.ActivityThread.main(ActivityThread.java:4813)
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:792)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:559)
at dalvik.system.NativeStart.main(Native Method)
04-20 18:05:00.219 4509-6923/eddine.charef.mechalikh.swipedemo I/System.out﹕ {"Msg":[{"cle":271,"heure":"18:01:18","date":"2015-04-20","email_m":"mecha","email_p":"a","message":"hhhh","type":"0","attachement":"12Maps.apk","attachementNomOrigin":"Maps.apk"}],"success":1,"message":"Msg telecharg\u00e9s"}
在jsonParser中,我奇怪了这个
System.out.println(String.valueOf(json);
你可以看到logcat中的json对象,即使异常升级......所以这是一个时间问题..你怎么看?
EDIT2 JsonParser.java
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();
}catch (Exception e){};
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();
json = sb.toString();
System.out.println(json);
//HERE IS THE SYSTEM.OUT.PRINT THAT I TALK ABOUT
//YOU CAN SEE THE RESULT IN THE LOGCAT
} 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;
}
}
让您了解面临的问题:
我想清楚EdittextHere:
发送消息之后,这就是为什么我检查postExecute中的成功标签..如果你有其他方式我会贬低...注意这是我的第一个应用程序,所以我不知道其他方法来做到这一点
答案 0 :(得分:0)
问题出在php代码中..这是正确的
<?php
date_default_timezone_set ("Africa/Algiers");
include('connect.php');
$response = array();
if (isset($_REQUEST['Emailm'])&& isset($_REQUEST['Mdp'])&&isset($_REQUEST['type']) && isset($_REQUEST['Emailp'])&&isset($_REQUEST['Msg']) ) {
$Emailm = $db->real_escape_string($_REQUEST['Emailm']);
$Emailp = $db->real_escape_string($_REQUEST['Emailp']);
$Mdp = $db->real_escape_string($_REQUEST['Mdp']);
$Msg = $_REQUEST['Msg'];
$Mdp = $_REQUEST['Mdp'];
$Msg= $db->real_escape_string(htmlentities(urldecode($Msg)));
$type= $_REQUEST['type'];
$target_path1 = "attachement/";
if($type=="0"){ //compte patient
if ($result = $db->query("SELECT * FROM `patient` WHERE `Email_p`='$Emailp' AND `Mdp`='$Mdp'")) {
$row_cnt = $result->num_rows;
}
}else { //compte médecin
if ($result = $db->query("SELECT * FROM `med` WHERE `Email`='$Emailm' AND `Mdp`='$Mdp'")) {
$row_cnt = $result->num_rows;
}
}
$b=false;
$a=false;
if ($row_cnt>0) {
if($_REQUEST['attacher']=="oui"){
$filecount = 0;
$files = glob($target_path1 . "*");
if ($files){
$filecount = count($files);
}
$nomFichier=$filecount.basename( $_FILES['attachement']['name']) . ".a";
$target_path1 = $target_path1 . $nomFichier;
$nomFichierOrigin=basename( $_FILES['attachement']['name']);
if(move_uploaded_file($_FILES['attachement']['tmp_name'], $target_path1)) {
$b=true; }
}
else{
$nomFichier="";
$nomFichierOrigin="";
};
$h=new DateTime("now") ;
$s=$h->format('G:i:s');
$s2=$h->format('Y-m-d');
if($result = mysqli_query($db,"INSERT INTO `msg`(`cle`, `email_m`, `email_p`, `message`, `attachement`, `type`, `attachementNomOrigin`, `heure`, `date`,`vu`)
VALUES ('','$Emailm','$Emailp','$Msg','$nomFichier','$type','$nomFichierOrigin','$s','$s2','non')"))
{$a=true;$dernierId = $db->insert_id;
}
if($a==true && $b==true && $_REQUEST['attacher']=="oui"){
if ($result = $db->query("SELECT * FROM msg WHERE cle='$dernierId'")) {
if (mysqli_num_rows($result) > 0) {
$response["Msg"] = array();
while ($row = mysqli_fetch_array($result)) {
$Msg = array();
$Msg["cle"] = intval($row["cle"]);
$Msg["heure"] = $row["heure"];
$Msg["date"] = $row["date"];
$Msg["email_m"] = $row["email_m"];
$Msg["email_p"] = $row["email_p"];
$Msg["message"] = $row["message"];
$Msg["type"] = $row["type"];
$Msg["attachement"] = $row["attachement"];
$Msg["attachementNomOrigin"] = $row["attachementNomOrigin"];
array_push($response["Msg"], $Msg);
}
$response["success"] = 1;
$response["message"] = "Succès";
}}} else
if($a==true && $_REQUEST['attacher']=="non"){
$response["success"] = 1;
$response["message"] = "Succès";
}else{
$response["success"] = 0;
$response["message"] = "Erreur lors de l'envoi";
}
} else {
$response["success"] = 0;
$response["message"] = "Email ou Mot de passe incorrect";
}
}else {
$response["success"] = 0;
$response["message"] = "Champs manqués";
} echo json_encode($response);
?>