2

I am new in android development, I want to insert call log details in MySQL database, here I have created simple ArrayAdapter that's not getting set in listview and second thing is, how to insert data in MySQL server.

Here is my java code

public class MainActivity extends Activity {
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    listView = (ListView) findViewById(R.id.lv);
    getCallDetails();
}
private void getCallDetails()
{
    StringBuffer sb = new StringBuffer();
    String strOrder = android.provider.CallLog.Calls.DATE + " DESC";
    Cursor managedCursor = managedQuery(CallLog.Calls.CONTENT_URI, null,null, null, strOrder);
    int number1 = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
    int type1 = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
    int duration1 = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
    sb.append("Call Log :");
    while (managedCursor.moveToNext())
    {
        final String number = managedCursor.getString(number1);
        final String type2 = managedCursor.getString(type1);
        final String date = managedCursor.getString(managedCursor.getColumnIndexOrThrow("date")).toString();
        java.util.Date date1 = new java.util.Date(Long.valueOf(date));
        final String duration = managedCursor.getString(duration1);
        String type = null;
        final String fDate = date1.toString();
        int callcode = Integer.parseInt(type2);
        switch (callcode)
        {
            case CallLog.Calls.OUTGOING_TYPE:
                type = "Outgoing";
                break;
            case CallLog.Calls.INCOMING_TYPE:
                type = "Incoming";
                break;
            case CallLog.Calls.MISSED_TYPE:
                type = "Missed";
                break;
        }
        List<DataBean> DataBeanList = new  ArrayList<DataBean>();
        DataBean dataBean = new DataBean(number, type, fDate, duration);
        DataBeanList.add(dataBean);
        Log.d("tag", DataBeanList.toString());
    }
    managedCursor.close();
    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,android.R.id.text1);
    listView.setAdapter(arrayAdapter);
   }
 }

Here is my php script.........

 <?php 
 //Importing our db connection script
 require_once('connect.php');

if($_SERVER['REQUEST_METHOD']=='POST'){
//Getting values
$number = $_POST['number'];
$duration = $_POST['duration'];
$type = $_POST['type'];
$time = $_POST['time'];

//Creating an sql query
$sql = "INSERT INTO call_detail (number,duration,type,time) VALUES   ('$number','$duration','$type','$time')";

    //Executing query to database
    if(mysqli_query($con,$sql)){
        echo 'Entry Added Successfully';
    }else{
        echo 'Could Not Add Entry';
    }

//Closing the database 
mysqli_close($con);
 }

2 Answers2

1

Well i am using this method to upload data from Android to MySQL Database. First of all you need an AsyncTask to communicate with the .php file and send the data. So i would suggest to try this:

public class MyInsertDataTask extends AsyncTask<String, Void, Boolean> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(YourActivity.this);
            pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            pDialog.setIndeterminate(true);
            pDialog.setMessage("Data Processing");
            pDialog.setCancelable(false);
            pDialog.setInverseBackgroundForced(true);
            pDialog.show();
        }

        @Override
        protected Boolean doInBackground(String... params) {
            try {
                URL url = new URL(params[0]);
                HttpURLConnection urlConnection =(HttpURLConnection) url.openConnection();
                urlConnection.setRequestProperty("Accept-Encoding", "application/json");
                urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
                urlConnection.setRequestMethod("POST");

                urlConnection.setDoInput(true);
                urlConnection.setDoOutput(true);
                urlConnection.connect();

                setupDataToDB();
                OutputStreamWriter outputStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream());
                outputStreamWriter.write(dataToWrite.toString());
                Log.e("Data To Write", dataToWrite.toString());
                outputStreamWriter.flush();
                outputStreamWriter.close();
                int responseCode = urlConnection.getResponseCode();
                Log.e("Response Code ", String.valueOf(responseCode));
                if (responseCode == 200){
                   InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());

                   StringBuilder jsonResult = inputStreamToString(inputStream, YourActivity.this);
                   JSONObject jsonResponse = new JSONObject(jsonResult.toString());
                   Log.e("Data From JSON", jsonResponse.toString());
                   return true;
                }else{
                    InputStream inputStream = new BufferedInputStream(urlConnection.getErrorStream());
                    Log.e("ERROR STREAM", inputStream.toString());
                    return false;
                }
            } catch (Exception e) {
                e.printStackTrace();

            }

            return false;
        }
        @Override
        protected void onPostExecute(Boolean aVoid) {
            super.onPostExecute(aVoid);
            pDialog.dismiss();
            if (aVoid){
                Toast.makeText(YourActivity.this, "Data Sent", Toast.LENGTH_LONG).show();
                YourActivity.this.finish();
            }else{
                Toast.makeText(YourActivity.this, "There was a problemm sending the data. Please try again", Toast.LENGTH_LONG).show();
            }

        }
    }

    private void setupDataToDB() {
        JSONObject dataToWrite = new JSONObject();
        try {
            dataToWrite.put("number", numberStringFromJava);
            dataToWrite.put("duration", durationStringFromJava);
            dataToWrite.put("type", typeStringFromJava);
            dataToWrite.put("time", timeStringFromJava);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    } 

and then your InputStreamToString method:

public StringBuilder inputStreamToString(InputStream is, Activity activity) {
        String rLine;
        StringBuilder answer = new StringBuilder();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        try {
            while ((rLine = rd.readLine()) != null) {
                answer.append(rLine);
            }
        } catch (Exception e) {
            activity.finish();
        }
        return answer;
    }

And this should insert the data if everything is correct. You have to execute it like this:

new MyInsertDataTask().execute("Your_php_file_path");

Hope it helps!!!

Kostas Drak
  • 3,222
  • 6
  • 28
  • 60
  • thank's for your answer........i do all posible way, and i also use AsyncTask method. see in my question link--http://stackoverflow.com/questions/40948014/how-to-convert-single-string-to-jsonarray-in-android – Secret_Volcano Dec 04 '16 at 13:54
  • my problem is that server is more load and then server is suspend. – Secret_Volcano Dec 04 '16 at 13:57
  • then the problem is with your server...find a better server – Kostas Drak Dec 04 '16 at 13:57
  • i dont know if there is another way because in either way you have to open a connection->send data->close connection. I cannot imagine a different way. – Kostas Drak Dec 04 '16 at 14:01
  • why do you want to convert string to json array? you can do JSONArray array = new JSONArray(yourString); – Kostas Drak Dec 04 '16 at 14:05
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/129734/discussion-between-secret-volcano-and-kostas-drak). – Secret_Volcano Dec 04 '16 at 14:07
0

Watch these videos and learn how to insert data into online phpmyadmin server using your android app. For this, get a free web hosting server from 000webhost for creating a database online to store data and then can retrieve data online.

Simple and Interesting way to learn how to store data online on a web server.

https://www.youtube.com/watch?v=k3O3CY75ITY

This is the first part of the video.

Harnirvair Singh
  • 583
  • 7
  • 23