Android空指针异常异步任务
我想使用asyncTask发送带有附加文件的邮件, 我的php代码还可以。。因为当上传小文件时,每次都可以,当我发送没有附件的消息时,一切都会如我所愿。。但当上传大文件(比如大于6MB的apk文件)时,我在这一行得到了空指针异常:(查看onPostExecute) 这是asyncTasckAndroid空指针异常异步任务,android,file-upload,android-asynctask,Android,File Upload,Android Asynctask,我想使用asyncTask发送带有附加文件的邮件, 我的php代码还可以。。因为当上传小文件时,每次都可以,当我发送没有附件的消息时,一切都会如我所愿。。但当上传大文件(比如大于6MB的apk文件)时,我在这一行得到了空指针异常:(查看onPostExecute) 这是asyncTasck public class PostDataAsyncTask extends AsyncTask<String, String, String> { protected void o
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();
} }
} }
请注意字符串“fichier”是我要加载的文件的路径
attach是一个布尔变量,表示我选择了要上载或不上载的文件
json2是一个全局变量(JSONObject),将在upload函数中初始化
我认为这就是您需要的(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);
}
?>
在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;
}
公共类JSONParser{
静态InputStream为空;
静态JSONObject jObj=null;
静态字符串json=“”;
//建造师
公共JSONParser(){
}
//函数从url获取json
//通过使用HTTP POST或GET方法
公共JSONObject makeHttpRequest(字符串url、字符串方法、,
列表参数){
//发出HTTP请求
试一试{
//检查请求方法
如果(方法==“POST”){
//请求方法为POST
//defaultHttpClient
DefaultHttpClient httpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(url);
setEntity(新的UrlEncodedFormEntity(参数));
HttpResponse HttpResponse=httpClient.execute(httpPost);
HttpEntity HttpEntity=httpResponse.getEntity();
is=httpEntity.getContent();
}else if(方法==“GET”){
//请求方法是GET
DefaultHttpClient httpClient=新的DefaultHttpClient();
String paramString=URLEncodedUtils.format(params,“utf-8”);
url+=“?”+参数字符串;
HttpGet HttpGet=新的HttpGet(url);
HttpResponse HttpResponse=httpClient.execute(httpGet);
HttpEntity HttpEntity=httpResponse.getEntity();
is=httpEntity.getContent();
}
}捕获(不支持的编码异常e){
e、 printStackTrace();
}捕获(客户端协议例外e){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}捕获(例外e){};
试一试{
BufferedReader reader=新的BufferedReader(新的InputStreamReader(
为“UTF-8”)、8);
StringBuilder sb=新的StringBuilder();
字符串行=null;
而((line=reader.readLine())!=null){
sb.追加(第+行“\n”);
}
is.close();
json=sb.toString();
System.out.println(json);
//这是我说的SYSTEM.OUT.PRINT
//您可以在LOGCAT中看到结果
}捕获(例外e){
Log.e(“缓冲区错误”,“错误转换结果”+e.toString());
}
//尝试将字符串解析为JSON对象
试一试{
jObj=新的JSONObject(json);
}捕获(JSONException e){
Log.e(“JSON解析器”,“错误解析数据”+e.toString());
}
//返回JSON字符串
返回jObj;
}
}
让您了解我面临的问题:
我想在这里清除文本:
发送消息后,这就是我在postExecute中检查成功标记的原因。如果您有其他方法,我将对此表示感谢。。请注意,这是我的第一个应用程序,所以我不知道其他方法来实现这一点问题出在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);
?>
在onPostExecute()
中什么是json2
?当您收到此错误时,文件是否已成功上载?在我看来,response
是null
,因此json2
也将是null。在本例中,此调用可能返回null
:response=httpclient.execute(httpost)代码>当我打开附件文件夹时,我可以打开或读取该文件。。这意味着即使应用程序停止,它也已成功上载,你是对的,我必须提到这一点,为什么在小文件(200 Kb大小)的情况下…为什么在这种情况下没有例外?BufferedReader BufferedReader=new BufferedReader(new InputStreamReader(response.getEntity().getContent());字符串msg=“”;字符串行=”;而((line=bufferreader.readLine())!=null){msg+=line;}Log.i(“msg=”,“”+msg);
System.out.println(String.valueOf(json);
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;
}
<?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);
?>