Am kind of new to android.the thing is i programmed a vb code to upload some data to SQL server including an image.so i want to create an android app to view these data by creating a drop down list with the main entry in the database..so whenever i choose something from the drop down list it suppose to show the rest of the columns..sorry for my English but i hope u guys got the idea.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void query2() {
Log.i("Android"," MySQL Connect Example.");
Connection conn = null;
try {
String driver = "net.sourceforge.jtds.jdbc.Driver";
Class.forName(driver).newInstance();
//test = com.microsoft.sqlserver.jdbc.SQLServerDriver.class;
String connString = "jdbc:jtds:sqlserver:// AMD/SQLEXPRESS :1433/***********;encrypt=fasle;user=*******;password=*********;instance=SQLEXPRESS;";
String username = "Shawtari";
String password = "";
conn = DriverManager.getConnection(connString,username,password);
Log.w("Connection","open");
Statement stmt = conn.createStatement();
ResultSet forest = stmt.executeQuery("select * from aspnet_Users");
//Print the data to the console
while(forest.next()){
Log.w("username",forest.getString(3));
}
conn.close();
} catch (Exception e) {
Log.w("Error connection","" + e.getMessage());
}
}
}
Use a Spinner to show your main entries and a ListView to show the columns
Add a OnItemSelectedListener for this spinner. In this listener, make the JDBC call as a background task preferably using AsyncTask.
After getting the response, populate the listview . You may need to implement a custom adapter which takes the ResultSet and parse it to feed it to your listview.
Related
I'm new to android and not much aware about it. I though have been through tutorial but still didn't get any solution. How to connect Android Studio with postgressql? Step by step!
I wrote this code in my MainActitvity.java. Is this correct? Or should I write it else where?
static final String JDBC_DRIVER = "org.postgresql.Driver";
static final String DB_URL = "jdbc:postgresql://localhost:5432/user1";
// Database credentials
static final String USER = "root";
static final String PASS = "root";
public static void main(String[] args)
{
Connection conn = null;
Statement st = null;
try{
//STEP 2: Register JDBC driver
Class.forName("org.postgresql.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/","root","root");
//STEP 4: Execute a query
System.out.println("Creating statement...");
st = conn.createStatement();
String sql;
sql = "SELECT first, last FROM Employees";
ResultSet rs = st.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
String first = rs.getString("first");
String last = rs.getString("last");
//Display values
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
//STEP 6: Clean-up environment
rs.close();
st.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}
finally
{
//finally block used to close resources
try{
if(st!=null)
st.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}
catch(SQLException se){
se.printStackTrace();
}//end finally try
}
}
use 10.0.2.2 instead of localhost, it works for me.
You cannot directly use java.sql.DriverManger, Connection, etc in Android. Android support SQLite DB, if you want to use DB in android you have to go with SQLite database. For Postgres you have to develop server side application and api services which you can the call from Android
Okay, this may be obsolete but still helpful for users (it was helpful for me)
I copied your example and worked with it because I also need to get postgres running on android. And it works!
conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/","root","root");
This will result in an error because you need to enter the database name without a slash at the and, like:
conn = DriverManager.getConnection("jdbc:postgresql://domain.com:5432/databaseName", "username", "password");
Network connections (like connection to database) must be done in an AsyncTask using doInBackground(). I did it inside an activity
public class dbactivity extends AppCompatActivity { //sry code formatting just broke
String message = null;
String conmsg = null;
private class pgsqlcon extends AsyncTask<Void, Void, Void>
{
public pgsqlcon()
{
super();
}
#Override
protected Void doInBackground(Void... voids) {
Connection conn = null;
Statement st = null;
try
{
//STEP 2: Register JDBC driver
Class.forName("org.postgresql.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
message = "Connecting to database...";
conn = DriverManager.getConnection("jdbc:postgresql://serverdomain.com:5432/databasename",
"dbusername", "password");
//and so on
If you need to make UI changes like setText, you must use runOnUiThread like so ():
//using quote because code formatting doesn't work anymore for me xD
private void setAsyncText(final TextView text,final String value){
runOnUiThread(new Runnable() {
#Override
public void run() {
if (value == null)
text.setText("null");
else
text.setText(value);
}
});
}
Oh yeah and last but not least, since I wrote this inside an Activiy, I have to trigger the trouble by calling my asynctask in OnCreate() of my Activity.
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dbactivity);
pgsqlcon pgcon = new pgsqlcon();
pgcon.execute();
}
}
I am not that experienced by myself so you can use this only for getting a connection at all to your postgresdb using JDBC only. Although I managed to get successful query results that way.
And again, sorry for the wrong code formatting. I did what they wanted (4 space rule etc.) and it didn't work. I hope you can read it anyway, good luck.
And if nothing of this does work, maybeeee you want to take a look at these little hints: https://jdbc.postgresql.org/documentation/head/prepare.html
(I assume you did that anyway since you have done a lot of almost correct code)
My app uses PostgreSQL as backend. Use the retrofit library for connecting to the backend. In my app backend is written in python which will make queries in the database. This will make the front-end codes more smooth and secure. And the more controls can be shifted to the back-end.
You can not connect the database with android studio directly,
you have to make connection with your application and database through api ,
and you can write your api in java, php etc.
?php
$db_connection = pg_connect("host=localhost dbname=record user=postgres password= ''");
//pg query
?>
This is your connect query api.
I have gone through all possible articles to get an overview of the logic behind retrieving the data from SQLite DB.But I still can't figure out the possible solution. It would be helpful if someone gives an overview of that.
For eg. I just get age as input from user and I have to display all the names matching with it.So in a table there can be n number of data matching with it.How to manage those dynamically and display that in UI?
Is there any predefined views present to handle?
You can use TableLayout but it does not show cell borders.
Alternatively you can make a custom ListView and populate it with a cursor adapter.
See this for populating a ListView with CursorAdapter.
Hope this helps.
using System;
using System.Data.SqlClient;
using System.Text;
namespace DisplayDataInUI
{
public partial class ProductListView : System.Web.UI.Page
{
StringBuilder table = new StringBuilder();
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection();
connection.ConnectionString = "Data Source=localhost;Initial Catalog=Product; Integrated Security=True";
try
{
connection.Open();
SqlCommand cmd = new SqlCommand("sp_GetAllProducts", connection);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
SqlDataReader dr = cmd.ExecuteReader();
table.Append("<table border='1'>");
table.Append("<tr>");
table.Append("<th>ProductID</th><th>Name</th><th>Product Type</th><th>Price</th><th>NumberofInvoices</th>");
table.Append("</tr>");
if(dr.HasRows)
{
while(dr.Read())
{
table.Append("<tr>");
table.Append("<td>"+ dr[0] +"</td>");
table.Append("<td>"+ dr[1] +"</td>");
table.Append("<td>"+ dr[2] +"</td>");
table.Append("<td>"+ dr[3] +"</td>");
table.Append("<td>" + dr[4] + "</td>");
table.Append("</tr>");
}
}
table.Append("</table>");
PlaceHolder1.Controls.Add(new System.Web.UI.WebControls.Literal { Text = table.ToString() });
dr.Close();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Data retrieval Error";
msg += ex.Message;
}
finally
{
connection.Close();
}
}
}
}
PHP file
$con=mysqli_connect("mysql3.000webhost.com","a9225790_studio","pwd","a9225790_studio");
$sub=$_REQUEST['$subject'];
$data=mysqli_query($con,"select * from Questions where Subject='$sub'");
if(mysqli_num_rows($data)>0)
{
$resp['question-status']="SUCCESS";
while($r=mysqli_fetch_array($data))
{
$resp['Questions'].=$r['Question'].",".$r['Option1'].",".$r['Option2'].",".$r['Option3'].",".$r['Option4'].",".$r['Answer'].";";
}
echo json_encode($resp);
}
else
{
$resp['question-status']="ERROR";
echo json_encode($resp);
}
mysqli_close($con);
?>
Select query not returning anything for the $sub Subject. However Question,options and answer for the corresponding $sub Subject is there in the table.
It always going in else loop
$resp['question-status']="ERROR";
Android Code
public class Exam extends AppCompatActivity implements View.OnClickListener {
TextView no,ques;
RadioGroup op;
RadioButton op1,op2,op3,op4;
Button ne,pass,submit;
String correctAnswer,userAnswer,n,subject;
int totalQuestion,currentQuestion;
ArrayList<String> allQuestion=new ArrayList<String>();
int score=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exam);
Bundle b=getIntent().getExtras();
n=b.getString("UN");
subject=b.getString("SUB");
userAnswer="";
// time=(TextView)findViewById(R.id.time);
//totq=(TextView)findViewById(R.id.totq);
no=(TextView)findViewById(R.id.no);
ques=(TextView)findViewById(R.id.ques);
op=(RadioGroup)findViewById(R.id.op);
op1=(RadioButton)findViewById(R.id.op1);
op2=(RadioButton)findViewById(R.id.op2);
op3=(RadioButton)findViewById(R.id.op3);
op4=(RadioButton)findViewById(R.id.op4);
ne=(Button)findViewById(R.id.ne);
pass=(Button)findViewById(R.id.pass);
submit=(Button)findViewById(R.id.submit);
ne.setOnClickListener(this);
pass.setOnClickListener(this);
submit.setOnClickListener(this);
op1.setOnClickListener(new MyAnswerListener());
op2.setOnClickListener(new MyAnswerListener());
op3.setOnClickListener(new MyAnswerListener());
op4.setOnClickListener(new MyAnswerListener());
ArrayList<NameValuePair> list=new ArrayList<NameValuePair>(1);
list.add(new BasicNameValuePair("subject",subject));
Toast.makeText(getApplicationContext(),subject,Toast.LENGTH_SHORT).show();
String res=MyJsonToStringConverter.convert(list,"http://rgworks.site90.net/android_studio/e_exam/FetchQuestions.php");
try
{
JSONObject j=new JSONObject(res);
if(j.getString("question-status").equals("SUCCESS"))
{
String [] data=j.getString("Questions").split(";");
for (String s1 : data)
{
allQuestion.add(s1);
}
}
else if(j.getString("question-status").equals("ERROR"))
{
Toast.makeText(getApplicationContext(), "No questions available", Toast.LENGTH_LONG).show();
}
}
catch(Exception e)
{
Log.e("log_e", e.toString());
}
totalQuestion=allQuestion.size();
if (totalQuestion == 0)
{
Toast.makeText(getApplicationContext(),"No Question",Toast.LENGTH_SHORT).show();
}
else
{
nextQuestion();
}
}
public void nextQuestion()
{
String [] q1=allQuestion.get(currentQuestion).split(",");
no.setText(String.valueOf(currentQuestion+1 +"."+" "));
ques.setText(q1[0]);
op1.setText(q1[1]);
op2.setText(q1[2]);
op3.setText(q1[3]);
op4.setText(q1[4]);
correctAnswer=q1[5];
op.clearCheck();
}
And in the android code i have checked for the value of 'subject' by printing it in Toast. Before sending this value to Php file it is Successfully printed. But in the php code it is unable to get anything from the table for the Subject '$sub'.
First i would suggest that you use PDO instead of mysqli in your php.
The php code seems ok but PDO is better agents sql injection.
And in your Android code use Volley i can give you good tutorials so you can learn ti, it is easy, if you want
I know this question is asked before also, but I want to know whether we can Connect to external database (e.g mySQL) from android device without using a webservice.
I have already build the app using webservice but now they have asked us to make it without using webservice.
Can anybody knows or give any reference about same ?
I have all the required data about the database location i.e. server name, db name etc.
Actually in my requirement I am downloading and xml using a webservice which will have all the details the connection string, database name, server name, username , password etc. but the connection is to be done on runtime.
Yes you can connect to remote database directly. I'm unsure about it's security though.
Try this:
Download MySQL JDBC
Add the .jar file in your Android project and add it as a library.
Create a class that extends AsyncTask and execute the method there.
public class connectToServer extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... args) {
try {
connect();
} catch (Exception e) {
Log.e("Error", e.toString());
}
return null;
}
#Override
protected void onPostExecute(String file_url)
{
}
}
public void connect(){
Log.e("Android", "SQL Connection start");
Connection conn = null;
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
String ip = "[your host server]";
String dbName = "[your dbName]";
String user = "[your userName]";
String password = "[your password]";
String connString = "jdbc:mysql://" + ip + "/" + dbName +
"";
conn = DriverManager.getConnection(connString, user, password);
Log.e("Connection", "Open");
Statement statement = conn.createStatement();
ResultSet set = statement.executeQuery("Select * from [table]");
statement.setQueryTimeout(0);
while(set.next())
{
Log.e("Data:", set.getString("[column_name]"));
}
}catch(Exception e)
{
Log.e("Error connection", e.toString());
}
}//end method
I have a web-service in .NET it's inserting and retrieving data's from database as object's..
I'll copy some part of web-service here..
[WebMethod(Description = "This is used to insert details into sql server")]
public string InsertDetails(DataTable myDetails, string STR1)
{
try
{
foreach (DataRow row in myDetails.Rows)
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "dbo.InsertQry";
cmd.Parameters.Add(new SqlParameter("#P_no", row["POD_Number"].ToString()));
cmd.Parameters.Add(new SqlParameter("#P_id", STR1));
cmd.Parameters.Add(new SqlParameter("#P_author", Convert.ToInt64(row["P_author"])));
//opening the connection
cmd.Connection = sqlCon;
sqlCon.Open();
int retValue = cmd.ExecuteNonQuery();
sqlCon.Close();
if (retValue == 0)
return "false";
}
return "true";
}
catch (Exception ex)
{
ErrorLogger(ex);
return "false";
}
}
//-----------------------------------------------------------------------------------
[WebMethod(Description = "This is used to get details from sql server")]
public DataSet GetDetails(string STR1)
{
DataSet ds = new DataSet();
try
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "dbo.SelectQryFromDB";
//opening the connection
cmd.Connection = sqlCon;
sqlCon.Open();
ds.DataSetName = "myTbl";
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds,"myTbl");
sqlCon.Close();
return ds;
}
catch (Exception ex)
{
ErrorLogger(ex);
ds.DataSetName = "Error";
return ds;
}
}
//----------------------------
Any-one Help me by providing me the details how can i send those data's and retrieve data's in Android..This is my first application so i don't know much??
Please Provide me details so that i can insert and get data's using web-service??
I heard of kSOAP2 and i'm trying to accomplish this by using kSOAP2..
Working in Ksoap can be challenging sometimes. You first need to make sure your webservice is working fine and is giving you the proper result.
If that's done then you can consume the same from Android using ksoap library.
Here are few links that will help solve your problem:
1) How to call a local web service from Android mobile application will help you understand how you need to make a Ksoap call.
2) Inserting data into remote database from Android via ksoap
3) Returning data from server to Android