Sunday, 8 December 2013

How to store and access data from SQL Database using Android without using sqlite

Here one example is given in which i am storing the data into SQL database from Android and also can Display the Data in  Android App from SQL

We are using JSON here because  It is very useful and it makes easy our work which is actually very difficult without JSON.

JSON (JavaScript Object Notation) is a lightweight data exchange format inspired by JavaScript object
literals. It is often used with JavaScript, Ajax, and RESTful web services but is completely language independent.

temp.php

<?php
mysql_connect("localhost","root","");
mysql_select_db("tempdb");
$name=$_REQUEST["firstname"];
$lname=$_REQUEST["lastname"];
$query="insert into tbl_student values(NULL,'".$name."','".$lname."')";
mysql_query($query);
?>

select.php

<?php
mysql_connect("localhost","root","");
mysql_select_db("tempdb");
$query="select * from tbl_student";
$resultset=mysql_query($query);
while($row=mysql_fetch_assoc($resultset))
{
$output[]=$row;
}
print(json_encode($output));
?>

MainActivity.java

public class MainActivity extends Activity {

String result = null;
InputStream is = null;
StringBuilder sb = null;

int ct_id;
String[] ct_name = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

// http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/mittal/select.php");
// 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);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
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());
}

// paring data
JSONArray jArray;
try {
jArray = new JSONArray(result);
JSONObject json_data = null;
ct_name = new String[jArray.length()];
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
ct_id = json_data.getInt("student_id");
ct_name[i] = json_data.getString("student_name")+" "+json_data.getString("student_sname");
}
} catch (JSONException e1) {
Toast.makeText(getBaseContext(), "No City Found", Toast.LENGTH_LONG)
.show();
} catch (ParseException e1) {
e1.printStackTrace();
}

ListView lv=(ListView)findViewById(R.id.listView1);
ArrayAdapter<String> lvadptr=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,ct_name);
lv.setAdapter(lvadptr);

// insert code start
Button btn=(Button)findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
EditText et1=(EditText)findViewById(R.id.editText1);
EditText et2=(EditText)findViewById(R.id.editText2);
String fname=et1.getText().toString();
String lname=et2.getText().toString();

ArrayList<NameValuePair> namevaluepairs=new ArrayList<NameValuePair>();
namevaluepairs.add(new BasicNameValuePair("firstname", fname));
namevaluepairs.add(new BasicNameValuePair("lastname", lname));

try
{
HttpClient httpclient=new DefaultHttpClient();
HttpPost httppost=new HttpPost("http://10.0.2.2/mittal/temp.php");
httppost.setEntity(new UrlEncodedFormEntity(namevaluepairs));

HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();

Intent newint=new Intent(getApplicationContext(), MainActivity.class);
startActivity(newint);

}
catch(Exception e)
{
Log.d("myerror", e.toString());
}
}
});
//insert code end
}

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