从PHP将数据保存到Android的数据库 [英] Saving data from PHP to Android Database

查看:136
本文介绍了从PHP将数据保存到Android的数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想数据从MySQL通过PHP保存到我的Andr​​oid SQLite数据库。我使用从其他教程code。

我使用一个数据库适配器和数据库助手的。

我试图使这项工作,但不知道接下来该怎么办,我还需要关闭数据库,以prevent内存泄漏。

谁能告诉我,如果这种做法是正确的,放什么在PhpAdapter将数据插入到数据库中。

感谢

PhpActivity.java

 进口java.io.BufferedReader中;
进口的java.io.InputStream;
进口java.io.InputStreamReader中;
进口的java.util.ArrayList;进口org.apache.http.HttpEntity;
进口org.apache.http.Htt presponse;
进口org.apache.http.NameValuePair;
进口org.apache.http.client.HttpClient;
进口org.apache.http.client.entity.UrlEn codedFormEntity;
进口org.apache.http.client.methods.HttpPost;
进口org.apache.http.impl.client.DefaultHttpClient;
进口org.apache.http.message.BasicNameValuePair;
进口org.json.JSONArray;
进口org.json.JSONException;
进口org.json.JSONObject;进口android.app.Activity;
进口android.os.Bundle;
进口android.util.Log;
进口android.widget.EditText;
进口android.widget.LinearLayout;
进口android.widget.TextView;
公共类PhpActivity延伸活动{
私人PhpAdapter dbHelper;
/ **当第一次创建活动调用。 * /TextView的TXT;
//的EditText edittxt;
@覆盖
公共无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.main);
dbHelper =新PhpAdapter(本);
dbHelper.open();
//创建一个视图原油 - 这确实应该通过布局资源设置
//但由于它的一个例子节省宣布他们在XML。
的LinearLayout rootLayout =新的LinearLayout(getApplicationContext());
TXT =新的TextView(getApplicationContext());
rootLayout.addView(TXT);
// edittxt =新的EditText(本);
//rootLayout.addView(edittxt);
的setContentView(rootLayout); //设置文本并调用connect函数。
 txt.setText(连接...);
//调用该方法来运行数据retreival
txt.setText(getServerData(KEY_121));}
公共静态最后弦乐KEY_121 =htt​​p://10.101.0.64/peopledata/getAllPeopleBornAfter.php; //我在这里用我的真实IP私人字符串getServerData(字符串returnString){InputStream为= NULL;字符串结果=;
//年的数据发送
ArrayList的<&的NameValuePair GT; namevaluepairs中=新的ArrayList<&的NameValuePair GT;();
nameValuePairs.add(新BasicNameValuePair(年,2007));
//nameValuePairs.add(new BasicNameValuePair(年,edittxt.getText()的toString()));// HTTP POST
尝试{
        HttpClient的HttpClient的=新DefaultHttpClient();
        HttpPost httppost =新HttpPost(KEY_121);
        httppost.setEntity(新UrlEn codedFormEntity(namevaluepairs中));
        HTT presponse响应= httpclient.execute(httppost);
        HttpEntity实体= response.getEntity();
        是= entity.getContent();}赶上(例外五){
        Log.e(log_tag,在HTTP连接错误+ e.toString());
}//响应转换为字符串
尝试{
        读者的BufferedReader =新的BufferedReader(新的InputStreamReader(是,ISO-8859-1),8);
        StringBuilder的SB =新的StringBuilder();
        串线= NULL;
        而((行= reader.readLine())!= NULL){
                sb.append(行+\\ n);
        }
        is.close();
        结果= sb.toString();
}赶上(例外五){
        Log.e(log_tag,错误转换结果+ e.toString());
}
//解析JSON数据
尝试{
        JSONArray jArray =新JSONArray(结果);
        的for(int i = 0; I< jArray.length();我++){
                JSONObject的json_data = jArray.getJSONObject(I)
                串qureylog =插入或替换成表(姓名,性别,birthyear)+
                        VALUES('+ json_data.getString(名称)+',+
                                '+ json_data.getString(性)+',+
                                '+ json_data.getString(birthyear)+');
                dbHelper.insert(qureylog);                Log.i(log_tag,I​​D:+ json_data.getInt(ID)+
                        ,名称:+ json_data.getString(名称)+
                        性别:+ json_data.getString(性)+
                        birthyear:+ json_data.getInt(birthyear)
                );
                //获取输出到屏幕上
               // returnString + =\\ n \\ t+ jArray.getJSONObject(I)
        }
}赶上(JSONException E){
        Log.e(log_tag,错误分析数据+ e.toString());
}
返回returnString;
}
}

PhpAdapter.java

 进口android.content.ContentValues​​;
进口android.content.Context;
进口android.database.Cursor;
进口android.database.SQLException;
进口android.database.sqlite.SQLiteDatabase;公共类PhpAdapter {私有静态最后弦乐DATABASE_TABLE =人;
私人上下文的背景下;
私人PhpAdapter dbHelper;
私人SQLiteDatabase数据库;公共PhpAdapter(上下文的背景下){
    this.context =背景;
}公共PhpAdapter的open(){
    dbHelper =新PhpAdapter(背景);
    //数据库= dbHelper.getWritableDatabase();
    返回此;
}公共无效的close(){
    dbHelper.close();
}公共无效插入(字符串qureylog){
    // TODO自动生成方法存根}}

DatabaseHelper

 进口android.content.Context;
进口android.database.sqlite.SQLiteDatabase;
进口android.database.sqlite.SQLiteOpenHelper;
进口android.util.Log;公共类DatabaseHelper扩展SQLiteOpenHelper {
私有静态最后弦乐DATABASE_NAME =phpdb;
私有静态最终诠释DATABASE_VERSION = 1;
公共DatabaseHelper(上下文的背景下){
    超(背景下,DATABASE_NAME,空,DATABASE_VERSION);
}私有静态最后弦乐DATABASE_CREATE =创建表的人+
        (_id整数主键自动增量,+
        性文本,文本的名字,birthyear文本);//方法是创建数据库中调用
    @覆盖
    公共无效的onCreate(SQLiteDatabase数据库){
        database.execSQL(DATABASE_CREATE);
    }    //方法是数据库的升级过程中调用,例如如果增加
    //数据库版本
    @覆盖
    公共无效onUpgrade(SQLiteDatabase数据库,诠释oldVersion,
            INT静态网页){
        Log.w(DatabaseHelper.class.getName(),
                + oldVersion +到从版本升级数据库
                        + NEWVERSION +,这将摧毁所有旧数据);
        database.execSQL(DROP TABLE IF EXISTS人);
        的onCreate(数据库);
    }
}


解决方案

基本上看起来不错。您可以关闭您在活动的的onDestroy()分贝。

对于dbAdapter后的youre ...值得怀疑的实施人在这里SO打算写你...但对于简单的dbAdapter例如一个很好的资源是雷托梅厄的Andr​​oid 2应用开发的书。

您可以在在以下链接样本code。你想看看的第7章的code房源它会帮助你很多。

<一个href=\"http://www.wrox.com/WileyCDA/WroxTitle/Professional-Android-2-Application-Development.productCd-0470565527,descCd-DOWNLOAD.html\" rel=\"nofollow\">http://www.wrox.com/WileyCDA/WroxTitle/Professional-Android-2-Application-Development.productCd-0470565527,descCd-DOWNLOAD.html

I would like to save data from MySQL via PHP to my Android SQLite Database. I am using code from other tutorials.

I make use of a Database Adapter and a Database Helper.

I tried to make this work but not sure what to do next and I also need close the database to prevent memory leak.

Can anyone tell me if this approach is correct and what to put in the PhpAdapter to insert the data to the database.

Thanks

PhpActivity.java

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;


public class PhpActivity extends Activity {
private PhpAdapter dbHelper;
/** Called when the activity is first created. */

TextView txt;
//EditText edittxt;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
dbHelper = new PhpAdapter(this);
dbHelper.open();
// Create a crude view - this should really be set via the layout resources 
// but since its an example saves declaring them in the XML. 
LinearLayout rootLayout = new LinearLayout(getApplicationContext()); 
txt = new TextView(getApplicationContext()); 
rootLayout.addView(txt); 
//edittxt = new EditText(this);
//rootLayout.addView(edittxt);
setContentView(rootLayout); 

 // Set the text and call the connect function. 
 txt.setText("Connecting...");
//call the method to run the data retreival
txt.setText(getServerData(KEY_121));



}
public static final String KEY_121 = "http://10.101.0.64/peopledata/getAllPeopleBornAfter.php"; //i use my real ip here



private String getServerData(String returnString) {

InputStream is = null;

String result = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("year", "2007"));
//nameValuePairs.add(new BasicNameValuePair("year", edittxt.getText().toString()));

//http post
try{
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(KEY_121);
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

}catch(Exception e){
        Log.e("log_tag", "Error in http connection "+e.toString());
}

//convert response to string
try{
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
        }
        is.close();
        result=sb.toString();
}catch(Exception e){
        Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try{
        JSONArray jArray = new JSONArray(result);
        for(int i=0;i<jArray.length();i++){
                JSONObject json_data = jArray.getJSONObject(i);
                String qureylog ="insert or replace into table(name, sex, birthyear) " +
                        "values('"+json_data.getString("name")+"'," +
                                " '"+json_data.getString("sex")+"'," +
                                " '"+json_data.getString("birthyear")+"')";
                dbHelper.insert(qureylog);

                Log.i("log_tag","id: "+json_data.getInt("id")+
                        ", name: "+json_data.getString("name")+
                        ", sex: "+json_data.getString("sex")+
                        ", birthyear: "+json_data.getInt("birthyear")
                );
                //Get an output to the screen
               // returnString += "\n\t" + jArray.getJSONObject(i);
        }
}catch(JSONException e){
        Log.e("log_tag", "Error parsing data "+e.toString());
}
return returnString;
}   


}

PhpAdapter.java

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class PhpAdapter {

private static final String DATABASE_TABLE = "people";
private Context context;
private PhpAdapter dbHelper;
private SQLiteDatabase database;

public PhpAdapter(Context context) {
    this.context = context;
}

public PhpAdapter open() {
    dbHelper = new PhpAdapter(context);
    //database = dbHelper.getWritableDatabase();
    return this;
}

public void close() {
    dbHelper.close();
}

public void insert(String qureylog) {
    // TODO Auto-generated method stub

}

}

DatabaseHelper

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "phpdb";
private static final int DATABASE_VERSION = 1;


public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

private static final String DATABASE_CREATE = "create table people" +
        " (_id integer primary key autoincrement, " +
        "sex text , name text , birthyear text);";

// Method is called during creation of the database
    @Override
    public void onCreate(SQLiteDatabase database) {
        database.execSQL(DATABASE_CREATE);
    }

    // Method is called during an upgrade of the database, e.g. if you increase
    // the database version
    @Override
    public void onUpgrade(SQLiteDatabase database, int oldVersion,
            int newVersion) {
        Log.w(DatabaseHelper.class.getName(),
                "Upgrading database from version " + oldVersion + " to "
                        + newVersion + ", which will destroy all old data");
        database.execSQL("DROP TABLE IF EXISTS people");
        onCreate(database);
    }
}

解决方案

Basically looks fine. You can close you db in your activity's onDestroy().

As for the implementation of the dbAdapter youre after...doubtful that people here on SO are going to write it for you...but a good resource for simple dbAdapter example is Reto Meir's Android 2 Application Development book.

You can get at the sample code at the following link. You want to look at the code listings for chapter 7. It will help you plenty.

http://www.wrox.com/WileyCDA/WroxTitle/Professional-Android-2-Application-Development.productCd-0470565527,descCd-DOWNLOAD.html

这篇关于从PHP将数据保存到Android的数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆