display web page source in android app - java

This is my first project in android java. I am trying to get a page source and display it. (I will use this with json later.) I followed a tutorial on lynda.com but I can't get this to work. there is a edittext, textview, and a button in this app. the user enter a url and press the button and the app adds the source to the page. When I click the button nothing happen. how can I fix this.
Note i have the internet permission added already.
Main.java
package com.example.news;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Main extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final EditText et = (EditText) findViewById(R.id.editText1);
final Button b = (Button) findViewById(R.id.button1);
final TextView tv = (TextView) findViewById(R.id.textView1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try{
URL url = null;
url = new URL(et.getText().toString());
URLConnection conn = url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = "";
while((line = reader.readLine()) != null){
tv.append(line);
}
}catch(Exception e){
}
}
});
}
}
This is my manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.news"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.news.Main"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I got this error: android.os.NetworkOnMainThreadException

You are using the Internet on Main Thread.
You should use the code in doInBackground().
class Abc extends ASyncTask<String, String, String>
{
public String doInBackground(String... params)
{
URL url = null;
url = new URL(et.getText().toString());
URLConnection conn = url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = "";
while((line = reader.readLine()) != null){
tv.append(line);
}
}
And in OnClick
new Abc.execute();

Related

Java.lang.securityException: Permission Denial: starting Intent

I'm constantly getting a security exception when trying to launch a different activity other than my MainActivity, code works fine when i'm launching my MainActivity but throws an exception when I try to launch any other activity other than MainActivity, I've been looking for answers and got a solution to put -android:exported="true"- in my Manifest, however this doesn't help the problem i'm facing, any help so far will be highly appreciated.
Manifest file for launching MainActivity - (Which works)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.infamuspips.cess">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:exported="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
<activity
android:name=".registration"
android:label="#string/app_name"></activity>
<activity
android:name=".reg_name"
android:label="#string/app_name"></activity>
<activity
android:name=".reg_securityquestions"
android:label="#string/app_name"></activity>
<activity
android:name=".reg_id"
android:label="#string/app_name"></activity>
<activity
android:name=".reg_cellnumber"
android:label="#string/app_name"></activity>
<activity
android:name=".reg_email"
android:label="#string/app_name"></activity>
<activity
android:name=".reg_password"
android:label="#string/app_name"></activity>
<activity
android:name=".Maindrawer"
android:label="#string/title_activity_maindrawer"
android:theme="#style/AppTheme"></activity>
</application>
</manifest>
.
Manifest file for launching registration Activity - (Which don't work)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.infamuspips.cess">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:exported="true"
android:theme="#style/AppTheme">
<activity android:name=".registration">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:label="#string/app_name"></activity>
<activity
android:name=".reg_name"
android:label="#string/app_name"></activity>
<activity
android:name=".reg_securityquestions"
android:label="#string/app_name"></activity>
<activity
android:name=".reg_id"
android:label="#string/app_name"></activity>
<activity
android:name=".reg_cellnumber"
android:label="#string/app_name"></activity>
<activity
android:name=".reg_email"
android:label="#string/app_name"></activity>
<activity
android:name=".reg_password"
android:label="#string/app_name"></activity>
<activity
android:name=".Maindrawer"
android:label="#string/title_activity_maindrawer"
android:theme="#style/AppTheme"></activity>
</application>
</manifest>
.
Here's my MainActivity Class
package com.infamuspips.cess;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.test.suitebuilder.annotation.Suppress;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Base64;
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 org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.InvalidParameterSpecException;
import java.util.ArrayList;
import java.util.List;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.HttpsURLConnection;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "Encryption";
EditText editText,username,password;
Button button;
TextView cancel,forgot_password;
static String Username = null;
static String PassWord = null;
static String GetUsername = null;
static String GetPassword = null;
SecretKey secretKey;
String cipherText, decryptedText;
KeyGenerator keyGen;
Cipher aesCipher;
FileOutputStream fos;
byte[] byteDataToEncrypt, byteCipherText, byteDecryptedText;
TextWatcher textwatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String User = username.getText().toString();
String Pass = password.getText().toString();
if (!User.isEmpty() && !Pass.isEmpty()) {
button.setEnabled(true);
} else {
button.setEnabled(false);
}
}
#Override
public void afterTextChanged(Editable s) {
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
editText = (EditText) findViewById(R.id.editText);
username.addTextChangedListener(textwatcher);
password.addTextChangedListener(textwatcher);
button = (Button) findViewById(R.id.logIn);
cancel = (TextView) findViewById(R.id.LoginCancel);
forgot_password = (TextView) findViewById(R.id.forgot_password);
//Set Clickable attributes
cancel.setClickable(true);
button.setEnabled(false);
editText.setEnabled(false);
//Call Operation Methods
username.requestFocus();
//Cancel();
//Forgot_Password();
Log_In();
}
private void Cancel(){
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),registration.class);
startActivity(i);
}
});
}
private void Forgot_Password(){
forgot_password.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
class PerformBackGround extends AsyncTask<Void, Void, String>{
private ProgressDialog mDialog;
public PerformBackGround() {
super();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mDialog = new ProgressDialog(MainActivity.this);
mDialog.setMessage("Please wait");
mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mDialog.setProgress(0);
mDialog.setMax(10);
mDialog.setCancelable(false);
mDialog.show();
}
#Override
protected String doInBackground(Void... params) {
try{
String link = "http://*************************";
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String result = bufferedReader.readLine();
return result;
}catch (Exception e){
return "Exception" + e.getMessage();
}
}
#Override
protected void onPostExecute(String result) {
String jsonStr = result;
String response;
if (jsonStr != null){
try{
JSONObject jsonObj = new JSONObject(jsonStr);
String User = jsonObj.get("name").toString();
String Password = jsonObj.get("surname").toString();
mDialog.cancel();
if (User.equals(Username) && Password.equals(PassWord)){
//String name = jsonObj.get("name").toString();
//String Surname = jsonObj.get("surname").toString();
response = jsonObj.get("surname").toString();
getResponse(response);
Intent i = new Intent(getApplicationContext(),Maindrawer.class);
startActivity(i);
}else{
response = "invalid";
getResponse(response);
}
}catch (Exception e){
mDialog.cancel();
e.printStackTrace();
response = "unable";
getResponse(response);
}
}else{
mDialog.cancel();
response = "unconnect";
getResponse(response);
}
}
}
private void Log_In(){
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//PerformBackGround bg = new PerformBackGround();
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
String user = username.getText().toString();
String pass = password.getText().toString();
Username = user;
PassWord = pass;
//addmodules addm =new addmodules();
//addm.execute();
Toast.makeText(MainActivity.this, md5(username.getText().toString()), Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(),Maindrawer.class);
startActivity(i);
username.getText().clear();
password.getText().clear();
}
});
}
public String md5(String text) {
try {
// Create MD5 Hash
MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
digest.update(text.getBytes());
byte messageDigest[] = digest.digest();
// Create Hex String
StringBuffer hexString = new StringBuffer();
for (int i=0; i<messageDigest.length; i++)
hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
}
}
Here's my registration Activity - (Which doesn't launch & throws an exception
)
package com.infamuspips.cess;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
/**
* Created by Rebone on 4/24/2016.
*/
public class registration extends AppCompatActivity {
EditText up, firstname, MidName, lastName,Email,id,password, confirmpassword;
Button logIn, Register;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.registration);
up = (EditText) findViewById(R.id.editText1);
logIn = (Button) findViewById(R.id.reg_login);
Register = (Button) findViewById(R.id.reg_register);
up.setEnabled(false);
Register.setEnabled(true);
LogIn();
Register();
}
public void LogIn() {
logIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
});
}
public void Register() {
Register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String initial = "Nothing";
//Modified
Intent a = new Intent(v.getContext(),reg_name.class);
//Intent a = new Intent(v.getContext(),reg_password.class);
a.putExtra("Results", initial);
startActivity(a);
}
});
}
}
-
And here's the full stack trace
08-09 13:59:52.444 220-10439/? W/ActivityManager: mDVFSLock.acquire()
08-09 13:59:52.444 220-10439/? W/ActivityManager: Permission denied: checkComponentPermission() owningUid=10118
08-09 13:59:52.444 220-10439/? W/ActivityManager: Permission Denial: starting Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.infamuspips.cess/.registration } from null (pid=13769, uid=2000) not exported from uid 10118
08-09 13:59:52.460 220-10439/? W/System.err: at com.android.server.am.ActivityStack.startActivityLocked(ActivityStack.java:2498)
08-09 13:59:52.460 220-10439/? W/System.err: at com.android.server.am.ActivityStack.startActivityMayWait(ActivityStack.java:3095)
08-09 13:59:52.460 220-10439/? W/System.err: at com.android.server.am.ActivityManagerService.startActivity(ActivityManagerService.java:2298)
08-09 13:59:52.460 220-10439/? W/System.err: at android.app.ActivityManagerNative.onTransact(ActivityManagerNative.java:147)
08-09 13:59:52.460 220-10439/? W/System.err: at com.android.server.am.ActivityManagerService.onTransact(ActivityManagerService.java:1603)
08-09 13:59:52.460 220-10439/? W/System.err: at android.os.Binder.execTransact(Binder.java:338)
08-09 13:59:52.460 220-10439/? W/System.err: at dalvik.system.NativeStart.run(Native Method)
Replace
<activity android:name=".registration">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
with
<activity android:name="com.infamuspips.cess.registration">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
Clean and rebuild your project

PHP MySQL Login app that will check the username and password from MySQL server In a Local Network

I'm creating Login App that will check the username and password from MySQL server In a Local Network, I've successfully logged in from a android Emulator to a MySQL Database .I've used PHP script for the validation of the User.
The Problem is that ,I'm Unable to Login From Android device to the MySQL Database. I made a Local Network in My home and Dumped the PHP scripts in The Server. But it not able to Login.
This Code is for connecting to the MySQL database
<?php
$db_name="user_details";
$mysql_username="root";
$mysql_password="";
$server_name="localhost";
$conn=mysqli_connect($server_name,$mysql_username,$mysql_password,$db_name);
?>
This Code is for Validating the User
<?php
require "user_conn.php";
$user_name=$_POST["username"];
$user_pass=$_POST["password"];
$mysql_qry="select * from user where username like '$user_name' and password like '$user_pass';";
$result=mysqli_query($conn,$mysql_qry);
if(mysqli_num_rows($result)>0)
{
echo "Login success";
}
else
{
echo "Login not success";
}
?>
These are the Java File of Android Code
Login.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class Login extends AppCompatActivity {
Button bLogin;
EditText etUser , etPass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
etUser = (EditText) findViewById(R.id.etuser);
etPass = (EditText) findViewById(R.id.etpass);
bLogin = (Button) findViewById(R.id.btlogin);
}
public void login(View view){
String u=etUser.getText().toString();
String p=etPass.getText().toString();
String l="login";
Background bg=new Background(this);
bg.execute(l,u,p);
}
}
Background.java
import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
public class Background extends AsyncTask<String, Void,String> {
AlertDialog a;
Context context;
public Background(Context ct) {
// TODO Auto-generated constructor stub
context=ct;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
a=new AlertDialog.Builder(context).create();
a.setTitle("Login Status");
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
a.setMessage(result);
a.show();
}
#Override
protected void onProgressUpdate(Void... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String type=params[0];
String login_url="http://10.0.2.2/login.php";
if(type.equals("login")){
try {
String username=params[1];
String password=params[2];
URL u=new URL(login_url);
HttpURLConnection http=(HttpURLConnection)u.openConnection();
http.setRequestMethod("POST");
http.setDoInput(true);
http.setDoOutput(true);
OutputStream out=http.getOutputStream();
BufferedWriter bf= new BufferedWriter(new OutputStreamWriter(out,"UTF-8"));
String post_data=URLEncoder.encode("username","UTF-8")+"="+URLEncoder.encode(username,"UTF-8")+"&"+
URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
bf.write(post_data);
bf.flush();
bf.close();
out.close();
InputStream in=http.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(in,"iso-8859-1"));
String result="";
String line="";
while((line=br.readLine())!=null)
{
result+=line;
}
bf.close();
in.close();
http.disconnect();
return result;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.login"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="23" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Background"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>

Network Requests return null - Android

i am working on a network communication project in android, but my app dose not work ! after some debugging, i find out that every network request has a null response from system.
i tried so many ways such as :
1) hard restart my phone
2) adding all network permissions to the manifest file
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
3) using local network ( my phone as a server )
4) letting all applications to connect to the network : setting > networked apps > ...
but ! nothing happened...
this is my similar problem link, but there is no answer in this topic:
can't connect to internet in ONLY in my android app. Each method to connect internet returns null
network is working on my phone because some apps like telegram and chrome are working well !
and there is a funny thing here, when i copy and past this code to the simple java project not android project, it works well !
because i wanted to find out where is the problem, i just copy 3 simple lines of codes to the simple android project, but still nothing happened!
manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.dltests"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
layout file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >
<TextView
android:id="#+id/hello"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
</RelativeLayout>
source file
package com.example.dltests;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView mTextView = (TextView) findViewById(R.id.hello);
try
{
URL mUrl = new URL("http://192.168.1.53:8080/some.zip");
HttpURLConnection mHttpURLConnection = (HttpURLConnection) mUrl.openConnection();
mTextView.setText(mHttpURLConnection.getContentLength());
}
catch (Exception e)
{
mTextView.setText("ERROR: " + e.getMessage());
}
}
}
and the result is :
ERROR: null
Android bars you from networking in the UI thread. What you need to do it spawn a separate thread to do the networking for you. Then you need either a receiver or handler to post/update the UI with the data.
1 - Create a new class:
import android.os.Handler;
import android.os.Message;
public class GetData extends Thread
{
// Holds url that data is stored on
private URL url
// Sets the url value
public GetData(URL newUrl)
{
url = newUrl;
}
// Runs when the thread is launched
public void run()
{
// Opens connection
HttpURLConnection con = (HttpURLConnection) url.openConnection();
// Sends back to UI using a Message
Message msg = MainActivity.MainActivityInterface.obtainMessage(MainActivity.getAndUpdate);
msg.obj = con.getContentLength(); // Adds the data
HomeScreen.homeScreenInterface.sendMessage(msg);
}
}
2 - Create handler in activity so UI can be updated as well as launch worker thread
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.os.Handler;
import android.os.Message;
public class MainActivity extends Activity {
// Holds activity instance
public static MainActivity currentInstance;
// Variable that allows us to separate messages for handler
public static final getAndUpdate = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
currentInstance = this;
TextView mTextView = (TextView) findViewById(R.id.hello);
try
{
URL mUrl = new URL("http://192.168.1.53:8080/some.zip");
// Spawns worker thread
GetData gd = new GetData(mUrl);
gd.start();
}
catch (Exception e)
{
mTextView.setText("ERROR: " + e.getMessage());
}
}
// Deals with service responses
public static Handler MainActivityInterface = new Handler()
{
#Override
public void handleMessage(Message msg)
{
switch(msg.what)
{
case getAndUpdate:
currentInstance.mTextView.setText((String) msg.obj); // Gets message object and updates UI
break;
}
}
}
}
I hope this helps. Note that I have not tested it as I am very far away from my coding computer!

Android, receive data from internet app does not work

I am completely new to android.
I am trying to build a basic app to get an idea on "android applications reading data from a server".
To get an idea about http connection on android i created this app watching a video tutorial, i have two java classes.
HttpExample.java class,
package com.raveen.testingthree;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.widget.TextView;
public class HttpExample extends Activity {
TextView httpStuff;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.detectAll().penaltyLog().build();
StrictMode.setThreadPolicy(policy);
super.onCreate(savedInstanceState);
httpStuff = (TextView) findViewById(R.id.tvHttp);
GetMethodHttp test = new GetMethodHttp();
String returned;
try {
returned = test.getInternetData();
httpStuff.setText(returned);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
and getmethodhttp.java class,
package com.raveen.testingthree;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class GetMethodHttp {
public String getInternetData () throws Exception{
BufferedReader in = null;
String data = null;
try{
HttpClient client = new DefaultHttpClient();
URI website = new URI("http://www.google.com");
HttpGet request = new HttpGet();
request.setURI(website);
HttpResponse responce = client.execute(request);
in = new BufferedReader(new InputStreamReader(responce.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String newLine = System.getProperty("line.separator");
while((line = in.readLine()) != null){
sb.append(line + newLine);
}
in.close();
data = sb.toString();
return data;
} finally {
if (in != null){
try{
in.close();
return data;
} catch (Exception e){
e.printStackTrace();
}
}
}
}
}
this is my AndroidManifest,
<uses-sdk
android:minSdkVersion="15"
android:targetSdkVersion="22" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".HttpExample"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
and my layout xml,
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/tvHttp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Loading Data"
android:textSize="20dp"
/>
</ScrollView>
</LinearLayout>
now when i run this on emulator or my android phone NOTHING IS DISPLAYED.. Just a blank white layout is visible.. what am i doing wrong here?
(i am using eclipse to program)
First of all you should not change the policy to force network calls on main thread instead use Async task.
If you want to read html contents then use jsoup which allows to parse html.
If you want to read data from webservice then try VOLLEY Library.This will save your time,works more efficiently and traceable.

Android NFC not opening correct class on tap

I have an app with 2 classes, I need my app to open the second class CardActivity when the NFC tag tapped/swiped. The app opens fine, but MainActivity is run, instead of CardActivity.
I would hazard a guess that this is an issue with my manifest, but it looks correct. Here it is regardless:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.spotsofmagic.spotsofmagic"
android:versionCode="1"
android:versionName="1.0" android:installLocation="auto">
<uses-sdk android:minSdkVersion="14" android:targetSdkVersion="14" />
<uses-permission android:name="android.permission.NFC" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-feature android:name="android.hardware.nfc" android:required="true" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".CardActivity"
android:label="#string/app_name" >
<!-- Handle a collectable card NDEF record -->
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED"/>
<data android:mimeType="application/vnd.spotsofmagic.spotsofmagic"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
</application>
</manifest>
I'm confident the tag itself is correct, as I have opened it in another app to view it's contents.
Below are the two classes.
CardActivity:
package com.spotsofmagic.spotsofmagic;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.bluetooth.*;
public class CardActivity extends Activity implements OnClickListener {
private static final String TAG = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.card_activity);
// see if app was started from a tag and show game console
Intent intent = getIntent();
Log.e(TAG, "Hello world. Intent Type: "+ intent.getType());
if(intent.getType() != null && intent.getType().equals(MimeType.NFC_DEMO)) {
Parcelable[] rawMsgs = getIntent().getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefMessage msg = (NdefMessage) rawMsgs[0];
NdefRecord cardRecord = msg.getRecords()[0];
String payload = new String(cardRecord.getPayload());
turnBluetoothOn(payload);
}
}
private void turnBluetoothOn(String payload) {
final AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("Alert Dialog");
builder.setMessage(payload);
builder.setIcon(android.R.drawable.ic_dialog_alert);
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
}
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
android.os.Process.killProcess(android.os.Process.myPid());
}
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}
MainActivity:
package com.spotsofmagic.spotsofmagic;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
private static final String TAG = "Activity...";
private NfcAdapter mAdapter;
private TextView mTextView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
// grab our NFC Adapter
mAdapter = NfcAdapter.getDefaultAdapter(this);
// TextView that we'll use to output messages to screen
mTextView = (TextView)findViewById(R.id.text_view);
displayMessage("Loading payload...");
}
private void displayMessage(String message) {
mTextView.setText(message);
}
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
}
}
Here is the code I used to write the tag. This is done on a different app incidentally:
NdefRecord appRecord = NdefRecord.createApplicationRecord("com.spotsofmagic.spotsofmagic");
// record that contains our custom "retro console" game data, using custom MIME_TYPE
byte[] payload = getPayload().getBytes();
byte[] mimeBytes = MimeType.NFC_DEMO.getBytes(Charset.forName("US-ASCII"));
NdefRecord cardRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, mimeBytes,
new byte[0], payload);
NdefMessage message = new NdefMessage(new NdefRecord[] { cardRecord, appRecord});
// Some code here removed for readability
Ndef ndef = Ndef.get(tag);
if (ndef != null) {
ndef.connect();
ndef.writeNdefMessage(message);
Does the NDEF message on the tag contain an Android Application Record? That could explain how MainActivity is launched. However, that can only be the cause if the AAR is the first record of the NDEF message on the tag or if the first record does not match the intent filter.

Categories

Resources