如何从mysql中获取数据并存储在android的Sqlite数据库中

Posted

技术标签:

【中文标题】如何从mysql中获取数据并存储在android的Sqlite数据库中【英文标题】:How to fetch data from mysql and store in Sqlite database in android 【发布时间】:2014-08-22 17:49:04 【问题描述】:

我正在开发一个 android 应用程序,我需要在其中通过服务器获取存储在 mysql 数据库中的数据。从 mysql 获取数据并显示到 android 很容易,我没有任何问题。但我不知道如何获取 mysql 数据,然后将其存储在 sqlite 数据库中以显示在表视图中。这是我的 mysql 到 android 的代码。请帮助我如何从 mysql 中获取数据并存储在 sqlite 中。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class MainActivity extends Activity

    private String jsonResult;
    private String url = "http://10.0.2.2/database/menu_details.php";
    private ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.listView1);
        accessWebService();
    

    @Override
    public boolean onCreateOptionsMenu(Menu menu) 

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    

    // Async Task to access the web
    private class JsonReadTask extends AsyncTask<String, Void, String> 
        @Override
        protected String doInBackground(String... params) 
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(params[0]);
            try 
                HttpResponse response = httpclient.execute(httppost);
                jsonResult = inputStreamToString(
                        response.getEntity().getContent()).toString();
            

            catch (ClientProtocolException e) 
                e.printStackTrace();
             catch (IOException e) 
                e.printStackTrace();
            
            return null;
        

        private StringBuilder inputStreamToString(InputStream is) 
            String rLine = "";
            StringBuilder answer = new StringBuilder();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));

            try 
                while ((rLine = rd.readLine()) != null) 
                    answer.append(rLine);
                
            

            catch (IOException e) 
                // e.printStackTrace();
                Toast.makeText(getApplicationContext(),
                        "Error..." + e.toString(), Toast.LENGTH_LONG).show();
            
            return answer;
        

        @Override
        protected void onPostExecute(String result) 
            ListDrwaer();
        
    // end async task

    public void accessWebService() 
        JsonReadTask task = new JsonReadTask();
        // passes values for the urls string array
        task.execute(new String[]  url );
    

    // build hash set for list view
    public void ListDrwaer() 
        List<Map<String, String>> menuList = new ArrayList<Map<String, String>>();

        try 
            JSONObject jsonResponse = new JSONObject(jsonResult);
            JSONArray jsonMainNode = jsonResponse.optJSONArray("menu");

            for (int i = 0; i < jsonMainNode.length(); i++) 
                JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
                String name = jsonChildNode.optString("name");
                String id = jsonChildNode.optString("id");
                String outPut = name + "-" + id;
                menuList.add(createMenu("Menu", outPut));
            
         
        catch (JSONException e) 
        
            Toast.makeText(getApplicationContext(), "Error" + e.toString(),Toast.LENGTH_SHORT).show();
        

        SimpleAdapter simpleAdapter = new SimpleAdapter(this, menuList,android.R.layout.simple_list_item_1,
                new String[]  "Menu" , new int[]  android.R.id.text1 );
        listView.setAdapter(simpleAdapter);
    

    private HashMap<String, String> createMenu(String name, String number) 
        HashMap<String, String> menuID = new HashMap<String, String>();
        menuID.put(name, number);
        return menuID;
    

【问题讨论】:

引用任何 sqlite 的 tuts 和 crete 它......你试图创建它吗?有什么问题吗? androidhive.info/2012/01/… 看看这个也许对你有帮助 @mona 我看过这么多教程但没有得到解决方案..我想要从 mysql 到 sqlite 的数据...然后在 android 活动中显示...!!! 你的意思是从远程 MySQl fetchinf 数据并本地存储在 sqlite db 中? 好的,你成功从服务器获取数据了吗? 【参考方案1】:
Follow the steps.

**1. Create table in database handler**

**2. create method in databse handler**
For example:- 



`    public void addUser(String name, String email,String userage) 

        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(KEY_NAME, name); // Name
        values.put(KEY_EMAIL, email); // Email
`



**3. you need to create hashmap and other things in database handler**

**4. Userfunction- create same name method in userfunction with params**

 then in main activity call the method using json. example


  ` UserFunctions userFunction = new UserFunctions();
                Log.d("Button", "Login");
                JSONObject json = userFunction.loginUser(email, password);`

【讨论】:

如果你帮助 php 做评论。【参考方案2】:

你应该这样做:

活动类:

private void registerUser(final String name, final String email, final String password) 

        StringRequest strReq = new StringRequest(Request.Method.POST,
                AppConfig.URL_INSERT_REGISTER, new Response.Listener<String>() 

            @Override
            public void onResponse(String response) 
                Log.d(TAG, "Register Response: " + response.toString());
                hideDialog();

                try 
                    ServiceController iia = new ServiceController(getApplicationContext());

                    if (iia.isInternetAvailable()) 
                        JSONObject jObj = new JSONObject(response);
                        boolean error = jObj.getBoolean("error");
                        if (!error) 
                            String uid = jObj.getString("uid");
                            JSONObject user = jObj.getJSONObject("user");
                            String name = user.getString("name");
                            String email = user.getString("email");

                            //The line below performs the insert to the sqllite database.
                            db.addUser(name, email, uid);
                        
                    
                 catch (JSONException e) 
                    e.printStackTrace();
                

            
        , new Response.ErrorListener() 

            @Override
            public void onErrorResponse(VolleyError error) 
                Log.e(TAG, "Registration Error: " + error.getMessage());
            
        ) 

            @Override
            protected Map<String, String> getParams() 
                Map<String, String> params = new HashMap<String, String>();
                params.put("name", name);
                params.put("email", email);
                params.put("password", password);

                return params;
            

        ;

        AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
    

在数据库创建类中需要添加如下方法:

public void addUser(String name, String email, String uid) 
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues params = new ContentValues();
    params.put(KEY_NAME, name);
    params.put(KEY_EMAIL, email);
    params.put(KEY_UID, uid);

    long id = db.insert(TABLE_USER, null, params);
    db.close();

    Log.d(TAG, "New record inserted in table user: " + id);

希望这会有所帮助:)

【讨论】:

以上是关于如何从mysql中获取数据并存储在android的Sqlite数据库中的主要内容,如果未能解决你的问题,请参考以下文章

从数据库获取事件并放置日历视图(android)

如何从 MySQL 数据库中获取数据并在 javascript 自动完成中使用?

从浏览器手动将图像存储在 Firebase 存储中。如何使其反映在实时数据库中。这样我就可以在 Android 应用程序中获取

从android应用程序获取数据并使用php将其存储在sql数据库中

在 Android Studio 中从用户那里获取图片并进行编码,以便可以将其存储在数据库中

Android - 如何使用 PHP 从 MySQL 数据库中获取响应?