Android Studio cant run a single class - java

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>

Related

Trying to import data from my university parking api in Android

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.

Turning off cell radio when no calls are received

I am trying to detect if any calls are presently being attended or the cell phone is ringing.If not, the cell radio should switch off.Since I am using telephony manager for the first time. I am not able to rectify the error.
The error is " cannot resolve 'setRadioPower(?)'.
My MainActivity.java is:
public class MainActivity extends AppCompatActivity {
private TelephonyManager tm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TelephonyManager telephonyManager =
(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
PhoneStateListener callStateListener = new PhoneStateListener() {
public void onCallStateChanged(int state, String incomingNumber)
{
if(state==TelephonyManager.CALL_STATE_RINGING){
Toast.makeText(getApplicationContext(),"Phone Is Ringing",
Toast.LENGTH_LONG).show();
}
if(state==TelephonyManager.CALL_STATE_OFFHOOK){
Toast.makeText(getApplicationContext(),"Phone is Currently in A call",
Toast.LENGTH_LONG).show();
}
if(state==TelephonyManager.CALL_STATE_IDLE){
tm.setRadioPower(disabled);
}
}
};
telephonyManager.listen(callStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
}
My AndroidManifest.xml is:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.vk9621.radiocall">
<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>
</application>
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
</manifest>
My imports are:
import android.content.Context;
import android.content.Intent;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
Can someone tell me how to rectify this error?
The reason you won't find it in the developer docs is that it is hidden.
However, you may always find hidden methods in the Android Source Code.
Code reference: public boolean setRadioPower(boolean turnOn){}
If your phone is not rooted, or if you do not have system permission android.Manifest.permission.MODIFY_PHONE_STATE, you won't be able to access this API.
However, if you do have those permissions, you can easily achieve this using the following code:
ITelephony iTelephony = ITelephony.Stub.asInterface(ServiceManager.getService(Context.TELEPHONY_SERVICE));
try {
iTelephony.setRadioPower(true);
} catch (RemoteException e) {
e.printStackTrace();
}

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>

What permissions do i need for a java ftpclient?

I'm new in java and I'm working on an android app that connects to a ftp server .I'm having problems because i don't know exactly what permissions do I need to add to AndroidManifest.xml .I also have problems because I can't get it to connect to the server.
MainActivity.java :
package com.mycompany.myapp;
import android.app.*;
import android.os.*;
import it.sauronsoftware.ftp4j.FTPClient;
import android.widget.*;
import it.sauronsoftware.ftp4j.*;
import java.io.*;public class MainActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
FTPClient client = new FTPClient();
try
{
client.connect("192.168.1.1", 21);
client.login("root", "root");
Toast.makeText(getApplicationContext(),"Connected!",Toast.LENGTH_SHORT).show();
}
catch (FTPException e)
{}
catch (IllegalStateException e)
{}
catch (IOException e)
{}
catch (FTPIllegalReplyException e)
{}
}
}
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mycompany.myapp" >
<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>
</application>
main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
All you should need is INTERNET. Although depending on what you want to do, READ_EXTERNAL_STORAGE or WRITE_EXTERNAL_STORAGE may make sense.

Application context returning null when using getFilesDir()

I don't know why this is happening. When i check the DDMS there is no files dir too. I'm trying to access this folder at my Application subclass. Any idea why this is happening?
I need the application context to be global so I can use on classes that doesn't extends Activity.
package mci.multipratic;
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
import android.app.Application;
import android.content.Context;
public class MultiPraticApp extends Application
{
private static MultiPraticApp instance;
public static MultiPraticAppHelper helper;
public MultiPraticApp()
{
instance = MultiPraticApp.this;
helper = new MultiPraticAppHelper();
}
public static Context getContext()
{
return instance;
}
}
class MultiPraticAppHelper
{
private int offsets = 0;
private int productIndex = 0;
private int recipeId = 0;
private Recipe selectedRecipe;
private Properties configFile;
public MultiPraticAppHelper()
{
Context context = MultiPraticApp.getContext();
String path = context.getFilesDir() + "/config.properties";
File file = new File(path);
try
{
FileInputStream fis = new FileInputStream(file);
Properties properties = new Properties();
properties.load(fis);
fis.close();
}catch(Exception ex)
{
ex.printStackTrace();
}
}
My manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="mci.multipratic"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="4" />
<application android:name=".MultiPraticApp"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#android:style/Theme.Black.NoTitleBar.Fullscreen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".EnableProductsActivity"
android:label="#string/app_name"
android:theme="#android:style/Theme.Black.NoTitleBar.Fullscreen">
</activity>
<activity
android:name=".RecipeSelectionActivity"
android:label="#string/app_name"
android:theme="#android:style/Theme.Black.NoTitleBar.Fullscreen">
</activity>
<activity
android:name=".ProductAdjustsActivity"
android:label="#string/app_name"
android:theme="#android:style/Theme.Black.NoTitleBar.Fullscreen"
>
</activity>
</application>
I believe the problem is you are trying to do initialization in the constructor. Move the code in constructor to OnCreate of Application class.
#Override
public void onCreate() {
super.onCreate();
if(instance != null)
instance = MultiPraticApp.this;
if(helper != null)
helper = new MultiPraticAppHelper();
}

Categories

Resources