How To Save Feedback Form in Android Apps With php mysql

How To Save Feedback Form in Android Apps With php mysql

This is very simple Save your record in a web site or android apps same data can access or save to android apps through  mobile apps like feed back form of the any apps .Its output Result


Its 4 major part of save a record in apps through web api 
1.Java File 
2.XML File with design
3.Php save file Code
4.Database  name or table when save record online link   
  
First We have add a xml page on the eclipse and add the forth Edit Text box  code in the page feedback.xml.

<?xml version="1.0" encoding="utf-8"?>


<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/scrollView1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="@drawable/background" >
        
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/background"
        android:orientation="vertical" >

<TableLayout
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:layout_gravity="left"
   android:background="#518CA3" >
       <TableRow
           android:id="@+id/tableRow2"
           android:layout_width="match_parent"
           android:layout_height="55dp"
           android:background="#518CA3"
           android:layout_gravity="left" >
        
       </TableRow>
</TableLayout>
        
    
    <TableLayout
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:layout_gravity="left"
   android:layout_marginTop="1dp"
   android:background="#c1c1c1" >

                        <TableRow
                            android:id="@+id/tableRow1"
                            android:layout_width="310dp"
                            android:layout_height="wrap_content" 
                            android:background="#ffffff"
                            android:layout_gravity="left">

                            <ImageView
                                android:id="@+id/imageView2"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                               android:src="@drawable/feedback1"
                                 android:layout_marginTop="5dp"
                                 android:layout_marginBottom="2dp"
                                 android:layout_marginRight="200dp"
                                     />

                        </TableRow>
                           <TableRow
                            android:id="@+id/tableRow1"
                            android:layout_width="310dp"
                            android:layout_height="wrap_content" 
                            android:background="#ffffff"
                            android:layout_gravity="left">

                            <ImageView
                                android:id="@+id/imageView2"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                               android:src="@drawable/feedback"
                                 android:layout_marginTop="6dp"
                                 android:layout_marginBottom="2dp"
                                 android:layout_marginLeft="1dp"
                                     />

                        </TableRow>
</TableLayout>
<LinearLayout 
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="horizontal">
       
</LinearLayout>
<LinearLayout 
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="horizontal">

    
   
    <EditText
        android:id="@+id/tvName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
      
        android:ems="10"
        android:hint="Your Name?" >

        <requestFocus />
    </EditText>
   
   
</LinearLayout>
    
<LinearLayout 
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="horizontal">

 </LinearLayout>

<LinearLayout 
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="horizontal">

        <EditText
            android:id="@+id/extEmail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="10dp"
      
        android:ems="10"
        android:hint="Your Email?" >
     
   </EditText>
   </LinearLayout>
<LinearLayout 
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="horizontal">
        <EditText
       android:id="@+id/extContact"
      android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
              android:layout_marginTop="13dp"
       
        android:ems="10"
        android:hint="Your Mobile No ?" >      
   </EditText>
   </LinearLayout>
   <LinearLayout 
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="horizontal">
   </LinearLayout>
   <LinearLayout 
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="horizontal">
        
        <EditText
       android:id="@+id/extMessage"
       android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
              android:layout_marginTop="15dp"
     
        android:ems="10"
        android:hint="Your Message" >      
   </EditText>
   </LinearLayout>

      
       <LinearLayout 
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="horizontal">
   </LinearLayout>
<LinearLayout 
 android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:orientation="horizontal"
         >

<TextView
   android:id="@+id/tvCurrentDate"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="Curent Date"
   android:textAppearance="?android:attr/textAppearanceSmall" />
   <TextView
   android:id="@+id/tvGetID"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="Get ID Phone"
   android:textAppearance="?android:attr/textAppearanceSmall" />
</LinearLayout>
<LinearLayout
       android:layout_width="match_parent"
       android:layout_height="40dp"
       android:orientation="horizontal"
       android:layout_marginTop="30dp"
       android:gravity="center" >
                        
   </LinearLayout>
    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText1"
        android:layout_below="@+id/editText1"
        android:layout_marginBottom="8dp"
        android:layout_marginTop="8dp"
        android:orientation="horizontal" >
        
        <Button
            android:id="@+id/button2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@null"
            android:text="Cancel"
            android:textColor="#f39c12" />

        <Button
            android:id="@+id/button1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginRight="10dp"
            android:layout_weight="0.60"
          
            android:text="Submit"
            android:textColor="#FFF" />
        
    </LinearLayout>
 
</LinearLayout>
</ScrollView>
.............................................................end of xml design code---------------------

Second page code
2 feedback.Java 


package com.serviceprovider; // its your packeg name



import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.serviceprovider.JsonParser;
import com.serviceprovider.SessionManager;




import connectiondetector.Category;
import connectiondetector.ServiceHandler;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;


public class Feedback extends Activity  {


TextView empId,CurrentDateTxt,updateDateTxt,getDeviceidTxt;
 
  private EditText tvName,extEmail,txtContact,extMessage;
 
  String tvNameText,extEmailText,txtContactText,extMessageText,CurrentDateText,GetIDText;
 
private Button btnAddNewCategory;
    final Context context = this;
// private Spinner spinnerFood,spinnerFood2;
//    
JSONObject jsonObject, data;
JSONArray dataArray;
SessionManager session;
JsonParser jsonParser;
ArrayList<NameValuePair> postParameters;
String uId;

//private ArrayList<Category> categoriesList;
// 
ProgressDialog pDialog;

private String URL_NEW_CATEGORY ="http://yourweb site link/ServiceProvider/Service_api/AddFeedback.php";

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from singleitemview.xml
setContentView(R.layout.feedbackform);
btnAddNewCategory = (Button) findViewById(R.id.button1);
CurrentDateTxt = (TextView) findViewById(R.id.tvCurrentDate);
   CurrentDateTxt.setVisibility(View.INVISIBLE);
   
   getDeviceidTxt = (TextView) findViewById(R.id.tvGetID);
   getDeviceidTxt.setVisibility(View.INVISIBLE);
   
  tvName = (EditText) findViewById(R.id.tvName);
//
  extEmail = (EditText) findViewById(R.id.extEmail);
  txtContact = (EditText) findViewById(R.id.extContact);
  extMessage = (EditText) findViewById(R.id.extMessage);
     
   ///--------------------code show data time in textview---------------------------
//    
//  //Toast.makeText(this, formattedDate, Toast.LENGTH_SHORT).show();
//
//        
//        
        long date = System.currentTimeMillis(); 
//
       SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss a");
       String dateString = sdf.format(date);   
       CurrentDateTxt.setText(dateString);
//        
//        
       //--------------------------- get phone id--------------------
       String android_id = Secure.getString(this.getContentResolver(),Secure.ANDROID_ID);

        Log.d("Android","Android ID : "+android_id);
        
        getDeviceidTxt.setText(android_id);
  
      
       
       
// // Add new category click event
btnAddNewCategory.setOnClickListener(new View.OnClickListener() {
//
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
if(isOnline(Feedback.this)){
tvNameText = tvName.getText().toString();
extEmailText = extEmail.getText().toString();
txtContactText = txtContact.getText().toString();
extMessageText =extMessage.getText().toString();
 
//  
   CurrentDateText=CurrentDateTxt.getText().toString();
   GetIDText  =getDeviceidTxt.getText().toString();
//
//
//
if (tvNameText.trim().length() == 0)
Toast.makeText(getApplicationContext(),"Please enter your name ", Toast.LENGTH_SHORT).show();
   else if (extEmailText.trim().length() == 0)
  Toast.makeText(getApplicationContext(),"Please enter your email", Toast.LENGTH_SHORT).show();
else if (txtContactText.trim().length() == 0)
  Toast.makeText(getApplicationContext(),"Please enter your mobile no", Toast.LENGTH_SHORT).show();
else if (extMessageText.trim().length() == 0)
  Toast.makeText(getApplicationContext(),"Please enter your message desciption", Toast.LENGTH_SHORT).show();
// else if (extcontactText.trim().length() == 0)
//   Toast.makeText(getApplicationContext(),"Please enter Your Mobile No", Toast.LENGTH_SHORT).show();
// else if (extcityText.trim().length() == 0)
//   Toast.makeText(getApplicationContext(),"Please enter Your City", Toast.LENGTH_SHORT).show();
else if(!isOnline(Feedback.this))
  Toast.makeText(Feedback.this,"Please check your internet connection.", Toast.LENGTH_LONG).show();
else 
//////// // Call Async task to create new category
new AddNewCategory().execute(tvNameText,extEmailText,txtContactText,extMessageText,CurrentDateText,GetIDText);
tvName.setText("");
extEmail.setText("");
txtContact.setText("");
extMessage.setText("");
Toast.makeText(getApplicationContext(), "Sending Successfully", Toast.LENGTH_LONG).show();
 
break;
}
else 
   {
       // Internet connection is not present
    Toast.makeText(getApplicationContext(), "Please check your internet connection.", Toast.LENGTH_SHORT).show();
   }
}
}
//code to check online details
private boolean isOnline(Context mContext) {
ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting())
   {
return true;
    }
   return false;
      }
     //Close code that check online details
});
 
}
 
// //-------code for Insert in php main-------------
private class AddNewCategory extends AsyncTask<String, Void, Void> {
boolean isNewCategoryCreated = false;
//
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Feedback.this);
pDialog.setMessage("Please Wait..");
pDialog.setCancelable(false);
pDialog.show();
}

@Override
protected Void doInBackground(String... arg) {
  //-------code for Insert in php 4-------------
String newName = arg[0];
  String newemail = arg[1];
  String newcontact = arg[2];
      String newmessage = arg[3];
         String newmessagedate = arg[4];
         String newDviceID = arg[5];
 
// // Preparing post params
  List<NameValuePair> params = new ArrayList<NameValuePair>();
                               //table name
    params.add(new BasicNameValuePair("name", newName));
params.add(new BasicNameValuePair("email", newemail));
  params.add(new BasicNameValuePair("contact", newcontact));
  params.add(new BasicNameValuePair("message", newmessage));
      params.add(new BasicNameValuePair("messagedate", newmessagedate));
      params.add(new BasicNameValuePair("deviceID", newDviceID));
   
      
// //-------Close-------------
 
ServiceHandler serviceClient = new ServiceHandler();
String json = serviceClient.makeServiceCall(URL_NEW_CATEGORY,ServiceHandler.POST, params);
Log.d("Create Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
boolean error = jsonObj.getBoolean("error");
// checking for error node in json
if (!error) {
// new category created successfully
isNewCategoryCreated = true;
} else {
Log.e("Create Category Error: ", "> " + jsonObj.getString("message"));
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
// //-------close-------------
//
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
if (isNewCategoryCreated) {
runOnUiThread(new Runnable() {
@Override
public void run() {
  }
});
}
}  
  }


}
 
 -----------------------------------------end of java code---------------------------------------

3 php code 
php code three major file add on your php server
1 file Config.php

<?php
/**
 * Database configuration
 */

define("DB_HOST", "localhost");
define("DB_USERNAME", "Your user name");
define("DB_PASSWORD", "your password");
define("DB_NAME", "your data base name ");





?>
 ----------------------------------------------------------------
2 file dbConnect.php

<?php



class DbConnect {
    
    private $conn;

    // constructor
    function __construct() {
        
        // connecting to database
        $this->connect();
    }

    // destructor
    function __destruct() {
        // closing db connection
        $this->close();
    }

    /**
     * Establishing database connection
     * @return database handler
     */
    function connect() {        
        include_once dirname(__FILE__) . './Config.php';
        
        // Connecting to mysql database
        $this->conn = mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD) or die(mysql_error());

        // Selecting database
        mysql_select_db(DB_NAME) or die(mysql_error());
        
        // returing connection resource
        return $this->conn;
    }

    /**
     * Closing database connection
     */
    function close() {
        // closing db connection
        mysql_close($this->conn);
    }

}

?>
-----------------------------------------------------
3 php file 

<?php

include_once './DbConnect.php';
function createNewCategory() {
    if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['contact'])) {
        // response array for json
        $response = array();
$name = $_POST["name"];
$email = $_POST["email"];
$contact = $_POST["contact"];
        $message = $_POST["message"];
 
$messagedate=$_POST["messagedate"];
 
$status=$_POST["status"];
$deviceID=$_POST["deviceID"];
 
        $db = new DbConnect();
//mysql_query("SET CHARACTER SET 'utf8'");
        // mysql query
        $query = "INSERT INTO serviceprovider_feedbackdata(name,email,contact,message,messagedate, status,deviceID) 
VALUES('$name', '$email', '$contact', '$message', '$messagedate', 'Active','$deviceID')";
        $result = mysql_query($query) or die(mysql_error());
        if ($result) {
            $response["error"] = false;
            $response["message"] = "Thank You for Feedback!";
        } else {
            $response["error"] = true;
            $response["message"] = "Failed To Send Data!";
        }
    } else {
        $response["error"] = true;
        $response["message"] = "Values name is missing!";
    }
    
    // echo json response
    echo json_encode($response);
}

createNewCategory();// its name of java code 
?>


-------------------------------------------------------------------------------


4 data base table  

create a table in mysql 


CREATE TABLE `serviceprovider_feedbackdata` (
  `id` int(100) NOT NULL,
  `name` varchar(200) COLLATE utf8_swedish_ci NOT NULL,
  `email` varchar(200) COLLATE utf8_swedish_ci NOT NULL,
  `contact` varchar(20) COLLATE utf8_swedish_ci NOT NULL,
  `message` varchar(500) COLLATE utf8_swedish_ci NOT NULL,
  `messagedate` varchar(100) COLLATE utf8_swedish_ci NOT NULL,
  `status` varchar(100) COLLATE utf8_swedish_ci NOT NULL,
  `deviceID` varchar(100) COLLATE utf8_swedish_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_swedish_ci;



--------------------------------------------------------------------------------------

its step by step follow and save record on your data in android .


thanks 






1 Comments

Previous Post Next Post

Design a beautiful Login/Signup (with google map) in Flutter | Flutter UI | VS Code | iOS Android