I am developing an android application in which I need to fetch data which is stored in mysql database over server. Fetching data from mysql and display to android is easy and I did without any problem. But I am not getting any idea about how to fetch mysql data and then store it in sqlite database to display in table view. This is my code for mysql to android. please help me how to fetch data from mysql and store in 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;
}
}
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);`
Here is how you should do it:
Activity class:
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);
}
In the database creation class you need to add the following method:
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);
}
Hope this helps :)