Trying to import data from my university parking api in Android - java

I am trying to acquire live parking information from an API which is provided by my university. I am able to get data when I run the java code. But when I put this code in the android studio, it is giving me an exception.
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.parth.p4">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="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" />
</intent-filter>
</activity>
<activity android:name=".Check"></activity>
</application>
</manifest>
This is my file where I am running the java code:
package com.example.parth.p4;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import java.net.URL;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Check extends AppCompatActivity {
public TextView t;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check);
try {
chk();
}catch (Exception e)
{
t.setText("Error");
}
}
private static Document loadTestDocument(String url) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
return factory.newDocumentBuilder().parse(new URL(url).openStream());
}
public void chk() throws Exception {
t = (TextView)findViewById(R.id.textView2);
String carPoolSpacesAvailable;
Document doc = loadTestDocument("https://api.uow.edu.au/parking/data/?format=xml");
NodeList nodes1 = doc.getElementsByTagName("parks");
carPoolSpacesAvailable = nodes1.item(6).getFirstChild().getNodeValue();
t.setText(carPoolSpacesAvailable);
}
}
This is my xml file where I am trying to show the data in a textview.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Check">
<TextView
android:id="#+id/textView2"
android:layout_width="44dp"
android:layout_height="23dp"
tools:layout_editor_absoluteX="331dp"
tools:layout_editor_absoluteY="16dp" />
</android.support.constraint.ConstraintLayout>
The output which I am getting is the error message which I have put in the catch block in the oncreate() method.Please help.

Make sure you are not making a network call on the MAIN UI Thread.
Try to call the chk() from background thread.
TextView t;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t = (TextView)findViewById(R.id.textView2);
new DownloadFilesTask().execute();
}
// doInBackground is called from the background thread while the onPostExecute is called on the Main Thread.
private class DownloadFilesTask extends AsyncTask<Void, Void, String> {
String carPoolSpacesAvailable = null;
#Override
protected String doInBackground(Void... voids) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
try {
Document
doc = factory.newDocumentBuilder().parse(new URL("https://api.uow.edu.au/parking/data/?format=xml").openStream());
NodeList nodes1 = doc.getElementsByTagName("parks");
carPoolSpacesAvailable = nodes1.item(6).getFirstChild().getNodeValue();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
return carPoolSpacesAvailable;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if(s!=null){
t.setText(s);
}
}
}
Try this in your second activity.

Replace your code by writing:
try {
chk();
}catch (Exception e)
{
Log.e("Error : ", "" + e.getMessage());
t.setText("Error");
}
After this run it, check the Logat in Error section and post a screenshot of the exception here.

Related

In android studio,How to rectify the error "E/Zygote: no v2" while fetching html content from url link?

I am new to android studio and I tried to get html content of a webpage using AsyncTask class(deprecated API).I have attached my AndroidManifest.xml file. I have added the neccessary permisions to access internet,still i am getting the error "E/Zygote : no v2" and my app crashes. Please explain what does this error mean and how to eliminate the error.I launched the app in a phone with Android 6.0.1
public class MainActivity extends AppCompatActivity {
public static class DownloadTask extends AsyncTask<String,Void,String>{
#Override
protected String doInBackground(String... urls) {
String result ="";
URL url;
HttpsURLConnection urlConnection;
try {
url = new URL(urls[0]);
urlConnection =(HttpsURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while(data!=-1){
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
But the LogCat came up with this error
[08-11 11:46:36.426 27036-27036/? E/Zygote: no v2
08-11 11:46:36.426 27036-27036/? W/SELinux: Function: selinux_compare_spd_ram, index[1], priority [2], priority version is VE=SEPF_SECMOBILE_6.0.1_0035
08-11 11:46:36.436 27036-27036/? W/SELinux: SELinux: seapp_context_lookup: seinfo=default, level=s0:c512,c768, pkgname=com.example.guessthecelebrity
08-11 11:46:36.436 27036-27036/? I/art: Late-enabling -Xcheck:jni
08-11 11:46:36.827 27036-27036/com.example.guessthecelebrity D/ResourcesManager: For user 0 new overlays fetched Null
08-11 11:46:36.847 27036-27036/com.example.guessthecelebrity W/System: ClassLoader referenced unknown path: /data/app/com.example.guessthecelebrity-2/lib/arm
08-11 11:46:36.907 27036-27036/com.example.guessthecelebrity D/ResourcesManager: For user 0 new overlays fetched Null
08-11 11:46:36.927 27036-27036/com.example.guessthecelebrity W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter androidx.vectordrawable.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.guessthecelebrity">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permissioandroid:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:largeHeap="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"/>
</intent-filter>
</activity>
</application>
</manifest>
I guess you are not good at using AsyncTask. You are not executing the AsyncTask anywhere. How ever, a better clean approach will be as follows,
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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
android:id="#+id/url_request"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Input a web page url to get." />
<Button
android:id="#+id/url_request_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Request Page"
android:onClick="downloadSiteData"/>
</LinearLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/url_response"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</ScrollView>
</LinearLayout>
MainActivity with AsyncTask:
package com.example.downloadsite;
import androidx.appcompat.app.AppCompatActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
EditText urlRequest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
urlRequest = findViewById(R.id.url_request);
}
public void downloadSiteData(View view) {
String url = urlRequest.getText().toString();
if ( url.equals("")) {
Toast.makeText(MainActivity.this, "URL can't be empty", Toast.LENGTH_SHORT).show();
}
else {
new DownloadTask().execute(url);
}
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(MainActivity.this, "Downloading site data", Toast.LENGTH_SHORT).show();
}
#Override
protected String doInBackground(String... urls) {
String value = urls[0];
String response = null;
URL url = null;
HttpURLConnection urlConnection = null;
InputStream in = null;
try {
url = new URL(value);
urlConnection = (HttpURLConnection) url.openConnection();
in = new BufferedInputStream(urlConnection.getInputStream());
response = readStream(in);
} catch (Exception e) { e.printStackTrace(); }
finally {
urlConnection.disconnect();
}
return response;
}
private String readStream(InputStream inputStream) {
StringBuilder sb = new StringBuilder();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String nextLine = "";
String newLine = "";
while ((newLine = reader.readLine()) != null) {
sb.append(nextLine + newLine);
}
} catch (IOException e) { e.printStackTrace(); }
return sb.toString();
}
#Override
protected void onPostExecute(String responseString) {
super.onPostExecute(responseString);
TextView tv = findViewById(R.id.url_response);
tv.setText(responseString);
}
}
}

Android Studio cant run a single class

I have a problem with Android Studio.
I have two classes with almost the same code.
The first class is running without a problem but the second class causes an error.
The first class:
package com.example.guenes2.emobilitylab;
import android.content.ComponentName;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class NEFZ2array extends AppCompatActivity implements Serializable {
public static void main(String[] args) {
FileReader file = null;
try {
file = new FileReader("NEFZ.txt");
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ArrayList<Double> Nlist = new ArrayList<Double>();
int i=0;
Double d= null;
try {
BufferedReader input = new BufferedReader(file);
String s=null;
while((s=input.readLine())!=null) {
StringTokenizer st = new StringTokenizer(s,",");
while(st.hasMoreTokens()) {
try {
d = Double.parseDouble(st.nextToken());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Nlist.add(i, d);
}
}
input.close();
} catch(Exception e) {
e.printStackTrace();
}
for(double j:Nlist) {
System.out.println(j);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nefz2array);
}
}
The second class:
package com.example.guenes2.emobilitylab;
import android.content.ComponentName;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class WLTP2array extends AppCompatActivity implements Serializable {
public void main(String[] args) {
FileReader file = null;
try {
file = new FileReader("WLTP.txt");
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ArrayList<Double> Wlist = new ArrayList<Double>();
int i=0;
Double d= null;
try {
BufferedReader input = new BufferedReader(file);
String s=null;
while((s=input.readLine())!=null) {
StringTokenizer st = new StringTokenizer(s,",");
while(st.hasMoreTokens()) {
try {
d = Double.parseDouble(st.nextToken());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Wlist.add(i, d);
}
}
input.close();
} catch(Exception e) {
e.printStackTrace();
}
for(double k:Wlist) {
System.out.println(k);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wltp2array);
}
}
The Error of the second class:
Error running 'WLTP2array': The activity must be exported or contain an intent-filter
I dont understand what is the reason for this error. I know I can fix the error with changing the Manifest but then I cant run this single class. The whole app runs.
Thanks for your advice.
Here is my Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.guenes2.emobilitylab">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="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" />
</intent-filter>
</activity>
<activity android:name=".fahrzeugsimulation" />
<activity android:name=".elektrofahrzeug" />
<activity android:name=".hybridfahrzeug" />
<activity android:name=".brennstoffzellenfahrzeug" />
<activity android:name=".ergebnisse" />
<activity android:name=".ausfuehrlicher" />
<activity android:name=".VerlRadleistung" />
<activity android:name=".HaufRad" />
<activity android:name=".VerlEM" />
<activity android:name=".BetriebsVKM" />
<activity android:name=".bearbeitung" />
<activity android:name=".info" />
<activity android:name=".info2" />
<activity android:name=".info3" />
<activity android:name=".ergebnisse2" />
<activity android:name=".elektroTabelle" />
<activity android:name=".hybridTabelle" />
<activity android:name=".brennstoffzelleTabelle" />
<activity android:name=".WLTP2array" />
<activity android:name=".NEFZ2array" />
</application>
</manifest>
EDIT-------------------------------------------------------------------
I tried to fix it with the help but now the first class is showing the same error and the second one is running correct. Maybe the two classes affect each other.
Firstly, as the error indicated
Error running 'WLTP2array': The activity must be exported or contain an intent-filter
You need to register your activity inside the manifest.xml file something similar as your activity NEFZ2array. Check your manifest.xml and declare WLTP2array properly.
Secondly, change below line
public void main(String[] args)
to
public static void main(String[] args)
You need key word static for main method, to run that class.
------ Edit ------
Finally, edit your Run/Debug Configuration.
Add New Configuration -> Application, Select Main class, Configure Working directory and Use classpath of module
Then right click on the class to run your single class, see below:
So, in the end, when you open your "Run/Debug Configurations", it should be something like below:
You must have this in your Manifest:
<activity android:name=".WLTP2array" >
<intent-filter>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

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>

Unable to create facebook login in android application cannot find symbol method getAccessToken()

I am creating a facebook login for my android application. I am getting following below errors which i tried to solve but i can not because i am unable to find solution.
1) Error:(46, 46) error: cannot find symbol method getAccessToken()
2) Error:(41, 55) error: incompatible types: > cannot be converted to FacebookCallback
My activity_main.xml is:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#5b9bd5"
tools:context="com.example.ratingapp.ratingapp.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/info"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:textSize="18sp"
/>
<com.facebook.login.widget.LoginButton
android:id="#+id/login_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
/>
</android.support.constraint.ConstraintLayout>
My MainActivity.java is:
package com.example.ratingapp.ratingapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.accountkit.LoginResult;
import com.facebook.login.LoginManager;
import com.facebook.login.widget.LoginButton;
import java.util.Arrays;
import java.util.List;
import static android.R.attr.data;
public class MainActivity extends AppCompatActivity {
private TextView info;
private LoginButton loginButton;
private CallbackManager callbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(this.getApplicationContext());
setContentView(R.layout.activity_main);
callbackManager = CallbackManager.Factory.create();
loginButton = (LoginButton) findViewById(R.id.login_button);
List<String> permissionNeeds = Arrays.asList("user_photos", "email", "user_birthday", "public_profile");
loginButton.setReadPermissions(permissionNeeds);
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
info.setText(
"User ID: "
+ loginResult.getAccessToken().getUserId()
+ "\n" +
"Auth Token: "
+ loginResult.getAccessToken().getToken()
);
}
#Override
public void onCancel() {
info.setText("Login attempt canceled.");
}
#Override
public void onError(FacebookException exception) {
info.setText("Login attempt failed.");
}
});
}
}
Please help me solve these errors what i am doing wrong in this code.
Please alsoc check my AndroidManifest.xml incase i put a wrong facebook library.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.ratingapp.ratingapp">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="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"
/>
</intent-filter>
</activity>
<activity android:name="com.facebook.FacebookActivity"
android:configChanges=
"keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:theme="#android:style/Theme.Translucent.NoTitleBar"
android:label="#string/app_name" />
<meta-data android:name="com.facebook.sdk.ApplicationId"
android:value="#string/facebook_app_id"/>
</application>
<uses-permission android:name="android.permission.INTERNET"/>
/manifest>
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>()
{
#Override
public void onSuccess (final LoginResult loginResult)
{
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback()
{
#Override
public void onCompleted (JSONObject object, GraphResponse response)
{
try
{
String id = response.getJSONObject().getString("id");
((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(passwordEditText.getWindowToken(), 0);
if (connect())
{
/*ENTER*/
}
else
{
Toast.makeText(getApplicationContext(), textProblemConnecting(), Toast.LENGTH_LONG).show();
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("YOUR FIELDS");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel ()
{
}
#Override
public void onError (FacebookException e)
{
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "first_name, email, id, last_name, birthday, locale");
request.setParameters(parameters);
request.executeAsync();

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.

Categories

Resources