I'm a complete beginner in android programming and am trying to make an app which requires access to the database on local host using the android studio, using the IP address of the server, I've watched many tutorial videos but still am not sure where to pass the IP address of the server.
The server uses MySQL, I've tried using JDBC but still unable to achieve the result.
Here is my code, any help would be appreciated.
`package com.example.vishal.connectiontest;
import java.sql.*;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import static android.R.attr.name;
import static com.example.vishal.connectiontest.DemoClass.main;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button B1 = (Button)findViewById(R.id.button);
final TextView e1 = (TextView) findViewById(R.id.HelloWorld);
B1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
String result = main();
e1.setText(result.toString());
}
catch(java.lang.Exception e){
System.out.println("Exception");
}
}
});
}
}
class DemoClass
{
public static String main()throws Exception
{
String url = "jdbc:mysql://125.10.10.214/demo" ;
String uname = "root";
String pass = "";
String ip = "";
String query = "Select UserName from user_info where Id = '90000515'";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, uname,pass);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
rs.next();
String name = rs.getString("UserName");
return (name);
}
}`
Easiest way of integrating Database to your Android Application is using Firebase.
It's really easy to use and other than Database, it has File Storage Services, Cloud Messaging, Analytics and many more.
I would recommend use of firebase database.
Here have a look at it's Documentation:
https://firebase.google.com/docs/database/
Related
I'm trying to connect my Android app to Oracle Database Express Edition 11g hosted on my laptop. I'm testing the app on my phone with its hotspot ON to which the laptop is connected via WiFi.
I've added ojdbc14.jar to app/libs directory and selected Add as Library option on it through Android Studio.
I'm getting the following errors:
Rejecting re-init on previously-failed class java.lang.Class<oracle.jdbc.pool.OracleDataSource>: java.lang.NoClassDefFoundError: Failed resolution of: Ljavax/naming/Referenceable;
Caused by: java.lang.ClassNotFoundException: Didn't find class "javax.naming.Referenceable" on path: DexPathList
W/System.err: java.sql.SQLException: Io exception: The Network Adapter could not establish the connection
P.s. I know using a server is a better approach. Doing this for a client who wants to use it in a secure private network and they don't want to host a separate server for the database connection.
I read elsewhere that I need to use Async task for connecting JDBC but I'm not sure how; consider me a beginner. All other answers I found related to this keep going off topic. I just want to know how to make JDBC work on Android, considering the risks.
Here's my MainActivity.java:
package com.absingh.apptest;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MainActivity extends AppCompatActivity {
private static final String DEFAULT_DRIVER = "oracle.jdbc.driver.OracleDriver";
private static final String DEFAULT_URL = "jdbc:oracle:thin:#192.168.42.49:1521:XE";
private static final String DEFAULT_USERNAME = "myusername";
private static final String DEFAULT_PASSWORD = "mypassword";
private Connection connection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
TextView tv = (TextView) findViewById(R.id.hello);
try {
this.connection = createConnection();
Toast.makeText(MainActivity.this, "Connected",
Toast.LENGTH_SHORT).show();
Statement stmt=connection.createStatement();
StringBuffer stringBuffer = new StringBuffer();
ResultSet rs=stmt.executeQuery("select * from testtable");
while(rs.next()) {
stringBuffer.append( rs.getString(1)+"\n");
}
tv.setText(stringBuffer.toString());
connection.close();
}
catch (Exception e) {
Toast.makeText(MainActivity.this, ""+e,
Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
public static Connection createConnection(String driver, String url, String username, String password) throws ClassNotFoundException, SQLException {
Class.forName(driver);
return DriverManager.getConnection(url, username, password);
}
public static Connection createConnection() throws ClassNotFoundException, SQLException {
return createConnection(DEFAULT_DRIVER, DEFAULT_URL, DEFAULT_USERNAME, DEFAULT_PASSWORD);
}
}
Nevermind, I figured it out.
The code in the question works fine if you add this above the application tag in AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
I'll leave the question be, in case someone else gets the same problem.
I am trying to make a dictionary application using Oxford Dictionary api. There is something wrong with my code JSON. Can anyone tell me how do I extract only the definition of the searched word, rather getting the whole JSON file
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class MainActivity extends AppCompatActivity {
private static final String APP_ID= "59028fc6";
private static final String API_KEY = "ad3e310307d7b2f8bf474c45e1efd01f";
private static final String TAG = MainActivity.class.getSimpleName();
private OkHttpClient okHttpClient;
private EditText textInput;
private Button submitButton;
private TextView definitionView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initialize ok http
okHttpClient = new OkHttpClient();
textInput = findViewById(R.id.textInput);
submitButton = findViewById(R.id.submitButton);
definitionView = findViewById(R.id.textMeaning);
submitButton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
findMeaningOfEnteredWord();
}
});
}
private void findMeaningOfEnteredWord() {
String word = textInput.getText().toString();
if (word.isEmpty()) {
Toast.makeText(this, "Nothing entered", Toast.LENGTH_SHORT).show();
return;
}
// create url from the word
String lowerCaseWord = word.toLowerCase();
String httpRequestUrl = "https://od-api.oxforddictionaries.com:443/api/v1/entries/en/" + lowerCaseWord;
// make request with REST url
new RequestAsyncTask().execute(httpRequestUrl);
}
private class RequestAsyncTask extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
String requestUrl = params[0];
Request request = new Request.Builder()
.url(requestUrl)
.addHeader("Accept", "application/json")
.addHeader("app_id", APP_ID)
.addHeader("app_key", API_KEY)
.build();
Response response = null;
try {
response = okHttpClient.newCall(request).execute();
return response.body().string();
} catch (IOException ex) {
Log.e(TAG, "caught error: " + ex.getMessage());
}
return "";
}
#Override
protected void onPostExecute(String result) {
try {
JSONObject responseAsJson = new JSONObject(result);
JSONArray results = responseAsJson.getJSONArray("results");
if (results.length() > 0) { // valid definitions were found
String lexicalEntries = results.getJSONObject(0).getString("lexicalEntries");
definitionView.setText(lexicalEntries);
}
Log.d(TAG, " " + responseAsJson.toString());
} catch (Exception ex) {
Log.d(TAG, "exception during json parsing: " + ex.getMessage());
}
}
}
}
JSON:
{"id":"aeroplane",
"language":"en",
"lexicalEntries": [
{
"entries": [{"etymologies":["late 19th century: from French aéroplane, from aéro- ‘air’ + Greek -planos ‘wandering’"],
"grammaticalFeatures":[{"text":"Singular","type":"Number"}],
"homographNumber":"000",
"senses":[{"crossReferenceMarkers":["North American term airplane"],
"crossReferences":[{"id":"airplane","text":"airplane","type":"see also"}],
"definitions":["a powered flying vehicle with fixed wings and a weight greater than that of the air it displaces."],
"domains":["Aviation"],
"id":"m_en_gbus0013220.005",
"regions":["British"],
"short_definitions":["powered flying vehicle with fixed wings"],
"thesaurusLinks":[{"entry_id":"plane","sense_id":"t_en_gb0011151.001"}]}]}],"language":"en","lexicalCategory":"Noun","pronunciations":[{"audioFile":"http:\/\/audio.oxforddictionaries.com\/en\/mp3\/aeroplane_gb_2.mp3","dialects":["British English"],"phoneticNotation":"IPA","phoneticSpelling":"ˈɛːrəpleɪn"}],"text":"aeroplane"}],
"type":"headword","word":"aeroplane"
}
Modify these lines :
String lexicalEntries = results.getJSONObject(0).getString("lexicalEntries");
definitionView.setText(lexicalEntries);
to :
String definition = results.getJSONObject(0).getString("lexicalEntries")
.getJSONArray("entries").getJSONObject(0).getJSONArray("senses")
.getJSONObject(0).getJSONArray("definitions").getString(0);
definitionView.setText(definition);
Of course you may need to modify your UI based on the number of definitions a word has.
Also, you should probably consider using POJOs instead of directly dealing with the JSON response.
I'd recommend Jackson or GSON for doing this.
String definitions=results.getJSONArray("lexicalEntries")
.getJSONObject(0)
.getJSONArray("entries")
.getJSONObject(0)
.getJSONArray("senses")
.getJSONArray("definitions")
.get(0)
So , The thing is , There are a lot of gaps in the JSON for different words .
Which means a word may have an array of "synonyms" but others don't , So in your code you are trying to reach something that doesn't actually exist (a NULL value) which is likely to throw an exception every time you search for a word that the JSON returned doesn't match the JSON you are expecting , Because there are missing (NULL) values .
The app I made using oxford dictionary required a lot of work just to make sure there is no thrown exception .
I used retrofit with moshi converter factory , And then Do the following :
1-In your custom classes , Make sure you annotate every data member with
#Json and provide the name of the keys in the JSON of oxford
2-make sure that every declared type is nullable , including both List and the type inside of it
You'll then be able to get the result , And Now comes the part where you handle evey call that may be null
I know this is a bit old question , But It happened that I struggled with this api once , So I hope this may help someone :)
I'm trying to create an application that allows two devices to connect using wifi direct and send a message from one device to another in a JSON file format and then parse that file into a text view. So far I'm not concern about the wifi part because I know it's very difficult and I want to start with the "easy" part of my project. I have this code so far.
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONObject;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class MainActivity extends AppCompatActivity {
EditText edtx1;
TextView txvw1;
TextView txvw2;
TextView txvw3;
TextView txvw4;
TextView txvw5;
Button btn;
String Message;
String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
edtx1 = (EditText) findViewById(R.id.editText1);
txvw1 = (TextView) findViewById(R.id.textView1);
txvw2 = (TextView) findViewById(R.id.textView2);
txvw3 = (TextView) findViewById(R.id.textView3);
txvw4 = (TextView) findViewById(R.id.textView4);
txvw5 = (TextView) findViewById(R.id.textView5);
//txvw1.setText(edtx1.getText().toString());
makeJSON();
}
});
}
public JSONArray makeJSON() {
JSONArray jArr = new JSONArray();
JSONObject jObj = new JSONObject();
try {
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wInfo = wifiManager.getConnectionInfo();
String macAddress = wInfo.getMacAddress();
//Long tsLong = System.currentTimeMillis() / 1000;
//String ts = tsLong.toString();
jObj.put("Created_on:", currentDateTimeString);
jObj.put("Sent_by:", Build.MODEL);
jObj.put("MAC_Address:", macAddress);
jObj.put("Number_of_Hops:", 1);
jObj.put("Message:", edtx1.getText());
txvw1.setText(jObj.getString("Created_on:"));
txvw2.setText(jObj.getString("Sent_by:"));
txvw3.setText(jObj.getString("MAC_Address:"));
txvw4.setText(jObj.getString("Number_of_Hops:"));
txvw5.setText(jObj.getString("Message:"));
jArr.put(jObj);
} catch (Exception e) {
System.out.println("Error:" + e);
}
return jArr;
}
}
I want to have a button and when clicked just send the information on the edittext to the json object called message. So at the end i will have something like this
{
"Created on": Date,
"Sent By": "name",
"MAC Address": "FF:FF:FF:FF:FF:FF",
"Number of Hops": "This number I will figure it out later",
"Message": "Message"
}
And then send that file to the other device.
UPDATE:
I just edited the code above and now it's kind of working, at least I think is doing what i want. The problem here is with the device name and the MAC address. I know that now the MAC address cannot be taken within the app but I can just fill in that part and make it static. But how can i retrieve the name of the device for example my device is called "Daniel" how can i have that retrieved with a code?
I haven't tested this out, but this might help.
Here are the official docs for using wifi-direct in case you need them
android docs: wifi-direct
You can try to send your json object over as a string (its what i have to do when i POST to my server) and on the other side parse it like a standard json.
Uri.Builder builder = new Uri.Builder();
builder.appendQueryParameter("key_1", "value_1");
builder.appendQueryParameter("key_2", "value_2");
String json = builder.build().getEncodedQuery();
Once you have a class built you can get the data from it and then set with .setText()
let me know if you need an example on how to do that.
--- EDIT ---
as far was getting your device name, i found this snippet of code that should work for you, as long as you are ok with asking for bluetooth permission.
add this to your manifest
<uses-permission android:name="android.permission.BLUETOOTH" />
and in your code
public String getPhoneName(){
BluetoothAdapter myDevice = BluetoothAdapter.getDefaultAdapter();
String deviceName = myDevice.getName();
return deviceName;
}
I have a text file that has this information
Casino Canberra;21 Binara Street, Canberra ACT, 2601;Canberra Casino is a casino located in Civic in the central part of the Australian capital city of Canberra. The Casino is relatively small compared with other casinos in Australia.;(02) 6257 7074;www.canberracasino.com.au
National Museum of Canberra;Parkes Place, Canberra ACT, 2601;The National Museum of Australia explores the land, nation and people of Australia. Open 9am - 5pm every day except Christmas Day. General admission free.;(02) 6240 6411;www.nga.gov.au
which is stored in the sdcard
after this i retrieve the values using this method
package au.edu.canberra.g30813706;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Environment;
public class FileReader extends Activity{{
ArrayList<read> sInfo = new ArrayList<read>();
ArrayList<String> sLines = new ArrayList<String>();
String line;
String[] saLineElements;
String txtName = "AccomodationTxt.txt";
File root = Environment.getExternalStorageDirectory();
File path = new File(root, "CanberraTourism/" + txtName);
try {
BufferedReader br = new BufferedReader (
new InputStreamReader(
new FileInputStream(path)));
while ((line = br.readLine()) != null)
{
sLines.add(line);
//The information is split into segments and stored into the array
saLineElements = line.split(";");
//for (int i = 0; i < saLineElements.length; i++)
// sInfo.add(new read(saLineElements[i]));
sInfo.add(new read(saLineElements[0], saLineElements[1], saLineElements[3], saLineElements[4], saLineElements[5]));
}
br.close();
}
catch (FileNotFoundException e) {
System.err.println("FileNotFoundException: " + e.getMessage());
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}}
}
But i also have and object class to store each individual item into
package au.edu.canberra.g30813706;
public class read {
public String name;
public String address;
public String info;
public String phone;
public String www;
public read (String name, String address, String info, String phone, String www)
{
this.name = name;
this.address = address;
this.info = info;
this.phone = phone;
this.www = www;
}
}
The only issue im having is trying to display the information in a text view which i have no idea how to call the values i need
This is where im trying to insert it
package au.edu.canberra.g30813706;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import au.edu.canberra.g30813706.FileReader;
import au.edu.canberra.g30813706.read;
public class Accommodation_info extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.accommodation_layout);
}}
You should probably look into using the Application class. You can think of Application as a GUI-less activity which works like the model in a program following the MVC pattern. You can put all of your read objects into a data structure in your Application and then access them with accessors and mutators of your own design.
Take a look at this official doc.
As your code stands, you can only access your instances of read by obtaining a reference to your FileReader class, but your two activities are separate entities. You'd have to do something like this:
// This is the main activity and should be launched first
// Check your manifest to make sure it launches with this activity
package au.edu.canberra.g30813706;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import au.edu.canberra.g30813706.FileReader;
import au.edu.canberra.g30813706.read;
public class Accommodation_info extends Activity
{
// Declare the file reader so you'll have a reference
FileReader reader;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.accommodation_layout);
// Instantiate the file reader
reader = new FileReader();
// Now you can access the array inside FileReader
// obviously, you need to have a text view called my_textView defined in the
// layout file associated with this activity
TextView myTextView = (TextView)findViewById(R.id.my_textView);
// displays the first element in FileReader's array list
myTextView.setText((String)reader.get(0));
}}
At the moment, you might be in a bit deep for your current understanding of Android and/or Java. I would encourage you to follow as many code examples as possible, get comfortable with Android and then go back to your project when you have a little more experience.
I created an ontology with Protégé. Then I created an Android interface which contains two edit texts and a button. The main function of my code is to make a connection between my application and the ontology and store these data into it. I use a triple store for storage.
But it didn't work correctly. I'm using Sesame as server but I don't know how to get the correct URL of the "update" service. I might have made other errors but here is my activity's code:
package com.example.ontologie1;
import com.hp.hpl.jena.ontology.DatatypeProperty;
import com.hp.hpl.jena.ontology.Individual;
import com.hp.hpl.jena.ontology.OntClass;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Property;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import java.io.IOException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private Button buttonconnexion;
private EditText editpseudo;
private EditText editpassword;
public String ps;
public String pa;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editpseudo = (EditText) findViewById(R.id.welcomeedittextlogin);
editpassword = (EditText) findViewById(R.id.welcomeedittextpassword);
buttonconnexion = (Button) findViewById(R.id.welcomebuttonconnexion);
buttonconnexion.setOnClickListener(click1);
}
protected OnClickListener click1 = new OnClickListener() {
public void onClick(View arg0) {
ps= editpseudo.getText().toString();
pa= editpassword.getText().toString();
try {
connexion(ps , pa);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
protected void connexion(String pseudo,String password) throws IOException {
String requete = "<http://www.w3.org/2002/07/owl#> .\n"
+ "INSERT DATA {\n"
+ " <http://www.owl-ontologies.com/Ontology_profile.owl#USER> a onto:USER;\n"
+ " onto:Login " + pseudo + ";\n"
+ " onto:Password " + password + ";\n"
+ "}";
PostMethod post = new PostMethod("<http://www.openrdf.org/config/repository#>");
NameValuePair[] paramRequete = {
new NameValuePair("query", requete),
};
post.setRequestBody(paramRequete);
InputStream in = post.getResponseBodyAsStream();
Toast t = null ;
t.setText(in.toString());
t=new Toast(null);
}
}
I don't have experience with Android programming, but there are some issues that suggest you need to rethink your goals.
An ontology is not a database. You don't store data in an ontology, and you don't need an ontology to store data in a triplestore.
To store data in a triplestore (using SPARQL), your triplestore needs a SPARQL endpoint. That endpoint has a URI that you send your POST or GET request to. If you installed Sesame on your local machine, that URI may look like http://localhost:8080/sparql. If you want to insert data, the triplestore needs to allow that.
You also need a valid SPARQL query, which your requete is not. The first line,
<http://www.w3.org/2002/07/owl#> .
is not complete. Usually there are PREFIXes on the first lines of a SPARQL query, but they don't end with a .. For example:
PREFIX owl: <http://www.w3.org/2002/07/owl#>
To use the prefix onto: as you do, you need to define it in the same way. For a complete SPARQL tutorial, see this.
Also, the lines
Toast t = null ;
t.setText(in.toString());
t=new Toast(null);
will generate a NullPointerException, as you call a method on t that is null.