gpt4 book ai didi

java - 如何使用 ArrayAdapter (Java) 将数据插入 MySQL 服务器?

转载 作者:行者123 更新时间:2023-11-29 02:46:51 24 4
gpt4 key购买 nike

我是 android 开发的新手,我想在 MySQL 数据库中插入调用日志详细信息,这里我创建了简单的 ArrayAdapter,它没有在 listview 中设置,第二件事是,如何在 listview 中插入数据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);
}

最佳答案

好吧,我正在使用这种方法将数据从 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");

希望对您有所帮助!!!

关于java - 如何使用 ArrayAdapter (Java) 将数据插入 MySQL 服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40958360/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com