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

时间:2014-07-02 03:55:22

标签: php android mysql json sqlite

我正在开发一个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;
    }
}

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您应该如何做到这一点:

活动类:

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

希望这会有所帮助:)