Voici mes codes :
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context=".AjouterPhoto"
tools:showIn="@layout/activity_ajouter_photo">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginBottom="@dimen/fab_margin">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Ajouter une photo"
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.AppCompat.Large"
android:textColor="@color/colorPrimaryDark"
android:textStyle="bold"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:paddingTop="5dp"
android:layout_marginBottom="@dimen/fab_margin">
<EditText
android:id="@+id/nameEditText"
android:layout_width="match_parent"
android:layout_height="1dp"
android:singleLine="true"
android:text="Téléphone"
android:visibility="invisible"
/>
<EditText
android:id="@+id/descriptionEditText"
android:layout_width="match_parent"
android:layout_height="1dp"
android:visibility="invisible"
android:text="Description"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:id="@+id/chooseBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Choisir une photo"
android:background="@drawable/bordure4"
android:textColor="#FFF"/>
<ImageView
android:id="@+id/imageView"
android:layout_marginTop="@dimen/fab_margin"
android:layout_marginBottom="@dimen/fab_margin"
android:layout_width="match_parent"
android:layout_height="300dp"
app:srcCompat="@drawable/placeholder" />
<ProgressBar
android:id="@+id/myProgressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:indeterminate="true"
android:indeterminateBehavior="cycle"
android:visibility="gone" />
</LinearLayout>
<Button
android:id="@+id/sendBtn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:background="@drawable/bordure"
android:clickable="true"
android:text="Ajouter à mon compte"
android:textColor="@android:color/white" />
</LinearLayout>
</LinearLayout>
</ScrollView>
</android.support.constraint.ConstraintLayout>
package xxx.xxxx.com.xxx;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.androidnetworking.AndroidNetworking;
import com.androidnetworking.common.Priority;
import com.androidnetworking.error.ANError;
import com.androidnetworking.interfaces.JSONObjectRequestListener;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
import static android.provider.MediaStore.Images.*;
import static android.provider.MediaStore.Images.Media.*;
public class AjouterPhoto extends AppCompatActivity {
private static final int READ_REQUEST_CODE = 42;
final int PICK_IMAGE_REQUEST = 234;
private Uri filePath;
EditText nameEditText,descriptionEditText;
private ImageView teacherImageView;
private Button showChooserBtn,sendToMySQLBtn;
private ProgressBar uploadProgressBar;
/******************************************************************************/
/*
Our data object. THE POJO CLASS
*/
class SpiritualTeacher{
private String name,description,imageURL;
public SpiritualTeacher(String name, String description) {
this.name = name;
this.description = description;
this.imageURL = imageURL;
}
public String getName() {return name;}
public String getDescription() {return description;}
}
/******************************************************************************/
/*
CLASS TO UPLOAD BOTH IMAGES AND TEXT
*/
public class MyUploader {
private static final String DATA_UPLOAD_URL="lien du fichier php qui affiche les données";
//INSTANCE FIELDS
private final Context c;
public MyUploader(Context c) {this.c = c;}
/*
SAVE/INSERT
*/
public void upload(SpiritualTeacher s, final View...inputViews)
{
if(s == null){Toast.makeText(c, "Aucune donnée à enregistrer", Toast.LENGTH_SHORT).show();}
else {
File imageFile;
try {
imageFile = new File(getImagePath(filePath));
}catch (Exception e){
Toast.makeText(c, "Importer une photo."+e.getMessage(), Toast.LENGTH_LONG).show();
return;
}
uploadProgressBar.setVisibility(View.VISIBLE);
AndroidNetworking.upload(DATA_UPLOAD_URL)
.addMultipartFile("image",imageFile)
.addMultipartParameter("teacher_name",s.getName())
.addMultipartParameter("teacher_description",s.getDescription())
.addMultipartParameter("name","upload")
.setTag("MYSQL_UPLOAD")
.setPriority(Priority.HIGH)
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
// Les versions 6 d'Android n'arrivent pas entrer dans : onResponse(JSONObject response)
@Override
public void onResponse(JSONObject response) {
if(response != null) {
try{
//SHOW RESPONSE FROM SERVER
String responseString = response.get("message").toString();
Toast.makeText(c, "Réponse du serveur : " + responseString, Toast.LENGTH_LONG).show();
if (responseString.equalsIgnoreCase("Success")) {
//RESET VIEWS
EditText nameEditText = (EditText) inputViews[0];
EditText descriptionEditText = (EditText) inputViews[1];
ImageView teacherImageView = (ImageView) inputViews[2];
nameEditText.setText("");
descriptionEditText.setText("");
teacherImageView.setImageResource(R.drawable.placeholder);
} else {
Toast.makeText(c, "Donnée non enregistrées. ", Toast.LENGTH_LONG).show();
}
}catch(Exception e)
{
e.printStackTrace();
Toast.makeText(c, "Message de traitement "+e.getMessage(), Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(c, "Aucune réponse. ", Toast.LENGTH_LONG).show();
}
uploadProgressBar.setVisibility(View.GONE);
}
// Les versions 6 d'Android rentrent directement ici
@Override
public void onError(ANError error) {
error.printStackTrace();
uploadProgressBar.setVisibility(View.GONE);
Toast.makeText(c, "Echec : voici la cause : \n"+error.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
}
/******************************************************************************/
/*
Show File Chooser Dialog
*/
public void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
//startActivityForResult(intent, READ_REQUEST_CODE);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Choisissez une photo à envoyer"), PICK_IMAGE_REQUEST);
}
//Sur certaines versions 6 Android, juste après la sélection de l'image, l'application fait un échec
/*
Receive Image data from FileChooser and set it to ImageView as Bitmap
*/
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
try {
Bitmap bitmap = getBitmap(getContentResolver(), filePath);
teacherImageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/*
Get Image Path propvided its android.net.Uri
*/
public String getImagePath(Uri uri)
{
String[] projection = new String[]{DATA};
Cursor cursor=getContentResolver().query(uri,projection,null,null,null);
if(cursor == null){
return null;
}
int columnIndex= cursor.getColumnIndexOrThrow(DATA);
cursor.moveToFirst();
String s=cursor.getString(columnIndex);
cursor.close();
return s;
}
/*
Perform basic data validation
*/
public boolean validateData()
{
String name=nameEditText.getText().toString();
String description=descriptionEditText.getText().toString();
if( name == null || description == null){ return false; }
if(name == "" || description == ""){ return false; }
if(filePath == null){return false;}
return true;
}
/*
OnCreate method. When activity is created
*/
//J'ai créé ici une base de données locale pour faire certains traitements vers le fichier php
SQLiteDatabase bd_foto_prints;
Cursor c1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ajouter_photo);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//**********************************************
// Je vérifie ici si la personne a un compte dans sa base de données locale de SQLite
bd_foto_prints = openOrCreateDatabase("gestion_compte", Context.MODE_PRIVATE, null);
Cursor c = bd_foto_prints.rawQuery("SELECT * FROM Compte ORDER BY moment_actuel DESC LIMIT 1", null);
while (c.moveToNext()) {
final String telephone = c.getString(2);
final String user_pass = c.getString(3);
if (telephone != "" && user_pass != "") {
//*************************************************************************************************
nameEditText=findViewById(R.id.nameEditText);
descriptionEditText=findViewById(R.id.descriptionEditText);
showChooserBtn=findViewById(R.id.chooseBtn);
sendToMySQLBtn=findViewById(R.id.sendBtn);
Button openActivityBtn=findViewById(R.id.openActivityBtn);
teacherImageView=findViewById(R.id.imageView);
uploadProgressBar=findViewById(R.id.myProgressBar);
showChooserBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showFileChooser();
}
});
sendToMySQLBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (validateData()) {
//GET VALUES
//String teacher_name = nameEditText.getText().toString();
//String teacher_description = descriptionEditText.getText().toString();
String teacher_name = nameEditText.getText().toString();
String teacher_description = descriptionEditText.getText().toString();
// J'envoie certaines de ses informations vers la base de données
SpiritualTeacher s = new SpiritualTeacher(telephone, user_pass);
//upload data to mysql
new MyUploader(AjouterPhoto.this).upload(s, nameEditText, descriptionEditText, teacherImageView);
} else {
Toast.makeText(AjouterPhoto.this, "Rassurez-vous que la photo a été bien choisie ", Toast.LENGTH_LONG).show();
}
}
});
//*************************************************************************************************
} else {
// S'il n'a pas de compte dans SQLite, alors, il est renvoyé pour le créé d'avance
Intent intent_accueil = new Intent(AjouterPhoto.this, Identification.class);
startActivity(intent_accueil);
Toast.makeText(AjouterPhoto.this, "Vous devez créer un compte pour continuer", Toast.LENGTH_LONG).show();
}
}
c.close();
//************************************************************************************************
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
<?php
/* Created by Oclemy for http://camposha.info and ProgrammingWizards TV.
* User: Oclemy
*/
class Constants
{
//DATABASE DETAILS
static $DB_SERVER="xxxxxxxxxxxxxx";
static $DB_NAME="xxxxxxxxxxx";
static $USERNAME="xxxxxxxxxxxxxxx";
static $PASSWORD="xxxxxxxxxxxxxx";
//STATEMENTS
static $SQL_SELECT_ALL="SELECT * FROM spiritualTeachersTB";
}
class Spirituality
{
/*/
/*
1.CONNECT TO DATABASE.
2. RETURN CONNECTION OBJECT
*/
public function connect()
{
$con=new mysqli(Constants::$DB_SERVER,Constants::$USERNAME,Constants::$PASSWORD,Constants::$DB_NAME);
if($con->connect_error)
{
// echo "Unable To Connect";
return null;
}else
{
return $con;
}
}
public function insert()
{
// INSERT
$con=$this->connect();
if($con != null)
{
// Get image name
$temps = date('YmdHi');
$image_name1 = $_FILES['image']['name'];
$image_name = 'FotoPrints_'.$temps.'_'.$image_name1;
// Get text
$teacher_name = mysqli_real_escape_string($con, $_POST['teacher_name']);
$teacher_description = mysqli_real_escape_string($con, $_POST['teacher_description']);
// image file directory
$target = "images/".basename($image_name);
$sql = "INSERT INTO spiritualTeachersTB (teacher_image_url, teacher_name,teacher_description) VALUES ('$image_name', '$teacher_name', '$teacher_description')";
try
{
$result=$con->query($sql);
if($result)
{
if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
print(json_encode(array("message"=>"Success")));
}else{
print(json_encode(array("message"=>"Enregistrer, mais les photos ne sont pas aller dans le dossier approprie")));
}
}else
{
print(json_encode(array("message"=>"Echec, les données ne sont pas enregistées.")));
}
$con->close();
}catch (Exception $e)
{
print(json_encode(array("message"=>"Echec, ne peut pas enregistrer. ".$e->getMessage())));
$con->close();
}
}else{
print(json_encode(array("message"=>"Echec, erreur de connexion au serveur.")));
}
}
?>
Merci de m'aider à trouver une solution.