I am currently new to android programming but I recently created a rest api using slim library that takes a GET request and adds it to the database it's parameters but I don't know how to send it inside android app.
here is my code:
Button btn;
#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) {
try
{
URLConnection myURLConnection=null;
URL myURL=null;
String mainUrl="http://107.170.31.137/StudentApp/v1/garden/name2/user2/pass2";
myURL = new URL(mainUrl);
myURLConnection = myURL.openConnection();
myURLConnection.connect();
}
catch (IOException e)
{
Toast.makeText(getBaseContext(), "in catch", Toast.LENGTH_LONG).show();
}
}
});
I even added the permissions :
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
still the app is not working. am i doing something wrong? please help. also, I want to change the GET parameters every time to the new variables I get from somewhere else how can i do that?
For Network Relational Operations Make Use of the following Libraries(Asyntask)
Retrofit (Recommended)
Okhttp
Volley
Check my Example Project on Retrofit
Related
I'm trying to execute a mysql query in my java application using JDBC but instead of a query result, I get an error
java.lang.UnsupportedOperationExeption.
I did these steps in my app:
Added mysql Connector.jar (version 8) in libs directory
Added <uses-permission android:name="android.permission.INTERNET" /> to manifest
Updated gradel, jdk to latest version
Changed api to 32 or 21 but it didn't work
The Mysql user privileges and tables are ok. I launched my app in Android Studio
Here is my code:
public class MainActivity extends AppCompatActivity {
TextView query_result_TextView, Error_textview;
Button show_btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
query_result_TextView = (TextView) findViewById(R.id.textView);
Error_textview = (TextView) findViewById(R.id.textView2);
show_btn = (Button) findViewById(R.id.showbtn);
show_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/adl","testuser","12345678");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM test ;");
query_result_TextView.setText(rs.toString());
}
catch (Exception ex) {
Error_textview.setText(ex.toString());
// java.lang.UnsupportedOperationExeption
}
}
});
}
}
I tried soooo much, but this error didn't get resolved.
Please help !
NOTE: i tried to coonect with eclipse IDE with same syntax and in Eclipse worked pefectly!!!! is there a option in Android Studio that's avoiding to connect?
I have a website which only shows one line of text which I need to extract the text form in android studio, I would prefer to get it as a string. How do I do this?
Something such as webView.getTitle() would work but than for the content of the site, is there such a quick way to get this or how should I else do it?
specific info
the site I need to get the information form is:
"<html> <head></head> <body> #4d636f </body> </html> "
from this I only need the text in the body, in this case a color as text.
You can use any Web Scraper/Crawler API to fetch data from web site.
For example:
JSOUP API For Java And Android
Update
Step By Step guide to solve the mentioned problem
Add Jsoup dependency to the app level of your build.gradle.
implementation 'org.jsoup:jsoup:1.11.1'
Add Internet permission to the Android Manifest file for internet access.
<uses-permission android:name="android.permission.INTERNET" />
Add button and text view in your app to get data from website on button click and display the result on text view.
Below is the sample code:
public class MainActivity extends AppCompatActivity {
private TextView result;
private Button fetch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = (TextView) findViewById(R.id.result);
fetch = (Button) findViewById(R.id.fetch);
fetch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getBodyText();
}
});
}
private void getBodyText() {
new Thread(new Runnable() {
#Override
public void run() {
final StringBuilder builder = new StringBuilder();
try {
String url="http://www.example.com";//your website url
Document doc = Jsoup.connect(url).get();
Element body = doc.body();
builder.append(body.text());
} catch (Exception e) {
builder.append("Error : ").append(e.getMessage()).append("\n");
}
runOnUiThread(new Runnable() {
#Override
public void run() {
result.setText(builder.toString());
}
});
}
}).start();
}
}
This type of process is known as web scrubbing. And you could do more research to see different methods. One methd I would suggest is getting the HTML from source and searching the DOM for any tags unique to the text you want.
By getting the HTML you avoid rendering the whole page (images, javascript, ect..)
Do you have a snippet of the source code you want to scrub from?
Sure here is an example. P.S. I'm not familiar with javascript, correct him for your case.
webView.evaluateJavascript("return document.getElementById(your_id)", new ValueCallback<String>() {
#Override
public void onReceiveValue(String value) {
// value is your result
}
});
I'm working on a relatively simple login app for a school project. I'm having an issue connecting my app to any URL, local or otherwise. I've added the permission for internet access to the android manifest file.
<uses-permission android:name="android.permission.INTERNET" />
The following code is located in my main activity:
public class MainActivity extends Activity {
private EditText username=null;
private EditText password=null;
private Button login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = (EditText)findViewById(R.id.ucidText);
password = (EditText)findViewById(R.id.passText);
login = (Button)findViewById(R.id.button1);
//URL CAN BE ANYTHING, WOULD NORMALLY BE 192.168.1.102
if(isConnectedToServer("<-URL to page on locally hosted server->",10)){
Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), "Connection failed", Toast.LENGTH_SHORT).show();
}
}
//Function to determine if connection exists
public boolean isConnectedToServer(String url, int timeout) {
try{
URL myUrl = new URL(url); //<--------- I believe the issue has to do with this line.
URLConnection connection = myUrl.openConnection();
connection.setConnectTimeout(timeout);
connection.connect();
return true;
} catch (Exception e) {
return false;
}
}
}
This is a stripped down version of my overall project. Everything checks out except the connectivity. I'm running the app from the SDK straight on my phone (Moto X). Any suggestions?
You got the android.os.NetworkOnMainThreadException because you perform your network request on the main thread. You should not do that because you will block the main thread. Instead, you can start a new thread to perform your network request, like this:
final Handler handler = new Handler();
new Thread(){
public void run(){
// check network connection here.
handler.post(/* do the toast work in a Runnable as the parameter here*/);
}
}.start();
You should use some protocol in the "url" string.
For example, you can use
"http://serverIP"
in which the serverIP is 192.168.1.102 and the port is default to 80.
We could not use "192.168.1.102" as the url because the protocol could not be ignored for the URL class.
I've been trying out Google Tag Manager for mobile devices, specifically Android but I keep getting a message saying "invalid macro" when trying getString(myKeyValue) on a Container.
Here's a part of my code in my MainActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtHello = (TextView)findViewById(R.id.txtHello);
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
String hello = mContainer.getString("hello");
long l = mContainer.getLong("long");
txtHello.setText(hello + l);
}
});
tagManager = TagManager.getInstance(this);
ContainerOpener.openContainer(tagManager, CONTAINER_ID, OpenType.PREFER_NON_DEFAULT, null, new ContainerOpener.Notifier() {
#Override
public void containerAvailable(Container container) {
mContainer = container;
}
});
}
I've added these permissions in the manifest:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
I have the right Container_id because it shows the right version after refreshing it programmatically.
And this is my assets/tagmanager/CONTAINER_ID.json file (of course with the right filename):
{
'hello': 'hola',
'long' : '12345679'
}
So after my container is initialized, I press a button that runs the code above, trying to get the values. But I get the error: "Invalid macro: hello" and "Invalid macro: long", also
"Failed to convert '' to a number"
This is a new service for mobile devices but can anybody help me with this?
I've found a problem for my case. I just downloaded a version from the web browser manager.
The important thing is to add a rule that allows GTM to use this macro. Always comes in handy here.
Don't forget to publish the version of your container
For people not getting what dumazy referring to
you'll also need to enable it with Always or any other appropriate rules
In your json you are using '123456' quotas to define long, you should not:
{
'string': 'hola',
'long': 123456,
'double': 123.123
}
If you have further problems look on: Android TagManager not getting default values
I am new to Android development. I am trying to join an existing VPN from my Android app. I want to integrate the VPN in my app; my app then is supposed to query a remote database.
I got some code and tried to use it to create a VPN. It emulates the built-in VPN manager on the Android phone. The code compiles and the manager is launched but the connection to the VPN does not succeed when I try to connect after all configuration. The protocol is PPTP. A VPN exists and has been tested.
I tried connecting from an android phone with the same settings and it was successful.
I thought maybe I am passing the parameters in the wrong way. I have put the code for the vpn part below. The url is not the actual but in same format.
Any help to identify what I am doing wrong would be appreciated. Also if there is a way I can directly call the VPN manager from my app.
Thanks very much for any help,
final Button button1 = (Button)findViewById(R.id.button1);
final Button button2 = (Button)findViewById(R.id.button2);
final Button button3 = (Button)findViewById(R.id.button3);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent("android.net.vpn.SETTINGS"));
}
});
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
URL url = null;
try {
String registrationUrl = String.format("daffy.zune.org");
url = new URL(registrationUrl);
URLConnection connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) connection;
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
Log.d("MyApp", "Registration success");
} else {
Log.w("MyApp", "Registration failed for: " + registrationUrl);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
button3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
setContentView(R.layout.register);
}
});
}
}
I suggest you look at the simplevpn project and browse the source here and view ShowAllVPNsActivity.java.
Hope this helps! We need more good VPN apps in the Market!