2016-12-04 74 views
2

我是Android開發新手,我想在MySQL數據庫中插入通話記錄詳細信息,在這裏我創建了簡單的ArrayAdapter,它沒有在listview中設置,第二件事是如何在MySQL服務器中插入數據。如何使用ArrayAdapter(Java)將數據插入MySQL服務器?

這裏是我的Java代碼

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); 
    } 
} 

這裏是我的PHP腳本.........

<?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); 
} 
+0

所以基本上你想插入到MySQL表中?你有沒有用PHP編寫腳本來從java獲取數據? –

+0

是的我已經在php中編寫了腳本....... @ helldawg –

+0

對,所以你只是想要一種方法來實際上將數據從android發送到php文件,然後將它們插入到mysql中。這可以實現與httpUrlConnection併發出POST請求 –

回答

0

觀看這些視頻,並學習如何將數據插入到網絡服務器的phpmyadmin使用你的Android應用程序。爲此,從000webhost獲得一個免費的Web託管服務器,用於在線創建數據庫以存儲數據,然後可以在線檢索數據。

簡單而有趣的方式來學習如何在Web服務器上在線存儲數據。

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

這是視頻的第一部分。

+0

使用SQLite存儲離線數據。 –

+0

不,我使用MySQL數據庫.... –

+0

我製作的家長控制應用程序的兒童安全.... –

1

那麼我使用這種方法上傳數據從Android到MySQL數據庫。首先,您需要使用AsyncTask與.php文件進行通信併發送數據。所以我建議試試這個:

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(); 
     } 
    } 

,然後你InputStreamToString方法:

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; 
    } 

,這應該插入數據,如果一切是正確的。你必須這樣執行:

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

希望它有幫助!

+0

感謝您的回答........我盡一切可能的方式,我也使用AsyncTask方法。看我的問題鏈接 - http://stackoverflow.com/questions/40948014/how-to-convert-single-string-to-jsonarray-in-android –

+0

我的問題是,服務器是更多的負載,然後服務器暫停。 –

+0

然後問題出在您的服務器上...找到一個更好的服務器 –

相關問題